// Account Detail — master-detail right pane

function AccountHeader({ acc, onClose, onOpen }) {
  return (
    <div className="px-5 pt-5 pb-3 border-b border-soft">
      <div className="flex items-start gap-3">
        <div className="w-10 h-10 rounded-lg flex items-center justify-center"
          style={{background:"var(--surface-2)", border:"1px solid var(--border)"}}>
          <Icon name="accounts" size={18} className="text-2"/>
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <StatusPill status={acc.status}/>
            <span className="text-3 text-[11px] mono">{acc.id}</span>
            <span className="text-4">·</span>
            <span className="text-3 text-[11px]">{acc.business}</span>
          </div>
          <h2 className="text-[18px] font-semibold tracking-tight mt-1 truncate">{acc.name}</h2>
        </div>
        <div className="flex items-center gap-1">
          <Button icon="external" onClick={onOpen}>Ads Manager</Button>
          <button onClick={onClose} className="h-8 w-8 rounded-md hover:bg-[var(--surface-2)] flex items-center justify-center text-3">
            <Icon name="x" size={14}/>
          </button>
        </div>
      </div>

      <div className="grid grid-cols-5 gap-4 mt-4">
        <MetaStat label="Currency" value={acc.ccy}/>
        <MetaStat label="Balance" value={window.fmtCCY(acc.balance, acc.ccy)}/>
        <MetaStat label="Spend cap" value={acc.spend_cap ? window.fmtCCY(acc.spend_cap, acc.ccy) : "—"}/>
        <MetaStat label="Account manager" value={acc.manager}/>
        <MetaStat label="Daily budget" value={window.fmtHKD(window.toHKD(acc.daily_budget, acc.ccy))} sub={`${Math.round(acc.ratio*100)}% of 30d avg`} tone={acc.ratio > 3 ? "red" : acc.ratio > 2 ? "amber" : "default"}/>
      </div>
    </div>
  );
}

function MetaStat({ label, value, sub, tone }) {
  const toneColor = tone === "red" ? "var(--red-400)" : tone === "amber" ? "var(--amber-400)" : "var(--text)";
  return (
    <div>
      <div className="text-3 text-[10.5px] uppercase tracking-wide">{label}</div>
      <div className="mt-1 tnum text-[14px] font-medium" style={{color: toneColor}}>{value}</div>
      {sub && <div className="text-3 text-[11px] tnum mt-0.5">{sub}</div>}
    </div>
  );
}

// Tab: Campaigns (tree)
function CampaignsTab({ acc, onOpenCampaign, onOpenAdset }) {
  const camps = window.FABCOM_DATA.campaigns.filter(c => c.account_id === acc.id);
  const [open, setOpen] = useState(() => new Set(camps.slice(0,2).map(c => c.id)));
  const toggle = (id) => setOpen(s => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n; });

  return (
    <div className="flex flex-col gap-1">
      <div className="flex items-center text-3 text-[11px] uppercase tracking-wide px-2 py-1.5 border-b border-soft">
        <span className="flex-1">Campaign · Adset · Ad</span>
        <span className="w-20 text-right">Status</span>
        <span className="w-28 text-right">Budget</span>
        <span className="w-24 text-right">Bid</span>
        <span className="w-8"></span>
      </div>
      {camps.map(c => {
        const isOpen = open.has(c.id);
        const adsets = window.FABCOM_DATA.adsets.filter(a => a.campaign_id === c.id);
        return (
          <div key={c.id}>
            <div className="row flex items-center px-2 py-2 rounded cursor-pointer" onClick={() => toggle(c.id)}>
              <Icon name="chevron-right" size={12} className={`chev mr-1 text-3 ${isOpen?"open":""}`}/>
              <Icon name="zap" size={13} className="text-2 mr-2"/>
              <div className="flex-1 min-w-0">
                <div className="text-[12.5px] font-medium truncate">{c.name}</div>
                <div className="mono text-3 text-[11px]">{c.id} · {c.objective}</div>
              </div>
              <div className="w-20 text-right"><StatusPill status={c.status}/></div>
              <div className="w-28 text-right tnum text-[12px]">{window.fmtCCY(c.daily_budget, acc.ccy)}<span className="text-3 text-[11px]">/d</span></div>
              <div className="w-24 text-right tnum text-2 text-[11.5px] mono">{(c.bid_strategy||"—").replace("LOWEST_COST_","LC_")}</div>
              <div className="w-8 text-right">
                <button onClick={(e)=>{e.stopPropagation(); onOpenCampaign(c.id);}} className="reveal-on-row text-3 hover:text-1">
                  <Icon name="arrow-right" size={13}/>
                </button>
              </div>
            </div>
            {isOpen && adsets.map(as => {
              const adsCount = as.ad_ids.length;
              return (
                <div key={as.id} className="row flex items-center pl-9 pr-2 py-1.5 rounded cursor-pointer"
                  onClick={() => onOpenAdset(as.id)}>
                  <Icon name="layers" size={13} className="text-3 mr-2"/>
                  <div className="flex-1 min-w-0">
                    <div className="text-[12.5px] truncate text-2">{as.name}</div>
                    <div className="mono text-3 text-[11px]">{as.id} · {adsCount} ads · {(as.audience||"—").split("—")[0].trim()}</div>
                  </div>
                  <div className="w-20 text-right"><StatusPill status={as.status}/></div>
                  <div className="w-28 text-right tnum text-[12px]">
                    {as.daily_budget ? <>{window.fmtCCY(as.daily_budget, acc.ccy)}<span className="text-3 text-[11px]">/d</span></>
                                     : <span className="text-3">LT {window.fmtCCY(as.lifetime_budget, acc.ccy)}</span>}
                  </div>
                  <div className="w-24 text-right tnum text-2 text-[11.5px] mono">{(as.optimization_goal||"—").slice(0,10)}</div>
                  <div className="w-8 text-right">
                    <Icon name="chevron-right" size={12} className="reveal-on-row text-3 inline-block"/>
                  </div>
                </div>
              );
            })}
          </div>
        );
      })}
    </div>
  );
}

