/* global React */
// Terminal LatAm — Core: theme + helpers + shell + Today screen
// Reusable across all 8 screens of MediaAgent prototype.

const T = {
  bg: "#0c1014",
  surface: "#11161c",
  surfaceHi: "#161d25",
  surfaceLo: "#0a0d11",
  line: "#1f2933",
  lineHi: "#2c3947",
  ink: "#e6edf3",
  inkSoft: "#c7d2dd",
  mute: "#7d8b9b",
  muteDim: "#566472",
  amber: "#ffb84d",
  cyan: "#5ad0e8",
  green: "#4ade80",
  red: "#f87171",
  violet: "#a78bfa",
  pink: "#f472b6",
};
const FM = "'JetBrains Mono', ui-monospace, Menlo, monospace";
const FS = "'Inter Tight', 'IBM Plex Sans', system-ui, sans-serif";

// SHELL — chrome for every screen
const TerminalShell = ({ activeScreen, onNav, cfoMode, setCfoMode, density, singleClient, children }) => {
  const D = window.MA_DATA;
  const [convOpen, setConvOpen] = React.useState(false);
  const [notifOpen, setNotifOpen] = React.useState(false);
  const unread = (window.MA_ALERTS || []).filter(a => !a.read).length;

  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") { e.preventDefault(); setConvOpen(v => !v); }
      if (e.key === "n" && (e.metaKey || e.ctrlKey) && e.shiftKey) { e.preventDefault(); setNotifOpen(v => !v); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);
  const ITEMS = [
    ["F1", "TODAY", "today"],
    ["F2", "OPTIMIZE", "optimize"],
    ["F3", "PLAN", "plan"],
    ["F4", "DIAGNOSE", "diagnose"],
    ["F5", "MEASURE", "measure"],
    ["F6", "CREATIVE", "creative"],
    ["F7", "COMPLY", "comply"],
    ["F8", "REPORT", "report"],
  ];
  const SETTINGS = [["CONNECT", "connect"], ["AUDIT", "audit"], ["SETTINGS", "settings"]];
  const visiblePortfolio = singleClient ? D.portfolio.slice(0, 1) : D.portfolio;

  return (
    <div data-density={density} style={{
      width: "100%", minHeight: "100vh", background: T.bg, color: T.ink,
      fontFamily: FM, fontSize: 12, lineHeight: 1.45,
      backgroundImage: `linear-gradient(${T.line} 1px, transparent 1px), linear-gradient(90deg, ${T.line} 1px, transparent 1px)`,
      backgroundSize: "48px 48px",
    }}>
      {/* TOP TICKER */}
      <div style={{ display: "flex", alignItems: "center", height: 36, borderBottom: `1px solid ${T.lineHi}`, background: T.surface, position: "sticky", top: 0, zIndex: 50 }}>
        <div style={{ padding: "0 14px", borderRight: `1px solid ${T.lineHi}`, display: "flex", alignItems: "center", gap: 8, height: "100%" }}>
          <a href="/" title="Back to landing" className="ma-back-landing" style={{ color: T.bg, background: T.amber, fontSize: 10, fontFamily: FM, fontWeight: 700, textDecoration: "none", padding: "3px 8px", letterSpacing: "0.1em", marginRight: 6 }}>← LANDING</a>
          <span style={{ width: 8, height: 8, background: T.amber, borderRadius: 1 }} />
          <span style={{ fontFamily: FS, fontWeight: 700, letterSpacing: "0.06em", fontSize: 11 }}>MEDIAAGENT</span>
          <span style={{ color: T.muteDim, fontSize: 10 }}>v0.4 · beta</span>
          <style>{`@keyframes maBackPulse { 0%,100% { box-shadow: 0 0 0 0 rgba(255,184,77,0.7); } 50% { box-shadow: 0 0 0 6px rgba(255,184,77,0); } } .ma-back-landing { animation: maBackPulse 1.6s ease-in-out infinite; } .ma-back-landing:hover { animation: none; background: #ffd07a !important; }`}</style>
        </div>
        <div style={{ flex: 1, display: "flex", height: "100%", overflow: "hidden" }}>
          {visiblePortfolio.map((p) => {
            const cplDelta = ((p.cpl - p.cplPrev) / p.cplPrev) * 100;
            const up = cplDelta > 0;
            return (
              <div key={p.id} style={{ flex: 1, display: "flex", alignItems: "center", gap: singleClient ? 22 : 14, padding: "0 18px", borderRight: `1px solid ${T.line}`, fontSize: 11, minWidth: 220 }}>
                <span style={{ color: T.amber, letterSpacing: "0.08em", fontWeight: singleClient ? 600 : 400 }}>{p.id.toUpperCase()}</span>
                {singleClient && <span style={{ color: T.ink, fontFamily: FS }}>{p.name}</span>}
                <span style={{ color: T.ink }}>CPL {p.currency} {p.cpl.toFixed(2)}</span>
                <span style={{ color: up ? T.red : T.green }}>{up ? "▲" : "▼"} {Math.abs(cplDelta).toFixed(1)}%</span>
                <span style={{ color: T.muteDim }}>MER {p.mer.toFixed(2)}x</span>
                {singleClient && <span style={{ color: T.muteDim }}>Spend {p.currency} {(p.spend30d/1000).toFixed(0)}k/30d</span>}
                {singleClient && <span style={{ color: T.muteDim }}>Leads {p.leads30d.toLocaleString()}</span>}
                {singleClient && <span style={{ color: T.muteDim }}>Payback {p.payback}</span>}
              </div>
            );
          })}
        </div>
        <div style={{ padding: "0 14px", borderLeft: `1px solid ${T.lineHi}`, display: "flex", alignItems: "center", gap: 12, fontSize: 11, color: T.mute }}>
          <span>{D.now.date}</span>
          <span style={{ color: T.amber }}>{D.now.time}</span>
          <span style={{ color: T.muteDim }}>{D.user.tz}</span>
        </div>
      </div>

      {/* COMMAND BAR */}
      <div style={{ display: "flex", alignItems: "center", height: 30, borderBottom: `1px solid ${T.line}`, background: T.bg, fontSize: 11, position: "sticky", top: 36, zIndex: 49 }}>
        {ITEMS.map(([k, label, id]) => {
          const active = id === activeScreen;
          return (
            <button key={k} onClick={() => onNav(id)} style={{
              padding: "0 14px", height: "100%", display: "flex", alignItems: "center", gap: 8,
              borderRight: `1px solid ${T.line}`, borderTop: "none", borderBottom: active ? `2px solid ${T.amber}` : "none",
              borderLeft: "none",
              background: active ? T.surfaceHi : "transparent",
              color: active ? T.amber : T.mute,
              cursor: "pointer", fontFamily: FM, fontSize: 11,
            }}>
              <span style={{ color: T.muteDim, fontSize: 10 }}>{k}</span>
              <span style={{ fontWeight: active ? 600 : 400, letterSpacing: "0.05em" }}>{label}</span>
            </button>
          );
        })}
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 0, color: T.mute, height: "100%" }}>
          {SETTINGS.map(([label, id]) => {
            const active = id === activeScreen;
            return (
              <button key={id} onClick={() => onNav(id)} style={{
                padding: "0 14px", height: "100%", border: "none", borderLeft: `1px solid ${T.line}`,
                background: active ? T.surfaceHi : "transparent", color: active ? T.cyan : T.mute,
                cursor: "pointer", fontFamily: FM, fontSize: 10, letterSpacing: "0.12em",
              }}>⚙ {label}</button>
            );
          })}
          <span style={{ display: "flex", alignItems: "center", gap: 6, padding: "0 14px", borderLeft: `1px solid ${T.line}`, height: "100%" }}>
            <span style={{ width: 6, height: 6, background: T.green, borderRadius: 99, boxShadow: `0 0 8px ${T.green}`, animation: "blink 2s infinite" }} />
            agent · live
          </span>
          <button onClick={() => setConvOpen(true)} title="⌘K · open agent conversation" style={{
            padding: "0 14px", height: "100%", border: "none", borderLeft: `1px solid ${T.line}`,
            background: convOpen ? T.surfaceHi : "transparent", color: T.amber,
            cursor: "pointer", fontFamily: FM, fontSize: 11, letterSpacing: "0.1em",
          }}>▶ ⌘K</button>
          {window.NotificationBell && <window.NotificationBell onClick={() => setNotifOpen(true)} count={unread} />}
          <button onClick={() => setCfoMode(!cfoMode)} style={{
            margin: "0 12px",
            background: cfoMode ? T.amber : "transparent", color: cfoMode ? T.bg : T.mute,
            border: `1px solid ${cfoMode ? T.amber : T.line}`, padding: "3px 10px", fontFamily: FM, fontSize: 10,
            letterSpacing: "0.08em", cursor: "pointer", borderRadius: 2,
          }}>CFO MODE {cfoMode ? "ON" : "OFF"}</button>
        </div>
      </div>

      {/* CONTENT */}
      <div>{children}</div>

      {/* FOOTER STATUS */}
      <div style={{ display: "flex", height: 28, fontSize: 10, color: T.muteDim, borderTop: `1px solid ${T.line}`, alignItems: "center", background: T.surface, position: "sticky", bottom: 0 }}>
        <FooterCell><span style={{ color: T.green }}>●</span> tracking · CAPI 3/3 · EC 3/3</FooterCell>
        <FooterCell><span style={{ color: T.green }}>●</span> consent v2 · OK</FooterCell>
        <FooterCell><span style={{ color: T.amber }}>●</span> learning · 1 cuenta</FooterCell>
        <FooterCell>experiments · 2 active · 1 pre-read</FooterCell>
        <FooterCell>last MMM rebuild · 12d ago</FooterCell>
        <div style={{ marginLeft: "auto", padding: "0 14px", color: T.mute }}>F1-F8 navegar · ⏎ ejecutar · ⌘K command palette</div>
      </div>

      <style>{`
        @keyframes blink { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
        @keyframes pulse { 0%,100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.4); opacity: 0.5; } }
        [data-density="cozy"] .ma-pad { padding: 22px 26px !important; }
        [data-density="cozy"] .ma-card { padding: 18px !important; }
        [data-density="cozy"] .ma-row { padding: 14px 0 !important; }
        button { font-family: inherit; }
      `}</style>
    </div>
  );
};

