// ================= Screens: Overview, Brands list =================

const OverviewScreen = ({ setView, tweaks, openContext }) => {
  const [filter, setFilter] = useStateS({ platform: null, tl: null, paceStatus: null, q: "" });
  const brands = window.BRANDS.filter(b => {
    if (filter.platform && !b.platforms.includes(filter.platform)) return false;
    if (filter.tl && b.tl !== filter.tl) return false;
    if (filter.paceStatus && b.pace_status !== filter.paceStatus) return false;
    if (filter.q && !(`${b.code} ${b.name}`.toLowerCase().includes(filter.q.toLowerCase()))) return false;
    return true;
  });

  const kpis = useMemoS(() => {
    const totalDaily = brands.reduce((s, b) => s + b.daily_budget_hkd, 0);
    const mtd = brands.reduce((s, b) => s + b.mtd_spend, 0);
    const plan = brands.reduce((s, b) => s + b.plan_mtd, 0);
    const today = brands.reduce((s, b) => s + b.accounts.reduce((s2, a) => s2 + a.today_spend, 0), 0);
    const gp = brands.reduce((s, b) => s + b.gp_mtd, 0);
    const sparkDaily = Array.from({ length: 30 }).map((_, i) => brands.reduce((s, b) => s + (b.daily_series[i] || 0), 0));
    return {
      myBrands: brands.length,
      totalDaily,
      today,
      mtd,
      plan,
      pace: mtd / Math.max(1, plan),
      gp,
      open: window.ALERTS.length,
      sparkDaily,
    };
  }, [brands.length]);

  const paceTone = (p) => p > 1.2 ? "danger" : p < 0.7 ? "warn" : "success";
  const paceLabel = (p) => p > 1.2 ? "Over" : p < 0.7 ? "Under" : "On track";

  const columns = [
    {
      key: "brand", header: "Brand", minWidth: 220,
      sort: (a, b) => a.name.localeCompare(b.name),
      render: (r) => (
        <div className="row gap-8">
          <span style={{ width: 28, height: 22, borderRadius: 5, background: "var(--bg-3)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 10.5, fontWeight: 600, fontFamily: "var(--font-mono)", color: "var(--text-1)" }}>{r.code}</span>
          <span className="truncate" style={{ maxWidth: 180 }}>{r.name}</span>
        </div>
      ),
    },
    {
      key: "platforms", header: "Platforms", width: 120,
      render: (r) => (
        <div className="row gap-4">
          {r.platforms.slice(0, 5).map(p => <PlatPill key={p} platform={p} size={18}/>)}
        </div>
      ),
    },
    {
      key: "daily_budget_hkd", header: "Daily budget", right: true, width: 120, num: true,
      sort: (a, b) => a.daily_budget_hkd - b.daily_budget_hkd,
      render: (r) => window.fmt.hkd(r.daily_budget_hkd),
    },
    {
      key: "mtd_spend", header: "MTD spend", right: true, width: 130, num: true,
      sort: (a, b) => a.mtd_spend - b.mtd_spend,
      render: (r) => (
        <div>
          <div>{window.fmt.hkd(r.mtd_spend)}</div>
          <div className="text-xs muted">of {window.fmt.hkdK(r.plan_mtd)}</div>
        </div>
      ),
    },
    {
      key: "pace", header: "Pace", width: 150,
      sort: (a, b) => a.pace - b.pace,
      render: (r) => (
        <div className="row gap-8">
          <Pacing pct={r.pace} planPct={0.73} tone={paceTone(r.pace)} width={70}/>
          <span className={`mono text-xs`} style={{ color: `var(--${paceTone(r.pace)})` }}>{(r.pace * 100).toFixed(0)}%</span>
        </div>
      ),
    },
    {
      key: "spend_7d", header: "7d", right: true, width: 120, num: true,
      sort: (a, b) => a.spend_7d - b.spend_7d,
      render: (r) => (
        <div className="row gap-8" style={{ justifyContent: "flex-end" }}>
          <Sparkline data={r.daily_series.slice(-7)} width={48} height={18}/>
          <span>{window.fmt.hkdK(r.spend_7d)}</span>
        </div>
      ),
    },
    {
      key: "spend_30d", header: "30d", right: true, width: 80, num: true,
      sort: (a, b) => a.spend_30d - b.spend_30d,
      render: (r) => window.fmt.hkdK(r.spend_30d),
    },
    {
      key: "non_media_mtd", header: "Non-media MTD", right: true, width: 130, num: true,
      sort: (a, b) => a.non_media_mtd - b.non_media_mtd,
      render: (r) => window.fmt.hkdK(r.non_media_mtd),
    },
    {
      key: "gp_mtd", header: "GP MTD", right: true, width: 110, num: true,
      sort: (a, b) => a.gp_mtd - b.gp_mtd,
      render: (r) => (
        <span className="mono">{window.fmt.hkdK(r.gp_mtd)} <span className="text-xs muted">({((r.gp_mtd / Math.max(1, r.mtd_spend)) * 100).toFixed(0)}%)</span></span>
      ),
    },
    {
      key: "last_change", header: "Last change", right: true, width: 100, num: true,
      sort: (a, b) => a.last_change - b.last_change,
      render: (r) => <span className="muted">{window.fmt.timeAgo(r.last_change)}</span>,
    },
    {
      key: "alerts", header: "Alerts", width: 72, right: true, num: true,
      sort: (a, b) => a.alerts - b.alerts,
      render: (r) => r.alerts > 0 ? <span className="chip danger">{r.alerts}</span> : <span className="dim">—</span>,
    },
  ];

  return (
    <div>
      <div style={{ padding: "16px 16px 0", display: "flex", alignItems: "center", gap: 12 }}>
        <div>
          <h1>Hi Vincent — here's your fleet</h1>
          <div className="muted text-sm mt-8">Wed, Apr 22, 2026 · data refreshed 18m ago via Fivetran</div>
        </div>
        <div style={{ marginLeft: "auto", display: "flex", gap: 6 }}>
          <button className="btn"><Icon name="export" size={12}/> Export</button>
          <button className="btn primary"><Icon name="plus" size={12}/> Quick action</button>
        </div>
      </div>

      {/* KPIs */}
      <div style={{ padding: 16, display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 12 }}>
        <KPI label="My brands" value={kpis.myBrands} sub={`across ${new Set(brands.flatMap(b => b.platforms)).size} platforms`}/>
        <KPI label="Daily budget" value={window.fmt.hkdK(kpis.totalDaily)} sub="HKD · active campaigns" spark={kpis.sparkDaily}/>
        <KPI label="Today's spend" value={window.fmt.hkdK(kpis.today)} trend={0.12} sub="vs yesterday"/>
        <KPI label="MTD pace" value={`${(kpis.pace * 100).toFixed(0)}%`} sub={`${window.fmt.hkdK(kpis.mtd)} of ${window.fmt.hkdK(kpis.plan)}`}
             trend={kpis.pace - 1}/>
        <KPI label="Open alerts" value={kpis.open} sub={`${window.ALERTS.filter(a => a.severity === "danger").length} critical`}/>
      </div>

      {/* Filter bar */}
      <div className="filterbar">
        <div className="row gap-4">
          <input className="input" placeholder="Filter brands…" value={filter.q}
                 onChange={e => setFilter(f => ({ ...f, q: e.target.value }))} style={{ width: 200 }}/>
        </div>
        <div className="vdivider" style={{ height: 18 }}/>
        <span className="text-xs muted">Platform</span>
        {window.PLATFORMS_LIST.map(p => (
          <div key={p.id} className={`filter-chip ${filter.platform === p.id ? "active" : ""}`}
               onClick={() => setFilter(f => ({ ...f, platform: f.platform === p.id ? null : p.id }))}>
            <PlatPill platform={p.id} size={14}/>
            {p.name}
          </div>
        ))}
        <div className="vdivider" style={{ height: 18 }}/>
        <span className="text-xs muted">Pace</span>
        {[["success", "On track"], ["warn", "Under"], ["danger", "Over"]].map(([id, lbl]) => (
          <div key={id} className={`filter-chip ${filter.paceStatus === id ? "active" : ""}`}
               onClick={() => setFilter(f => ({ ...f, paceStatus: f.paceStatus === id ? null : id }))}>
            <span className={`dot ${id}`}/> {lbl}
          </div>
        ))}
        <div className="vdivider" style={{ height: 18 }}/>
        <span className="text-xs muted">Team lead</span>
        {window.PEOPLE.TLS.map(tl => (
          <div key={tl} className={`filter-chip ${filter.tl === tl ? "active" : ""}`}
               onClick={() => setFilter(f => ({ ...f, tl: f.tl === tl ? null : tl }))}>
            {tl}
          </div>
        ))}
        <div style={{ marginLeft: "auto", display: "flex", gap: 6 }}>
          <span className="text-xs muted">{brands.length} of {window.BRANDS.length} brands</span>
          <button className="btn sm ghost"><Icon name="export" size={11}/> Sheets</button>
        </div>
      </div>

      <div style={{ padding: "12px 16px 80px" }}>
        <Table
          columns={columns}
          rows={brands}
          rowKey={r => r.code}
          onRowClick={r => setView({ name: "brand", brand: r.code })}
          onRowContext={(r, e) => openContext(e, r, "brand")}
          striped={tweaks.tableStyle === "striped"}
          lined={tweaks.tableStyle === "lined"}
        />
      </div>
    </div>
  );
};

window.OverviewScreen = OverviewScreen;
