// ================= Brand detail screen =================

const BrandDetailScreen = ({ brandCode, setView, tweaks, openContext, onMounted }) => {
  const brand = window.BRANDS.find(b => b.code === brandCode);
  const [tab, setTab] = useStateS("overview");
  const [, setTick] = useStateS(0);
  const [loadingDetail, setLoadingDetail] = useStateS(false);
  useEffectS(() => {
    if (!brand) return;
    if ((brand.accounts || []).length > 0) return;
    if (!window.__fabcomLoadBrandDetail) return;
    setLoadingDetail(true);
    window.__fabcomLoadBrandDetail(brandCode)
      .then(() => { setLoadingDetail(false); setTick(x => x + 1); onMounted && onMounted(); })
      .catch(() => setLoadingDetail(false));
  }, [brandCode]);
  if (!brand) return <div className="p-16 muted">Brand not found or no access.</div>;
  const accounts = brand.accounts || [];
  const allCampaigns = accounts.flatMap(a => a.campaigns || []);
  const brandNonMediaAll = window.NON_MEDIA.filter(r => r.brand_code === brand.code);
  const nmClientTotal = brandNonMediaAll.reduce((s, r) => s + r.client_cost_with_ac, 0);

  const platSplit = useMemoS(() => {
    const map = {};
    for (const a of accounts) {
      const spend = a.campaigns.reduce((s, c) => s + c.mtd_spend, 0);
      map[a.platform] = (map[a.platform] || 0) + spend;
    }
    const palette = { meta: "#1877f2", google: "#ea4335", dv360: "#34a853", tiktok: "#b5b8c0", ttd: "#ff6e00", youtube: "#ff0000" };
    return Object.entries(map).map(([k, v]) => ({ label: k, value: v, color: palette[k] }));
  }, [brand.code]);

  const paceTone = brand.pace_status;

  return (
    <div>
      {/* Sticky brand header */}
      <div style={{ position: "sticky", top: 0, zIndex: 5, background: "var(--bg-1)", borderBottom: "1px solid var(--border)", padding: "14px 16px" }}>
        <div className="row gap-12">
          <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--bg-3)", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-mono)", fontWeight: 600, fontSize: 13 }}>{brand.code}</div>
          <div className="grow">
            <div className="row gap-8">
              <h1 style={{ fontSize: 18 }}>{brand.name}</h1>
              <span className="chip">{brand.industry}</span>
              <span className="chip accent">{brand.code}</span>
            </div>
            <div className="row gap-12 mt-8 text-xs muted">
              <span><span className="dim">AM</span> {brand.am}</span>
              <span><span className="dim">Team Lead</span> {brand.tl}</span>
              <span><span className="dim">Platforms</span></span>
              {brand.platforms.map(p => <PlatPill key={p} platform={p} size={14}/>)}
            </div>
          </div>
          <div style={{ display: "flex", gap: 20, alignItems: "center" }}>
            <div className="col" style={{ alignItems: "flex-end" }}>
              <div className="text-xs muted">Media MTD</div>
              <div className="mono mt-8" style={{ fontSize: 15 }}>{window.fmt.hkdK(brand.mtd_spend)}</div>
              <div className="text-xs muted mt-8">of {window.fmt.hkdK(brand.plan_mtd)}</div>
            </div>
            <div className="vdivider" style={{ height: 44 }}/>
            <div className="col" style={{ alignItems: "flex-end" }}>
              <div className="text-xs muted">Non-media MTD</div>
              <div className="mono mt-8" style={{ fontSize: 15, color: "#8b5cf6" }}>{window.fmt.hkdK(nmClientTotal)}</div>
              <div className="text-xs muted mt-8">{brandNonMediaAll.length} records</div>
            </div>
            <div className="vdivider" style={{ height: 44 }}/>
            <div className="col" style={{ alignItems: "flex-end" }}>
              <div className="text-xs muted">MTD pace</div>
              <div className="row gap-8 mt-8">
                <Pacing pct={brand.pace} planPct={0.73} tone={paceTone} width={120}/>
                <span className="mono" style={{ color: `var(--${paceTone})`, fontSize: 13 }}>{(brand.pace * 100).toFixed(0)}%</span>
              </div>
              <div className="text-xs muted mt-8">Total {window.fmt.hkdK(brand.mtd_spend + nmClientTotal)}</div>
            </div>
            <button className="btn"><Icon name="external" size={12}/> Ads Managers</button>
            <button className="btn"><Icon name="export" size={12}/> Sheets</button>
          </div>
        </div>
      </div>

      <Tabs
        tabs={[
          { id: "overview",   label: "Overview" },
          { id: "accounts",   label: "Accounts",   count: accounts.length },
          { id: "campaigns",  label: "Campaigns",  count: allCampaigns.length },
          { id: "pacing",     label: "Budget pacing" },
          { id: "nonmedia",   label: "Non-media costs" },
          { id: "changes",    label: "Changes" },
          { id: "creatives",  label: "Creatives" },
        ]}
        active={tab}
        onChange={setTab}
      />

      <div style={{ padding: 16 }}>
        {tab === "overview" && (() => {
          const brandNonMedia = window.NON_MEDIA.filter(r => r.brand_code === brand.code);
          const nmClient = brandNonMedia.reduce((s, r) => s + r.client_cost_with_ac, 0);
          const nmGP = brandNonMedia.reduce((s, r) => s + r.gross_profit, 0);
          const nmOverdue = brandNonMedia.filter(r => r.invoice_status === "Overdue").length;
          const totalInvestment = brand.mtd_spend + nmClient;
          return (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
            <div className="card p-16">
              <h4 style={{ marginBottom: 10 }}>Spend by platform · MTD</h4>
              <div style={{ display: "flex", gap: 16, alignItems: "center" }}>
                <Donut items={platSplit} size={140} thick={22}/>
                <div className="col gap-8" style={{ flex: 1 }}>
                  {platSplit.map(it => (
                    <div key={it.label} className="row gap-8 text-xs">
                      <span style={{ width: 10, height: 10, background: it.color, borderRadius: 2 }}/>
                      <span className="grow truncate">{it.label}</span>
                      <span className="mono">{window.fmt.hkdK(it.value)}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
            <div className="card p-16" style={{ gridColumn: "span 2" }}>
              <h4 style={{ marginBottom: 10 }}>Daily spend · last 30 days</h4>
              <LineChart
                width={700} height={200}
                series={[
                  { label: "Spend", color: "var(--accent)", data: brand.daily_series, fill: true },
                  { label: "Plan",  color: "var(--text-3)", data: brand.daily_series.map(() => brand.plan_mtd / 30) },
                ]}
              />
            </div>

            {/* Media vs Non-media split */}
            <div className="card p-16">
              <h4 style={{ marginBottom: 10 }}>Media vs non-media · MTD</h4>
              <div className="row gap-8" style={{ justifyContent: "space-between", alignItems: "baseline" }}>
                <span className="mono" style={{ fontSize: 22 }}>{window.fmt.hkdK(totalInvestment)}</span>
                <span className="muted text-xs">total client investment</span>
              </div>
              <div className="mt-16">
                <StackedBar items={[
                  { value: brand.mtd_spend, color: "var(--accent)" },
                  { value: nmClient, color: "#8b5cf6" },
                ]} width={280} height={10}/>
              </div>
              <div className="row gap-12 mt-8 text-xs">
                <span className="row gap-4"><span className="dot" style={{ background: "var(--accent)" }}/><span className="muted">Media</span> <span className="mono">{window.fmt.hkdK(brand.mtd_spend)}</span></span>
                <span className="row gap-4"><span className="dot" style={{ background: "#8b5cf6" }}/><span className="muted">Non-media</span> <span className="mono">{window.fmt.hkdK(nmClient)}</span></span>
              </div>
              <div className="divider mt-16"/>
              <div className="row gap-12 mt-16 text-xs">
                <div className="col grow"><span className="muted">Non-media GP</span><span className="mono" style={{ fontSize: 14 }}>{window.fmt.hkdK(nmGP)}</span></div>
                <div className="col grow"><span className="muted">Records</span><span className="mono" style={{ fontSize: 14 }}>{brandNonMedia.length}</span></div>
                <div className="col grow"><span className="muted">Overdue</span><span className="mono" style={{ fontSize: 14, color: nmOverdue > 0 ? "var(--danger)" : "var(--text)" }}>{nmOverdue}</span></div>
              </div>
            </div>

            {/* Recent non-media records */}
            <div className="card" style={{ gridColumn: "span 2", padding: 0 }}>
              <div style={{ padding: "10px 14px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center" }}>
                <h4>Recent non-media records</h4>
                <span className="muted text-xs" style={{ marginLeft: "auto" }}>retainers · production · agency fees · vendor PO</span>
                <button className="btn sm ghost" style={{ marginLeft: 10 }} onClick={() => setTab("nonmedia")}>View all <Icon name="chev_r" size={11}/></button>
              </div>
              <Table
                columns={[
                  { key: "vendor_name", header: "Vendor", render: r => <span className="text-sm">{r.vendor_name}</span> },
                  { key: "service_type", header: "Service", width: 130, render: r => <span className="muted text-xs">{r.service_type}</span> },
                  { key: "period", header: "Period", width: 160, render: r => <span className="muted text-xs">{r.start_date} → {r.end_date}</span> },
                  { key: "client_cost_with_ac", header: "Client cost", right: true, num: true, width: 110, render: r => window.fmt.hkdK(r.client_cost_with_ac) },
                  { key: "gross_profit", header: "GP", right: true, num: true, width: 90, render: r => <span className="mono">{window.fmt.hkdK(r.gross_profit)}</span> },
                  { key: "invoice_status", header: "Invoice", width: 100, render: r => <span className={`chip ${r.invoice_status === "Paid" ? "success" : r.invoice_status === "Overdue" ? "danger" : r.invoice_status === "Issued" ? "info" : ""}`}>{r.invoice_status}</span> },
                  { key: "workflow_state", header: "Workflow", width: 130, render: r => <span className={`chip ${r.workflow_state === "Paid" ? "success" : r.workflow_state === "Pending approval" ? "warn" : ""}`}>{r.workflow_state}</span> },
                ]}
                rows={brandNonMedia.slice(0, 5)}
                striped={tweaks.tableStyle === "striped"}
                lined={tweaks.tableStyle === "lined"}
              />
            </div>

            <div className="card" style={{ gridColumn: "span 3", padding: 0 }}>
              <div style={{ padding: "10px 14px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center" }}>
                <h4>Top campaigns by MTD spend</h4>
                <span className="muted text-xs" style={{ marginLeft: "auto" }}>click a row to drill</span>
              </div>
              <Table
                columns={[
                  { key: "plat", header: "", width: 36, render: r => <PlatPill platform={r.platform} size={18}/> },
                  { key: "name", header: "Campaign", render: r => <span className="mono text-sm truncate">{r.name}</span> },
                  { key: "status", header: "", width: 80, render: r => <StatusDot status={r.status}/> },
                  { key: "mtd_spend", header: "MTD spend", right: true, num: true, width: 110, render: r => window.fmt.hkdK(r.mtd_spend) },
                  { key: "impr", header: "Impr.", right: true, num: true, width: 100, render: r => window.fmt.int(r.impressions) },
                  { key: "ctr", header: "CTR", right: true, num: true, width: 70, render: r => window.fmt.pct(r.ctr, 2) },
                  { key: "cpc", header: "CPC", right: true, num: true, width: 70, render: r => window.fmt.money2(r.cpc) },
                  { key: "spark", header: "Trend", width: 100, render: r => <Sparkline data={r.daily_series.slice(-14)}/> },
                ]}
                rows={allCampaigns.slice().sort((a,b) => b.mtd_spend - a.mtd_spend).slice(0, 8)}
                striped={tweaks.tableStyle === "striped"}
                lined={tweaks.tableStyle === "lined"}
                onRowClick={(r) => setView({ name: "campaign", brand: brand.code, account: r.account_id, campaign: r.id })}
                onRowContext={(r, e) => openContext(e, r, "campaign")}
              />
            </div>
          </div>
          );
        })()}

        {tab === "accounts" && (
          <Table
            columns={[
              { key: "plat", header: "", width: 36, render: r => <PlatPill platform={r.platform} size={18}/> },
              { key: "name", header: "Account", render: r => <div><div className="text-sm">{r.name}</div><div className="text-xs dim mono">{r.id}</div></div> },
              { key: "daily_budget_hkd", header: "Daily budget", right: true, num: true, width: 110, render: r => window.fmt.hkd(r.daily_budget_hkd) },
              { key: "today_spend", header: "Today", right: true, num: true, width: 100, render: r => window.fmt.hkdK(r.today_spend) },
              { key: "spend_7d", header: "7d", right: true, num: true, width: 100, render: r => window.fmt.hkdK(r.spend_7d) },
              { key: "spend_30d", header: "30d", right: true, num: true, width: 100, render: r => window.fmt.hkdK(r.spend_30d) },
              { key: "ctr", header: "CTR", right: true, num: true, width: 70, render: r => window.fmt.pct(r.ctr, 2) },
              { key: "cpc", header: "CPC", right: true, num: true, width: 70, render: r => window.fmt.money2(r.cpc) },
              { key: "cpa", header: "CPA", right: true, num: true, width: 80, render: r => window.fmt.money2(r.cpa) },
              { key: "roas", header: "ROAS", right: true, num: true, width: 70, render: r => r.roas.toFixed(2) + "x" },
            ]}
            rows={accounts}
            onRowClick={(r) => setView({ name: "account", brand: brand.code, account: r.id })}
            onRowContext={(r, e) => openContext(e, r, "account")}
            striped={tweaks.tableStyle === "striped"}
            lined={tweaks.tableStyle === "lined"}
          />
        )}

        {tab === "campaigns" && (
          <Table
            columns={[
              { key: "plat", header: "", width: 36, render: r => <PlatPill platform={r.platform} size={18}/> },
              { key: "name", header: "Campaign", render: r => <span className="mono text-sm truncate">{r.name}</span> },
              { key: "status", header: "Status", width: 90, render: r => <StatusDot status={r.status}/> },
              { key: "daily_budget", header: "Daily", right: true, num: true, width: 90, render: r => window.fmt.hkd(r.daily_budget) },
              { key: "mtd_spend", header: "MTD", right: true, num: true, width: 100, render: r => window.fmt.hkdK(r.mtd_spend) },
              { key: "impressions", header: "Impr.", right: true, num: true, width: 100, render: r => window.fmt.int(r.impressions) },
              { key: "clicks", header: "Clicks", right: true, num: true, width: 90, render: r => window.fmt.int(r.clicks) },
              { key: "ctr", header: "CTR", right: true, num: true, width: 70, render: r => window.fmt.pct(r.ctr, 2) },
              { key: "cpm", header: "CPM", right: true, num: true, width: 80, render: r => window.fmt.money2(r.cpm) },
              { key: "cpc", header: "CPC", right: true, num: true, width: 70, render: r => window.fmt.money2(r.cpc) },
              { key: "conv", header: "Conv.", right: true, num: true, width: 70, render: r => window.fmt.int(r.conv) },
              { key: "cpa", header: "CPA", right: true, num: true, width: 80, render: r => window.fmt.money2(r.cpa) },
            ]}
            rows={allCampaigns}
            onRowClick={(r) => setView({ name: "campaign", brand: brand.code, account: r.account_id, campaign: r.id })}
            onRowContext={(r, e) => openContext(e, r, "campaign")}
            striped={tweaks.tableStyle === "striped"}
            lined={tweaks.tableStyle === "lined"}
          />
        )}

        {tab === "pacing" && (
          <Table
            columns={[
              { key: "plat", header: "", width: 36, render: r => <PlatPill platform={r.platform} size={18}/> },
              { key: "name", header: "Campaign", render: r => <span className="mono text-sm truncate">{r.name}</span> },
              { key: "flight", header: "Flight", width: 110, render: r => <span className="text-xs muted">{r.days_elapsed}/{r.flight_days}d</span> },
              { key: "plan", header: "Plan", right: true, num: true, width: 110, render: r => window.fmt.hkdK(r.plan_budget) },
              { key: "spend", header: "Spent", right: true, num: true, width: 110, render: r => window.fmt.hkdK(r.spend) },
              { key: "pace", header: "Pace", width: 170, render: r => {
                const p = r.spend / Math.max(1, r.plan_budget * (r.days_elapsed / r.flight_days));
                const t = p > 1.2 ? "danger" : p < 0.7 ? "warn" : "success";
                return <div className="row gap-8"><Pacing pct={p} planPct={0.73} tone={t} width={100}/><span className="mono text-xs" style={{ color: `var(--${t})` }}>{(p * 100).toFixed(0)}%</span></div>;
              } },
              { key: "forecast", header: "EOM forecast", right: true, num: true, width: 120, render: r => window.fmt.hkdK(r.spend / Math.max(1, r.days_elapsed) * r.flight_days) },
              { key: "var", header: "Variance", right: true, num: true, width: 90, render: r => {
                const f = r.spend / Math.max(1, r.days_elapsed) * r.flight_days;
                const v = (f - r.plan_budget) / Math.max(1, r.plan_budget);
                return <span className="mono" style={{ color: v > 0.2 ? "var(--danger)" : v < -0.2 ? "var(--warn)" : "var(--text-2)" }}>{window.fmt.pctDelta(v)}</span>;
              } },
            ]}
            rows={allCampaigns}
            onRowClick={(r) => setView({ name: "campaign", brand: brand.code, account: r.account_id, campaign: r.id })}
            onRowContext={(r, e) => openContext(e, r, "campaign")}
            striped={tweaks.tableStyle === "striped"}
            lined={tweaks.tableStyle === "lined"}
          />
        )}

        {tab === "nonmedia" && (
          <Table
            columns={[
              { key: "vendor_name", header: "Vendor", render: r => r.vendor_name },
              { key: "service_type", header: "Service", render: r => <span className="muted">{r.service_type}</span> },
              { key: "campaign_name", header: "Campaign", render: r => <span className="mono text-sm truncate">{r.campaign_name}</span> },
              { key: "period", header: "Period", width: 170, render: r => <span className="muted text-xs">{r.start_date} → {r.end_date}</span> },
              { key: "net_vendor_cost", header: "Net vendor", right: true, num: true, width: 110, render: r => window.fmt.hkdK(r.net_vendor_cost) },
              { key: "client_cost_with_ac", header: "Client cost", right: true, num: true, width: 110, render: r => window.fmt.hkdK(r.client_cost_with_ac) },
              { key: "gross_profit", header: "GP", right: true, num: true, width: 100, render: r => <span className="mono">{window.fmt.hkdK(r.gross_profit)}</span> },
              { key: "invoice_status", header: "Invoice", width: 110, render: r => <span className={`chip ${r.invoice_status === "Paid" ? "success" : r.invoice_status === "Overdue" ? "danger" : "warn"}`}>{r.invoice_status}</span> },
              { key: "workflow_state", header: "Workflow", width: 130, render: r => <span className="chip">{r.workflow_state}</span> },
            ]}
            rows={window.NON_MEDIA.filter(r => r.brand_code === brand.code)}
            striped={tweaks.tableStyle === "striped"}
            lined={tweaks.tableStyle === "lined"}
          />
        )}

        {tab === "changes" && (
          <div className="card">
            {window.CHANGES.filter(c => c.brand_code === brand.code).slice(0, 24).map(c => (
              <div key={c.id} style={{ padding: "10px 14px", borderBottom: "1px solid var(--border)", display: "flex", gap: 10 }}>
                <div style={{ width: 24, height: 24, borderRadius: "50%", background: "var(--bg-3)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, fontWeight: 600 }}>{c.actor.slice(0, 2).toUpperCase()}</div>
                <div className="grow">
                  <div className="text-sm"><span className="bold">{c.actor}</span> <span className="muted">{c.action}</span> <span className="mono text-xs">{c.campaign}</span></div>
                  <div className="text-xs muted mt-8"><span className="mono">{c.prev}</span> → <span className="mono" style={{ color: "var(--accent)" }}>{c.next}</span> · {c.platform.toUpperCase()} · {c.account}</div>
                </div>
                <div className="text-xs muted">{window.fmt.timeAgo(c.hours_ago)}</div>
              </div>
            ))}
          </div>
        )}

        {tab === "creatives" && (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 12 }}>
            {Array.from({ length: 18 }).map((_, i) => {
              const c = allCampaigns[i % allCampaigns.length];
              const palette = ["#1a2340", "#0ea5a0", "#e5e8ee", "#ff6e00", "#8b5cf6", "#ec4899"];
              const bg = palette[i % palette.length];
              return (
                <div key={i} className="card" style={{ overflow: "hidden" }}>
                  <div style={{ aspectRatio: "1/1", background: bg, position: "relative", display: "flex", alignItems: "flex-end", padding: 10 }}>
                    <div style={{ position: "absolute", top: 8, left: 8 }}><PlatPill platform={c.platform} size={16}/></div>
                    <div style={{ position: "absolute", inset: 0, background: `radial-gradient(ellipse at 30% 30%, rgba(255,255,255,0.15), transparent 60%)` }}/>
                    <div style={{ color: "#fff", fontSize: 11, fontWeight: 500, position: "relative" }}>{brand.code}_AD_{String(i+1).padStart(3, "0")}</div>
                  </div>
                  <div style={{ padding: 8, fontSize: 11 }}>
                    <div className="row gap-8"><span className="muted">Spend</span><span className="mono" style={{ marginLeft: "auto" }}>{window.fmt.hkdK(randCr(i))}</span></div>
                    <div className="row gap-8"><span className="muted">CTR</span><span className="mono" style={{ marginLeft: "auto" }}>{(0.8 + (i%10)*0.15).toFixed(2)}%</span></div>
                    <div className="row gap-8"><span className="muted">ROAS</span><span className="mono" style={{ marginLeft: "auto" }}>{(1.2 + (i%9)*0.3).toFixed(2)}x</span></div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};
const randCr = (i) => 3000 + (i * 2213) % 48000;

window.BrandDetailScreen = BrandDetailScreen;
