// Overview / Home screen

function StatCard({ label, value, sub, icon, tone = "default", spark }) {
  const tones = {
    default: "text-1",
    red:     "accent-text",
  };
  return (
    <div className="surface rounded-xl p-4 flex flex-col gap-2 relative overflow-hidden">
      <div className="flex items-center gap-2 text-3 text-[11.5px] uppercase tracking-wide">
        {icon && <Icon name={icon} size={13}/>}
        <span>{label}</span>
      </div>
      <div className="flex items-baseline gap-2">
        <div className={`text-[26px] font-semibold tnum tracking-tight ${tones[tone] || ""}`}>{value}</div>
        {sub && <div className="text-3 text-[12px]">{sub}</div>}
      </div>
      {spark && (
        <div className="absolute right-3 bottom-3 opacity-70">
          <Sparkline data={spark} w={110} h={28} strokeWidth={1.5}/>
        </div>
      )}
    </div>
  );
}

function FilterBar({ query, setQuery, business, setBusiness, currency, setCurrency, status, setStatus, businessOptions, onExport }) {
  return (
    <div className="flex items-center gap-2 flex-wrap">
      <SearchInput value={query} onChange={setQuery} placeholder="Search accounts…" kbd="⌘K" className="w-[240px]"/>
      <Select value={business} onChange={setBusiness}
        options={[{value:"", label:"All businesses"}, ...businessOptions.map(b => ({value:b, label:b}))]}/>
      <Select value={currency} onChange={setCurrency}
        options={[{value:"", label:"All currencies"}, {value:"HKD", label:"HKD"}, {value:"USD", label:"USD"}, {value:"TWD", label:"TWD"}]}/>
      <Select value={status} onChange={setStatus}
        options={[{value:"", label:"All status"}, {value:"ACTIVE", label:"Active"}, {value:"PAUSED", label:"Paused"}]}/>
      <div className="flex-1"/>
      <Button icon="sheet" onClick={onExport}>Export to Sheets</Button>
      <Button icon="filter">Saved views</Button>
    </div>
  );
}

