/* global React */
// Terminal LatAm — Settings (Profile · Members · Permissions · HITL · Alerts · Branding · Routines · Billing)

const TS_T = window.T_THEME;
const TS_FM = window.T_FM;
const TS_FS = window.T_FS;
const TS_B = window.TerminalBtn;

const SECTIONS = [
  { id: "profile", label: "Profile" },
  { id: "briefing", label: "Agent Briefing", star: true },
  { id: "hitl", label: "HITL Thresholds", star: true },
  { id: "members", label: "Members" },
  { id: "permissions", label: "Permissions" },
  { id: "alertsCfg", label: "Alerts" },
  { id: "branding", label: "Branding" },
  { id: "routinesCfg", label: "Routines", soon: true },
  { id: "billing", label: "Billing" },
];

const SettingsHeader = ({ tag, title, sub }) => (
  <div style={{ marginBottom: 22, paddingBottom: 18, borderBottom: `1px solid ${TS_T.line}` }}>
    <div style={{ fontFamily: TS_FM, fontSize: 10, color: TS_T.mute, letterSpacing: "0.18em", marginBottom: 6 }}>// SETTINGS · {tag}</div>
    <div style={{ fontFamily: TS_FS, fontSize: 24, fontWeight: 600, color: TS_T.ink }}>{title}</div>
    {sub && <div style={{ fontSize: 12, color: TS_T.mute, marginTop: 6, lineHeight: 1.6 }}>{sub}</div>}
  </div>
);

const Field = ({ label, children, sub }) => (
  <div style={{ marginBottom: 18 }}>
    <div style={{ fontSize: 10, color: TS_T.muteDim, letterSpacing: "0.14em", marginBottom: 6 }}>{label}</div>
    {children}
    {sub && <div style={{ fontSize: 10, color: TS_T.muteDim, marginTop: 4, fontStyle: "italic" }}>{sub}</div>}
  </div>
);

const TInput = (props) => (
  <input {...props} style={{
    width: "100%", padding: "8px 10px", background: TS_T.surface, border: `1px solid ${TS_T.line}`,
    color: TS_T.ink, fontFamily: TS_FM, fontSize: 12, outline: "none", ...props.style,
  }} />
);

const TSelect = ({ value, onChange, options, ...rest }) => (
  <select value={value} onChange={onChange} {...rest} style={{
    width: "100%", padding: "8px 10px", background: TS_T.surface, border: `1px solid ${TS_T.line}`,
    color: TS_T.ink, fontFamily: TS_FM, fontSize: 12, outline: "none",
  }}>
    {options.map(o => <option key={o.value || o} value={o.value || o}>{o.label || o}</option>)}
  </select>
);

// ─── PROFILE ─────────────────────────────────────────────────────────────
const ProfilePage = () => (
  <div>
    <SettingsHeader tag="PROFILE" title="Tu perfil" sub="Información personal · timezone · idioma · preferencias por defecto" />
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
      <Field label="NOMBRE COMPLETO"><TInput defaultValue="Pablo Ríos" /></Field>
      <Field label="EMAIL"><TInput type="email" defaultValue="pablo@bluenose.pe" /></Field>
      <Field label="TIMEZONE"><TSelect defaultValue="GMT-5" options={["GMT-5 · Lima","GMT-3 · Buenos Aires","GMT-6 · México","GMT-3 · São Paulo"]} /></Field>
      <Field label="IDIOMA UI"><TSelect defaultValue="es" options={[{value:"es",label:"Español"},{value:"en",label:"English"}]} /></Field>
      <Field label="LOCALE NÚMERO/MONEDA"><TSelect defaultValue="PE" options={["PE · S/","MX · MX$","AR · AR$","CL · CLP","BR · R$","CO · COP"]} /></Field>
      <Field label="MODO POR DEFECTO" sub="puedes alternar en Tweaks panel"><TSelect defaultValue="single" options={[{value:"single",label:"Single-client"},{value:"multi",label:"Multi-client"}]} /></Field>
    </div>
  </div>
);