// Tab: Budget Health
function BudgetHealthTab({ acc }) {
  const camps = window.FABCOM_DATA.campaigns.filter(c => c.account_id === acc.id);
  const rows = camps.map(c => {
    // fake 30d avg per campaign (proportional to acc's series)
    const share = c.daily_budget / (acc.daily_budget || 1);
    const avg30 = Math.max(1, Math.round(acc.avg_30d_spend * share * (0.7 + (c.id.length % 5) * 0.1)));
    const ratio = c.daily_budget / avg30;
    const sev = ratio > 3 ? "red" : ratio > 2 ? "amber" : ratio > 0.2 ? "green" : "amber";
    const series = acc.series.map((v,i) => Math.round(v * share * (0.8 + ((i+c.id.length)%7)/10)));
    return { c, avg30, ratio, sev, series };
  }).sort((a,b) => b.ratio - a.ratio);

  return (
    <table className="w-full">
      <thead>
        <tr>
          <th className="text-left">Campaign</th>
          <th className="text-right">Daily budget</th>
          <th className="text-right">30d avg spend</th>
          <th className="text-right">Ratio</th>
          <th className="text-left">Trend (30d)</th>
          <th className="text-right">Status</th>
        </tr>
      </thead>
      <tbody>
        {rows.map(({c, avg30, ratio, sev, series}) => (
          <tr key={c.id} className="row">
            <td className="text-left">
              <div className={`flex items-center ${sev==="red"?"sev-red":sev==="amber"?"sev-amber":"sev-green"}`}>
                <div>
                  <div className="text-1 font-medium">{c.name}</div>
                  <div className="mono text-3 text-[11px]">{c.id}</div>
                </div>
              </div>
            </td>
            <td className="text-right tnum">{window.fmtCCY(c.daily_budget, acc.ccy)}</td>
            <td className="text-right tnum text-2">{window.fmtCCY(avg30, acc.ccy)}</td>
            <td className="text-right"><Ratio ratio={ratio}/></td>
            <td className="text-left"><Sparkline data={series} w={120} h={22}
              stroke={sev==="red"?"var(--red-400)":sev==="amber"?"var(--amber-400)":"var(--green-400)"}/></td>
            <td className="text-right"><StatusPill status={c.status}/></td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// Tab: Recent Changes (7d)
function RecentChangesTab({ acc }) {
  const history = window.FABCOM_DATA.history.filter(h =>
    h.account_id === acc.id && (Date.now() - h.ts) < 7*86400e3
  );
  if (!history.length) return <div className="text-3 text-[12px] text-center py-10">No changes in the last 7 days.</div>;
  return (
    <table className="w-full">
      <thead>
        <tr>
          <th className="text-left">When</th>
          <th className="text-left">Actor</th>
          <th className="text-left">Entity</th>
          <th className="text-left">Field</th>
          <th className="text-left">Before → After</th>
        </tr>
      </thead>
      <tbody>
        {history.map(h => (
          <tr key={h.id} className="row">
            <td className="text-left tnum">
              <div>{window.timeAgo(h.ts)}</div>
              <div className="text-3 text-[11px]">{window.formatFullTs(h.ts)}</div>
            </td>
            <td className="text-left">
              <div className="flex items-center gap-2">
                <div className="w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-semibold"
                  style={{background:"color-mix(in oklab, var(--accent-500) 24%, transparent)", color:"var(--accent-400)"}}>
                  {h.actor.startsWith("Auto") ? "⚙" : h.actor.split(" ").map(x=>x[0]).slice(0,2).join("")}
                </div>
                <span className="text-2 text-[12px]">{h.actor}</span>
              </div>
            </td>
            <td className="text-left">
              <div className="flex items-center gap-1.5">
                <Chip tone="default">{h.entity_kind}</Chip>
                <span className="text-2 text-[12px] truncate max-w-[240px]">{h.entity_name}</span>
              </div>
            </td>
            <td className="text-left mono text-[11.5px] text-2">{h.field}</td>
            <td className="text-left"><Diff oldV={h.old_value} newV={h.new_value} money={h.field.includes("budget")} ccy={acc.ccy}/></td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// Tab: Creatives
function CreativesTab({ acc }) {
  const ads = window.FABCOM_DATA.ads.filter(a => a.account_id === acc.id && a.status === "ACTIVE").slice(0, 18);
  return (
    <div className="grid grid-cols-3 gap-3">
      {ads.map(ad => (
        <div key={ad.id} className="surface rounded-lg overflow-hidden">
          <div className={`aspect-[4/3] ${ad.thumb_cls} relative flex items-end p-3`}>
            <div className="absolute inset-0" style={{background:"linear-gradient(to top, rgba(0,0,0,.55), transparent 60%)"}}/>
            <div className="relative text-white">
              <div className="text-[13px] font-semibold leading-tight drop-shadow">{ad.headline}</div>
              <div className="text-[11px] opacity-90 mt-1 leading-snug line-clamp-2">{ad.description}</div>
            </div>
            <div className="absolute top-2 right-2 flex items-center gap-1">
              <StatusPill status={ad.status}/>
            </div>
          </div>
          <div className="p-2.5 flex items-center gap-2 text-[11px]">
            <Chip tone="accent">{ad.cta.replace("_"," ")}</Chip>
            <span className="mono text-3 ml-auto">{ad.id}</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function AccountDetail({ accountId, onClose, onOpenCampaign, onOpenAdset }) {
  const acc = window.FABCOM_DATA.accounts.find(a => a.id === accountId);
  const [tab, setTab] = useState("campaigns");
  if (!acc) return null;

  const camps = window.FABCOM_DATA.campaigns.filter(c => c.account_id === acc.id);
  const changes7d = window.FABCOM_DATA.history.filter(h => h.account_id === acc.id && (Date.now()-h.ts) < 7*86400e3);
  const ads = window.FABCOM_DATA.ads.filter(a => a.account_id === acc.id && a.status === "ACTIVE");

  return (
    <div className="surface rounded-xl h-full flex flex-col overflow-hidden slide-in">
      <AccountHeader acc={acc} onClose={onClose} onOpen={() => {}}/>
      <div className="px-5 pt-3">
        <Tabs value={tab} onChange={setTab} tabs={[
          {value:"campaigns", label:"Campaigns", count: camps.length},
          {value:"health",    label:"Budget Health"},
          {value:"changes",   label:"Recent changes (7d)", count: changes7d.length},
          {value:"creatives", label:"Creatives", count: ads.length},
        ]}/>
      </div>
      <div className="flex-1 overflow-auto px-5 py-4">
        {tab === "campaigns" && <CampaignsTab acc={acc} onOpenCampaign={onOpenCampaign} onOpenAdset={onOpenAdset}/>}
        {tab === "health" && <BudgetHealthTab acc={acc}/>}
        {tab === "changes" && <RecentChangesTab acc={acc}/>}
        {tab === "creatives" && <CreativesTab acc={acc}/>}
      </div>
    </div>
  );
}

Object.assign(window, { AccountDetail });