function AccountsTable({ accounts, selectedId, onSelect, onContextMenu }) {
  const [sortBy, setSortBy] = useState("daily_budget_hkd");
  const [sortDir, setSortDir] = useState("desc");
  const sorted = useMemo(() => {
    const s = [...accounts];
    s.sort((a,b) => {
      const av = sortBy === "daily_budget_hkd" ? window.toHKD(a.daily_budget, a.ccy)
               : sortBy === "ratio" ? a.ratio
               : sortBy === "last" ? a.last_change_ts
               : sortBy === "name" ? a.name.localeCompare(b.name) * -1
               : 0;
      const bv = sortBy === "daily_budget_hkd" ? window.toHKD(b.daily_budget, b.ccy)
               : sortBy === "ratio" ? b.ratio
               : sortBy === "last" ? b.last_change_ts
               : sortBy === "name" ? 0
               : 0;
      return (sortDir === "desc" ? -1 : 1) * (av < bv ? -1 : av > bv ? 1 : 0);
    });
    return s;
  }, [accounts, sortBy, sortDir]);

  const toggleSort = (k) => {
    if (sortBy === k) setSortDir(d => d === "desc" ? "asc" : "desc");
    else { setSortBy(k); setSortDir("desc"); }
  };
  const caret = (k) => sortBy === k ? <span className="ml-1 text-2">{sortDir==="desc"?"▾":"▴"}</span> : null;

  return (
    <div className="surface rounded-xl overflow-hidden">
      <div className="overflow-auto" style={{maxHeight:"calc(100vh - 320px)"}}>
        <table className="w-full sticky-head">
          <thead>
            <tr>
              <th className="text-left" onClick={() => toggleSort("name")}>Account{caret("name")}</th>
              <th className="text-left">Business</th>
              <th className="text-left">Ccy</th>
              <th className="text-right">Camps</th>
              <th className="text-right">Adsets</th>
              <th className="text-right cursor-pointer select-none" onClick={() => toggleSort("daily_budget_hkd")}>Daily budget (HKD){caret("daily_budget_hkd")}</th>
              <th className="text-right cursor-pointer select-none" onClick={() => toggleSort("ratio")}>vs 30d avg{caret("ratio")}</th>
              <th className="text-left">30d spend</th>
              <th className="text-left cursor-pointer select-none" onClick={() => toggleSort("last")}>Last change{caret("last")}</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {sorted.map(a => {
              const activeCamps = window.FABCOM_DATA.campaigns.filter(c => c.account_id === a.id && c.status === "ACTIVE").length;
              const activeAdsets = window.FABCOM_DATA.adsets.filter(s => s.account_id === a.id && s.status === "ACTIVE").length;
              const sev = a.ratio > 3 ? "red" : a.ratio > 2 ? "amber" : null;
              return (
                <tr key={a.id}
                  className={`row cursor-pointer ${selectedId === a.id ? "selected" : ""}`}
                  onClick={() => onSelect(a.id)}
                  onContextMenu={(e) => { e.preventDefault(); onContextMenu(e, a); }}>
                  <td className="text-left align-middle">
                    <div className="flex items-center gap-2">
                      <span className={sev === "red" ? "sev-red" : sev === "amber" ? "sev-amber" : ""}/>
                      <div className="min-w-0">
                        <div className="text-1 font-medium whitespace-nowrap overflow-hidden text-ellipsis" style={{maxWidth:260}}>{a.name}</div>
                        <div className="mono text-3 text-[11px]">{a.id}</div>
                      </div>
                    </div>
                  </td>
                  <td className="text-2">{a.business}</td>
                  <td className="mono text-2">{a.ccy}</td>
                  <td className="text-right tnum">{activeCamps}<span className="text-3">/{a.campaign_ids.length}</span></td>
                  <td className="text-right tnum text-2">{activeAdsets}</td>
                  <td className="text-right">
                    <div className="tnum font-medium text-1">{window.fmtHKD(window.toHKD(a.daily_budget, a.ccy))}</div>
                    {a.ccy !== "HKD" && <div className="mono text-3 text-[11px] tnum">{window.fmtCCY(a.daily_budget, a.ccy)}</div>}
                  </td>
                  <td className="text-right"><Ratio ratio={a.ratio}/></td>
                  <td className="text-left">
                    <Sparkline data={a.series} w={90} h={20}
                      stroke={sev === "red" ? "var(--red-400)" : sev === "amber" ? "var(--amber-400)" : "var(--accent-500)"}/>
                  </td>
                  <td className="text-2 tnum">
                    <div>{window.timeAgo(a.last_change_ts)}</div>
                    <div className="text-3 text-[11px]">{window.formatFullTs(a.last_change_ts)}</div>
                  </td>
                  <td className="text-right pr-3">
                    <div className="reveal-on-row flex items-center justify-end gap-1">
                      <span className="kbd">→</span>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <div className="flex items-center justify-between px-3 py-2 border-t border-soft text-3 text-[11.5px]">
        <span>Showing {sorted.length} of {window.FABCOM_DATA.meta.total_accounts} accounts</span>
        <span>Right-click a row for BQ query, copy ID, or open in Ads Manager.</span>
      </div>
    </div>
  );
}

function AlertsRail({ alerts, onInvestigate }) {
  const [tab, setTab] = useState("all");
  const filtered = alerts.filter(a => tab === "all" || a.severity === tab).slice(0, 18);
  const redCount = alerts.filter(a => a.severity === "red").length;
  const amberCount = alerts.filter(a => a.severity === "amber").length;
  return (
    <aside className="surface rounded-xl flex flex-col overflow-hidden" style={{minWidth:300}}>
      <div className="px-4 pt-4 pb-3 border-b border-soft">
        <div className="flex items-center gap-2">
          <Icon name="alerts" size={14} className="accent-text"/>
          <div className="text-1 font-medium text-[13px]">Alerts</div>
          <span className="ml-auto text-3 text-[11px]">{alerts.length} open</span>
        </div>
        <div className="flex gap-1 mt-3">
          <button onClick={() => setTab("all")} className={`px-2 py-1 rounded-md text-[11px] ${tab==="all"?"bg-[var(--surface-2)] text-1":"text-3"}`}>All <span className="tnum">{alerts.length}</span></button>
          <button onClick={() => setTab("red")} className={`px-2 py-1 rounded-md text-[11px] flex items-center gap-1 ${tab==="red"?"bg-[color-mix(in_oklab,var(--red-500)_18%,transparent)] text-[var(--red-400)]":"text-3"}`}>
            <SevDot level="red"/> Critical <span className="tnum">{redCount}</span>
          </button>
          <button onClick={() => setTab("amber")} className={`px-2 py-1 rounded-md text-[11px] flex items-center gap-1 ${tab==="amber"?"bg-[color-mix(in_oklab,var(--amber-500)_18%,transparent)] text-[var(--amber-400)]":"text-3"}`}>
            <SevDot level="amber"/> Watch <span className="tnum">{amberCount}</span>
          </button>
        </div>
      </div>
      <div className="overflow-auto flex-1">
        {filtered.length === 0 && (
          <div className="text-3 text-[12px] p-6 text-center">No {tab === "all" ? "alerts" : tab + " alerts"}. 🎉</div>
        )}
        {filtered.map(al => {
          const acc = window.FABCOM_DATA.accounts.find(a => a.id === al.account_id);
          return (
            <div key={al.id} className="px-4 py-3 border-b border-soft hover:bg-[var(--row-hover)]">
              <div className="flex items-start gap-2">
                <span className="mt-1.5"><SevDot level={al.severity}/></span>
                <div className="flex-1 min-w-0">
                  <div className="text-1 text-[12.5px] font-medium truncate">{al.title}</div>
                  <div className="text-3 text-[11.5px] mt-0.5">{al.detail}</div>
                  {al.kind === "budget_vs_baseline" && acc && (
                    <div className="mt-2 mono text-[11px] tnum flex items-center gap-2">
                      <span className="text-2">{window.fmtHKD(window.toHKD(al.value, acc.ccy))}</span>
                      <span className="text-4">vs baseline</span>
                      <span className="text-3">{window.fmtHKD(window.toHKD(al.baseline, acc.ccy))}</span>
                    </div>
                  )}
                  {al.kind === "big_edit" && (
                    <div className="mt-2 flex items-center gap-2 mono text-[11px] tnum">
                      <Diff oldV={al.baseline} newV={al.value} money ccy={acc?.ccy || "HKD"}/>
                    </div>
                  )}
                  <div className="mt-2 flex items-center gap-2">
                    <Button kind="subtle" size="xs" onClick={() => onInvestigate(al)}>Investigate</Button>
                    <Button kind="ghost" size="xs">Snooze 4h</Button>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
      <div className="px-4 py-2 border-t border-soft text-3 text-[11px]">Thresholds: red &gt; 3× baseline · amber &gt; 2×</div>
    </aside>
  );
}

function Overview({ filters, setFilters, selectedId, onSelect, onContextMenu, onInvestigate }) {
  const data = window.FABCOM_DATA;
  const businesses = [...new Set(data.accounts.map(a => a.business))].sort();
  const filtered = data.accounts.filter(a => {
    if (filters.query && !(a.name.toLowerCase().includes(filters.query.toLowerCase()) || a.business.toLowerCase().includes(filters.query.toLowerCase()))) return false;
    if (filters.business && a.business !== filters.business) return false;
    if (filters.currency && a.ccy !== filters.currency) return false;
    if (filters.status && a.status !== filters.status) return false;
    return true;
  });

  const activeAccounts = data.accounts.filter(a => a.status === "ACTIVE").length;
  const totalDailyHKD = data.accounts.filter(a => a.status === "ACTIVE")
    .reduce((s,a) => s + window.toHKD(a.daily_budget, a.ccy), 0);
  const liveCampaigns = data.campaigns.filter(c => c.status === "ACTIVE").length;
  const changesToday = data.history.filter(h => Date.now() - h.ts < 24*3600e3).length;
  const heroSpark = Array.from({length: 30}, (_, i) =>
    data.accounts.reduce((s, a) => s + window.toHKD(a.series[i] || 0, a.ccy), 0)
  );

  const [toast, setToast] = useState(null);

  return (
    <div className="flex gap-4 h-full">
      <div className="flex-1 min-w-0 flex flex-col gap-4">
        <div>
          <div className="text-3 text-[12px] mb-1">Overview · all accounts</div>
          <div className="flex items-end justify-between">
            <h1 className="text-[22px] font-semibold tracking-tight">Media Ops — Control Room</h1>
            <div className="flex items-center gap-2 text-3 text-[11.5px]">
              <span className="live-dot inline-block" style={{width:6,height:6,borderRadius:6,background:"var(--accent-500)"}}/>
              Last refreshed {window.timeAgo(data.meta.last_refreshed)} · next sync in 4h
            </div>
          </div>
        </div>

        <div className="grid grid-cols-4 gap-3">
          <StatCard label="Active accounts" value={activeAccounts} sub={`of ${data.meta.sample_accounts} in view`} icon="accounts"/>
          <StatCard label="Total daily budget" value={window.fmtHKD(totalDailyHKD)} sub="HKD equiv." icon="money" spark={heroSpark}/>
          <StatCard label="Live campaigns" value={liveCampaigns.toLocaleString()} sub={`${data.campaigns.length} total`} icon="zap"/>
          <StatCard label="Changes today" value={changesToday} sub={`${data.history.length} in 14d`} icon="feed"/>
        </div>

        <FilterBar
          query={filters.query} setQuery={v => setFilters({...filters, query:v})}
          business={filters.business} setBusiness={v => setFilters({...filters, business:v})}
          currency={filters.currency} setCurrency={v => setFilters({...filters, currency:v})}
          status={filters.status} setStatus={v => setFilters({...filters, status:v})}
          businessOptions={businesses}
          onExport={() => setToast("Exporting 20 accounts to a new Google Sheet…")}
        />

        <AccountsTable
          accounts={filtered}
          selectedId={selectedId}
          onSelect={onSelect}
          onContextMenu={onContextMenu}
        />
      </div>

      <AlertsRail alerts={data.alerts} onInvestigate={onInvestigate}/>

      {toast && <Toast text={toast} onDone={() => setToast(null)}/>}
    </div>
  );
}

Object.assign(window, { Overview, StatCard, AlertsRail });