// ─── MEMBERS ─────────────────────────────────────────────────────────────
const MembersPage = () => {
  const members = [
    { name: "Pablo Ríos", email: "pablo@bluenose.pe", role: "owner", login: "ahora", status: "active" },
    { name: "Carla Mendoza", email: "carla@bluenose.pe", role: "strategist", login: "hace 2h", status: "active" },
    { name: "Diego Vargas", email: "diego.vargas@uar.edu.pe", role: "viewer", login: "ayer", status: "active" },
    { name: "María Fernández", email: "m.fernandez@segurofacil.pe", role: "admin", login: "—", status: "pending" },
  ];
  return (
    <div>
      <SettingsHeader tag="MEMBERS" title="Miembros del workspace" sub="Roles · invitaciones · last login. Owner solo puede haber 1." />
      <TS_B kind="amber">+ INVITAR MIEMBRO</TS_B>
      <div style={{ marginTop: 16, border: `1px solid ${TS_T.line}` }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 130px 100px 80px 100px", gap: 10, padding: "10px 14px", background: TS_T.surfaceHi, fontSize: 9, color: TS_T.muteDim, letterSpacing: "0.14em", borderBottom: `1px solid ${TS_T.line}` }}>
          <span>NOMBRE</span><span>EMAIL</span><span>ROL</span><span>LAST LOGIN</span><span>STATUS</span><span></span>
        </div>
        {members.map((m, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1fr 130px 100px 80px 100px", gap: 10, padding: "12px 14px", borderBottom: i < members.length - 1 ? `1px solid ${TS_T.line}` : "none", background: TS_T.surface, alignItems: "center", fontSize: 11 }}>
            <span style={{ color: TS_T.ink, fontWeight: 500 }}>{m.name}</span>
            <span style={{ color: TS_T.muteDim, fontFamily: TS_FM, fontSize: 10 }}>{m.email}</span>
            <span style={{ color: TS_T.cyan, fontFamily: TS_FM, fontSize: 10, letterSpacing: "0.1em" }}>{m.role.toUpperCase()}</span>
            <span style={{ color: TS_T.muteDim, fontSize: 10 }}>{m.login}</span>
            <span style={{ color: m.status === "active" ? TS_T.green : TS_T.amber, fontSize: 10, fontFamily: TS_FM }}>● {m.status}</span>
            <span style={{ color: TS_T.muteDim, textAlign: "right" }}>⋯</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ─── PERMISSIONS ─────────────────────────────────────────────────────────
const PermissionsPage = () => {
  const D = window.MA_DATA;
  const platforms = ["Meta","Google","TikTok","LinkedIn"];
  return (
    <div>
      <SettingsHeader tag="PERMISSIONS" title="Write-access matrix" sub="Por defecto, todas las cuentas son read. Activa write explícitamente por platform · revocable inmediato." />
      <div style={{ border: `1px solid ${TS_T.line}` }}>
        <div style={{ display: "grid", gridTemplateColumns: `1fr repeat(${platforms.length}, 90px)`, padding: "10px 14px", background: TS_T.surfaceHi, fontSize: 9, color: TS_T.muteDim, letterSpacing: "0.14em", borderBottom: `1px solid ${TS_T.line}` }}>
          <span>CLIENTE</span>
          {platforms.map(p => <span key={p} style={{ textAlign: "center" }}>{p.toUpperCase()}</span>)}
        </div>
        {D.portfolio.map((c, i) => (
          <div key={c.id} style={{ display: "grid", gridTemplateColumns: `1fr repeat(${platforms.length}, 90px)`, padding: "12px 14px", borderBottom: i < D.portfolio.length - 1 ? `1px solid ${TS_T.line}` : "none", background: TS_T.surface, alignItems: "center", fontSize: 11 }}>
            <span style={{ color: TS_T.ink, fontFamily: TS_FS, fontWeight: 500 }}>{c.name}</span>
            {platforms.map((p, j) => {
              const on = (c.id === "uar" && j < 3) || (c.id === "sf" && j < 2) || (c.id === "vl" && j === 0);
              return (
                <span key={p} style={{ textAlign: "center" }}>
                  <span style={{ display: "inline-block", padding: "3px 8px", fontSize: 9, fontFamily: TS_FM, letterSpacing: "0.1em", border: `1px solid ${on ? TS_T.green : TS_T.line}`, color: on ? TS_T.green : TS_T.muteDim, cursor: "pointer" }}>
                    {on ? "● R+W" : "○ R only"}
                  </span>
                </span>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
};

// ─── HITL THRESHOLDS · the star ──────────────────────────────────────────
const HITL_DEFAULTS = {
  conservative: { budget: { auto: 0, hitl: 0, cool: 14 }, bidding: { auto: 0, hitl: 0, cool: 14 }, creative: { auto: 0, hitl: 0, cool: 7 }, placement: { auto: 0, hitl: 0, cool: 7 }, negKw: { auto: 0, hitl: 0, cool: 0 }, tracking: { auto: 0, hitl: 0, cool: 0 }, experiment: { auto: 0, hitl: 0, cool: 0 }, comply: { auto: 0, hitl: 0, cool: 0 } },
  balanced:     { budget: { auto: 20, hitl: 50, cool: 7 }, bidding: { auto: 0, hitl: 0, cool: 5 },  creative: { auto: 100, hitl: 100, cool: 3 }, placement: { auto: 30, hitl: 60, cool: 7 }, negKw: { auto: 100, hitl: 100, cool: 0 }, tracking: { auto: 50, hitl: 80, cool: 1 }, experiment: { auto: 0, hitl: 0, cool: 14 }, comply: { auto: 0, hitl: 0, cool: 0 } },
  aggressive:   { budget: { auto: 50, hitl: 80, cool: 3 }, bidding: { auto: 30, hitl: 60, cool: 2 }, creative: { auto: 100, hitl: 100, cool: 1 }, placement: { auto: 60, hitl: 90, cool: 3 }, negKw: { auto: 100, hitl: 100, cool: 0 }, tracking: { auto: 80, hitl: 95, cool: 0 }, experiment: { auto: 30, hitl: 60, cool: 7 }, comply: { auto: 0, hitl: 0, cool: 0 } },
};

const CATS = [
  { id: "budget", label: "Budget", note: "% cambio sobre baseline diario" },
  { id: "bidding", label: "Bidding", note: "% ajuste de bids" },
  { id: "creative", label: "Creative", note: "pause/launch · % decisiones" },
  { id: "placement", label: "Placement", note: "exclude/include placements" },
  { id: "negKw", label: "Negative KW", note: "exclusiones automáticas" },
  { id: "tracking", label: "Tracking", note: "fix dedupe/EMQ menores" },
  { id: "experiment", label: "Experiment", note: "iniciar/parar tests" },
  { id: "comply", label: "Compliance", note: "siempre HITL · no auto" },
];

const HITLPage = () => {
  const [mode, setMode] = React.useState("balanced");
  const [thresh, setThresh] = React.useState(HITL_DEFAULTS.balanced);

  const setPreset = (m) => {
    setMode(m);
    if (m !== "custom") setThresh(HITL_DEFAULTS[m]);
  };
  const setCat = (cat, key, val) => {
    setMode("custom");
    setThresh(t => ({ ...t, [cat]: { ...t[cat], [key]: val } }));
  };

  // Simulated "would have"
  const wouldAuto = Object.values(thresh).reduce((s, c) => s + Math.round(c.auto / 8), 0);
  const wouldHitl = 47 - wouldAuto;

  return (
    <div>
      <SettingsHeader
        tag="HITL THRESHOLDS · ⭐ crítico"
        title="Define qué puede hacer el agente sin pedirte permiso"
        sub="Acciones FUERA de estos rangos → tu Inbox · acciones DENTRO → ejecutadas automáticamente · todo queda en ledger revertible 14 días."
      />

      {/* PRESETS */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, marginBottom: 22 }}>
        {[
          { id: "conservative", l: "CONSERVATIVE", sub: "todo HITL · cero auto", c: TS_T.cyan },
          { id: "balanced", l: "BALANCED · DEFAULT", sub: "pauses + negKw auto · budget>20% HITL", c: TS_T.amber },
          { id: "aggressive", l: "AGGRESSIVE", sub: "auto hasta 50% budget", c: TS_T.red },
          { id: "custom", l: "CUSTOM", sub: "ajusta sliders abajo", c: TS_T.violet },
        ].map(p => (
          <button key={p.id} onClick={() => setPreset(p.id)} style={{
            padding: "12px 14px", background: mode === p.id ? TS_T.surface : TS_T.bg, textAlign: "left",
            border: `1px solid ${mode === p.id ? p.c : TS_T.line}`, borderLeft: mode === p.id ? `3px solid ${p.c}` : `1px solid ${TS_T.line}`, cursor: "pointer",
          }}>
            <div style={{ fontFamily: TS_FM, fontSize: 11, color: mode === p.id ? p.c : TS_T.ink, letterSpacing: "0.14em", fontWeight: 600 }}>{p.l}</div>
            <div style={{ fontSize: 10, color: TS_T.muteDim, marginTop: 4 }}>{p.sub}</div>
          </button>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 280px", gap: 18 }}>
        {/* TABLE */}
        <div style={{ border: `1px solid ${TS_T.line}` }}>
          <div style={{ display: "grid", gridTemplateColumns: "150px 1fr 1fr 90px", gap: 10, padding: "10px 14px", background: TS_T.surfaceHi, fontSize: 9, color: TS_T.muteDim, letterSpacing: "0.14em", borderBottom: `1px solid ${TS_T.line}` }}>
            <span>CATEGORÍA</span><span>AUTO si &lt;</span><span>HITL si &gt;</span><span style={{ textAlign: "right" }}>COOLDOWN</span>
          </div>
          {CATS.map((c, i) => {
            const t = thresh[c.id] || { auto: 0, hitl: 0, cool: 0 };
            return (
              <div key={c.id} style={{ padding: "12px 14px", borderBottom: i < CATS.length - 1 ? `1px solid ${TS_T.line}` : "none", display: "grid", gridTemplateColumns: "150px 1fr 1fr 90px", gap: 10, alignItems: "center", background: TS_T.surface }}>
                <div>
                  <div style={{ fontSize: 12, color: TS_T.ink, fontFamily: TS_FS, fontWeight: 500 }}>{c.label}</div>
                  <div style={{ fontSize: 9, color: TS_T.muteDim, marginTop: 2 }}>{c.note}</div>
                </div>
                <div>
                  <input type="range" min="0" max="100" step="5" value={t.auto} onChange={(e) => setCat(c.id, "auto", +e.target.value)} style={{ width: "100%", accentColor: TS_T.green }} />
                  <div style={{ fontSize: 10, color: t.auto > 0 ? TS_T.green : TS_T.muteDim, fontFamily: TS_FM, marginTop: 3 }}>{t.auto > 0 ? `≤ ${t.auto}%` : "siempre HITL"}</div>
                </div>
                <div>
                  <input type="range" min="0" max="100" step="5" value={t.hitl} onChange={(e) => setCat(c.id, "hitl", +e.target.value)} style={{ width: "100%", accentColor: TS_T.amber }} />
                  <div style={{ fontSize: 10, color: t.hitl > 0 ? TS_T.amber : TS_T.muteDim, fontFamily: TS_FM, marginTop: 3 }}>{t.hitl > 0 ? `≥ ${t.hitl}%` : "—"}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <input type="number" min="0" max="30" value={t.cool} onChange={(e) => setCat(c.id, "cool", +e.target.value)} style={{ width: 60, padding: "4px 6px", background: TS_T.bg, border: `1px solid ${TS_T.line}`, color: TS_T.ink, fontFamily: TS_FM, fontSize: 11, textAlign: "center", outline: "none" }} />
                  <div style={{ fontSize: 9, color: TS_T.muteDim, marginTop: 3 }}>días</div>
                </div>
              </div>
            );
          })}
        </div>

        {/* LIVE PREVIEW */}
        <div style={{ background: TS_T.surface, border: `1px solid ${TS_T.amber}`, borderLeftWidth: 3, padding: "16px 18px", height: "fit-content", position: "sticky", top: 20 }}>
          <div style={{ fontFamily: TS_FM, fontSize: 10, color: TS_T.amber, letterSpacing: "0.16em", marginBottom: 14 }}>// LIVE PREVIEW · últimos 7d</div>
          <div style={{ fontSize: 12, color: TS_T.ink, lineHeight: 1.6, marginBottom: 16 }}>
            Con estos thresholds, el agente <b style={{ color: TS_T.green }}>HUBIERA ejecutado {wouldAuto}</b> de las últimas <b>47</b> acciones automáticamente · <b style={{ color: TS_T.amber }}>{wouldHitl} habrían ido a tu Inbox</b>.
          </div>
          {/* mini timeline */}
          <div style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 9, color: TS_T.muteDim, letterSpacing: "0.14em", marginBottom: 6 }}>TIMELINE 7D</div>
            <div style={{ display: "flex", gap: 2 }}>
              {Array.from({ length: 47 }).map((_, i) => (
                <div key={i} style={{ flex: 1, height: 22, background: i < wouldAuto ? TS_T.green : TS_T.amber, opacity: 0.7 }} />
              ))}
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 9, color: TS_T.muteDim, fontFamily: TS_FM, marginTop: 4 }}>
              <span>30 abr</span><span>hoy</span>
            </div>
          </div>
          <div style={{ fontSize: 10, color: TS_T.muteDim, lineHeight: 1.6 }}>
            <span style={{ color: TS_T.green }}>■</span> auto-ejecutadas &nbsp;
            <span style={{ color: TS_T.amber }}>■</span> tu Inbox
          </div>
          <div style={{ marginTop: 14, padding: "10px 12px", background: TS_T.bg, fontSize: 10, color: TS_T.cyan, lineHeight: 1.6 }}>
            override por cliente disponible · UAR conservative · SF balanced · VL aggressive
          </div>
        </div>
      </div>
    </div>
  );
};

// ─── AGENT BRIEFING · the system-prompt for the agent ────────────────────
const BRIEFING_BLOCKS = [
  {
    id: "context", label: "Contexto del negocio", icon: "01",
    sub: "Qué hace la empresa · quién es el buyer · cómo se vende",
    placeholder: "UAR es la principal universidad privada del sur del Perú. Vende admisión a 14 carreras de pregrado · ticket promedio S/ 18k/año · ciclo de venta 45-90 días desde lead a matrícula.\n\nBuyer principal: padres de familia NSE B/B+ en Arequipa, Cusco, Tacna · decisión conjunta con el postulante (17-19 años).",
    weight: 18, filled: 92,
  },
  {
    id: "priorities", label: "Prioridades estratégicas Q2", icon: "02",
    sub: "Lo que importa AHORA · objetivos del trimestre · north star",
    placeholder: "1. Llenar admisión 2026-II · meta 1,420 matriculados (vs 1,247 año pasado).\n2. Bajar CAC en Medicina y Derecho (carreras premium).\n3. Defender share-of-voice frente a competidor X que entró en Cusco.\n\nNORTH STAR: leads calificados / S 5k invertidos.",
    weight: 22, filled: 88,
  },
  {
    id: "targets", label: "Targets CFO-language", icon: "03",
    sub: "CAC · LTV · MER · payback · floors & ceilings cuantitativos",
    placeholder: "CAC máximo aceptable: S/ 320 (matrícula confirmada).\nLTV promedio: S/ 31k a 4 años · LTV/CAC ≥ 90:1 sostenible.\nMER objetivo: 4.2x · floor 3.4x.\nCAC payback: ≤ 75 días (deja margen runway).\nMatrícula → revenue: 38% conversion blended.",
    weight: 16, filled: 100,
  },
  {
    id: "constraints", label: "Restricciones · do-not-touch", icon: "04",
    sub: "Canales prohibidos · keywords de marca · zonas que el agente no toca",
    placeholder: "NO PAUSAR campañas de marca (siempre on, instrucción del CMO).\nNO BAJAR budget de Medicina < S/ 4k/día (compromiso con decanato).\nKeywords prohibidas en copy: 'la mejor', 'única', 'garantizado' (regulación SUNEDU).\nNO EXPERIMENTOS en Lima · piloto solo Arequipa hasta jul.",
    weight: 14, filled: 76,
  },
  {
    id: "voice", label: "Voz para reports & emails", icon: "05",
    sub: "Cómo escribe el agente cuando comunica al CMO/CFO/dirección",
    placeholder: "Directo, sin adornos · siempre delta vs ayer y vs plan.\nNunca jerga publicitaria sin traducir (CPM → 'costo de mostrar a 1k personas').\nFirma todos los reports como 'MediaAgent · supervisado por Pablo Ríos'.\nLongitud máx 6 bullets en email semanal · CFO digest 1 párrafo.",
    weight: 8, filled: 60,
  },
  {
    id: "antipatterns", label: "Anti-patterns específicos", icon: "06",
    sub: "Errores que YA cometimos · que el agente debe vetar siempre",
    placeholder: "1. En 2024 fragmentamos a 60+ ad sets por carrera · CAC subió 40%. NUNCA replicar.\n2. Tocar bidding diariamente en campañas de Medicina · el algoritmo se reinicia. Cooldown mínimo 5d.\n3. Atribuir matrículas a último-click en formulario · ignora awareness de Meta. Triangulación obligatoria.",
    weight: 12, filled: 100,
  },
  {
    id: "glossary", label: "Glosario interno", icon: "07",
    sub: "Acrónimos · stages CRM · términos no estándar de tu org",
    placeholder: "MQL en UAR = lead que descargó brochure + abrió 2 emails.\nSAL = MQL que respondió WhatsApp del asesor.\nSQL = SAL que reservó visita al campus o llamada.\n'Ciclo' = semestre académico (oct-feb / mar-jul).\n'Postulante activo' = registrado en plataforma de admisión.",
    weight: 6, filled: 100,
  },
  {
    id: "stakeholders", label: "Stakeholders", icon: "08",
    sub: "Quién decide qué · qué le importa a cada uno",
    placeholder: "CMO Daniela · responde lunes 9am · le importa volumen y crecimiento vs competencia.\nCFO Ricardo · ve report mensual · le importa MER y payback.\nDecano Medicina · veto sobre presupuesto Medicina · contactar antes de cualquier corte.\nPablo (yo) · ejecuto/apruebo · revisor final.",
    weight: 4, filled: 50,
  },
];

const BriefingPage = () => {
  const [active, setActive] = React.useState("context");
  const [content, setContent] = React.useState(() =>
    Object.fromEntries(BRIEFING_BLOCKS.map(b => [b.id, b.placeholder]))
  );

  // weighted completeness
  const totalWeight = BRIEFING_BLOCKS.reduce((s, b) => s + b.weight, 0);
  const score = Math.round(
    BRIEFING_BLOCKS.reduce((s, b) => s + b.weight * (b.filled / 100), 0) / totalWeight * 100
  );
  const scoreColor = score >= 85 ? TS_T.green : score >= 60 ? TS_T.amber : TS_T.red;

  const block = BRIEFING_BLOCKS.find(b => b.id === active);

  return (
    <div>
      <SettingsHeader
        tag="AGENT BRIEFING · ⭐ crítico"
        title="Lo que el agente sabe sobre tu negocio"
        sub="Esto es el system-prompt del agente para tu cuenta. Mientras mejor lo briefees, mejores recomendaciones · más jerga interna · menos preguntas obvias en el Inbox. El agente lee esto antes de cualquier decisión."
      />

      {/* SCORE STRIP */}
      <div style={{ display: "grid", gridTemplateColumns: "180px 1fr 200px", gap: 16, padding: "16px 18px", border: `1px solid ${scoreColor}`, borderLeft: `3px solid ${scoreColor}`, background: TS_T.surface, marginBottom: 22, alignItems: "center" }}>
        <div>
          <div style={{ fontSize: 9, color: TS_T.muteDim, letterSpacing: "0.14em", marginBottom: 4 }}>BRIEFING COMPLETENESS</div>
          <div style={{ fontFamily: TS_FS, fontSize: 38, fontWeight: 700, color: scoreColor, lineHeight: 1 }}>{score}<span style={{ fontSize: 16, color: TS_T.muteDim }}>/100</span></div>
        </div>
        <div>
          <div style={{ fontSize: 11, color: TS_T.ink, lineHeight: 1.6, marginBottom: 8 }}>
            {score >= 85 ? "Briefing sólido · el agente puede operar con autonomía calibrada." : score >= 60 ? "Briefing decente · falta detalle en stakeholders y voz para evitar preguntas obvias." : "Briefing pobre · el agente preguntará mucho hasta entender tu negocio."}
          </div>
          {/* mini bars per block */}
          <div style={{ display: "flex", gap: 3 }}>
            {BRIEFING_BLOCKS.map(b => (
              <div key={b.id} title={`${b.label} · ${b.filled}%`} style={{ flex: b.weight, height: 8, background: TS_T.bg, position: "relative", cursor: "pointer" }} onClick={() => setActive(b.id)}>
                <div style={{ position: "absolute", inset: 0, width: `${b.filled}%`, background: b.filled >= 85 ? TS_T.green : b.filled >= 60 ? TS_T.amber : TS_T.red, opacity: 0.85 }} />
              </div>
            ))}
          </div>
        </div>
        <div style={{ textAlign: "right", fontSize: 10, color: TS_T.muteDim, lineHeight: 1.6 }}>
          última edición<br />
          <span style={{ color: TS_T.cyan, fontFamily: TS_FM }}>4 may · 16:42 · Pablo</span><br />
          <span style={{ color: TS_T.muteDim, fontFamily: TS_FM, fontSize: 9 }}>v3 · 8 revisiones</span>
        </div>
      </div>

      {/* TWO-COL: blocks list + editor */}
      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 16, alignItems: "start" }}>
        {/* LIST */}
        <div style={{ border: `1px solid ${TS_T.line}` }}>
          {BRIEFING_BLOCKS.map((b, i) => {
            const isActive = b.id === active;
            const col = b.filled >= 85 ? TS_T.green : b.filled >= 60 ? TS_T.amber : TS_T.red;
            return (
              <button key={b.id} onClick={() => setActive(b.id)} style={{
                width: "100%", textAlign: "left", padding: "12px 14px",
                background: isActive ? TS_T.surface : TS_T.bg, border: "none",
                borderLeft: isActive ? `3px solid ${TS_T.amber}` : `3px solid transparent`,
                borderBottom: i < BRIEFING_BLOCKS.length - 1 ? `1px solid ${TS_T.line}` : "none",
                cursor: "pointer", display: "grid", gridTemplateColumns: "30px 1fr 30px", gap: 8, alignItems: "center",
              }}>
                <span style={{ fontFamily: TS_FM, fontSize: 11, color: isActive ? TS_T.amber : TS_T.muteDim, letterSpacing: "0.1em" }}>{b.icon}</span>
                <div>
                  <div style={{ fontSize: 12, color: isActive ? TS_T.amber : TS_T.ink, fontFamily: TS_FS, fontWeight: 500, marginBottom: 2 }}>{b.label}</div>
                  <div style={{ fontSize: 9, color: TS_T.muteDim, lineHeight: 1.4 }}>{b.sub}</div>
                </div>
                <span style={{ fontFamily: TS_FM, fontSize: 9, color: col, textAlign: "right" }}>{b.filled}%</span>
              </button>
            );
          })}
        </div>

        {/* EDITOR */}
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <span style={{ fontFamily: TS_FM, fontSize: 10, color: TS_T.amber, letterSpacing: "0.18em" }}>// {block.icon} · {block.label.toUpperCase()}</span>
            <span style={{ fontSize: 9, color: TS_T.muteDim, fontFamily: TS_FM, marginLeft: "auto" }}>peso en briefing · {block.weight}%</span>
          </div>
          <textarea
            value={content[block.id]}
            onChange={(e) => setContent(c => ({ ...c, [block.id]: e.target.value }))}
            style={{
              width: "100%", minHeight: 260, padding: "14px 16px",
              background: TS_T.surface, border: `1px solid ${TS_T.line}`, borderLeft: `3px solid ${TS_T.cyan}`,
              color: TS_T.ink, fontFamily: TS_FM, fontSize: 12, lineHeight: 1.7,
              resize: "vertical", outline: "none",
            }}
          />
          {/* AGENT SUGGESTION */}
          <div style={{ marginTop: 10, padding: "12px 14px", background: TS_T.surface, border: `1px solid ${TS_T.amber}`, borderLeftWidth: 3 }}>
            <div style={{ fontFamily: TS_FM, fontSize: 9, color: TS_T.amber, letterSpacing: "0.16em", marginBottom: 6 }}>// AGENT.SUGIERE</div>
            <div style={{ fontSize: 11, color: TS_T.ink, lineHeight: 1.6 }}>
              {block.id === "context" && "Falta mencionar el modelo de financiamiento (becas/créditos). Si 30%+ del CAC depende de planes de pago, tengo que saberlo para no recomendar segmentos sin acceso a crédito."}
              {block.id === "priorities" && "Detecté que tu meta de matriculados implica 18% growth YoY. ¿Es realista con el budget actual? Te puedo mostrar la response curve necesaria."}
              {block.id === "targets" && "Tus targets están bien definidos · agrégame también el floor de ROAS por canal si tienes mix targets diferenciados."}
              {block.id === "constraints" && "Veo NO-PAUSAR de marca pero no tienes floor de budget para marca. ¿Qué tal definir min S/ 800/día permanente?"}
              {block.id === "voice" && "Tu briefing de voz es corto. ¿Puedo ver 2-3 emails que ya enviaste a CFO/CMO? Aprendo el estilo más rápido."}
              {block.id === "antipatterns" && "Buen detalle. Estoy aplicando estas reglas como hard-stops · cualquier acción que las viole, va a tu Inbox aunque entre en thresholds auto."}
              {block.id === "glossary" && "Detecté en tus reports históricos los términos: 'cohorte de admisión', 'feria educativa', 'examen ordinario'. ¿Los agrego al glosario?"}
              {block.id === "stakeholders" && "Falta el rol de Decano Medicina con poder de veto. Esta sección está al 50% · sin ella, podría tomar decisiones que rompan políticas internas."}
            </div>
            <div style={{ marginTop: 10, display: "flex", gap: 8 }}>
              <TS_B kind="amber">APLICAR SUGERENCIA</TS_B>
              <TS_B>IGNORAR</TS_B>
            </div>
          </div>
        </div>
      </div>

      {/* HISTORY */}
      <div style={{ marginTop: 22, padding: "14px 16px", border: `1px solid ${TS_T.line}`, background: TS_T.surface }}>
        <div style={{ fontSize: 10, color: TS_T.muteDim, letterSpacing: "0.14em", marginBottom: 10 }}>// HISTORIAL DE BRIEFING · revertible 90d</div>
        {[
          { v: "v3 · ACTUAL", w: "Pablo", d: "4 may 16:42", c: "Agregó anti-pattern fragmentación + glosario stages" },
          { v: "v2", w: "Carla", d: "22 abr 11:03", c: "Actualizó targets Q2 · subió MER floor a 3.4x" },
          { v: "v1", w: "Pablo", d: "1 abr 09:18", c: "Briefing inicial post-onboarding" },
        ].map((h, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "100px 80px 100px 1fr 80px", gap: 10, padding: "8px 0", borderBottom: i < 2 ? `1px dashed ${TS_T.line}` : "none", fontSize: 10, alignItems: "center" }}>
            <span style={{ color: i === 0 ? TS_T.amber : TS_T.cyan, fontFamily: TS_FM, letterSpacing: "0.1em" }}>{h.v}</span>
            <span style={{ color: TS_T.muteDim }}>{h.w}</span>
            <span style={{ color: TS_T.muteDim, fontFamily: TS_FM }}>{h.d}</span>
            <span style={{ color: TS_T.ink, fontSize: 11 }}>{h.c}</span>
            <span style={{ textAlign: "right" }}>{i > 0 && <TS_B>RESTAURAR</TS_B>}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ─── ALERTS · BRANDING · ROUTINES · BILLING (compact) ────────────────────
const AlertsPage = () => (
  <div>
    <SettingsHeader tag="ALERTS" title="Canales y severidades" sub="Configuración granular · matriz canal × severidad · quiet hours · weekend digest." />
    <div style={{ border: `1px solid ${TS_T.line}` }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 80px 80px 80px 130px 100px", padding: "10px 14px", background: TS_T.surfaceHi, fontSize: 9, color: TS_T.muteDim, letterSpacing: "0.14em", borderBottom: `1px solid ${TS_T.line}` }}>
        <span>CANAL</span><span style={{textAlign:"center"}}>P0</span><span style={{textAlign:"center"}}>P1</span><span style={{textAlign:"center"}}>P2</span><span>FREQUENCY</span><span style={{textAlign:"right"}}>TEST</span>
      </div>
      {[
        { ch: "Dashboard (drawer)", lv: ["P0","P1","P2"], freq: "immediate" },
        { ch: "Email · pablo@bluenose.pe", lv: ["P0","P1"], freq: "digest hourly" },
        { ch: "WhatsApp · +51 999 ███ 142", lv: ["P0"], freq: "immediate" },
        { ch: "Slack · #media-alerts", lv: ["P0","P1"], freq: "immediate" },
      ].map((c,i) => (
        <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 80px 80px 80px 130px 100px", padding: "12px 14px", background: TS_T.surface, borderBottom: i < 3 ? `1px solid ${TS_T.line}` : "none", alignItems: "center", fontSize: 11 }}>
          <span style={{ color: TS_T.ink }}>{c.ch}</span>
          {["P0","P1","P2"].map(lv => (
            <span key={lv} style={{ textAlign: "center" }}>
              <span style={{ display: "inline-block", width: 28, height: 16, background: c.lv.includes(lv) ? TS_T.green : TS_T.line, position: "relative", borderRadius: 99 }}>
                <span style={{ position: "absolute", top: 2, left: c.lv.includes(lv) ? 14 : 2, width: 12, height: 12, background: TS_T.bg, borderRadius: 99 }} />
              </span>
            </span>
          ))}
          <span style={{ color: TS_T.cyan, fontFamily: TS_FM, fontSize: 10 }}>{c.freq}</span>
          <span style={{ textAlign: "right" }}><TS_B>SEND TEST</TS_B></span>
        </div>
      ))}
    </div>
    <div style={{ marginTop: 22, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
      <Field label="QUIET HOURS"><div style={{ display: "flex", gap: 8 }}><TInput type="time" defaultValue="21:00" /><TInput type="time" defaultValue="07:00" /></div></Field>
      <Field label="WEEKEND DIGEST"><TSelect defaultValue="dom 18:00" options={["dom 18:00","sáb 09:00","off"]} /></Field>
    </div>
  </div>
);

const BrandingPage = () => (
  <div>
    <SettingsHeader tag="BRANDING · WHITE-LABEL" title="Tu marca, no la nuestra" sub="Logo · color primario · dominio custom · footer credit. Aplicado a toda la UI en runtime." />
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
      <Field label="LOGO (PNG/SVG)"><div style={{ padding: "30px 14px", border: `1px dashed ${TS_T.line}`, textAlign: "center", color: TS_T.muteDim, fontSize: 11, background: TS_T.surface }}>arrastra archivo · max 2MB · reemplaza "MEDIAAGENT"</div></Field>
      <Field label="COLOR PRIMARIO" sub="reemplaza el ámbar default">
        <div style={{ display: "flex", gap: 6 }}>
          {["#ffb84d","#5ad0e8","#a78bfa","#4ade80","#f87171","#ec4899"].map(c => (
            <div key={c} style={{ width: 40, height: 40, background: c, cursor: "pointer", border: c === "#ffb84d" ? `2px solid ${TS_T.ink}` : "none" }} />
          ))}
        </div>
      </Field>
      <Field label="DOMINIO CUSTOM"><TInput placeholder="mediaagent.tu-empresa.com" defaultValue="mediaagent.bluenose.pe" /></Field>
      <Field label="POWERED BY MEDIAAGENT" sub="footer credit"><TSelect defaultValue="hide" options={[{value:"show",label:"Show · default"},{value:"hide",label:"Hide · enterprise"}]} /></Field>
    </div>
    <div style={{ marginTop: 24, padding: "14px 16px", background: TS_T.surface, border: `1px solid ${TS_T.line}` }}>
      <div style={{ fontSize: 10, color: TS_T.muteDim, letterSpacing: "0.14em", marginBottom: 10 }}>PREVIEW · ticker con tu branding</div>
      <div style={{ height: 38, background: TS_T.bg, border: `1px solid ${TS_T.line}`, display: "flex", alignItems: "center", padding: "0 16px", fontFamily: TS_FM, fontSize: 11, color: TS_T.amber, letterSpacing: "0.16em" }}>
        BLUENOSE · MEDIA OS
        <span style={{ marginLeft: 24, color: TS_T.green }}>● live</span>
        <span style={{ marginLeft: "auto", color: TS_T.muteDim, fontSize: 9 }}>powered by mediaagent · OFF</span>
      </div>
    </div>
  </div>
);

const RoutinesPage = () => (
  <div>
    <SettingsHeader tag="ROUTINES · próximamente" title="Cadencias programadas del agente" sub="Daily audit · weekly review · monthly MMM rebuild · experiment check-in. Configurable en sesión 3." />
    {[
      { n: "Daily audit", c: "07:00 GMT-5 todos los días", st: "default · activo" },
      { n: "Weekly review", c: "Lunes 09:00", st: "default · activo" },
      { n: "Monthly MMM rebuild", c: "Día 1 · 04:00", st: "default · activo" },
      { n: "Experiment check-in", c: "ad-hoc · cuando hay test live", st: "auto-trigger" },
    ].map((r, i) => (
      <div key={i} style={{ padding: "14px 16px", border: `1px solid ${TS_T.line}`, background: TS_T.surface, marginBottom: 8, display: "grid", gridTemplateColumns: "1fr 200px 140px 100px", gap: 12, alignItems: "center" }}>
        <div>
          <div style={{ fontSize: 12, color: TS_T.ink, fontWeight: 500 }}>{r.n}</div>
          <div style={{ fontSize: 10, color: TS_T.muteDim, marginTop: 3 }}>{r.c}</div>
        </div>
        <span style={{ fontSize: 10, color: TS_T.green, fontFamily: TS_FM }}>● {r.st}</span>
        <span style={{ fontSize: 10, color: TS_T.muteDim }}>last run · hace 4h</span>
        <button disabled style={{ padding: "6px 12px", background: TS_T.bg, color: TS_T.muteDim, border: `1px solid ${TS_T.line}`, fontFamily: TS_FM, fontSize: 10, letterSpacing: "0.12em", cursor: "not-allowed" }}>CONFIGURAR · V1</button>
      </div>
    ))}
  </div>
);

const BillingPage = () => (
  <div>
    <SettingsHeader tag="BILLING · self-hosted enterprise" title="License & deployment info" sub="Licencia perpetua single-tenant · upgrades vía tu integrador · sin Stripe in-app." />
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
      {[
        { k: "PRODUCTO", v: "MediaAgent Enterprise · Single-Cliente" },
        { k: "LICENSE HASH", v: "8c2f1ab · sha256 verificado" },
        { k: "VENCE", v: "2026-12-31 · 239 días" },
        { k: "INSTALL FINGERPRINT", v: "srv-pe-prd-04 · v0.4.2" },
        { k: "ÚLTIMA ACTUALIZACIÓN", v: "5 may 2026 · vía bluenose ops" },
        { k: "CONTACTO SOPORTE", v: "pablo@bluenose.pe" },
      ].map((kv, i) => (
        <div key={i} style={{ padding: "12px 14px", border: `1px solid ${TS_T.line}`, background: TS_T.surface }}>
          <div style={{ fontSize: 9, color: TS_T.muteDim, letterSpacing: "0.14em", marginBottom: 6 }}>{kv.k}</div>
          <div style={{ fontSize: 12, color: TS_T.ink, fontFamily: TS_FM }}>{kv.v}</div>
        </div>
      ))}
    </div>
    <div style={{ marginTop: 22 }}>
      <div style={{ fontSize: 10, color: TS_T.muteDim, letterSpacing: "0.14em", marginBottom: 10 }}>CHANGELOG · last 5</div>
      {[
        { v: "v0.4.2", d: "2026-05-05", c: "Actions Inbox · HITL flow · conversation pane" },
        { v: "v0.4.1", d: "2026-04-22", c: "Optimize screen · cost ledger · bidders status" },
        { v: "v0.4.0", d: "2026-04-08", c: "Connect screen · platform integrations" },
        { v: "v0.3.5", d: "2026-03-19", c: "Comply · 6 países LATAM · regulatory radar" },
        { v: "v0.3.4", d: "2026-03-05", c: "Creative matrix 4D · fatigue auto-pause" },
      ].map((cl, i) => (
        <div key={i} style={{ padding: "8px 0", borderBottom: i < 4 ? `1px dashed ${TS_T.line}` : "none", display: "grid", gridTemplateColumns: "70px 100px 1fr", gap: 10, fontSize: 11 }}>
          <span style={{ color: TS_T.cyan, fontFamily: TS_FM }}>{cl.v}</span>
          <span style={{ color: TS_T.muteDim, fontFamily: TS_FM, fontSize: 10 }}>{cl.d}</span>
          <span style={{ color: TS_T.ink }}>{cl.c}</span>
        </div>
      ))}
    </div>
  </div>
);

// ─── SHELL ───────────────────────────────────────────────────────────────
const SettingsScreen = () => {
  const [section, setSection] = React.useState("hitl");
  const [dirty, setDirty] = React.useState(false);

  const renderSection = () => {
    if (section === "profile") return <ProfilePage />;
    if (section === "members") return <MembersPage />;
    if (section === "permissions") return <PermissionsPage />;
    if (section === "briefing") return <BriefingPage />;
    if (section === "hitl") return <HITLPage />;
    if (section === "alertsCfg") return <AlertsPage />;
    if (section === "branding") return <BrandingPage />;
    if (section === "routinesCfg") return <RoutinesPage />;
    if (section === "billing") return <BillingPage />;
    return null;
  };

  return (
    <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", minHeight: "100%" }}>
      {/* SIDEBAR */}
      <div style={{ borderRight: `1px solid ${TS_T.line}`, padding: "20px 0", background: TS_T.surface, position: "sticky", top: 0, height: "fit-content" }}>
        <div style={{ padding: "0 22px 14px", fontSize: 10, color: TS_T.amber, letterSpacing: "0.18em", fontFamily: TS_FM, borderBottom: `1px solid ${TS_T.line}`, marginBottom: 8 }}>// SETTINGS</div>
        {SECTIONS.map(s => (
          <button key={s.id} onClick={() => !s.soon && setSection(s.id)} disabled={s.soon} style={{
            width: "100%", padding: "10px 22px", textAlign: "left", background: section === s.id ? TS_T.bg : "transparent",
            border: "none", borderLeft: section === s.id ? `2px solid ${TS_T.amber}` : "2px solid transparent",
            color: s.soon ? TS_T.muteDim : section === s.id ? TS_T.amber : TS_T.ink, fontFamily: TS_FS, fontSize: 12,
            cursor: s.soon ? "not-allowed" : "pointer", display: "flex", justifyContent: "space-between", alignItems: "center",
          }}>
            <span>{s.label}</span>
            {s.star && <span style={{ color: TS_T.amber, fontSize: 10 }}>⭐</span>}
            {s.soon && <span style={{ fontSize: 9, color: TS_T.muteDim, fontFamily: TS_FM, letterSpacing: "0.1em" }}>SOON</span>}
          </button>
        ))}
      </div>

      {/* MAIN */}
      <div style={{ padding: "26px 28px 100px", overflowY: "auto" }}>
        {renderSection()}
      </div>

      {/* SAVE BAR */}
      {dirty && (
        <div style={{ position: "fixed", bottom: 0, left: 240, right: 0, padding: "14px 28px", background: TS_T.surfaceHi, borderTop: `1px solid ${TS_T.amber}`, display: "flex", alignItems: "center", gap: 12, zIndex: 100 }}>
          <span style={{ color: TS_T.amber, fontFamily: TS_FM, fontSize: 11, letterSpacing: "0.12em" }}>● 12 cambios sin guardar</span>
          <span style={{ marginLeft: "auto" }}><TS_B onClick={() => setDirty(false)}>DESCARTAR</TS_B></span>
          <TS_B kind="green" onClick={() => setDirty(false)}>GUARDAR</TS_B>
        </div>
      )}
    </div>
  );
};

window.SettingsScreen = SettingsScreen;
