// ================= Pacing, Non-media, Changes, Login screens =================

const PacingScreen = ({ setView, tweaks, openContext }) => {
  const [filter, setFilter] = useStateS({ platform: null, tl: null, severity: null, q: "" });
  const rows = useMemoS(() => {
    const base = window.PACING_ROWS || [];
    return base.filter(r => {
      if (filter.platform && r.platform !== filter.platform) return false;
      if (filter.tl && r.tl !== filter.tl) return false;
      if (filter.severity && r.sev !== filter.severity) return false;
      if (filter.q && !(`${r.brand_code || ""} ${r.name || ""}`.toLowerCase().includes(filter.q.toLowerCase()))) return false;
      return true;
    });
  }, [filter]);

  return (
    <div>
      <div style={{ padding: 16 }}>
        <h1>Budget pacing</h1>
        <div className="muted text-sm mt-8">All active campaigns across all brands · plan vs actual vs end-of-month forecast</div>
      </div>

      <div className="filterbar">
        <input className="input" placeholder="Search campaign…" style={{ width: 220 }}
               value={filter.q} onChange={e => setFilter(f => ({ ...f, q: e.target.value }))}/>
        <div className="vdivider" style={{ height: 18 }}/>
        {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 }}/>
        {[["danger", "Over"], ["warn", "Off-track"], ["success", "On track"]].map(([id, lbl]) => (
          <div key={id} className={`filter-chip ${filter.severity === id ? "active" : ""}`}
               onClick={() => setFilter(f => ({ ...f, severity: f.severity === id ? null : id }))}>
            <span className={`dot ${id}`}/> {lbl}
          </div>
        ))}
        <div style={{ marginLeft: "auto" }}>
          <span className="text-xs muted">{rows.length} campaigns</span>
          <button className="btn sm ghost" style={{ marginLeft: 8 }}><Icon name="export" size={11}/> Sheets</button>
        </div>
      </div>

      <div style={{ padding: "12px 16px 40px" }}>
        <Table
          columns={[
            { key: "brand", header: "Brand", width: 100, render: r => <span className="mono text-xs muted">{r.brand_code}</span> },
            { key: "plat", header: "", width: 28, render: r => <PlatPill platform={r.platform} size={16}/> },
            { key: "name", header: "Campaign", render: r => <span className="mono text-sm truncate">{r.name}</span> },
            { key: "flight", header: "Flight", width: 160, render: r => <span className="text-xs muted">{r.start_date} → {r.end_date}</span> },
            { key: "days", header: "Days", width: 90, render: r => <span className="mono text-xs">{r.days_elapsed}/{r.flight_days}d</span> },
            { key: "plan", header: "Plan", right: true, num: true, width: 100, render: r => window.fmt.hkdK(r.plan_budget) },
            { key: "spend", header: "Spent", right: true, num: true, width: 100, render: r => window.fmt.hkdK(r.spend) },
            { key: "pace", header: "Pace", width: 170, sort: (a, b) => a.pace - b.pace,
              render: r => <div className="row gap-8"><Pacing pct={r.pace} planPct={r.days_elapsed / r.flight_days} tone={r.sev} width={100}/><span className="mono text-xs" style={{ color: `var(--${r.sev})` }}>{(r.pace * 100).toFixed(0)}%</span></div> },
            { key: "forecast", header: "EOM forecast", right: true, num: true, width: 120, render: r => window.fmt.hkdK(r.forecast) },
            { key: "var", header: "Var %", right: true, num: true, width: 90,
              render: r => <span className="mono" style={{ color: r.variance > 0.2 ? "var(--danger)" : r.variance < -0.2 ? "var(--warn)" : "var(--text-2)" }}>{window.fmt.pctDelta(r.variance)}</span> },
          ]}
          rows={rows}
          onRowClick={(r) => setView({ name: "campaign", brand: r.brand_code, account: r.account_id, campaign: r.id })}
          onRowContext={(r, e) => openContext(e, r, "campaign")}
          striped={tweaks.tableStyle === "striped"}
          lined={tweaks.tableStyle === "lined"}
        />
      </div>
    </div>
  );
};

