// ================= App shell =================
const { useState: useStateS, useEffect: useEffectS, useRef: useRefS, useMemo: useMemoS, useCallback: useCallbackS } = React;

// Sidebar
const Sidebar = ({ view, setView, alertsCount, onLogout }) => {
  const me = window.ME || { name: "—", email: "—", picture: null };
  const initials = (me.name || me.email || "??").split(/[\s@]+/).filter(Boolean).slice(0, 2).map(s => s[0] || "").join("").toUpperCase() || "??";
  const roleLabel = window.ME_ADMIN ? "Admin" : (window.ME_BRANDS ? `${(window.ME_BRANDS || []).length} brands` : "viewer");
  const items = [
    { id: "home",     label: "Overview",       icon: "home" },
    { id: "brands",   label: "Brands",         icon: "brand", count: window.BRANDS.length },
    { id: "pacing",   label: "Budget pacing",  icon: "pacing" },
    { id: "nonmedia", label: "Non-media",      icon: "nonmedia", count: window.NON_MEDIA.length },
    { id: "changes",  label: "Changes",        icon: "clock" },
    { id: "alerts",   label: "Alerts",         icon: "alert", count: alertsCount },
  ];
  const settings = [
    { id: "settings_meta",   label: "Meta settings",    icon: "settings" },
    { id: "settings_google", label: "Google settings",  icon: "settings" },
    { id: "settings_dv360",  label: "DV360 settings",   icon: "settings" },
  ];
  return (
    <aside className="sidebar">
      <div style={{ padding: "14px 14px 10px", display: "flex", alignItems: "center", gap: 9 }}>
        <div style={{
          width: 26, height: 26, borderRadius: 7,
          background: "var(--brand-navy)", display: "flex", alignItems: "center", justifyContent: "center",
          color: "var(--brand-teal)", position: "relative", overflow: "hidden"
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24"><path d="M4 4 L11 4 L20 20 L13 20 Z" fill="currentColor"/><path d="M20 4 L13 20" stroke="currentColor" strokeWidth="2.8" fill="none"/></svg>
        </div>
        <div style={{ lineHeight: 1.1 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Fabcom</div>
          <div className="text-xs muted">Media Ops</div>
        </div>
      </div>

      <div style={{ padding: "6px 10px 0" }}>
        <div className="btn w-full" style={{ justifyContent: "flex-start", gap: 8, height: 30 }}
             onClick={() => window.__openPalette?.()}>
          <Icon name="search" size={13}/>
          <span className="muted" style={{ fontSize: 12 }}>Search everything…</span>
          <span style={{ marginLeft: "auto", display: "flex", gap: 3 }}>
            <span className="kbd">⌘</span><span className="kbd">K</span>
          </span>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: "auto", marginTop: 8 }}>
        {items.map(it => (
          <div key={it.id} className={`sb-item ${view.name === it.id ? "active" : ""}`}
               onClick={() => setView({ name: it.id })}>
            <Icon name={it.icon} size={14}/>
            <span>{it.label}</span>
            {it.count != null && <span className="count">{it.count}</span>}
          </div>
        ))}
        <div className="sb-section">Pinned brands</div>
        {window.BRANDS.slice(0, 6).map(b => (
          <div key={b.code} className={`sb-item ${view.name === "brand" && view.brand === b.code ? "active" : ""}`}
               onClick={() => setView({ name: "brand", brand: b.code })}>
            <span style={{ width: 18, height: 18, borderRadius: 5, background: "var(--bg-3)", color: "var(--text-1)", fontSize: 9.5, fontWeight: 600, display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-mono)" }}>{b.code}</span>
            <span className="truncate">{b.name}</span>
          </div>
        ))}
        <div className="sb-section">Settings</div>
        {settings.map(it => (
          <div key={it.id} className="sb-item" onClick={() => setView({ name: it.id })}>
            <Icon name={it.icon} size={14}/>
            <span>{it.label}</span>
          </div>
        ))}
      </div>

      <div className="divider"/>
      <div style={{ padding: 10, display: "flex", alignItems: "center", gap: 9 }}>
        {me.picture
          ? <img src={me.picture} alt="" style={{ width: 26, height: 26, borderRadius: "50%" }}/>
          : <div style={{ width: 26, height: 26, borderRadius: "50%", background: "linear-gradient(135deg,#0ea5a0,#1a2340)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 600 }}>{initials}</div>}
        <div style={{ lineHeight: 1.15, minWidth: 0, flex: 1 }}>
          <div className="truncate" style={{ fontSize: 12.5 }}>{me.name || me.email}</div>
          <div className="truncate text-xs muted">{roleLabel}</div>
        </div>
        <button className="btn ghost icon" title="Sign out" onClick={onLogout} style={{ width: 24, height: 24 }}>
          <Icon name="external" size={11}/>
        </button>
      </div>
    </aside>
  );
};

// Topbar
const Topbar = ({ crumbs, theme, setTheme, setAlertsOpen, alertsCount, onRefresh, lastSynced, role, setRole }) => {
  return (
    <div className="topbar">
      <div className="grow" style={{ minWidth: 0 }}>
        <Crumbs items={crumbs} />
      </div>
      <div className="row gap-8">
        <div className="chip" title="Data freshness">
          <span className="dot success"/>
          <span className="text-xs muted">Synced {lastSynced}</span>
        </div>
        <button className="btn ghost icon" title="Refresh" onClick={onRefresh}>
          <Icon name="refresh" size={13}/>
        </button>
        <div className="vdivider" style={{ height: 20 }}/>
        <div className="tweak-seg" style={{ height: 24 }}>
          {["AM", "TL", "Admin"].map(r => (
            <button key={r} className={role === r ? "active" : ""} onClick={() => setRole(r)}>{r}</button>
          ))}
        </div>
        <button className="btn ghost icon" title="Toggle theme" onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
          <Icon name={theme === "dark" ? "sun" : "moon"} size={13}/>
        </button>
        <button className="btn ghost icon" title="Alerts" onClick={() => setAlertsOpen(true)} style={{ position: "relative" }}>
          <Icon name="bell" size={13}/>
          {alertsCount > 0 && (
            <span style={{ position: "absolute", top: 2, right: 2, width: 7, height: 7, borderRadius: 999, background: "var(--danger)" }}/>
          )}
        </button>
      </div>
    </div>
  );
};

// Command palette
const CommandPalette = ({ open, onClose, onNav }) => {
  const [q, setQ] = useStateS("");
  const [idx, setIdx] = useStateS(0);
  const inputRef = useRefS();
  useEffectS(() => { if (open) { setQ(""); setIdx(0); setTimeout(() => inputRef.current?.focus(), 10); } }, [open]);

  const results = useMemoS(() => {
    const ql = q.toLowerCase().trim();
    const out = [];
    // actions
    const acts = [
      { kind: "nav",  label: "Go to Overview",       to: { name: "home" } },
      { kind: "nav",  label: "Go to Brands",         to: { name: "brands" } },
      { kind: "nav",  label: "Go to Budget pacing",  to: { name: "pacing" } },
      { kind: "nav",  label: "Go to Non-media",      to: { name: "nonmedia" } },
      { kind: "nav",  label: "Go to Changes",        to: { name: "changes" } },
      { kind: "nav",  label: "Open Alerts drawer",   action: "alerts" },
    ];
    for (const a of acts) if (!ql || a.label.toLowerCase().includes(ql)) out.push(a);
    for (const b of window.BRANDS) {
      if (!ql || `${b.code} ${b.name}`.toLowerCase().includes(ql)) {
        out.push({ kind: "brand", label: b.name, trail: b.code, to: { name: "brand", brand: b.code } });
      }
    }
    for (const a of window.ALL_ACCOUNTS) {
      if (ql && `${a.id} ${a.name}`.toLowerCase().includes(ql)) {
        out.push({ kind: "account", label: a.name, trail: a.id, to: { name: "account", brand: a.brand_code, account: a.id } });
      }
    }
    for (const c of window.ALL_CAMPAIGNS) {
      if (ql && c.name.toLowerCase().includes(ql)) {
        out.push({ kind: "campaign", label: c.name, trail: c.platform.toUpperCase(), to: { name: "campaign", brand: c.brand_code, account: c.account_id, campaign: c.id } });
      }
    }
    return out.slice(0, 40);
  }, [q]);

  useEffectS(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      else if (e.key === "ArrowDown") { e.preventDefault(); setIdx(i => Math.min(results.length - 1, i + 1)); }
      else if (e.key === "ArrowUp")   { e.preventDefault(); setIdx(i => Math.max(0, i - 1)); }
      else if (e.key === "Enter")     { const r = results[idx]; if (r) pickResult(r); }
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, results, idx]);

  const pickResult = (r) => {
    if (r.action === "alerts") window.__openAlerts?.();
    else if (r.to) onNav(r.to);
    onClose();
  };

  if (!open) return null;
  return (
    <div className="palette-backdrop" onClick={onClose}>
      <div className="palette" onClick={(e) => e.stopPropagation()}>
        <input ref={inputRef} className="palette-input" placeholder="Search brands, accounts, campaigns, actions…"
               value={q} onChange={e => { setQ(e.target.value); setIdx(0); }}/>
        <div className="palette-results">
          {results.length === 0 && <div className="palette-item dim">No matches</div>}
          {results.map((r, i) => (
            <div key={i} className={`palette-item ${idx === i ? "active" : ""}`}
                 onMouseEnter={() => setIdx(i)}
                 onClick={() => pickResult(r)}>
              <span className="kind" style={{ width: 60 }}>{r.kind}</span>
              <span className="truncate" style={{ maxWidth: 300 }}>{r.label}</span>
              <span className="trail">
                {r.trail && <span>{r.trail}</span>}
                {idx === i && <span className="kbd">↵</span>}
              </span>
            </div>
          ))}
        </div>
        <div style={{ borderTop: "1px solid var(--border)", padding: "8px 12px", display: "flex", gap: 12, fontSize: 11, color: "var(--text-3)" }}>
          <span><span className="kbd">↑↓</span> navigate</span>
          <span><span className="kbd">↵</span> open</span>
          <span><span className="kbd">esc</span> close</span>
          <span style={{ marginLeft: "auto" }}>{results.length} results</span>
        </div>
      </div>
    </div>
  );
};

// Alerts drawer
const AlertsDrawer = ({ open, onClose, onNav }) => {
  if (!open) return null;
  const groups = { danger: [], warn: [], info: [] };
  for (const a of window.ALERTS) (groups[a.severity] || groups.info).push(a);
  return (
    <>
      <div className="drawer-backdrop" onClick={onClose}/>
      <div className="drawer">
        <div style={{ padding: "14px 16px", display: "flex", alignItems: "center", gap: 8, borderBottom: "1px solid var(--border)" }}>
          <Icon name="alert" size={14}/>
          <h2 style={{ fontSize: 14 }}>Alerts</h2>
          <span className="chip">{window.ALERTS.length} active</span>
          <button className="btn ghost icon" style={{ marginLeft: "auto" }} onClick={onClose}><Icon name="x" size={13}/></button>
        </div>
        <div style={{ padding: "10px 12px", borderBottom: "1px solid var(--border)", display: "flex", gap: 6 }}>
          <span className="chip danger">{groups.danger.length} critical</span>
          <span className="chip warn">{groups.warn.length} warn</span>
          <span className="chip info">{groups.info.length} info</span>
        </div>
        <div style={{ overflowY: "auto", flex: 1 }}>
          {window.ALERTS.map(a => (
            <div key={a.id} style={{ padding: "11px 16px", borderBottom: "1px solid var(--border)", cursor: "pointer" }}
                 onClick={() => { onNav({ name: "campaign", brand: a.brand_code, account: null, campaign: a.campaign_id }); onClose(); }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                <span className={`dot ${a.severity}`}/>
                <span style={{ fontSize: 12.5, fontWeight: 500 }}>{a.title}</span>
                <span className="muted text-xs" style={{ marginLeft: "auto" }}>{window.fmt.mins(a.detected_at)}</span>
              </div>
              <div className="text-xs muted truncate">{a.brand_name} · <PlatPill platform={a.platform} size={14}/> {a.account_name}</div>
              <div className="text-xs dim truncate mono" style={{ marginTop: 3 }}>{a.campaign_name}</div>
              <div className="row gap-4 mt-8">
                <span className="chip">{a.kind}</span>
                <span className="chip" style={{ marginLeft: "auto" }}>Jump to entity →</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

// Tweaks panel
const TweaksPanel = ({ enabled, tweaks, setTweaks }) => {
  if (!enabled) return null;
  const accents = [
    { id: "teal",   color: "#0ea5a0" },
    { id: "violet", color: "#8b5cf6" },
    { id: "amber",  color: "#f59e0b" },
    { id: "pink",   color: "#ec4899" },
    { id: "green",  color: "#22c55e" },
  ];
  const set = (k, v) => setTweaks(t => ({ ...t, [k]: v }));
  return (
    <div className="tweaks">
      <div className="tweaks-head">
        <Icon name="settings" size={13}/>
        <span style={{ fontSize: 13, fontWeight: 600 }}>Tweaks</span>
        <span className="muted text-xs" style={{ marginLeft: "auto" }}>Design knobs</span>
      </div>
      <div className="tweaks-body">
        <div className="tweak-row">
          <div className="lbl">Density</div>
          <div className="tweak-seg">
            {["compact", "cozy", "comfortable"].map(d => (
              <button key={d} className={tweaks.density === d ? "active" : ""} onClick={() => set("density", d)}>{d}</button>
            ))}
          </div>
        </div>
        <div className="tweak-row">
          <div className="lbl">Accent</div>
          <div className="swatches">
            {accents.map(a => (
              <div key={a.id}
                   className={`swatch ${tweaks.accent === a.id ? "active" : ""}`}
                   style={{ background: a.color }}
                   onClick={() => set("accent", a.id)}/>
            ))}
          </div>
        </div>
        <div className="tweak-row">
          <div className="lbl">Table style</div>
          <div className="tweak-seg">
            {[["plain", "Plain"], ["striped", "Striped"], ["lined", "Lined"]].map(([id, lbl]) => (
              <button key={id} className={tweaks.tableStyle === id ? "active" : ""} onClick={() => set("tableStyle", id)}>{lbl}</button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Sidebar, Topbar, CommandPalette, AlertsDrawer, TweaksPanel });
