/* global React */
// Terminal LatAm — Screens A: Audit, Plan, Diagnose, Measure
// Uses globals from terminal-core: T_THEME, T_FM, T_FS, TerminalSectionLabel, TerminalRow, TerminalBtn, TerminalPill, TerminalStat, TerminalCard

const TA_T = window.T_THEME;
const TA_FM = window.T_FM;
const TA_FS = window.T_FS;
const TA_S = window.TerminalSectionLabel;
const TA_R = window.TerminalRow;
const TA_B = window.TerminalBtn;
const TA_P = window.TerminalPill;
const TA_C = window.TerminalCard;

// ====================================================================
// AUDIT — pre-engagement health check (Phase 1 of skill)
// ====================================================================
const AuditScreen = () => {
  const D = window.MA_DATA;
  const [account, setAccount] = React.useState(D.portfolio[1]);
  const checks = [
    { area: "Tracking", checks: [
      { k: "CAPI server-side", s: "ok",   v: "EMQ 8.7", note: "deduplicated by event_id" },
      { k: "Enhanced Conversions", s: "ok", v: "active", note: "linked to CRM Hubspot" },
      { k: "Pixel quality",  s: "warn", v: "EMQ 6.1", note: "fbp cookie missing on 18% events" },
      { k: "Cross-domain UTMs", s: "ok", v: "consistent", note: "channel/source/campaign/content" },
      { k: "Lead validation in-CRM", s: "ok", v: "MQL → SAL → SQL → Won", note: "back-fed to ad platform" },
    ]},
    { area: "Account hygiene", checks: [
      { k: "Ad set fragmentation", s: "fail", v: "47 ad sets · S/ 2.1 avg/day", note: "ML cannot learn under S/ 5/day · CONSOLIDATE" },
      { k: "CBO usage", s: "warn", v: "31% of spend", note: "should be ≥70% for portfolio bid mgmt" },
      { k: "Audience overlap", s: "fail", v: "63% on top 3 ad sets", note: "internal auction, paying twice" },
      { k: "Naming convention", s: "ok", v: "v2 schema applied", note: "{obj}_{aud}_{geo}_{angle}_{format}_{date}" },
      { k: "Learning phase status", s: "warn", v: "8/47 in learning", note: "consolidation will fix" },
    ]},
    { area: "Compliance · LatAm", checks: [
      { k: "Consent Mode v2", s: "ok", v: "active 3/3", note: "Ley 29733 PE · LGPD BR · Ley 25326 AR" },
      { k: "Special Ad Category", s: "info", v: "housing flagged", note: "Vivienda Lima · LAL blocked · geo radius 15mi max" },
      { k: "iOS ATT", s: "ok", v: "AEM enabled", note: "Aggregated Event Measurement priorities set" },
      { k: "Brand safety", s: "ok", v: "GARM v3", note: "exclusion lists synced last 24h" },
    ]},
    { area: "Measurement maturity", checks: [
      { k: "MMM cadence", s: "warn", v: "12d since rebuild", note: "target ≤ 14d · OK but stale" },
      { k: "Geo-lift active", s: "ok", v: "1 of 3 accounts", note: "Vivienda Lima · day 9/14" },
      { k: "Holdout cell", s: "fail", v: "none", note: "5% national holdout would unlock causal MMM priors" },
      { k: "Survey instrument", s: "ok", v: "post-purchase + brand", note: "weekly cohort, n=200" },
    ]},
  ];
  const stats = checks.flatMap(g => g.checks);
  const okC = stats.filter(c => c.s === "ok").length;
  const warnC = stats.filter(c => c.s === "warn").length;
  const failC = stats.filter(c => c.s === "fail").length;
  const score = Math.round((okC * 100 + warnC * 50) / stats.length);

  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: TA_T.mute, letterSpacing: "0.18em", marginBottom: 6 }}>// AUDIT · pre-flight</div>
          <div style={{ fontFamily: TA_FS, fontSize: 26, fontWeight: 600, color: TA_T.ink }}>Foundation health · <span style={{ color: TA_T.amber }}>{account.name}</span></div>
          <div style={{ fontSize: 11, color: TA_T.mute, marginTop: 4 }}>{account.sector} · {stats.length} checks · auditado hoy 06:00 · build 8c2f1ab</div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          {D.portfolio.map(p => (
            <button key={p.id} onClick={() => setAccount(p)} style={{
              padding: "8px 14px", border: `1px solid ${p.id === account.id ? TA_T.amber : TA_T.line}`,
              background: p.id === account.id ? TA_T.surfaceHi : "transparent",
              color: p.id === account.id ? TA_T.amber : TA_T.mute,
              fontFamily: TA_FM, fontSize: 11, cursor: "pointer", letterSpacing: "0.06em",
            }}>{p.id.toUpperCase()}</button>
          ))}
        </div>
      </div>

      {/* SCORE BAR */}
      <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", border: `1px solid ${TA_T.line}` }}>
        <div style={{ padding: "20px 22px", borderRight: `1px solid ${TA_T.line}`, background: TA_T.surfaceHi }}>
          <div style={{ fontSize: 10, color: TA_T.mute, letterSpacing: "0.16em", marginBottom: 12 }}>FOUNDATION SCORE</div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
            <span style={{ fontFamily: TA_FS, fontSize: 56, fontWeight: 600, color: score >= 80 ? TA_T.green : score >= 60 ? TA_T.amber : TA_T.red, lineHeight: 1 }}>{score}</span>
            <span style={{ color: TA_T.muteDim, fontSize: 13 }}>/ 100</span>
          </div>
          <div style={{ marginTop: 10, fontSize: 11, color: TA_T.mute }}>{score >= 80 ? "Listo para escalar" : score >= 60 ? "Arreglar antes de subir budget" : "No escalar — corregir base"}</div>
        </div>
        <div style={{ padding: "20px 22px", display: "flex", alignItems: "center", gap: 24 }}>
          <div style={{ flex: 1 }}>
            <div style={{ display: "flex", height: 28, border: `1px solid ${TA_T.line}` }}>
              <div style={{ flex: okC, background: TA_T.green, opacity: 0.85 }} />
              <div style={{ flex: warnC, background: TA_T.amber, opacity: 0.85 }} />
              <div style={{ flex: failC, background: TA_T.red, opacity: 0.85 }} />
            </div>
            <div style={{ display: "flex", marginTop: 8, gap: 18, fontSize: 11 }}>
              <span><span style={{ color: TA_T.green }}>● </span><span style={{ color: TA_T.muteDim }}>OK </span><b style={{ color: TA_T.ink }}>{okC}</b></span>
              <span><span style={{ color: TA_T.amber }}>● </span><span style={{ color: TA_T.muteDim }}>warn </span><b style={{ color: TA_T.ink }}>{warnC}</b></span>
              <span><span style={{ color: TA_T.red }}>● </span><span style={{ color: TA_T.muteDim }}>fail </span><b style={{ color: TA_T.ink }}>{failC}</b></span>
              <span style={{ marginLeft: "auto", color: TA_T.muteDim }}>último audit · hoy 06:00</span>
            </div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <TA_B kind="amber">RE-RUN AUDIT</TA_B>
            <TA_B>EXPORT PDF</TA_B>
          </div>
        </div>
      </div>

      {/* CHECK GROUPS */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        {checks.map((g, gi) => (
          <div key={gi} style={{ border: `1px solid ${TA_T.line}`, background: TA_T.surface }}>
            <div style={{ padding: "10px 14px", borderBottom: `1px solid ${TA_T.line}`, display: "flex", justifyContent: "space-between", background: TA_T.surfaceHi }}>
              <span style={{ fontFamily: TA_FS, fontSize: 13, fontWeight: 600, color: TA_T.ink }}>{g.area}</span>
              <span style={{ color: TA_T.muteDim, fontSize: 10 }}>{g.checks.length} checks</span>
            </div>
            {g.checks.map((c, ci) => {
              const col = c.s === "ok" ? TA_T.green : c.s === "warn" ? TA_T.amber : c.s === "fail" ? TA_T.red : TA_T.cyan;
              const sym = c.s === "ok" ? "✓" : c.s === "warn" ? "!" : c.s === "fail" ? "✕" : "i";
              return (
                <div key={ci} style={{
                  display: "grid", gridTemplateColumns: "26px 1fr 110px",
                  padding: "10px 14px", borderBottom: ci < g.checks.length-1 ? `1px solid ${TA_T.line}` : "none",
                  alignItems: "flex-start", gap: 12,
                }}>
                  <span style={{ color: col, fontWeight: 700, fontSize: 14 }}>{sym}</span>
                  <div>
                    <div style={{ color: TA_T.ink, fontSize: 11 }}>{c.k}</div>
                    <div style={{ color: TA_T.muteDim, fontSize: 10, marginTop: 3 }}>{c.note}</div>
                  </div>
                  <div style={{ textAlign: "right", color: col, fontSize: 11 }}>{c.v}</div>
                </div>
              );
            })}
          </div>
        ))}
      </div>

      {/* AGENT PRESCRIPTION */}
      <div style={{ border: `1px solid ${TA_T.amber}`, borderLeftWidth: 3, padding: "16px 20px", background: TA_T.surface }}>
        <div style={{ fontSize: 10, color: TA_T.amber, letterSpacing: "0.16em", marginBottom: 8 }}>AGENT · PRESCRIPCIÓN PRIORIZADA</div>
        <div style={{ fontFamily: TA_FS, fontSize: 16, color: TA_T.ink, marginBottom: 12 }}>3 acciones P0 antes de tocar budget · ETA 5 días hábiles</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          {[
            { p: "P0", t: "Consolidar 47 → 6 ad sets", w: "ML aprende mejor · -S/ 8.4k/mes desperdicio · MER +0.4x esperado", eta: "Día 1-2" },
            { p: "P0", t: "Implementar holdout 5% nacional", w: "Unlock priors causales para próximo MMM · 2 semanas hold", eta: "Día 1" },
            { p: "P0", t: "Fix Pixel EMQ 6.1 → 8.5+", w: "AEM perdiendo 18% señal · ROAS subestimado ~12%", eta: "Día 3-5" },
          ].map((a,i) => (
            <div key={i} style={{ padding: "12px 14px", border: `1px solid ${TA_T.line}`, background: TA_T.bg }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                <span style={{ color: TA_T.red, fontSize: 9, padding: "2px 6px", border: `1px solid ${TA_T.red}`, letterSpacing: "0.12em" }}>{a.p}</span>
                <span style={{ color: TA_T.muteDim, fontSize: 10 }}>{a.eta}</span>
              </div>
              <div style={{ fontFamily: TA_FS, fontSize: 13, color: TA_T.ink, marginBottom: 6 }}>{a.t}</div>
              <div style={{ fontSize: 10, color: TA_T.mute }}>{a.w}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ====================================================================
// PLAN — budget + forecast + sensitivity
// ====================================================================
const PlanScreen = () => {
  const D = window.MA_DATA;
  const [budget, setBudget] = React.useState(1420000);
  const [scenario, setScenario] = React.useState("Base");
  const sc = D.forecast.scenarios.find(s => s.name === scenario);
  const factor = budget / 1420000;
  const projLeads = Math.round(sc.leads * Math.pow(factor, 0.92)); // sub-linear
  const projCpl = sc.cpl * Math.pow(factor, 0.08);

  const channels = [
    { id: "Meta",      pct: 0.46, target: 0.42, mer: 2.94, ceiling: "S/ 720k/mo", color: TA_T.cyan },
    { id: "Google",    pct: 0.28, target: 0.30, mer: 3.18, ceiling: "S/ 540k/mo", color: TA_T.amber },
    { id: "TikTok",    pct: 0.14, target: 0.18, mer: 2.41, ceiling: "S/ 280k/mo", color: TA_T.violet },
    { id: "LinkedIn",  pct: 0.08, target: 0.07, mer: 1.92, ceiling: "S/ 140k/mo", color: TA_T.green },
    { id: "Display/PR",pct: 0.04, target: 0.03, mer: 1.21, ceiling: "branding",   color: TA_T.pink },
  ];

  return (
    <div className="ma-pad" style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 22 }}>
      <div>
        <div style={{ fontSize: 10, color: TA_T.mute, letterSpacing: "0.18em", marginBottom: 6 }}>// PLAN · Q3 2026 · 92 días</div>
        <div style={{ fontFamily: TA_FS, fontSize: 26, fontWeight: 600, color: TA_T.ink }}>Decidir presupuesto con confianza</div>
        <div style={{ fontSize: 11, color: TA_T.mute, marginTop: 4 }}>3 escenarios · sensitivity en vivo · MMM v4 priors · última recalibración hace 12d</div>
      </div>

      {/* BUDGET DIAL */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div style={{ border: `1px solid ${TA_T.line}`, background: TA_T.surface, padding: "20px 22px" }}>
          <TA_S text="BUDGET DIAL · live" right={<span style={{ color: TA_T.mute }}>S/</span>} />
          <div style={{ marginTop: 16, display: "flex", alignItems: "baseline", gap: 12 }}>
            <span style={{ fontFamily: TA_FS, fontSize: 42, fontWeight: 600, color: TA_T.amber, letterSpacing: "-0.02em" }}>{(budget/1000).toFixed(0)}k</span>
            <span style={{ color: TA_T.muteDim, fontSize: 14 }}>· S/ {(budget/92/3).toFixed(0)}/día/cuenta</span>
          </div>
          <input
            type="range" min={800000} max={2200000} step={20000} value={budget}
            onChange={e => setBudget(+e.target.value)}
            style={{ width: "100%", marginTop: 18, accentColor: TA_T.amber }}
          />
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 10, color: TA_T.muteDim, marginTop: 6 }}>
            <span>800k</span><span>1.42M (planned)</span><span>2.2M</span>
          </div>
          <div style={{ marginTop: 16, padding: "12px 14px", background: TA_T.bg, border: `1px solid ${TA_T.line}` }}>
            <div style={{ fontSize: 10, color: TA_T.cyan, letterSpacing: "0.14em", marginBottom: 8 }}>SENSITIVITY · top 3 levers</div>
            {[
              { l: "+15% CTR (creative refresh)", v: "+2,712 leads", c: TA_T.green },
              { l: "-10% CPM (consolidation)",    v: "+1,128 leads", c: TA_T.green },
              { l: "+5pp consent rate",           v: "+   612 leads", c: TA_T.green },
              { l: "-1d learning phase",           v: "+   320 leads", c: TA_T.cyan },
            ].map((s,i) => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "5px 0", fontSize: 11, borderTop: i ? `1px dashed ${TA_T.line}` : "none" }}>
                <span style={{ color: TA_T.mute }}>{s.l}</span>
                <span style={{ color: s.c }}>{s.v}</span>
              </div>
            ))}
          </div>
        </div>

        {/* SCENARIO PROJECTION */}
        <div style={{ border: `1px solid ${TA_T.line}`, background: TA_T.surface }}>
          <div style={{ display: "flex", borderBottom: `1px solid ${TA_T.line}` }}>
            {D.forecast.scenarios.map(s => (
              <button key={s.name} onClick={() => setScenario(s.name)} style={{
                flex: 1, padding: "12px 0", fontFamily: TA_FM, fontSize: 11, letterSpacing: "0.1em",
                background: s.name === scenario ? TA_T.surfaceHi : "transparent",
                color: s.name === scenario ? TA_T.amber : TA_T.mute,
                border: "none", borderRight: `1px solid ${TA_T.line}`,
                borderBottom: s.name === scenario ? `2px solid ${TA_T.amber}` : "none",
                cursor: "pointer",
              }}>{s.name.toUpperCase()} · p={s.prob}</button>
            ))}
          </div>
          <div style={{ padding: "20px 22px" }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
              <Big k="Leads proyectados" v={projLeads.toLocaleString()} sub={`vs ${sc.leads.toLocaleString()} a S/ 1.42M`} col={TA_T.amber} />
              <Big k="CPL esperado" v={`S/ ${projCpl.toFixed(2)}`} sub={`σ ± S/ ${(projCpl*0.08).toFixed(2)}`} col={TA_T.ink} />
              <Big k="MER blended" v={`${(sc.mer * Math.pow(factor, -0.04)).toFixed(2)}x`} sub="real, no plataforma" col={TA_T.green} />
              <Big k="CAC payback" v={`${(6.8 / sc.mer * 2.7).toFixed(1)} mo`} sub="LTV/CAC ~ 4.1" col={TA_T.violet} />
            </div>
            {/* curva diminishing returns */}
            <div style={{ marginTop: 18, padding: 12, background: TA_T.bg, border: `1px solid ${TA_T.line}` }}>
              <div style={{ fontSize: 10, color: TA_T.mute, letterSpacing: "0.14em", marginBottom: 8 }}>RESPONSE CURVE · spend → leads (sub-linear)</div>
              <svg width="100%" height="100" viewBox="0 0 400 100" preserveAspectRatio="none">
                <defs><linearGradient id="rc" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stopColor={TA_T.amber} stopOpacity="0.3"/><stop offset="1" stopColor={TA_T.amber} stopOpacity="0"/></linearGradient></defs>
                <path d={`M0,100 ${Array.from({length:50},(_,i)=>{const x=(i/49)*400; const y=100-Math.pow(i/49,0.55)*92; return `L${x},${y}`}).join(" ")} L400,100 Z`} fill="url(#rc)" />
                <path d={`M0,100 ${Array.from({length:50},(_,i)=>{const x=(i/49)*400; const y=100-Math.pow(i/49,0.55)*92; return `L${x},${y}`}).join(" ")}`} fill="none" stroke={TA_T.amber} strokeWidth="1.5" />
                {(() => {
                  const i = (budget - 800000) / (2200000 - 800000); const x = i*400; const y = 100 - Math.pow(i, 0.55)*92;
                  return <g><line x1={x} y1={0} x2={x} y2={100} stroke={TA_T.green} strokeDasharray="2 3" /><circle cx={x} cy={y} r="4" fill={TA_T.green}/></g>;
                })()}
              </svg>
              <div style={{ marginTop: 4, fontSize: 10, color: TA_T.muteDim }}>Saturación empieza ~ S/ 1.85M/Q · sobre eso, CAC sube 18%+</div>
            </div>
          </div>
        </div>
      </div>

      {/* CHANNEL ALLOCATION */}
      <div>
        <TA_S text="CHANNEL ALLOCATION · current vs target" right={<span style={{ color: TA_T.mute }}>MMM v4 · drag para reasignar</span>} />
        <div style={{ marginTop: 12, border: `1px solid ${TA_T.line}` }}>
          {channels.map((c,i) => (
            <div key={c.id} style={{ display: "grid", gridTemplateColumns: "100px 1fr 90px 90px 110px", padding: "14px 18px", alignItems: "center", borderBottom: i<channels.length-1?`1px solid ${TA_T.line}`:"none", background: TA_T.surface, gap: 14 }}>
              <span style={{ fontFamily: TA_FS, fontWeight: 600, color: TA_T.ink, fontSize: 13 }}>{c.id}</span>
              <div style={{ position: "relative", height: 18 }}>
                <div style={{ position: "absolute", inset: 0, background: TA_T.line }} />
                <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${c.pct*100}%`, background: c.color, opacity: 0.85 }} />
                <div style={{ position: "absolute", left: `${c.target*100}%`, top: -4, bottom: -4, width: 2, background: TA_T.ink }} title="target" />
                <span style={{ position: "absolute", left: `${c.pct*100 + 1}%`, top: -16, fontSize: 9, color: c.color }}>{(c.pct*100).toFixed(0)}%</span>
                <span style={{ position: "absolute", left: `${c.target*100 + 1}%`, top: 20, fontSize: 9, color: TA_T.muteDim }}>target {(c.target*100).toFixed(0)}%</span>
              </div>
              <span style={{ color: TA_T.green, fontSize: 11, textAlign: "right" }}>MER {c.mer}x</span>
              <span style={{ color: TA_T.muteDim, fontSize: 10, textAlign: "right" }}>{c.ceiling}</span>
              <span style={{ color: c.pct > c.target ? TA_T.amber : c.pct < c.target ? TA_T.cyan : TA_T.green, fontSize: 11, textAlign: "right" }}>
                {c.pct > c.target ? "↓ -" : "↑ +"}{Math.abs((c.target-c.pct)*100).toFixed(0)}pp
              </span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", gap: 8 }}>
        <TA_B kind="amber">EJECUTAR PLAN</TA_B>
        <TA_B kind="violet">LOCK FOR Q3</TA_B>
        <TA_B>SAVE AS DRAFT</TA_B>
        <TA_B>EXPORT TO CFO DECK</TA_B>
      </div>
    </div>
  );
};
const Big = ({ k, v, sub, col }) => (
  <div>
    <div style={{ fontSize: 10, color: TA_T.muteDim, letterSpacing: "0.12em", marginBottom: 6 }}>{k.toUpperCase()}</div>
    <div style={{ fontFamily: TA_FS, fontSize: 26, fontWeight: 600, color: col || TA_T.ink, letterSpacing: "-0.01em" }}>{v}</div>
    <div style={{ fontSize: 10, color: TA_T.mute, marginTop: 4 }}>{sub}</div>
  </div>
);

// ====================================================================
// DIAGNOSE — full decision tree, interactive
// ====================================================================
const DiagnoseScreen = () => {
  const D = window.MA_DATA;
  const [pick, setPick] = React.useState(2); // CTR
  const branches = [
    { i:0, k: "Frequency",   r: "ok",   v: "2.1", line: "<3 ✓ no fatiga unitaria", deep: ["7d freq por ad set", "campaña más alta · 2.6", "no acción"] },
    { i:1, k: "CPM",         r: "ok",   v: "+4%", line: "ruido (σ ±6%)", deep: ["Meta auction +3%", "Google +2%", "TikTok +9% · monitor"] },
    { i:2, k: "CTR",         r: "warn", v: "-19%", line: "fatiga creativa o off-target", deep: ["hook rate -38% en top-3", "thumbstop 0.42s → 0.31s", "swipe-thru +14% (señal off-message)"] },
    { i:3, k: "CVR landing", r: "warn", v: "-11%", line: "LCP 3.8s · sobre umbral", deep: ["LCP 3.8s (Δ +1.2s)", "form abandono 28%→34%", "form fields 9 (target 5)"] },
    { i:4, k: "Attribution", r: "ok",   v: "EMQ 8.4", line: "señal sólida", deep: ["CAPI dedupe 99.2%", "EC linked", "iOS AEM priorities OK"] },
    { i:5, k: "Seasonality", r: "ok",   v: "0.98",  line: "índice ~baseline", deep: ["semana santa LM", "Día del Padre +6d", "no acción"] },
  ];
  const cur = branches[pick];
  return (
    <div className="ma-pad" style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 22 }}>
      <div>
        <div style={{ fontSize: 10, color: TA_T.mute, letterSpacing: "0.18em", marginBottom: 6 }}>// DIAGNOSE · interactive tree</div>
        <div style={{ fontFamily: TA_FS, fontSize: 26, fontWeight: 600, color: TA_T.ink }}>CPL subiendo en SeguroFácil — <span style={{ color: TA_T.amber }}>¿por qué?</span></div>
        <div style={{ fontSize: 11, color: TA_T.mute, marginTop: 4 }}>SEV med · activado 09:14 · agente recorrió 6 ramas en 1.8s · profundizar manualmente</div>
      </div>

      {/* TREE */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(6,1fr)", gap: 0, border: `1px solid ${TA_T.line}` }}>
        {branches.map((b,i) => {
          const col = b.r === "ok" ? TA_T.green : b.r === "warn" ? TA_T.amber : TA_T.red;
          const active = i === pick;
          return (
            <button key={i} onClick={() => setPick(i)} style={{
              padding: "16px 14px", borderRight: i<5?`1px solid ${TA_T.line}`:"none",
              background: active ? TA_T.surfaceHi : b.r === "warn" ? "#1a1410" : TA_T.surface,
              borderTop: active ? `3px solid ${col}` : `3px solid transparent`,
              border: "none", borderRight: i<5?`1px solid ${TA_T.line}`:"none",
              cursor: "pointer", textAlign: "left", fontFamily: TA_FM, color: TA_T.ink,
              borderBottom: active ? `none` : `1px solid transparent`,
            }}>
              <div style={{ fontSize: 9, color: TA_T.muteDim, letterSpacing: "0.14em", marginBottom: 8 }}>{(i+1).toString().padStart(2,"0")} · NODE</div>
              <div style={{ color: col, fontFamily: TA_FS, fontSize: 18, fontWeight: 600, marginBottom: 4 }}>{b.k}</div>
              <div style={{ color: col, fontSize: 11, marginBottom: 6 }}>{b.v}</div>
              <div style={{ fontSize: 10, color: TA_T.mute, lineHeight: 1.4 }}>{b.line}</div>
              <div style={{ marginTop: 10, height: 2, background: col, opacity: active ? 1 : 0.4 }} />
            </button>
          );
        })}
      </div>

      {/* DEEP DIVE */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
        <div style={{ border: `1px solid ${TA_T.line}`, background: TA_T.surface, padding: "16px 18px" }}>
          <TA_S text={`DEEP DIVE · ${cur.k.toUpperCase()}`} />
          <ul style={{ marginTop: 12, padding: 0, listStyle: "none" }}>
            {cur.deep.map((d,i) => (
              <li key={i} style={{ padding: "8px 0", borderBottom: i < cur.deep.length-1 ? `1px solid ${TA_T.line}` : "none", color: TA_T.ink, fontSize: 11, display: "flex", gap: 10 }}>
                <span style={{ color: TA_T.muteDim, width: 16 }}>↳</span>
                <span>{d}</span>
              </li>
            ))}
          </ul>
        </div>
        <div style={{ border: `1px solid ${TA_T.line}`, background: TA_T.surface, padding: "16px 18px" }}>
          <TA_S text="HYPOTHESIS · agent ranked" />
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 10 }}>
            {[
              { p: 0.62, h: "Fatiga creativa en top-3 hooks · activos 18d sin refresh" },
              { p: 0.24, h: "LP lenta · LCP 3.8s post-deploy del lunes" },
              { p: 0.09, h: "Audience overlap · 63% en top ad sets" },
              { p: 0.05, h: "Variación estacional · ya descartada" },
            ].map((h,i) => (
              <div key={i}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, marginBottom: 4 }}>
                  <span style={{ color: TA_T.ink }}>{h.h}</span>
                  <span style={{ color: TA_T.amber, fontFamily: TA_FM }}>{(h.p*100).toFixed(0)}%</span>
                </div>
                <div style={{ height: 3, background: TA_T.line }}>
                  <div style={{ width: `${h.p*100}%`, height: "100%", background: i===0?TA_T.amber:TA_T.cyan, opacity: 0.85 }} />
                </div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ border: `1px solid ${TA_T.amber}`, borderLeftWidth: 3, background: TA_T.surface, padding: "16px 18px" }}>
          <div style={{ fontSize: 10, color: TA_T.amber, letterSpacing: "0.16em", marginBottom: 8 }}>VERDICT · agent</div>
          <div style={{ fontFamily: TA_FS, fontSize: 16, color: TA_T.ink, marginBottom: 10, lineHeight: 1.35 }}>{D.diagnostic.verdict}</div>
          <div style={{ fontSize: 11, color: TA_T.mute, marginBottom: 14 }}>→ {D.diagnostic.action}</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <TA_B kind="amber">PAUSAR 4 CREATIVOS</TA_B>
            <TA_B kind="violet">BRIEF 8 ANGLES NUEVOS</TA_B>
            <TA_B kind="green">TICKET LCP P0 → ENG</TA_B>
            <TA_B>OVERRIDE · NO HACER</TA_B>
          </div>
        </div>
      </div>

      {/* ANTI-PATTERN ALARM */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div style={{ border: `1px solid ${TA_T.red}`, borderLeftWidth: 3, padding: "14px 18px", background: TA_T.surface }}>
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
            <span style={{ color: TA_T.red, fontSize: 10, letterSpacing: "0.16em" }}>ANTI-PATTERN · 2021-era</span>
            <span style={{ color: TA_T.muteDim, fontSize: 10 }}>detectado por agent</span>
          </div>
          <div style={{ fontFamily: TA_FS, fontSize: 14, color: TA_T.ink, marginBottom: 8 }}>"Más ad sets = más control"</div>
          <div style={{ fontSize: 11, color: TA_T.mute, lineHeight: 1.5 }}>
            Hace 5 años, sí. Hoy con Advantage+ y Smart Bidding, fragmentar bajo S/ 5/día por ad set rompe el ML.
            Tu cuenta SeguroFácil tiene 47 ad sets · 23 sin salir de learning.
            <br/><br/>
            <span style={{ color: TA_T.amber }}>→ Consolidar a 6 ad sets unlock S/ 8.4k/mes en eficiencia.</span>
          </div>
        </div>
        <div style={{ border: `1px solid ${TA_T.cyan}`, borderLeftWidth: 3, padding: "14px 18px", background: TA_T.surface }}>
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
            <span style={{ color: TA_T.cyan, fontSize: 10, letterSpacing: "0.16em" }}>EVITAR TINKERING · daily</span>
            <span style={{ color: TA_T.muteDim, fontSize: 10 }}>weekly cadence enforced</span>
          </div>
          <div style={{ fontFamily: TA_FS, fontSize: 14, color: TA_T.ink, marginBottom: 8 }}>Last manual edit · sáb 18:42</div>
          <div style={{ fontSize: 11, color: TA_T.mute, lineHeight: 1.5 }}>
            Lock activo. Próximo cambio material · vie 10 May 10:00 (3d 14h 18m).
            <br/><br/>
            <span style={{ color: TA_T.cyan }}>Override solo con justificación de impacto &gt; S/ 5k.</span>
          </div>
        </div>
      </div>
    </div>
  );
};

// ====================================================================
// MEASURE — triangulation deep, holdout, MMM cadence
// ====================================================================
const MeasureScreen = () => {
  const D = window.MA_DATA;
  return (
    <div className="ma-pad" style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 22 }}>
      <div>
        <div style={{ fontSize: 10, color: TA_T.mute, letterSpacing: "0.18em", marginBottom: 6 }}>// MEASURE · triangulation</div>
        <div style={{ fontFamily: TA_FS, fontSize: 26, fontWeight: 600, color: TA_T.ink }}>4 lentes lado a lado · una sola verdad</div>
        <div style={{ fontSize: 11, color: TA_T.mute, marginTop: 4 }}>iROAS por canal · UAR · 30d · weighted consensus 2.97x · confidence 0.86</div>
      </div>

      {/* 4 LENSES TABLE */}
      <div>
        <div style={{ display: "grid", gridTemplateColumns: "180px repeat(4, 1fr)", border: `1px solid ${TA_T.line}` }}>
          {["", "MMM (Meridian)", "Geo-lift", "Platform reported", "Post-purchase survey"].map((h,i) => (
            <div key={i} style={{ padding: "12px 16px", borderRight: i<4?`1px solid ${TA_T.line}`:"none", background: TA_T.surfaceHi, fontSize: 10, letterSpacing: "0.12em", color: TA_T.mute }}>
              {h.toUpperCase()}
            </div>
          ))}
          {[
            { k: "iROAS Meta",     vals: ["2.84", "3.12", "4.92", "2.95"], cis: ["2.41–3.18", "2.78–3.51", "self-attrib", "n=187"], warn: 2 },
            { k: "iROAS Google",   vals: ["2.41", "—", "3.81", "2.55"],     cis: ["2.10–2.78", "no test", "self-attrib", "n=164"], warn: 2 },
            { k: "iROAS TikTok",   vals: ["1.94", "—", "2.82", "1.82"],     cis: ["1.52–2.31", "no test", "self-attrib", "n=121"], warn: 2 },
            { k: "Brand lift",     vals: ["+8.1pp", "—", "—", "+9.4pp"],    cis: ["MMM brand var", "—", "—", "Δ aided awareness"], warn: -1 },
            { k: "Decay halflife", vals: ["6.1 sem", "—", "—", "—"],        cis: ["MMM v4 prior", "—", "—", "—"], warn: -1 },
          ].map((row, ri) => (
            <React.Fragment key={ri}>
              <div style={{ padding: "14px 16px", borderTop: `1px solid ${TA_T.line}`, borderRight: `1px solid ${TA_T.line}`, background: TA_T.surface, fontSize: 11, color: TA_T.ink, fontFamily: TA_FS, fontWeight: 500 }}>{row.k}</div>
              {row.vals.map((v, vi) => (
                <div key={vi} style={{ padding: "14px 16px", borderTop: `1px solid ${TA_T.line}`, borderRight: vi<3?`1px solid ${TA_T.line}`:"none", background: TA_T.surface }}>
                  <div style={{ color: row.warn === vi ? TA_T.red : v === "—" ? TA_T.muteDim : TA_T.ink, fontSize: 14, fontFamily: TA_FS, fontWeight: 600 }}>{v}</div>
                  <div style={{ color: TA_T.muteDim, fontSize: 10, marginTop: 4 }}>{row.cis[vi]}</div>
                </div>
              ))}
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* AGENT NOTE */}
      <div style={{ padding: "14px 18px", background: TA_T.surface, border: `1px solid ${TA_T.amber}`, borderLeftWidth: 3 }}>
        <div style={{ fontSize: 10, color: TA_T.amber, letterSpacing: "0.16em", marginBottom: 8 }}>AGENT · porqué la divergencia</div>
        <div style={{ fontSize: 11, color: TA_T.ink, lineHeight: 1.6 }}>
          Plataforma reporta <b style={{ color: TA_T.red }}>4.92x</b> en Meta, pero MMM y geo-lift convergen en <b style={{ color: TA_T.green }}>2.84-3.12x</b>.
          La diferencia (~1.8x) es <b>self-attribution</b>: Meta cuenta clicks/views que el usuario habría convertido orgánicamente.
          <br/>El consensus ponderado <b style={{ color: TA_T.green }}>2.97x</b> es la verdad accionable. Reportar 4.92x al CFO inflaría el caso · perderías credibilidad.
        </div>
      </div>

      {/* EXPERIMENTS + HOLDOUT + CADENCE */}
      <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr 1fr", gap: 16 }}>
        <div style={{ border: `1px solid ${TA_T.line}`, background: TA_T.surface, padding: "16px 18px" }}>
          <TA_S text="ACTIVE EXPERIMENTS" right={<span style={{ color: TA_T.green }}>● 2 running</span>} />
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 12 }}>
            {[
              { n: "Geo-lift · Vivienda Lima", state: "running", day: "9/14", read: "iROAS prov 1.42 (CI 1.18-1.71)", col: TA_T.green },
              { n: "Smart+ vs Manual · SF", state: "running", day: "11/21", read: "no significance yet · power 0.61", col: TA_T.amber },
              { n: "Holdout 5% nacional · UAR", state: "queued", day: "—", read: "blocked · audit P0 fix LP first", col: TA_T.muteDim },
            ].map((x,i) => (
              <div key={i} style={{ padding: "10px 12px", border: `1px solid ${TA_T.line}`, background: TA_T.bg }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
                  <span style={{ color: TA_T.ink, fontSize: 11, fontFamily: TA_FS, fontWeight: 500 }}>{x.n}</span>
                  <span style={{ color: x.col, fontSize: 10, letterSpacing: "0.1em" }}>{x.state.toUpperCase()} {x.day}</span>
                </div>
                <div style={{ color: TA_T.mute, fontSize: 10 }}>{x.read}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ border: `1px solid ${TA_T.line}`, background: TA_T.surface, padding: "16px 18px" }}>
          <TA_S text="MMM CADENCE" right={<span style={{ color: TA_T.amber }}>12d ago</span>} />
          <div style={{ marginTop: 12 }}>
            {Array.from({length: 14}, (_,i) => i).map(d => (
              <div key={d} style={{ display: "inline-block", width: 18, height: 18, marginRight: 3, marginBottom: 3, background: d < 12 ? TA_T.surfaceLo : d === 13 ? TA_T.amber : TA_T.cyan, border: `1px solid ${TA_T.line}` }} title={`day ${d}`} />
            ))}
            <div style={{ marginTop: 12, fontSize: 10, color: TA_T.mute, lineHeight: 1.5 }}>
              Próxima recalibración · vie 10 May<br/>
              Trigger automático · cuando MMM >=14d o cambio macro >5%<br/>
              Kalman update diario para drift menor
            </div>
          </div>
        </div>
        <div style={{ border: `1px solid ${TA_T.line}`, background: TA_T.surface, padding: "16px 18px" }}>
          <TA_S text="CONSENSUS · weighted" />
          <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 10 }}>
            {D.triangulation.lenses.map((l,i) => (
              <div key={i}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, marginBottom: 4 }}>
                  <span style={{ color: l.warn ? TA_T.red : TA_T.ink }}>{l.name}</span>
                  <span style={{ color: TA_T.amber }}>{(l.weight*100).toFixed(0)}%</span>
                </div>
                <div style={{ height: 4, background: TA_T.line }}>
                  <div style={{ width: `${l.weight*100}%`, height: "100%", background: l.warn ? TA_T.red : TA_T.amber, opacity: 0.85 }} />
                </div>
              </div>
            ))}
            <div style={{ marginTop: 10, padding: "10px 12px", background: TA_T.bg, border: `1px solid ${TA_T.green}` }}>
              <div style={{ fontSize: 10, color: TA_T.green, letterSpacing: "0.14em" }}>CONSENSUS iROAS</div>
              <div style={{ fontFamily: TA_FS, fontSize: 22, fontWeight: 600, color: TA_T.green, marginTop: 4 }}>{D.triangulation.consensus}x</div>
              <div style={{ fontSize: 10, color: TA_T.mute, marginTop: 4 }}>confidence {D.triangulation.confidence}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AuditScreen, PlanScreen, DiagnoseScreen, MeasureScreen });