const NonMediaScreen = ({ tweaks, openContext }) => {
  const [filter, setFilter] = useStateS({ state: null, q: "" });
  const rows = window.NON_MEDIA.filter(r => {
    if (filter.state && r.workflow_state !== filter.state) return false;
    if (filter.q && !(`${r.brand_code} ${r.vendor_name} ${r.campaign_name}`.toLowerCase().includes(filter.q.toLowerCase()))) return false;
    return true;
  });
  const states = ["Draft", "Pending approval", "Approved", "Invoiced", "Paid"];
  const totalGP = rows.reduce((s, r) => s + r.gross_profit, 0);
  const totalCost = rows.reduce((s, r) => s + r.client_cost_with_ac, 0);
  const overdue = rows.filter(r => r.invoice_status === "Overdue").length;

  return (
    <div>
      <div style={{ padding: 16 }}>
        <h1>Non-media spending</h1>
        <div className="muted text-sm mt-8">Direct / non-biddable costs — retainers, creative production, agency fees, vendor PO</div>
      </div>
      <div style={{ padding: "0 16px", display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
        <KPI label="Records" value={rows.length}/>
        <KPI label="Client cost" value={window.fmt.hkdK(totalCost)}/>
        <KPI label="Gross profit" value={window.fmt.hkdK(totalGP)} sub={`${((totalGP/Math.max(1,totalCost))*100).toFixed(0)}% margin`}/>
        <KPI label="Overdue invoices" value={overdue} sub="across vendors"/>
      </div>
      <div className="filterbar" style={{ marginTop: 12 }}>
        <input className="input" placeholder="Search vendor / brand / campaign…" style={{ width: 260 }}
               value={filter.q} onChange={e => setFilter(f => ({ ...f, q: e.target.value }))}/>
        <div className="vdivider" style={{ height: 18 }}/>
        <span className="text-xs muted">Workflow</span>
        {states.map(s => (
          <div key={s} className={`filter-chip ${filter.state === s ? "active" : ""}`}
               onClick={() => setFilter(f => ({ ...f, state: f.state === s ? null : s }))}>{s}</div>
        ))}
        <div style={{ marginLeft: "auto" }}>
          <button className="btn sm ghost"><Icon name="export" size={11}/> Sheets</button>
        </div>
      </div>
      <div style={{ padding: "12px 16px 40px" }}>
        <Table
          columns={[
            { key: "brand_code", header: "Brand", width: 70, render: r => <span className="mono text-xs muted">{r.brand_code}</span> },
            { key: "vendor_name", header: "Vendor", width: 200, render: r => r.vendor_name },
            { key: "service_type", header: "Service", width: 140, 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: 110, 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" : r.invoice_status === "Issued" ? "info" : ""}`}>{r.invoice_status}</span> },
            { key: "vendor_po_status", header: "PO", width: 110, render: r => <span className="chip">{r.vendor_po_status}</span> },
            { key: "workflow_state", header: "Workflow", width: 140, render: r => <span className={`chip ${r.workflow_state === "Paid" ? "success" : r.workflow_state === "Pending approval" ? "warn" : ""}`}>{r.workflow_state}</span> },
          ]}
          rows={rows}
          onRowContext={(r, e) => openContext(e, r, "nonmedia")}
          striped={tweaks.tableStyle === "striped"}
          lined={tweaks.tableStyle === "lined"}
        />
      </div>
    </div>
  );
};

const ChangesScreen = ({ setView }) => {
  return (
    <div>
      <div style={{ padding: 16 }}>
        <h1>Changes</h1>
        <div className="muted text-sm mt-8">Cross-platform audit feed · who edited what, when</div>
      </div>
      <div style={{ padding: "0 16px 40px" }}>
        <div className="card">
          {window.CHANGES.map(c => (
            <div key={c.id} style={{ padding: "10px 14px", borderBottom: "1px solid var(--border)", display: "flex", gap: 10, alignItems: "center" }}>
              <div style={{ width: 26, height: 26, borderRadius: "50%", background: "var(--bg-3)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10.5, fontWeight: 600 }}>{c.actor.slice(0, 2).toUpperCase()}</div>
              <div className="grow">
                <div className="text-sm row gap-8">
                  <span className="bold">{c.actor}</span>
                  <span className="muted">{c.action}</span>
                  <PlatPill platform={c.platform} size={14}/>
                  <span className="mono text-xs truncate" style={{ maxWidth: 340 }}>{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>
                  <span className="dim"> · {c.brand_name} · {c.account}</span>
                </div>
              </div>
              <div className="text-xs muted">{window.fmt.timeAgo(c.hours_ago)}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const SettingsScreen = ({ platform }) => (
  <div style={{ padding: 16 }}>
    <h1>{platform === "meta" ? "Meta" : platform === "google" ? "Google Ads" : "DV360"} settings</h1>
    <div className="muted text-sm mt-8">Audit trail from <span className="mono">fabcom-etl-core.{platform}_ads_settings.*_history</span></div>
    <div className="card mt-16 p-16">
      <div className="muted text-sm">This view is wired to the existing <span className="mono">*_history</span> tables. Placeholder shown in this prototype.</div>
    </div>
  </div>
);

// ---------- Login ----------
const LoginScreen = ({ onCredential, theme, errorMsg }) => {
  const btnRef = useRefS();
  const [gisReady, setGisReady] = useStateS(!!(window.google && window.google.accounts && window.google.accounts.id));
  const clientId = (window.FABCOM_CONFIG && window.FABCOM_CONFIG.googleClientId) || "";

  useEffectS(() => {
    if (gisReady) return;
    const iv = setInterval(() => {
      if (window.google && window.google.accounts && window.google.accounts.id) {
        setGisReady(true); clearInterval(iv);
      }
    }, 150);
    return () => clearInterval(iv);
  }, [gisReady]);

  useEffectS(() => {
    if (!gisReady || !clientId) return;
    window.google.accounts.id.initialize({
      client_id: clientId,
      callback: (resp) => onCredential && onCredential(resp.credential),
      ux_mode: "popup",
      hd: "fabcom.hk",
      auto_select: false,
    });
    if (btnRef.current) {
      btnRef.current.innerHTML = "";
      window.google.accounts.id.renderButton(btnRef.current, {
        type: "standard", theme: "filled_blue", size: "large", shape: "pill", text: "signin_with", logo_alignment: "left", width: 320,
      });
    }
  }, [gisReady, clientId, onCredential]);

  return (
    <div className="login-wrap">
      <div className="login-hero">
        <div className="row gap-8">
          <svg width="28" height="28" viewBox="0 0 24 24"><path d="M4 4 L11 4 L20 20 L13 20 Z" fill="#0ea5a0"/><path d="M20 4 L13 20" stroke="#0ea5a0" strokeWidth="2.8" fill="none"/></svg>
          <div style={{ fontSize: 15, fontWeight: 600 }}>Fabcom</div>
        </div>
        <div>
          <div style={{ fontSize: 40, fontWeight: 600, letterSpacing: "-0.02em", lineHeight: 1.08, maxWidth: 500 }}>One portal for every platform, every brand, every dollar.</div>
          <div style={{ fontSize: 14, color: "#b9c4d4", maxWidth: 480, marginTop: 18 }}>Settings, spend, performance, budget pacing and non-media cost across Meta, Google, DV360, TikTok, TTD and YouTube — all in one place.</div>
          <div style={{ marginTop: 28, display: "flex", gap: 8, flexWrap: "wrap" }}>
            {["Meta", "Google Ads", "DV360", "TikTok", "TTD", "YouTube"].map(p => (
              <span key={p} style={{ padding: "5px 10px", fontSize: 11.5, color: "#b9c4d4", background: "rgba(255,255,255,0.06)", borderRadius: 999 }}>{p}</span>
            ))}
          </div>
        </div>
        <div style={{ fontSize: 11.5, color: "#7a8596" }}>© Fabcom 2026 · ops.fabcom.app</div>
      </div>
      <div className="login-form">
        <div style={{ width: 340 }}>
          <h1 style={{ fontSize: 22 }}>Sign in</h1>
          <div className="muted text-sm mt-8">Access restricted to Fabcom team members (@fabcom.hk).</div>
          {!clientId && (
            <div className="mt-16 text-xs" style={{ padding: 10, background: "rgba(239,68,68,0.12)", color: "#fca5a5", borderRadius: 8 }}>
              Google client not configured on server. Set GOOGLE_CLIENT_ID.
            </div>
          )}
          {errorMsg && (
            <div className="mt-16 text-xs" style={{ padding: 10, background: "rgba(239,68,68,0.12)", color: "#fca5a5", borderRadius: 8 }}>{errorMsg}</div>
          )}
          <div ref={btnRef} className="mt-24" style={{ display: "flex", justifyContent: "center", minHeight: 44 }}/>
          {!gisReady && clientId && (
            <div className="muted text-xs mt-8" style={{ textAlign: "center" }}>Loading Google Sign-In…</div>
          )}
          <div className="text-xs dim mt-16" style={{ textAlign: "center" }}>
            Row-level access is applied from <span className="mono">main_am_contact</span> and <span className="mono">team_lead</span>.
          </div>
          <div className="divider mt-24"/>
          <div className="text-xs muted mt-16" style={{ display: "flex", gap: 12, justifyContent: "center" }}>
            <a className="crumb">Status</a>
            <a className="crumb">Docs</a>
            <a className="crumb">Contact Vincent</a>
          </div>
        </div>
      </div>
    </div>
  );
};

window.PacingScreen = PacingScreen;
window.NonMediaScreen = NonMediaScreen;
window.ChangesScreen = ChangesScreen;
window.SettingsScreen = SettingsScreen;
window.LoginScreen = LoginScreen;
