// ================= Account detail, Campaign detail =================

const AccountDetailScreen = ({ brandCode, accountId, setView, tweaks, openContext }) => {
  const brand = window.BRANDS.find(b => b.code === brandCode);
  const account = brand?.accounts.find(a => a.id === accountId);
  const [tab, setTab] = useStateS("campaigns");
  const [attribution, setAttribution] = useStateS(7);
  const [expanded, setExpanded] = useStateS({});
  if (!account) return null;
  const daily = Array.from({ length: 30 }).map((_, i) => account.campaigns.reduce((s, c) => s + (c.daily_series[i] || 0), 0));

  return (
    <div>
      <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">
          <PlatPill platform={account.platform} size={32}/>
          <div className="grow">
            <h1 style={{ fontSize: 17 }}>{account.name}</h1>
            <div className="row gap-12 mt-8 text-xs muted">
              <span className="mono">{account.id}</span>
              <span>·</span>
              <span>{brand.name}</span>
            </div>
          </div>
          <button className="btn"><Icon name="external" size={12}/> Open in {account.platform === "meta" ? "Ads Manager" : account.platform === "google" ? "Google Ads" : account.platform.toUpperCase()}</button>
        </div>
      </div>

      <div style={{ padding: 16, display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 10 }}>
        <KPI label="Balance" value={window.fmt.hkdK(account.balance_hkd)} sub="HKD"/>
        <KPI label="Spend cap" value={window.fmt.hkdK(account.spend_cap_hkd)}/>
        <KPI label="Daily budget" value={window.fmt.hkd(account.daily_budget_hkd)}/>
        <KPI label="Today · Yesterday" value={window.fmt.hkdK(account.today_spend)} sub={`yesterday ${window.fmt.hkdK(account.yesterday_spend)}`}/>
        <KPI label="7d · 30d" value={window.fmt.hkdK(account.spend_7d)} sub={`30d ${window.fmt.hkdK(account.spend_30d)}`} spark={daily.slice(-14)}/>
        <KPI label="CTR · CPM · CPC" value={window.fmt.pct(account.ctr, 2)} sub={`CPM ${window.fmt.money2(account.cpm)} · CPC ${window.fmt.money2(account.cpc)}`}/>
      </div>
      <div style={{ padding: "0 16px 16px", display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
        <KPI label="Conversions (7d)" value={window.fmt.int(account.conv)}/>
        <KPI label="CPA" value={window.fmt.money2(account.cpa)}/>
        <KPI label="ROAS" value={`${account.roas.toFixed(2)}x`} trend={(account.roas - 2) / 2}/>
      </div>

      <Tabs
        tabs={[
          { id: "campaigns",    label: "Campaigns" },
          { id: "performance",  label: "Performance" },
          { id: "conversions",  label: "Conversions" },
          { id: "creatives",    label: "Creatives" },
          { id: "changes",      label: "Changes" },
          { id: "targeting",    label: "Targeting" },
        ]}
        active={tab}
        onChange={setTab}
      />

      <div style={{ padding: 16 }}>
        {tab === "campaigns" && (
          <div className="tbl-wrap">
            <table className={`tbl ${tweaks.tableStyle === "striped" ? "striped" : ""} ${tweaks.tableStyle === "lined" ? "lined" : ""}`}>
              <thead>
                <tr>
                  <th style={{ width: 24 }}></th>
                  <th>Campaign / Ad set / Ad</th>
                  <th style={{ width: 90 }}>Status</th>
                  <th className="right" style={{ width: 90 }}>Daily</th>
                  <th className="right" style={{ width: 110 }}>MTD spend</th>
                  <th className="right" style={{ width: 100 }}>Impr.</th>
                  <th className="right" style={{ width: 80 }}>CTR</th>
                  <th className="right" style={{ width: 80 }}>CPC</th>
                  <th className="right" style={{ width: 80 }}>Conv</th>
                  <th style={{ width: 110 }}>Trend</th>
                </tr>
              </thead>
              <tbody>
                {account.campaigns.map(c => (
                  <React.Fragment key={c.id}>
                    <tr className="clickable" onClick={() => setView({ name: "campaign", brand: brandCode, account: accountId, campaign: c.id })}
                        onContextMenu={(e) => { e.preventDefault(); openContext(e, c, "campaign"); }}>
                      <td><span className="tree-toggle" onClick={(e) => { e.stopPropagation(); setExpanded(x => ({ ...x, [c.id]: !x[c.id] })); }}>
                        <Icon name={expanded[c.id] ? "chev_d" : "chev_r"} size={10}/>
                      </span></td>
                      <td><span className="mono text-sm truncate">{c.name}</span></td>
                      <td><StatusDot status={c.status}/></td>
                      <td className="right num">{window.fmt.hkd(c.daily_budget)}</td>
                      <td className="right num">{window.fmt.hkdK(c.mtd_spend)}</td>
                      <td className="right num">{window.fmt.int(c.impressions)}</td>
                      <td className="right num">{window.fmt.pct(c.ctr, 2)}</td>
                      <td className="right num">{window.fmt.money2(c.cpc)}</td>
                      <td className="right num">{window.fmt.int(c.conv)}</td>
                      <td><Sparkline data={c.daily_series.slice(-14)}/></td>
                    </tr>
                    {expanded[c.id] && Array.from({ length: 3 }).map((_, i) => (
                      <tr key={`${c.id}_${i}`} style={{ background: "var(--bg-2)" }}>
                        <td></td>
                        <td style={{ paddingLeft: 28 }}><span className="mono text-xs muted">├ {c.name.split("_")[1] || "SET"}_{String(i+1).padStart(2,"0")}</span></td>
                        <td><StatusDot status={{ label: "Active", tone: "success" }}/></td>
                        <td className="right num muted">{window.fmt.hkd(c.daily_budget / 3)}</td>
                        <td className="right num muted">{window.fmt.hkdK(c.mtd_spend / 3)}</td>
                        <td className="right num muted">{window.fmt.int(c.impressions / 3)}</td>
                        <td className="right num muted">{window.fmt.pct(c.ctr * (0.8 + i*0.1), 2)}</td>
                        <td className="right num muted">{window.fmt.money2(c.cpc * (0.9 + i*0.05))}</td>
                        <td className="right num muted">{window.fmt.int(c.conv / 3)}</td>
                        <td></td>
                      </tr>
                    ))}
                  </React.Fragment>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {tab === "performance" && (
          <div className="card p-16">
            <div className="row gap-8 mb-8"><h3>Daily spend · 30d</h3><span className="muted text-xs" style={{ marginLeft: "auto" }}>markers show budget / bid changes</span></div>
            <LineChart
              width={820} height={240}
              series={[
                { label: "Spend", color: "var(--accent)", data: daily, fill: true },
                { label: "Clicks ×50", color: "#8b5cf6", data: daily.map(v => v * 0.02 * 50) },
              ]}
            />
          </div>
        )}

        {tab === "conversions" && (
          <div>
            <div className="row gap-8 mb-8">
              <span className="muted text-sm">Attribution:</span>
              <div className="tweak-seg" style={{ width: 240 }}>
                {[7, 14, 28].map(d => <button key={d} className={attribution === d ? "active" : ""} onClick={() => setAttribution(d)}>{d}d</button>)}
              </div>
            </div>
            <Table
              columns={[
                { key: "event", header: "Event", render: r => <span className="mono text-sm">{r.event}</span> },
                { key: "count", header: "Count", right: true, num: true, render: r => window.fmt.int(r.count) },
                { key: "cpa", header: "CPA", right: true, num: true, render: r => window.fmt.money2(r.cpa) },
                { key: "roas", header: "ROAS", right: true, num: true, render: r => `${r.roas.toFixed(2)}x` },
                { key: "rate", header: "Rate", right: true, num: true, render: r => window.fmt.pct(r.rate, 2) },
              ]}
              rows={[
                { id: 1, event: "purchase",      count: Math.round(account.conv * 0.35 * (attribution/7)), cpa: account.cpa * 1.2, roas: account.roas * 1.1, rate: 0.021 * (attribution/7) },
                { id: 2, event: "add_to_cart",   count: Math.round(account.conv * 1.6 * (attribution/7)), cpa: account.cpa * 0.3, roas: 0, rate: 0.085 * (attribution/7) },
                { id: 3, event: "lead",          count: Math.round(account.conv * 0.8 * (attribution/7)), cpa: account.cpa * 0.6, roas: 0, rate: 0.055 * (attribution/7) },
                { id: 4, event: "view_content",  count: Math.round(account.conv * 4.2 * (attribution/7)), cpa: account.cpa * 0.1, roas: 0, rate: 0.210 * (attribution/7) },
                { id: 5, event: "sign_up",       count: Math.round(account.conv * 0.25 * (attribution/7)), cpa: account.cpa * 1.8, roas: 0, rate: 0.012 * (attribution/7) },
              ]}
              striped={tweaks.tableStyle === "striped"}
              lined={tweaks.tableStyle === "lined"}
            />
          </div>
        )}

        {tab === "creatives" && (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 12 }}>
            {Array.from({ length: 12 }).map((_, i) => (
              <div key={i} className="card" style={{ overflow: "hidden" }}>
                <div style={{ aspectRatio: "1/1", background: `hsl(${(i * 47) % 360}, 35%, 30%)`, display: "flex", alignItems: "flex-end", padding: 10, position: "relative" }}>
                  <div style={{ position: "absolute", top: 8, left: 8 }}><PlatPill platform={account.platform} size={16}/></div>
                  <div style={{ color: "#fff", fontSize: 11, fontWeight: 500 }}>{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(2500 + i*1800)}</span></div>
                  <div className="row gap-8"><span className="muted">CTR</span><span className="mono" style={{ marginLeft: "auto" }}>{(0.8 + i*0.15).toFixed(2)}%</span></div>
                </div>
              </div>
            ))}
          </div>
        )}

        {tab === "changes" && (
          <div className="card">
            {window.CHANGES.filter(c => c.brand_code === brandCode).slice(0, 12).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></div>
                  <div className="text-xs muted mt-8"><span className="mono">{c.prev}</span> → <span className="mono" style={{ color: "var(--accent)" }}>{c.next}</span></div>
                </div>
                <div className="text-xs muted">{window.fmt.timeAgo(c.hours_ago)}</div>
              </div>
            ))}
          </div>
        )}

        {tab === "targeting" && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div className="card p-16">
              <h4 style={{ marginBottom: 10 }}>Audiences</h4>
              {["Lookalike 1%", "Website visitors 30d", "Purchasers 180d", "Interest: Parents", "Interest: Pet owners"].map((a, i) => (
                <div key={i} className="row gap-8" style={{ padding: "8px 0", borderBottom: i < 4 ? "1px solid var(--border)" : "none" }}>
                  <span className="text-sm grow">{a}</span>
                  <span className="mono text-xs muted">{(120000 + i*45000).toLocaleString()} reach</span>
                </div>
              ))}
            </div>
            <div className="card p-16">
              <h4 style={{ marginBottom: 10 }}>Geo · demo</h4>
              <div className="text-xs muted mb-8">Top regions</div>
              {[["HK", 62], ["MO", 14], ["SG", 12], ["TW", 8], ["MY", 4]].map(([g, pct]) => (
                <div key={g} className="row gap-8" style={{ padding: "6px 0" }}>
                  <span className="mono text-sm" style={{ width: 24 }}>{g}</span>
                  <div style={{ flex: 1, height: 6, background: "var(--bg-3)", borderRadius: 4, position: "relative" }}>
                    <div style={{ position: "absolute", inset: 0, width: `${pct}%`, background: "var(--accent)", borderRadius: 4 }}/>
                  </div>
                  <span className="mono text-xs" style={{ width: 36, textAlign: "right" }}>{pct}%</span>
                </div>
              ))}
              <div className="text-xs muted mb-8" style={{ marginTop: 12 }}>Gender · Age</div>
              <StackedBar items={[{ value: 55, color: "#0ea5a0" }, { value: 42, color: "#8b5cf6" }, { value: 3, color: "var(--text-3)" }]} width={280}/>
              <div className="row gap-12 mt-8 text-xs muted"><span><span className="dot" style={{ background: "#0ea5a0" }}/> F 55%</span><span><span className="dot" style={{ background: "#8b5cf6" }}/> M 42%</span><span>O 3%</span></div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// ---------- Campaign drill ----------
const CampaignDetailScreen = ({ brandCode, accountId, campaignId, setView, tweaks }) => {
  const brand = window.BRANDS.find(b => b.code === brandCode);
  const account = brand?.accounts.find(a => a.id === accountId) || brand?.accounts.find(a => a.campaigns.some(c => c.id === campaignId));
  const c = account?.campaigns.find(x => x.id === campaignId);
  if (!c) return <div className="p-16 muted">Campaign not found</div>;
  const adsetLabel = c.platform === "google" ? "Ad group" : c.platform === "dv360" || c.platform === "ttd" ? "Insertion order" : "Ad set";
  const pace = c.spend / Math.max(1, c.plan_budget * (c.days_elapsed / c.flight_days));
  const paceTone = pace > 1.2 ? "danger" : pace < 0.7 ? "warn" : "success";

  return (
    <div>
      <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">
          <PlatPill platform={c.platform} size={30}/>
          <div className="grow">
            <div className="row gap-8"><h1 className="mono" style={{ fontSize: 15 }}>{c.name}</h1><StatusDot status={c.status}/></div>
            <div className="row gap-12 mt-8 text-xs muted">
              <span><span className="dim">Bid</span> {c.bid_strategy}</span>
              <span><span className="dim">Budget</span> {c.budget_type} {window.fmt.hkd(c.daily_budget)}/d</span>
              <span><span className="dim">Flight</span> {c.start_date} → {c.end_date}</span>
              <span><span className="dim">Objective</span> {c.objective}</span>
            </div>
          </div>
          <button className="btn"><Icon name="copy" size={12}/> Copy ID</button>
          <button className="btn"><Icon name="external" size={12}/> Open</button>
        </div>
      </div>

      <div style={{ padding: 16, display: "grid", gridTemplateColumns: "repeat(2, 2fr) 1fr", gap: 12 }}>
        <div className="card p-16" style={{ gridColumn: "span 2" }}>
          <div className="row gap-8 mb-8"><h3>Performance · 30d</h3><span className="muted text-xs" style={{ marginLeft: "auto" }}>spend + impressions + clicks + conversions</span></div>
          <LineChart
            width={720} height={220}
            series={[
              { label: "Spend", color: "var(--accent)", data: c.daily_series, fill: true },
              { label: "Clicks", color: "#8b5cf6", data: c.daily_series.map(v => v * 0.02 * 80) },
              { label: "Conv",   color: "#f59e0b", data: c.daily_series.map(v => v * 0.001 * 200) },
            ]}
          />
        </div>
        <div className="card p-16">
          <h3>Pacing</h3>
          <div className="row gap-8 mt-16"><Pacing pct={pace} planPct={c.days_elapsed / c.flight_days} tone={paceTone} width={160}/><span className="mono" style={{ color: `var(--${paceTone})` }}>{(pace * 100).toFixed(0)}%</span></div>
          <div className="text-xs muted mt-8">{window.fmt.hkdK(c.spend)} of {window.fmt.hkdK(c.plan_budget)}</div>
          <div className="divider mt-16"/>
          <div className="text-xs muted mt-16">Days remaining</div>
          <div className="mono" style={{ fontSize: 22, marginTop: 4 }}>{c.days_remaining}<span className="muted text-xs"> / {c.flight_days}d</span></div>
          <div className="text-xs muted mt-16">EOM forecast</div>
          <div className="mono" style={{ fontSize: 16 }}>{window.fmt.hkdK(c.spend / Math.max(1, c.days_elapsed) * c.flight_days)}</div>
        </div>
      </div>

      <div style={{ padding: "0 16px 16px" }}>
        <div className="card" style={{ padding: 0 }}>
          <div style={{ padding: "10px 14px", borderBottom: "1px solid var(--border)" }}>
            <h4>{adsetLabel}s breakdown</h4>
          </div>
          <Table
            columns={[
              { key: "name", header: adsetLabel, render: r => <span className="mono text-sm">{r.name}</span> },
              { key: "status", header: "Status", width: 90, render: r => <StatusDot status={r.status}/> },
              { key: "spend", header: "MTD spend", right: true, num: true, width: 110, render: r => window.fmt.hkdK(r.spend) },
              { key: "impr", header: "Impr.", right: true, num: true, width: 100, render: r => window.fmt.int(r.impr) },
              { key: "ctr", header: "CTR", right: true, num: true, width: 80, render: r => window.fmt.pct(r.ctr, 2) },
              { key: "cpa", header: "CPA", right: true, num: true, width: 80, render: r => window.fmt.money2(r.cpa) },
              { key: "spark", header: "Trend", width: 90, render: r => <Sparkline data={c.daily_series.slice(-14).map(v => v * r.mul)}/> },
            ]}
            rows={Array.from({ length: 4 }).map((_, i) => ({
              id: i,
              name: `${c.name.split("_")[1] || "SET"}_${String(i+1).padStart(2, "0")}`,
              status: i === 3 ? { label: "Paused", tone: "info" } : c.status,
              spend: c.mtd_spend * [0.38, 0.30, 0.22, 0.10][i],
              impr: Math.round(c.impressions * [0.38, 0.30, 0.22, 0.10][i]),
              ctr: c.ctr * [1.1, 0.95, 1.2, 0.7][i],
              cpa: c.cpa * [0.9, 1.1, 0.8, 1.6][i],
              mul: [1.1, 0.95, 1.2, 0.6][i],
            }))}
            striped={tweaks.tableStyle === "striped"}
            lined={tweaks.tableStyle === "lined"}
          />
        </div>
      </div>
    </div>
  );
};

window.AccountDetailScreen = AccountDetailScreen;
window.CampaignDetailScreen = CampaignDetailScreen;
