/* global React */
// Terminal LatAm — Screens B: Creative, Comply, Report + main App orchestrator

const TB_T = window.T_THEME;
const TB_FM = window.T_FM;
const TB_FS = window.T_FS;
const TB_S = window.TerminalSectionLabel;
const TB_R = window.TerminalRow;
const TB_B = window.TerminalBtn;

// ====================================================================
// CREATIVE — 4D matrix full + brief generator + fatigue
// ====================================================================
const CreativeScreen = () => {
  const D = window.MA_DATA;
  const angles = D.creative.angles;
  const formats = D.creative.formats;
  const hooks = D.creative.hooks;
  const cells = angles.map((a, ai) => formats.map((f, fi) => {
    const seed = (ai*7 + fi*3) % 11;
    const filled = seed > 3;
    const fatigued = filled && seed === 10;
    const rate = filled ? (fatigued ? 0.6 : 0.8 + (seed%3)*0.2) : 0;
    return { angle: a, format: f, filled, fatigued, rate, days: filled ? 4 + seed : 0 };
  }));

  return (
    <div className="ma-pad" style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 22 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
        <div>
          <div style={{ fontSize: 10, color: TB_T.mute, letterSpacing: "0.18em", marginBottom: 6 }}>// CREATIVE · 4D matrix</div>
          <div style={{ fontFamily: TB_FS, fontSize: 26, fontWeight: 600, color: TB_T.ink }}>{D.creative.concept}</div>
          <div style={{ fontSize: 11, color: TB_T.mute, marginTop: 4 }}>
            {angles.length} angles × {formats.length} formats × {hooks.length} hooks · {angles.length*formats.length*hooks.length} permutaciones · velocidad {D.creative.activeCount}/{D.creative.targetCount}/mes
          </div>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <TB_B kind="amber">+ NUEVO BRIEF</TB_B>
          <TB_B kind="violet">DESCARGAR PACKAGE</TB_B>
          <TB_B>VER FATIGADOS</TB_B>
        </div>
      </div>

      {/* MATRIX */}
      <div style={{ border: `1px solid ${TB_T.line}`, background: TB_T.surface, overflow: "auto" }}>
        <div style={{ display: "grid", gridTemplateColumns: `140px repeat(${formats.length}, 1fr)`, gap: 1, background: TB_T.line }}>
          <div style={{ padding: "10px 12px", background: TB_T.surfaceHi, fontSize: 10, color: TB_T.mute, letterSpacing: "0.12em" }}>ANGLE \\ FORMAT</div>
          {formats.map(f => (
            <div key={f} style={{ padding: "10px 12px", background: TB_T.surfaceHi, fontSize: 10, color: TB_T.mute, letterSpacing: "0.12em", textAlign: "center" }}>{f.toUpperCase()}</div>
          ))}
          {cells.map((row, ai) => (
            <React.Fragment key={ai}>
              <div style={{ padding: "14px 12px", background: TB_T.bg, fontSize: 11, color: TB_T.ink, fontFamily: TB_FS, fontWeight: 500 }}>{angles[ai]}</div>
              {row.map((c, fi) => (
                <div key={fi} style={{
                  padding: "14px 10px", background: TB_T.bg, position: "relative",
                  borderLeft: c.fatigued ? `2px solid ${TB_T.red}` : c.filled ? `2px solid ${TB_T.green}` : `2px solid transparent`,
                  cursor: "pointer", minHeight: 70,
                }}>
                  {c.filled ? (
                    <>
                      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                        <span style={{ color: c.fatigued ? TB_T.red : TB_T.green, fontSize: 11, fontWeight: 600 }}>{c.fatigued ? "FATIGUED" : "ACTIVE"}</span>
                        <span style={{ color: TB_T.muteDim, fontSize: 9 }}>{c.days}d</span>
                      </div>
                      <div style={{ height: 4, background: TB_T.line, marginBottom: 6 }}>
                        <div style={{ width: `${c.rate*100}%`, height: "100%", background: c.fatigued ? TB_T.red : TB_T.amber, opacity: 0.85 }} />
                      </div>
                      <div style={{ fontSize: 10, color: TB_T.mute }}>HR {c.rate.toFixed(2)}</div>
                    </>
                  ) : (
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%", color: TB_T.muteDim, fontSize: 14 }}>+</div>
                  )}
                </div>
              ))}
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* HOOKS + FATIGUE QUEUE */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div style={{ border: `1px solid ${TB_T.line}`, background: TB_T.surface, padding: "16px 18px" }}>
          <TB_S text="HOOK BANK · ranked" right={<span style={{ color: TB_T.mute }}>thumbstop · last 14d</span>} />
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 8 }}>
            {hooks.map((h,i) => {
              const ts = [0.42, 0.31, 0.39, 0.46, 0.28][i];
              const top = ts > 0.40;
              return (
                <div key={h} style={{ display: "grid", gridTemplateColumns: "16px 1fr 60px 80px", padding: "8px 0", alignItems: "center", borderBottom: i<hooks.length-1?`1px solid ${TB_T.line}`:"none", fontSize: 11, gap: 12 }}>
                  <span style={{ color: TB_T.muteDim }}>{(i+1).toString().padStart(2,"0")}</span>
                  <span style={{ color: TB_T.ink }}>{h}</span>
                  <span style={{ color: top ? TB_T.green : TB_T.amber, textAlign: "right" }}>{ts}s</span>
                  <span style={{ color: top ? TB_T.green : TB_T.muteDim, textAlign: "right", fontSize: 10 }}>{top ? "★ winner" : "test more"}</span>
                </div>
              );
            })}
          </div>
        </div>
        <div style={{ border: `1px solid ${TB_T.red}`, borderLeftWidth: 3, background: TB_T.surface, padding: "16px 18px" }}>
          <TB_S text="FATIGUE QUEUE · auto-pause" right={<span style={{ color: TB_T.red }}>{D.creative.fatigueQueue} ads</span>} />
          <div style={{ marginTop: 12, fontSize: 11, color: TB_T.mute, lineHeight: 1.5 }}>
            Trigger · frecuencia &gt; 4 OR hook rate -25% vs 7d OR CTR -30% vs intro.<br/>
            Acción · pause + briefing automático del angle/format ganador con variación de hook.
          </div>
          <div style={{ marginTop: 14 }}>
            {[
              { n: "Padres·UGC·Hook-A", f: 4.2, hr: -38, days: 21 },
              { n: "Postulantes·VO·B", f: 3.6, hr: -29, days: 18 },
              { n: "Becas·Carousel·POV", f: 2.9, hr: -26, days: 14 },
            ].map((x,i) => (
              <div key={i} style={{ padding: "10px 0", borderBottom: i<2?`1px dashed ${TB_T.line}`:"none", display: "grid", gridTemplateColumns: "1fr 50px 50px 50px", gap: 8, fontSize: 11 }}>
                <span style={{ color: TB_T.ink }}>{x.n}</span>
                <span style={{ color: TB_T.red, textAlign: "right" }}>f {x.f}</span>
                <span style={{ color: TB_T.red, textAlign: "right" }}>{x.hr}%</span>
                <span style={{ color: TB_T.muteDim, textAlign: "right" }}>{x.days}d</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* AGENT BRIEF */}
      <div style={{ border: `1px solid ${TB_T.violet}`, borderLeftWidth: 3, padding: "16px 20px", background: TB_T.surface }}>
        <div style={{ fontSize: 10, color: TB_T.violet, letterSpacing: "0.16em", marginBottom: 8 }}>AGENT · auto-brief generado</div>
        <div style={{ fontFamily: TB_FS, fontSize: 16, color: TB_T.ink, marginBottom: 12 }}>8 nuevos creativos sugeridos · vacíos en matriz · ETA producción 5-7d</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 10 }}>
          {[
            { a: "Reingreso", f: "UGC selfie", h: "Pattern interrupt", w: "vacío 12 sem" },
            { a: "Reingreso", f: "VO + B-roll", h: "Testimonio", w: "vacío 12 sem" },
            { a: "Becas", f: "Demo campus", h: "POV", w: "vacío 8 sem" },
            { a: "Padres", f: "Static carousel", h: "PAS", w: "ganador en otro angle" },
            { a: "Postulantes", f: "Demo campus", h: "Antes/después", w: "format probado" },
            { a: "Becas", f: "UGC selfie", h: "Pattern interrupt", w: "winner cross-pollination" },
            { a: "Padres", f: "Demo campus", h: "POV", w: "vacío 6 sem" },
            { a: "Reingreso", f: "Static carousel", h: "PAS", w: "low-cost test" },
          ].map((b,i) => (
            <div key={i} style={{ padding: "10px 12px", border: `1px solid ${TB_T.line}`, background: TB_T.bg }}>
              <div style={{ fontSize: 10, color: TB_T.muteDim, letterSpacing: "0.12em", marginBottom: 6 }}>BRIEF #{(i+1).toString().padStart(2,"0")}</div>
              <div style={{ color: TB_T.ink, fontSize: 11, fontFamily: TB_FS, marginBottom: 4 }}>{b.a} · {b.f}</div>
              <div style={{ color: TB_T.amber, fontSize: 10 }}>{b.h}</div>
              <div style={{ color: TB_T.mute, fontSize: 10, marginTop: 6 }}>{b.w}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ====================================================================
// COMPLY — LatAm regulatory + privacy + SAC
// ====================================================================
const ComplyScreen = () => {
  const items = [
    { c: "Perú", flag: "🇵🇪", item: "Ley 29733 · ANPD", state: "ok",   note: "registrado · update Q4 2025 · DPO asignado", since: "vigente" },
    { c: "Perú", flag: "🇵🇪", item: "Indecopi · publicidad",  state: "ok",   note: "sustento de claims archivado", since: "vigente" },
    { c: "Brasil", flag: "🇧🇷", item: "LGPD · ANPD",        state: "ok",   note: "consent v2 · PIA elaborado", since: "vigente" },
    { c: "Argentina", flag: "🇦🇷", item: "Ley 25326 · AAIP", state: "warn", note: "actualizar política privacy ene-2026", since: "review pendiente" },
    { c: "Chile", flag: "🇨🇱", item: "Ley 19628",            state: "ok",   note: "transferencia internacional documentada", since: "vigente" },
    { c: "México", flag: "🇲🇽", item: "LFPDPPP · INAI",       state: "ok",   note: "aviso de privacidad simplificado + integral", since: "vigente" },
  ];
  const platform = [
    { p: "Meta · Special Ad Cat",  state: "info", note: "Vivienda Lima → housing · LAL bloqueado · geo radius 15mi máx" },
    { p: "Meta · Limited Data Use",state: "ok",   note: "applied for CA users · enabled" },
    { p: "Google · LDU mode",       state: "ok",   note: "TCF v2.2 string passing" },
    { p: "TikTok · Restricted",      state: "ok",   note: "no menores 13, no betting, no medical claims" },
    { p: "iOS · ATT",                state: "ok",   note: "AEM priorities set · 8 events ranked" },
    { p: "Consent Mode v2",          state: "ok",   note: "ad_storage, ad_user_data, ad_personalization granted/denied tracked" },
    { p: "GARM brand safety",        state: "ok",   note: "v3 exclusion lists synced 24h" },
  ];
  return (
    <div className="ma-pad" style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 22 }}>
      <div>
        <div style={{ fontSize: 10, color: TB_T.mute, letterSpacing: "0.18em", marginBottom: 6 }}>// COMPLY · LatAm regulatorio</div>
        <div style={{ fontFamily: TB_FS, fontSize: 26, fontWeight: 600, color: TB_T.ink }}>Tablero de cumplimiento · 6 países · 7 plataformas</div>
        <div style={{ fontSize: 11, color: TB_T.mute, marginTop: 4 }}>Última auditoría · hoy 06:00 · 1 warn pendiente · resto OK</div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div style={{ border: `1px solid ${TB_T.line}`, background: TB_T.surface }}>
          <div style={{ padding: "10px 14px", borderBottom: `1px solid ${TB_T.line}`, background: TB_T.surfaceHi, fontFamily: TB_FS, fontSize: 13, fontWeight: 600 }}>Privacidad por jurisdicción</div>
          {items.map((x,i) => {
            const col = x.state === "ok" ? TB_T.green : x.state === "warn" ? TB_T.amber : TB_T.red;
            return (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "32px 1fr 80px", padding: "12px 14px", borderBottom: i<items.length-1?`1px solid ${TB_T.line}`:"none", alignItems: "flex-start", gap: 10 }}>
                <span style={{ fontSize: 18 }}>{x.flag}</span>
                <div>
                  <div style={{ color: TB_T.ink, fontSize: 11, marginBottom: 3 }}><b>{x.c}</b> · {x.item}</div>
                  <div style={{ color: TB_T.muteDim, fontSize: 10 }}>{x.note}</div>
                </div>
                <span style={{ color: col, fontSize: 10, letterSpacing: "0.12em", textAlign: "right" }}>{x.state.toUpperCase()}<br/><span style={{ color: TB_T.muteDim, letterSpacing: "0.06em" }}>{x.since}</span></span>
              </div>
            );
          })}
        </div>
        <div style={{ border: `1px solid ${TB_T.line}`, background: TB_T.surface }}>
          <div style={{ padding: "10px 14px", borderBottom: `1px solid ${TB_T.line}`, background: TB_T.surfaceHi, fontFamily: TB_FS, fontSize: 13, fontWeight: 600 }}>Plataforma · políticas + privacidad</div>
          {platform.map((x,i) => {
            const col = x.state === "ok" ? TB_T.green : x.state === "warn" ? TB_T.amber : x.state === "info" ? TB_T.cyan : TB_T.red;
            return (
              <div key={i} style={{ padding: "12px 14px", borderBottom: i<platform.length-1?`1px solid ${TB_T.line}`:"none" }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                  <span style={{ color: TB_T.ink, fontSize: 11, fontWeight: 500 }}>{x.p}</span>
                  <span style={{ color: col, fontSize: 10, letterSpacing: "0.14em" }}>{x.state.toUpperCase()}</span>
                </div>
                <div style={{ color: TB_T.mute, fontSize: 10 }}>{x.note}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* AGENT WATCHER */}
      <div style={{ border: `1px solid ${TB_T.cyan}`, borderLeftWidth: 3, padding: "14px 18px", background: TB_T.surface }}>
        <div style={{ fontSize: 10, color: TB_T.cyan, letterSpacing: "0.16em", marginBottom: 8 }}>AGENT · radar regulatorio</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          {[
            { d: "Hace 2d", t: "Meta cambió targeting de housing en LATAM · ya aplicado a Vivienda Lima", c: TB_T.green },
            { d: "Hace 5d", t: "ANPD Perú multó a banco por consent · revisar checkboxes en LP UAR", c: TB_T.amber },
            { d: "Hoy 06:00", t: "iOS 18.4 endurece SKAdNetwork · AEM priority de UAR re-rankeada", c: TB_T.cyan },
          ].map((n,i) => (
            <div key={i} style={{ padding: "10px 12px", border: `1px solid ${TB_T.line}`, background: TB_T.bg, borderLeft: `2px solid ${n.c}` }}>
              <div style={{ fontSize: 10, color: TB_T.muteDim, marginBottom: 4 }}>{n.d}</div>
              <div style={{ fontSize: 11, color: TB_T.ink, lineHeight: 1.4 }}>{n.t}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ====================================================================
// REPORT — CFO-language report builder
// ====================================================================
const ReportScreen = ({ cfoMode }) => {
  const D = window.MA_DATA;
  return (
    <div className="ma-pad" style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 22 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
        <div>
          <div style={{ fontSize: 10, color: TB_T.mute, letterSpacing: "0.18em", marginBottom: 6 }}>// REPORT · CFO board · Q2 → Q3 brief</div>
          <div style={{ fontFamily: TB_FS, fontSize: 26, fontWeight: 600, color: TB_T.ink }}>Hablar el idioma del CFO</div>
          <div style={{ fontSize: 11, color: TB_T.mute, marginTop: 4 }}>Auto-traducido · MER real · CAC payback · LTV/CAC · contribution margin · evita platform-reported ROAS</div>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <TB_B kind="amber">EXPORT PDF</TB_B>
          <TB_B kind="violet">EXPORT PPTX</TB_B>
          <TB_B>SHARE BOARD LINK</TB_B>
        </div>
      </div>

      {/* HEADLINE */}
      <div style={{ border: `1px solid ${TB_T.amber}`, borderLeftWidth: 3, padding: "20px 24px", background: TB_T.surface }}>
        <div style={{ fontSize: 10, color: TB_T.amber, letterSpacing: "0.16em", marginBottom: 8 }}>HEADLINE · 1 frase para el board</div>
        <div style={{ fontFamily: TB_FS, fontSize: 22, fontWeight: 600, color: TB_T.ink, lineHeight: 1.35 }}>
          En Q2, S/ 423k de spend generaron <span style={{ color: TB_T.green }}>S/ 1.18M en revenue atribuido</span> (MER real 2.78x, CAC payback 6.8 meses).<br/>
          Q3 propone <span style={{ color: TB_T.amber }}>S/ 1.42M de spend</span> con leads esperados <span style={{ color: TB_T.green }}>+27%</span> sobre Q2 a CAC similar.
        </div>
      </div>

      {/* KPI GRID */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12 }}>
        {[
          { k: "MER real", v: "2.78x", sub: "consensus · platform 4.92x descontado", col: TB_T.green },
          { k: "CAC payback", v: "6.8 mo", sub: "vs 9.4 mo Q1 · −2.6 mo", col: TB_T.green },
          { k: "LTV / CAC", v: "4.1", sub: "target ≥3.0 · OK", col: TB_T.green },
          { k: "Contribution margin", v: "38.4%", sub: "neto de spend · pre-overhead", col: TB_T.amber },
          { k: "Spend / leads", v: "S/ 73.50", sub: "blended CPL · −21.9% vs Q1", col: TB_T.ink },
          { k: "Velocity creativa", v: "38/mo", sub: "target 60 · ramping", col: TB_T.amber },
          { k: "Forecast Q3 leads", v: "18.1k", sub: "p=0.55 · Base scenario", col: TB_T.violet },
          { k: "Forecast Q3 MER", v: "2.7x", sub: "estable · sin saturación", col: TB_T.violet },
        ].map((m,i) => (
          <div key={i} style={{ padding: "14px 16px", border: `1px solid ${TB_T.line}`, background: TB_T.surface }}>
            <div style={{ fontSize: 10, color: TB_T.muteDim, letterSpacing: "0.1em", marginBottom: 8 }}>{m.k.toUpperCase()}</div>
            <div style={{ fontFamily: TB_FS, fontSize: 22, fontWeight: 600, color: m.col }}>{m.v}</div>
            <div style={{ fontSize: 10, color: TB_T.mute, marginTop: 6 }}>{m.sub}</div>
          </div>
        ))}
      </div>

      {/* WATERFALL Q2 → Q3 */}
      <div style={{ border: `1px solid ${TB_T.line}`, background: TB_T.surface, padding: "16px 18px" }}>
        <TB_S text="WATERFALL · qué cambió Q1 → Q2 (intervenciones del agente)" />
        <div style={{ marginTop: 16, display: "grid", gridTemplateColumns: "180px 1fr 100px", gap: 12 }}>
          {[
            { l: "CPL Q1 baseline",        v: 94.10, abs: true, col: TB_T.muteDim },
            { l: "Consolidación 47→11",    v: -8.40, col: TB_T.green },
            { l: "Refresh creativo (38)",  v: -6.10, col: TB_T.green },
            { l: "EMQ 6.1 → 8.4",          v: -3.20, col: TB_T.green },
            { l: "Reasignación placement", v: -2.40, col: TB_T.green },
            { l: "Estacionalidad",         v: -0.50, col: TB_T.cyan },
            { l: "CPL Q2 actual",          v: 73.50, abs: true, col: TB_T.amber },
          ].map((row,i) => {
            const max = 95;
            const w = (Math.abs(row.v) / max) * 100;
            return (
              <React.Fragment key={i}>
                <div style={{ color: TB_T.ink, fontSize: 11, paddingTop: 4 }}>{row.l}</div>
                <div style={{ position: "relative", height: 22, background: TB_T.bg }}>
                  {row.abs ? (
                    <div style={{ position: "absolute", inset: 0, width: `${(row.v/max)*100}%`, background: row.col, opacity: 0.85 }} />
                  ) : (
                    <div style={{ position: "absolute", left: row.v < 0 ? `${(73.5/max)*100}%` : `${(73.5/max)*100}%`, top: 0, bottom: 0, width: `${w}%`, background: row.col, opacity: 0.85, transform: row.v < 0 ? "translateX(-100%)" : "none" }} />
                  )}
                </div>
                <div style={{ color: row.col, fontSize: 11, textAlign: "right", paddingTop: 4, fontFamily: TB_FS, fontWeight: 500 }}>
                  {row.abs ? `S/ ${row.v.toFixed(2)}` : `${row.v > 0 ? "+" : ""}${row.v.toFixed(2)}`}
                </div>
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* BOARD NARRATIVE */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
        {[
          { h: "Lo que funcionó", c: TB_T.green, items: [
            "Consolidación de ad sets · ML aprende mejor, ahorró S/ 8.4k/mes en cuenta SF",
            "Velocity creativa 4.2x vs Q1 · CTR +14% blended",
            "Tracking server-side · señal +18%, ROAS subestimado corregido",
            "Pacing diario automático · 0 anomalías P0 last 30d",
          ]},
          { h: "Lo que duele", c: TB_T.amber, items: [
            "MMM stale 12d · próxima recalibración vie 10 May (auto-trigger)",
            "Holdout nacional aún no implementado · pendiente de fix LP",
            "Pixel EMQ 6.1 en SF · perdiendo ~12% señal hasta resolución",
            "1 cuenta en learning phase · se libera vie",
          ]},
          { h: "Próxima decisión", c: TB_T.violet, items: [
            "Aprobar S/ 1.42M Q3 (Base) o S/ 1.78M (Agresivo, p=0.25)",
            "Lock Q3 hasta 31 Jul · cambios solo con justificación &gt; S/ 5k",
            "Iniciar geo-lift en UAR · dato causal antes de Andromeda 2026",
            "Compromiso: 60 creativos/mes · contratar 1 editor freelance",
          ]},
        ].map((col,i) => (
          <div key={i} style={{ border: `1px solid ${col.c}`, borderLeftWidth: 3, padding: "16px 18px", background: TB_T.surface }}>
            <div style={{ color: col.c, fontSize: 10, letterSpacing: "0.14em", marginBottom: 12 }}>{col.h.toUpperCase()}</div>
            <ul style={{ padding: 0, listStyle: "none", margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
              {col.items.map((it,j) => (
                <li key={j} style={{ fontSize: 11, color: TB_T.ink, lineHeight: 1.5, paddingLeft: 14, position: "relative" }}>
                  <span style={{ position: "absolute", left: 0, color: col.c }}>→</span>{it}
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>

      {/* SIGN OFF */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 16px", border: `1px solid ${TB_T.line}`, background: TB_T.surface, fontSize: 10, color: TB_T.muteDim }}>
        <span>Generado por agente v0.4 · firmado · Pablo Ríos · 7 May 2026 11:42 GMT-5</span>
        <span>diff hash · 8c2f1ab · auditable · revertible</span>
      </div>
    </div>
  );
};

// ====================================================================
// MAIN APP
// ====================================================================
const TerminalApp = () => {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "density": "compact",
    "cfoMode": false,
    "singleClient": true,
    "showOnboarding": false,
    "accent": "#ffb84d"
  }/*EDITMODE-END*/;
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [screen, setScreen] = React.useState("today");

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === "F1") { e.preventDefault(); setScreen("today"); }
      else if (e.key === "F2") { e.preventDefault(); setScreen("optimize"); }
      else if (e.key === "F3") { e.preventDefault(); setScreen("plan"); }
      else if (e.key === "F4") { e.preventDefault(); setScreen("diagnose"); }
      else if (e.key === "F5") { e.preventDefault(); setScreen("measure"); }
      else if (e.key === "F6") { e.preventDefault(); setScreen("creative"); }
      else if (e.key === "F7") { e.preventDefault(); setScreen("comply"); }
      else if (e.key === "F8") { e.preventDefault(); setScreen("report"); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const screens = {
    today: <window.TodayScreen cfoMode={t.cfoMode} />,
    optimize: <window.OptimizeScreen />,
    plan: <window.PlanScreen />,
    diagnose: <window.DiagnoseScreen />,
    measure: <window.MeasureScreen />,
    creative: <window.CreativeScreen />,
    comply: <window.ComplyScreen />,
    report: <window.ReportScreen cfoMode={t.cfoMode} />,
    connect: <window.ConnectScreen />,
    audit: <window.AuditScreen />,
    settings: <window.SettingsScreen />,
  };
  const labels = { today: "01 Today", optimize: "02 Optimize", plan: "03 Plan", diagnose: "04 Diagnose", measure: "05 Measure", creative: "06 Creative", comply: "07 Comply", report: "08 Report", connect: "Connect", audit: "Audit", settings: "Settings" };

  const { TweaksPanel, TweakSection, TweakRadio, TweakToggle } = window;

  return (
    <>
      {t.showOnboarding && window.OnboardingFlow && <window.OnboardingFlow onComplete={() => setTweak("showOnboarding", false)} />}
      <window.TerminalShell
        activeScreen={screen}
        onNav={setScreen}
        cfoMode={t.cfoMode}
        setCfoMode={(v) => setTweak("cfoMode", v)}
        density={t.density}
        singleClient={t.singleClient}
      >
        <div data-screen-label={labels[screen]}>{screens[screen]}</div>
      </window.TerminalShell>

      <TweaksPanel title="Tweaks">
        <TweakSection title="Densidad" subtitle="Compact = bloomberg · Cozy = más aire">
          <TweakRadio
            value={t.density}
            options={[{ value: "compact", label: "Compact" }, { value: "cozy", label: "Cozy" }]}
            onChange={(v) => setTweak("density", v)}
          />
        </TweakSection>
        <TweakSection title="CFO Mode" subtitle="Traduce métricas tácticas a lenguaje de board">
          <TweakToggle value={t.cfoMode} onChange={(v) => setTweak("cfoMode", v)} label={t.cfoMode ? "ON" : "OFF"} />
        </TweakSection>
        <TweakSection title="Modo cuenta" subtitle="Single-client (1 cliente compra) o Multi-client (planner senior)">
          <TweakRadio
            value={t.singleClient ? "single" : "multi"}
            options={[{ value: "single", label: "Single" }, { value: "multi", label: "Multi" }]}
            onChange={(v) => setTweak("singleClient", v === "single")}
          />
        </TweakSection>
        <TweakSection title="Onboarding bootstrap" subtitle="Re-ejecuta el flow de Welcome → OAuth → Tracking → CRM → First Audit (demo)">
          <TweakToggle value={t.showOnboarding} onChange={(v) => setTweak("showOnboarding", v)} label={t.showOnboarding ? "ACTIVO" : "OFF"} />
        </TweakSection>
      </TweaksPanel>
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<TerminalApp />);