// HELPERS — exported globally
const SectionLabel = ({ text, right }) => (
  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: `1px dashed ${T.line}`, paddingBottom: 6 }}>
    <span style={{ fontSize: 10, color: T.mute, letterSpacing: "0.18em" }}>{text}</span>
    {right && <span style={{ fontSize: 10 }}>{right}</span>}
  </div>
);
const Row = ({ k, v, kCol, vCol }) => (
  <div style={{ display: "flex", justifyContent: "space-between", padding: "3px 0", fontSize: 11 }}>
    <span style={{ color: kCol || T.muteDim }}>{k}</span>
    <span style={{ color: vCol || T.ink }}>{v}</span>
  </div>
);
const FooterCell = ({ children }) => (
  <div style={{ padding: "0 14px", height: "100%", display: "flex", alignItems: "center", gap: 6, borderRight: `1px solid ${T.line}` }}>
    {children}
  </div>
);
const Btn = ({ children, kind, onClick }) => (
  <button onClick={onClick} style={{
    background: kind === "amber" ? T.amber : kind === "violet" ? T.violet : kind === "green" ? T.green : "transparent",
    color: kind ? T.bg : T.mute,
    border: `1px solid ${kind === "amber" ? T.amber : kind === "violet" ? T.violet : kind === "green" ? T.green : T.line}`,
    padding: "5px 10px", fontFamily: FM, fontSize: 10, letterSpacing: "0.1em",
    cursor: "pointer", borderRadius: 0,
  }}>{children}</button>
);
const Pill = ({ col, children }) => (
  <span style={{
    display: "inline-flex", alignItems: "center", gap: 6, padding: "3px 8px",
    border: `1px solid ${col || T.line}`, color: col || T.mute, fontSize: 9, letterSpacing: "0.12em",
  }}>{children}</span>
);
const Stat = ({ k, v, col }) => (
  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 2 }}>
    <span style={{ color: T.muteDim, fontSize: 9, letterSpacing: "0.1em" }}>{k.toUpperCase()}</span>
    <span style={{ color: col || T.ink, fontSize: 13, fontFamily: FS, fontWeight: 600 }}>{v}</span>
  </div>
);
const Card = ({ title, right, children, accent }) => (
  <div className="ma-card" style={{ border: `1px solid ${accent || T.line}`, padding: 14, background: T.surface, ...(accent && { borderLeftWidth: 3 }) }}>
    {title && <SectionLabel text={title} right={right} />}
    <div style={{ marginTop: title ? 12 : 0 }}>{children}</div>
  </div>
);

// TODAY SCREEN — content only (no chrome)
const TodayScreen = ({ cfoMode }) => {
  const D = window.MA_DATA;
  return (
    <>
      {/* ACTIONS INBOX — hero */}
      <div className="ma-pad" style={{ padding: "20px 24px 16px", borderBottom: `1px solid ${T.line}` }}>
        <window.ActionsInbox />
      </div>
      {/* SECONDARY · VERSUS proof */}
      <div className="ma-pad" style={{ padding: "20px 24px 16px", borderBottom: `1px solid ${T.line}` }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 10, color: T.mute, letterSpacing: "0.18em", marginBottom: 6 }}>// VERSUS · {D.versus.period}</div>
            <div style={{ fontFamily: FS, fontSize: 28, fontWeight: 600, letterSpacing: "-0.01em", color: T.ink }}>
              Buenos días, Pablo. <span style={{ color: T.amber }}>El agente intervino {D.versus.interventions} veces</span> y <span style={{ color: T.green }}>+{D.versus.timeSaved.hrs}h</span> volvieron a ti.
            </div>
          </div>
          <div style={{ textAlign: "right", color: T.muteDim, fontSize: 10 }}>
            <div>signed · agent v0.4</div>
            <div>diff hash · 8c2f1ab</div>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", border: `1px solid ${T.line}`, background: T.surface }}>
          {[
            { k: "Leads", now: D.versus.blended.leads.now.toLocaleString(), prev: D.versus.blended.leads.prev.toLocaleString(), delta: D.versus.blended.leads.delta },
            { k: "CPL blended", now: `S/ ${D.versus.blended.cpl.now.toFixed(2)}`, prev: `S/ ${D.versus.blended.cpl.prev.toFixed(2)}`, delta: D.versus.blended.cpl.delta },
            { k: cfoMode ? "MER (verdad)" : "MER", now: `${D.versus.blended.mer.now}x`, prev: `${D.versus.blended.mer.prev}x`, delta: D.versus.blended.mer.delta },
            { k: "CAC payback", now: `${D.versus.blended.cacPayback.now} mo`, prev: `${D.versus.blended.cacPayback.prev} mo`, delta: D.versus.blended.cacPayback.delta },
            { k: "EMQ avg", now: D.versus.blended.emq.now, prev: D.versus.blended.emq.prev, delta: D.versus.blended.emq.delta },
            { k: "Ad sets", now: D.versus.blended.adSetCount.now, prev: D.versus.blended.adSetCount.prev, delta: D.versus.blended.adSetCount.delta, note: "consolidation" },
            { k: "Net new creatives", now: D.versus.blended.creativeNet.now, prev: D.versus.blended.creativeNet.prev, delta: D.versus.blended.creativeNet.delta },
            { k: "Spend deploy", now: `${(D.versus.blended.spendDeploy.now*100).toFixed(0)}%`, prev: `${(D.versus.blended.spendDeploy.prev*100).toFixed(0)}%`, delta: D.versus.blended.spendDeploy.delta },
          ].map((m, i) => (
            <div key={i} style={{
              padding: "14px 16px", borderRight: i % 4 !== 3 ? `1px solid ${T.line}` : "none",
              borderBottom: i < 4 ? `1px solid ${T.line}` : "none",
            }}>
              <div style={{ fontSize: 10, color: T.mute, letterSpacing: "0.1em", marginBottom: 8 }}>{m.k.toUpperCase()}</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
                <span style={{ fontFamily: FS, fontSize: 22, fontWeight: 600, color: T.ink }}>{m.now}</span>
                <span style={{ color: T.muteDim, fontSize: 11 }}>← {m.prev}</span>
              </div>
              <div style={{ marginTop: 6, display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ color: T.green, fontSize: 11, fontWeight: 600 }}>{m.delta}</span>
                {m.note && <span style={{ color: T.muteDim, fontSize: 10 }}>· {m.note}</span>}
              </div>
              <svg width="100%" height="18" style={{ marginTop: 8, display: "block" }}>
                <polyline
                  points={Array.from({length:14}, (_,j) => `${(j/13)*100}%,${10 + Math.sin(j*0.7+m.k.length)*4 + (j>10?-3:0)}`).join(" ")}
                  fill="none" stroke={T.amber} strokeWidth="1" opacity="0.85" vectorEffect="non-scaling-stroke"
                />
              </svg>
            </div>
          ))}
        </div>
      </div>

      {/* MAIN GRID */}
      <div style={{ display: "grid", gridTemplateColumns: "340px 1fr 380px", borderBottom: `1px solid ${T.line}` }}>
        {/* LEFT — agent log */}
        <div style={{ borderRight: `1px solid ${T.line}`, padding: "18px 18px" }}>
          <SectionLabel text="AGENT.LOG · live" right={<span style={{ color: T.amber }}>● {D.versus.interventions}/24h</span>} />
          <div style={{ marginTop: 12 }}>
            {D.activity.map((a, i) => (
              <div key={i} className="ma-row" style={{
                display: "grid", gridTemplateColumns: "44px 14px 1fr", gap: 8, padding: "10px 0",
                borderBottom: i < D.activity.length-1 ? `1px solid ${T.line}` : "none",
                fontSize: 11,
              }}>
                <span style={{ color: T.muteDim, fontSize: 10 }}>{a.t}</span>
                <span style={{ color: a.actor === "agent" ? T.amber : a.actor === "human" ? T.cyan : T.muteDim, textAlign: "center" }}>{a.icon}</span>
                <div>
                  <div style={{ color: T.ink, lineHeight: 1.4 }}>{a.text}</div>
                  <div style={{ marginTop: 4, display: "flex", gap: 8, alignItems: "center" }}>
                    <span style={{ color: T.muteDim, fontSize: 9, letterSpacing: "0.1em" }}>#{a.tag}</span>
                    {a.impact && <span style={{ color: T.green, fontSize: 9 }}>{a.impact}</span>}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* CENTER — Pacing + Diagnostic + Forecast */}
        <div className="ma-pad" style={{ padding: "18px 22px", display: "flex", flexDirection: "column", gap: 22 }}>
          <div>
            <SectionLabel text="PACING · minute by minute" right={<span style={{ color: T.mute }}>day 7/30 · S/ 14.3k spent today</span>} />
            <PacingTimeline />
          </div>
          <div>
            <SectionLabel text={`DIAGNOSTIC · ${D.diagnostic.title}`} right={<span style={{ color: T.amber, padding: "2px 6px", border: `1px solid ${T.amber}`, fontSize: 9, letterSpacing: "0.1em" }}>SEV {D.diagnostic.severity.toUpperCase()}</span>} />
            <div style={{ marginTop: 12, display: "grid", gridTemplateColumns: "repeat(6, 1fr)", border: `1px solid ${T.line}` }}>
              {D.diagnostic.tree.map((s, i) => {
                const col = s.result === "ok" ? T.green : s.result === "warn" ? T.amber : T.red;
                return (
                  <div key={i} style={{ padding: "10px 12px", borderRight: i < 5 ? `1px solid ${T.line}` : "none", background: s.result === "warn" ? "#1a1410" : T.surface }}>
                    <div style={{ fontSize: 9, color: T.muteDim, letterSpacing: "0.12em", marginBottom: 6 }}>{(i+1).toString().padStart(2,"0")} · {s.step.toUpperCase()}</div>
                    <div style={{ color: col, fontSize: 11, fontWeight: 600 }}>{s.value}</div>
                    <div style={{ marginTop: 6, height: 2, background: col, opacity: 0.7 }} />
                  </div>
                );
              })}
            </div>
            <div style={{ marginTop: 12, padding: "12px 14px", background: T.surface, border: `1px solid ${T.amber}`, borderLeftWidth: 3 }}>
              <div style={{ fontSize: 10, color: T.amber, letterSpacing: "0.14em", marginBottom: 6 }}>VERDICT · agent</div>
              <div style={{ fontFamily: FS, fontSize: 14, color: T.ink, marginBottom: 8 }}>{D.diagnostic.verdict}</div>
              <div style={{ fontSize: 11, color: T.mute }}>→ {D.diagnostic.action}</div>
              <div style={{ marginTop: 10, display: "flex", gap: 6 }}>
                <Btn kind="amber">EJECUTAR ACCIÓN</Btn>
                <Btn>VER ÁRBOL COMPLETO</Btn>
                <Btn>OVERRIDE</Btn>
              </div>
            </div>
          </div>
          <div>
            <SectionLabel text={`FORECAST · ${D.forecast.horizon}`} right={<span style={{ color: T.mute }}>spend S/ {(D.forecast.spend/1000).toFixed(0)}k</span>} />
            <div style={{ marginTop: 12, display: "grid", gridTemplateColumns: "repeat(3,1fr)", border: `1px solid ${T.line}` }}>
              {D.forecast.scenarios.map((s, i) => {
                const isBase = s.name === "Base";
                return (
                  <div key={i} style={{
                    padding: "14px 16px", borderRight: i < 2 ? `1px solid ${T.line}` : "none",
                    background: isBase ? T.surfaceHi : T.surface, position: "relative"
                  }}>
                    {isBase && <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 2, background: T.amber }} />}
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
                      <span style={{ fontFamily: FS, fontWeight: 600, fontSize: 14, color: T.ink }}>{s.name}</span>
                      <span style={{ color: T.muteDim, fontSize: 10 }}>p={s.prob}</span>
                    </div>
                    <Row k="CPL" v={`S/ ${s.cpl.toFixed(2)}`} />
                    <Row k="Leads" v={s.leads.toLocaleString()} />
                    <Row k="MER" v={`${s.mer}x`} />
                    <div style={{ marginTop: 12, height: 4, background: T.line }}>
                      <div style={{ width: `${s.prob*100}%`, height: "100%", background: isBase ? T.amber : T.cyan }} />
                    </div>
                  </div>
                );
              })}
            </div>
            <div style={{ marginTop: 10, padding: "8px 12px", background: T.surface, fontSize: 11, color: T.mute, borderLeft: `2px solid ${T.cyan}` }}>
              <span style={{ color: T.cyan, letterSpacing: "0.1em", fontSize: 10 }}>SENSITIVITY · </span>
              {D.forecast.sensitivityWinner}
            </div>
          </div>
        </div>

        {/* RIGHT — Triangulation + Lock + Anti-pattern + Creative */}
        <div style={{ borderLeft: `1px solid ${T.line}`, padding: "18px 18px", display: "flex", flexDirection: "column", gap: 22 }}>
          <div>
            <SectionLabel text="TRIANGULATION · truth ⌬" right={<span style={{ color: T.green }}>conf {D.triangulation.confidence}</span>} />
            <Triangulation data={D.triangulation} />
          </div>
          <div style={{ border: `1px solid ${T.violet}`, padding: 14, background: "#15121f" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
              <span style={{ color: T.violet, fontSize: 14 }}>⏼</span>
              <span style={{ fontSize: 10, color: T.violet, letterSpacing: "0.16em" }}>OPTIMIZATION LOCK</span>
            </div>
            <div style={{ fontFamily: FS, fontSize: 22, fontWeight: 600, color: T.ink, marginBottom: 4 }}>{D.lock.countdownLabel}</div>
            <div style={{ fontSize: 10, color: T.mute, marginBottom: 10 }}>{D.lock.reason}</div>
            <div style={{ height: 4, background: T.line, marginBottom: 8 }}>
              <div style={{ width: `${D.lock.progress*100}%`, height: "100%", background: T.violet }} />
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: T.muteDim }}>
              <span>locked since · sáb</span>
              <span>unlock · {D.lock.until}</span>
            </div>
          </div>
          <div>
            <SectionLabel text="ANTI-PATTERN · alarms" />
            <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 8 }}>
              {D.flags.map((f, i) => {
                const sev = f.severity === "high" ? T.red : f.severity === "info" ? T.amber : T.green;
                return (
                  <div key={i} style={{ padding: "10px 12px", border: `1px solid ${T.line}`, borderLeft: `3px solid ${sev}`, background: T.surface }}>
                    <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                      <span style={{ fontSize: 9, color: sev, letterSpacing: "0.14em" }}>{f.kind.toUpperCase()}</span>
                      <span style={{ fontSize: 9, color: T.muteDim }}>{f.since}</span>
                    </div>
                    <div style={{ fontSize: 11, color: T.ink, lineHeight: 1.45 }}>{f.text}</div>
                  </div>
                );
              })}
            </div>
          </div>
          <div>
            <SectionLabel text="CREATIVE 4D · matrix" right={<span style={{ color: T.mute }}>{D.creative.activeCount}/{D.creative.targetCount} mes</span>} />
            <CreativeMatrixMini data={D.creative} />
          </div>
        </div>
      </div>

      {/* CFO TRANSLATIONS */}
      <div className="ma-pad" style={{ padding: "16px 24px", background: T.surface, borderBottom: `1px solid ${T.line}` }}>
        <SectionLabel text="CFO LANGUAGE · auto-translate" right={<span style={{ color: T.mute }}>tap CFO MODE to speak board</span>} />
        <div style={{ marginTop: 12, display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12 }}>
          {D.cfoTranslations.map((t, i) => (
            <div key={i} style={{ padding: "12px 14px", border: `1px solid ${T.line}`, background: T.bg }}>
              <div style={{ color: T.muteDim, fontSize: 10, letterSpacing: "0.1em", marginBottom: 6 }}>TACTICAL</div>
              <div style={{ color: T.ink, fontSize: 11, marginBottom: 10 }}>{t.tactical}</div>
              <div style={{ height: 1, background: T.line, marginBottom: 10 }} />
              <div style={{ color: T.amber, fontSize: 10, letterSpacing: "0.1em", marginBottom: 6 }}>CFO</div>
              <div style={{ color: T.ink, fontSize: 11, fontFamily: FS, lineHeight: 1.4 }}>{t.cfo}</div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

// PACING TIMELINE
const PacingTimeline = () => {
  const ticks = [3, 7, 9, 9.2, 9.5, 10, 10.5, 11, 11.2, 11.6];
  const now = 11.7;
  return (
    <div style={{ marginTop: 12, padding: "14px 0", border: `1px solid ${T.line}`, background: T.surface, position: "relative" }}>
      <div style={{ position: "relative", height: 70, margin: "0 18px" }}>
        <div style={{ position: "absolute", top: 35, left: 0, right: 0, height: 1, background: T.line }} />
        {[0, 6, 12, 18, 24].map(h => (
          <div key={h} style={{ position: "absolute", top: 42, left: `${(h/24)*100}%`, transform: "translateX(-50%)", fontSize: 9, color: T.muteDim }}>
            {h.toString().padStart(2,"0")}:00
          </div>
        ))}
        <svg width="100%" height="35" style={{ position: "absolute", top: 0, left: 0 }} preserveAspectRatio="none">
          <defs>
            <linearGradient id="spend" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor={T.cyan} stopOpacity="0.5" />
              <stop offset="100%" stopColor={T.cyan} stopOpacity="0" />
            </linearGradient>
          </defs>
          <polyline
            points={`0,35 ${Array.from({length:48},(_,i) => `${(i/47)*100}%,${35 - (i<23 ? Math.min(28, i*1.4) : 28)}`).join(" ")} 100%,7`}
            fill="none" stroke={T.cyan} strokeWidth="1.5" vectorEffect="non-scaling-stroke"
          />
        </svg>
        {ticks.map((t,i) => (
          <div key={i} style={{ position: "absolute", top: 32, left: `${(t/24)*100}%`, width: 2, height: 8, background: T.amber, transform: "translateX(-50%)" }} />
        ))}
        <div style={{ position: "absolute", top: 0, left: `${(now/24)*100}%`, width: 1, height: 35, background: T.green }} />
        <div style={{ position: "absolute", top: -2, left: `${(now/24)*100}%`, transform: "translateX(-50%)", fontSize: 9, color: T.green, fontWeight: 600 }}>NOW</div>
      </div>
      <div style={{ display: "flex", justifyContent: "space-around", marginTop: 8, paddingTop: 8, borderTop: `1px solid ${T.line}`, fontSize: 10 }}>
        <Stat k="Spend pacing" v="+1.2%" col={T.green} />
        <Stat k="Agent ticks" v="10 hoy" col={T.amber} />
        <Stat k="Anomalies" v="0 P0" col={T.green} />
        <Stat k="Next window" v="00:00" col={T.cyan} />
        <Stat k="Budget left" v="S/ 5,840" col={T.ink} />
      </div>
    </div>
  );
};

const Triangulation = ({ data }) => {
  const W = 320, H = 240;
  const verts = [
    { x: W/2, y: 22 },
    { x: 26, y: H-26 },
    { x: W-26, y: H-26 },
  ];
  const cx = (verts[0].x*0.45 + verts[1].x*0.40 + verts[2].x*0.05 + W/2*0.10);
  const cy = (verts[0].y*0.45 + verts[1].y*0.40 + verts[2].y*0.05 + H/2*0.10);
  return (
    <div style={{ marginTop: 12, padding: 14, border: `1px solid ${T.line}`, background: T.surface }}>
      <div style={{ fontSize: 10, color: T.muteDim, marginBottom: 8 }}>{data.target}</div>
      <svg width={W} height={H} style={{ display: "block" }}>
        <polygon points={verts.map(v => `${v.x},${v.y}`).join(" ")} fill="none" stroke={T.line} strokeWidth="1" />
        {verts.map((v,i) => (
          <line key={i} x1={v.x} y1={v.y} x2={cx} y2={cy}
            stroke={i===2 ? T.muteDim : T.amber}
            strokeWidth={data.lenses[i].weight * 4}
            opacity={0.7} strokeDasharray={i===2 ? "3 3" : "0"} />
        ))}
        {verts.map((v,i) => (
          <g key={i}>
            <circle cx={v.x} cy={v.y} r={5} fill={i===2 ? T.muteDim : T.amber} />
            <text x={v.x} y={i===0 ? v.y - 8 : v.y + 16} textAnchor="middle" fontSize="10"
                  fill={i===2 ? T.muteDim : T.ink} fontFamily={FS} fontWeight={600}>
              {data.lenses[i].name.split(" ")[0]}
            </text>
            <text x={v.x} y={i===0 ? v.y - 22 : v.y + 28} textAnchor="middle" fontSize="9" fill={T.mute}>
              {data.lenses[i].value.toFixed(2)}x
            </text>
          </g>
        ))}
        <circle cx={cx} cy={cy} r={9} fill={T.green} opacity={0.25} />
        <circle cx={cx} cy={cy} r={5} fill={T.green} />
        <text x={cx} y={cy + 22} textAnchor="middle" fontSize="11" fontWeight={700} fill={T.green} fontFamily={FS}>
          consensus {data.consensus}x
        </text>
      </svg>
      <div style={{ marginTop: 8, fontSize: 10, color: T.mute, lineHeight: 1.5 }}>
        Plataforma reporta <span style={{ color: T.red }}>4.92x</span> — descontado por self-attribution.
      </div>
    </div>
  );
};

const CreativeMatrixMini = ({ data }) => (
  <div style={{ marginTop: 12, padding: 12, border: `1px solid ${T.line}`, background: T.surface }}>
    <div style={{ fontFamily: FS, fontSize: 13, color: T.ink, marginBottom: 4 }}>{data.concept}</div>
    <div style={{ fontSize: 10, color: T.mute, marginBottom: 12 }}>{data.angles.length}×{data.formats.length}×{data.hooks.length} = {data.angles.length * data.formats.length * data.hooks.length} permutaciones</div>
    <div style={{ display: "grid", gridTemplateColumns: `60px repeat(${data.formats.length}, 1fr)`, gap: 1, background: T.line }}>
      <div style={{ padding: "6px 4px", background: T.bg }}> </div>
      {data.formats.map(f => (
        <div key={f} style={{ padding: "6px 4px", background: T.bg, fontSize: 9, color: T.mute, textAlign: "center", lineHeight: 1.2 }}>{f}</div>
      ))}
      {data.angles.map((a, ai) => (
        <React.Fragment key={a}>
          <div style={{ padding: "6px 4px", background: T.bg, fontSize: 9, color: T.mute }}>{a}</div>
          {data.formats.map((f, fi) => {
            const seed = (ai*7 + fi*3) % 11;
            const filled = seed > 3;
            const fatigued = filled && seed === 10;
            return (
              <div key={f+a} style={{ padding: "6px 4px", background: T.bg, textAlign: "center", fontSize: 10, color: fatigued ? T.red : filled ? T.green : T.muteDim }}>
                {filled ? (fatigued ? "✕" : "●") : "·"}
              </div>
            );
          })}
        </React.Fragment>
      ))}
    </div>
    <div style={{ marginTop: 10, display: "flex", justifyContent: "space-between", fontSize: 10 }}>
      <span style={{ color: T.green }}>● {data.activeCount} activos</span>
      <span style={{ color: T.red }}>✕ {data.fatigueQueue} fatigados</span>
      <span style={{ color: T.muteDim }}>· vacíos</span>
    </div>
  </div>
);

Object.assign(window, {
  T_THEME: T, T_FM: FM, T_FS: FS,
  TerminalShell, TodayScreen,
  TerminalSectionLabel: SectionLabel, TerminalRow: Row, TerminalBtn: Btn, TerminalPill: Pill, TerminalStat: Stat, TerminalCard: Card, TerminalFooterCell: FooterCell,
});
