// ─── ExpertSteam — app screens ──────────────────────────────────────
// Login → Hub → (Wizard | Audit | Guides) ⇄ Results / Report

const ES_SCREENS = [
  { id: "hub",      label: "Hub", section: null },
  { id: "wizard",   label: "Diagnóstico individual", section: "Análisis" },
  { id: "results",  label: "Resultados", section: "Análisis" },
  { id: "audit",    label: "Auditoría de trampas", section: "Análisis" },
  { id: "guides",   label: "Guías y diagramas", section: "Recursos" },
  { id: "report",   label: "Reporte imprimible", section: "Recursos" },
];

// ─── 1. LOGIN ───────────────────────────────────────────────────────
function ESLogin({ onLogin, variant }) {
  const [user, setUser] = React.useState("");
  const [pass, setPass] = React.useState("");
  const [showPass, setShowPass] = React.useState(false);
  return (
    <div data-screen-label="ExpertSteam Login" style={{
      minHeight: "calc(100vh - 80px)",
      display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)",
      gap: 0,
    }}>
      {/* Left — branding pane (always dark, brand showcase) */}
      <div style={{
        position: "relative",
        background: "linear-gradient(160deg, #0D1117 0%, #141B24 50%, #1C2A38 100%)",
        padding: "var(--pad-5)",
        overflow: "hidden",
        display: "flex", flexDirection: "column", justifyContent: "space-between",
        color: "#f1f5fb",
        minHeight: 540,
      }}>
        {/* Decorative grid + accent glow */}
        <div aria-hidden style={{
          position: "absolute", inset: 0, pointerEvents: "none",
          backgroundImage:
            "linear-gradient(rgba(240,135,30,.06) 1px, transparent 1px), linear-gradient(90deg, rgba(240,135,30,.06) 1px, transparent 1px)",
          backgroundSize: "28px 28px",
          maskImage: "radial-gradient(ellipse at 30% 50%, black 0%, transparent 75%)",
        }} />
        <div aria-hidden style={{
          position: "absolute", top: -120, right: -120, width: 360, height: 360,
          background: "radial-gradient(circle, rgba(240,135,30,.28) 0%, transparent 60%)",
          pointerEvents: "none",
        }} />

        {/* Top — logo + product name */}
        <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 14 }}>
          <img src="assets/ceia-mark.png" alt="CEIA" width={56} height={56} style={{ display: "block", flexShrink: 0 }} />
          <div>
            <div style={{
              fontFamily: "var(--font-display)",
              fontSize: 26, fontWeight: 600, lineHeight: 1,
              color: "#ffffff", letterSpacing: "-.02em",
            }}>ExpertSteam™</div>
            <div className="mono" style={{ fontSize: 10, color: "#F0871E", letterSpacing: ".24em", textTransform: "uppercase", marginTop: 6, fontWeight: 600 }}>
              by CEIA Ingeniería
            </div>
          </div>
        </div>

        {/* Middle — message */}
        <div style={{ position: "relative" }}>
          <div className="mono" style={{ fontSize: 10.5, color: "#F0871E", letterSpacing: ".24em", textTransform: "uppercase", marginBottom: "var(--gap-3)", fontWeight: 600 }}>
            <span style={{
              display: "inline-block", width: 6, height: 6, borderRadius: 999,
              background: "#F0871E", boxShadow: "0 0 8px #F0871E", marginRight: 8, verticalAlign: "middle",
            }} />
            Acceso restringido
          </div>
          <h1 className="display" style={{
            fontSize: "clamp(36px, 4vw, 54px)", fontWeight: 400, margin: 0,
            lineHeight: 1.08, color: "#ffffff",
          }}>
            Diagnóstico técnico<br/>
            <em style={{
              fontStyle: variant === "schematic" ? "italic" : "normal",
              color: "#F0871E",
              fontWeight: variant === "brutalist" ? 800 : "inherit",
            }}>
              para plantas de vapor.
            </em>
          </h1>
          <p style={{ marginTop: "var(--gap-3)", fontSize: 15, color: "#94a3b8", maxWidth: 440, lineHeight: 1.55 }}>
            Captura síntomas, mediciones y condiciones de operación.
            Obtenga un diagnóstico ponderado con plan de acción trazable.
          </p>

          {/* Feature ticks */}
          <ul style={{ listStyle: "none", padding: 0, margin: "var(--gap-3) 0 0", display: "grid", gap: 8 }}>
            {[
              "23 modos de falla evaluados",
              "10+ reglas críticas de severidad",
              "Reporte imprimible trazable",
            ].map(t => (
              <li key={t} style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 13, color: "#c4d2e2" }}>
                <span style={{
                  width: 18, height: 18,
                  border: "1px solid #F0871E",
                  borderRadius: variant === "brutalist" ? 0 : 999,
                  display: "grid", placeItems: "center",
                  color: "#F0871E", flexShrink: 0,
                }}><IconCheck size={11}/></span>
                <span>{t}</span>
              </li>
            ))}
          </ul>
        </div>

        {/* Bottom — metadata */}
        <div style={{ position: "relative", display: "flex", justifyContent: "space-between", alignItems: "end", paddingTop: "var(--gap-3)", borderTop: "1px solid rgba(240,135,30,.18)" }}>
          <div className="mono" style={{ fontSize: 10, color: "#6a7c8e", letterSpacing: ".24em", textTransform: "uppercase" }}>
            DOC.LOGIN-001 · Rev. A
          </div>
          <div className="mono" style={{ fontSize: 10, color: "#6a7c8e", letterSpacing: ".24em", textTransform: "uppercase" }}>
            CONFIDENCIAL
          </div>
        </div>
      </div>

      {/* Right — form */}
      <div style={{
        padding: "var(--pad-5)",
        display: "flex", flexDirection: "column", justifyContent: "center",
        background: "var(--bg)",
      }}>
        <div style={{ maxWidth: 380, width: "100%", marginInline: "auto" }}>
          <div className="eyebrow-muted">Inicio de sesión · 01</div>
          <h2 className="display" style={{ fontSize: 36, fontWeight: 400, marginTop: 8, marginBottom: "var(--gap-4)" }}>
            Bienvenido al sistema.
          </h2>

          <form onSubmit={(e) => { e.preventDefault(); onLogin(); }} style={{ display: "grid", gap: "var(--gap-3)" }}>
            <label>
              <div className="mono" style={{ fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 8 }}>
                Usuario
              </div>
              <div style={{ position: "relative" }}>
                <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-soft)" }}>
                  <IconUser size={16}/>
                </span>
                <input className="input" placeholder="ingeniero@ceia.co"
                       value={user} onChange={e => setUser(e.target.value)}
                       style={{ paddingLeft: 38 }} />
              </div>
            </label>

            <label>
              <div className="mono" style={{ fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 8 }}>
                Contraseña
              </div>
              <div style={{ position: "relative" }}>
                <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-soft)" }}>
                  <IconLock size={16}/>
                </span>
                <input className="input" type={showPass ? "text" : "password"} placeholder="••••••••"
                       value={pass} onChange={e => setPass(e.target.value)}
                       style={{ paddingLeft: 38, paddingRight: 70 }} />
                <button type="button" onClick={() => setShowPass(s => !s)} className="mono"
                  style={{
                    position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)",
                    background: "none", border: 0, color: "var(--fg-muted)",
                    fontSize: 10, letterSpacing: ".14em", textTransform: "uppercase", cursor: "pointer",
                  }}>
                  {showPass ? "Ocultar" : "Mostrar"}
                </button>
              </div>
            </label>

            <button className="btn btn-primary" type="submit" style={{ marginTop: 8, padding: ".9em 1.25em" }}>
              Acceder al sistema <IconArrowRight size={16}/>
            </button>

            <a href="#" className="link-anim mono" style={{
              fontSize: 11, color: "var(--fg-muted)", letterSpacing: ".14em",
              textTransform: "uppercase", textDecoration: "none", justifySelf: "start", marginTop: 4,
            }}>
              ¿Olvidó su contraseña?
            </a>
          </form>
        </div>
      </div>
    </div>
  );
}

// ─── 2. HUB ─────────────────────────────────────────────────────────
const HUB_MODULES = [
  { id: "wizard", code: "M01", title: "Diagnóstico individual", desc: "Captura paso a paso una trampa o equipo y obtenga su modo de falla más probable.",
    icon: "gauge", stat: "7 pasos · ~4 min" },
  { id: "audit",  code: "M02", title: "Auditoría de trampas", desc: "Análisis a escala de planta. Carga masiva, scoring por trampa y resumen ejecutivo.",
    icon: "chart", stat: "+ planta completa" },
  { id: "guides", code: "M03", title: "Guías y diagramas", desc: "Referencias técnicas: tipos de trampa, esquemáticos, normativa y mejores prácticas.",
    icon: "book", stat: "23 documentos" },
];

function ESHub({ onOpen, variant }) {
  const isBrutalist = variant === "brutalist";
  return (
    <div data-screen-label="ExpertSteam Hub" className="container" style={{ paddingTop: "var(--pad-5)", paddingBottom: "var(--pad-5)" }}>
      {/* Greeting */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: "var(--gap-5)", alignItems: "end", marginBottom: "var(--gap-5)" }}>
        <div>
          <div className="eyebrow-muted">Sesión activa · ing. Juan C. Rodríguez</div>
          <h1 className="display" style={{ fontSize: "clamp(40px, 5vw, 68px)", fontWeight: 400, marginTop: "var(--gap-2)", lineHeight: 1.05 }}>
            Buen día, Juan.<br/>
            <em style={{ fontStyle: variant === "schematic" ? "italic" : "normal", color: "var(--accent)" }}>¿Qué planta auditamos hoy?</em>
          </h1>
        </div>
        <div className="card" style={{ padding: "var(--pad-3)" }}>
          <div className="eyebrow-muted" style={{ marginBottom: 10 }}>Actividad reciente</div>
          {[
            { d: "20/05", k: "Auditoría", v: "Lácteos Andinos · 84 trampas", c: "var(--good)" },
            { d: "18/05", k: "Diagnóstico", v: "TR-014 · F02 Falla abierta", c: "var(--critical)" },
            { d: "15/05", k: "Reporte", v: "Cervecería del Valle · Rev. B", c: "var(--accent)" },
          ].map((r, i) => (
            <div key={i} style={{
              display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 10, alignItems: "center",
              padding: "8px 0", borderTop: i > 0 ? "1px dashed var(--line-soft)" : "none", fontSize: 13,
            }}>
              <span className="mono" style={{ fontSize: 10, color: "var(--fg-soft)" }}>{r.d}</span>
              <span style={{ color: "var(--fg-muted)" }}><b style={{ color: "var(--fg)", fontWeight: 600 }}>{r.k}</b> — {r.v}</span>
              <span style={{ width: 6, height: 6, borderRadius: isBrutalist ? 0 : 999, background: r.c }} />
            </div>
          ))}
        </div>
      </div>

      {/* Module cards */}
      <div className="eyebrow-muted" style={{ marginBottom: "var(--gap-3)" }}>Módulos disponibles · {HUB_MODULES.length}</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: "var(--gap-2)" }}>
        {HUB_MODULES.map((m, i) => (
          <button key={m.id} className="card fade-up"
            onClick={() => onOpen(m.id)}
            style={{
              padding: "var(--pad-3)", textAlign: "left", cursor: "pointer",
              display: "flex", flexDirection: "column", gap: "var(--gap-2)",
              minHeight: 280, background: "var(--card-bg)",
              animationDelay: `${i * 80}ms`,
              border: variant === "brutalist" ? "1.5px solid var(--line)" : "var(--card-bd)",
              transition: "transform .15s, box-shadow .15s, border-color .15s",
              borderRadius: "var(--card-r)",
              color: "var(--fg)",
              fontFamily: "inherit",
            }}
            onMouseEnter={e => { e.currentTarget.style.transform = "translateY(-3px)"; e.currentTarget.style.borderColor = "var(--accent)"; }}
            onMouseLeave={e => { e.currentTarget.style.transform = ""; e.currentTarget.style.borderColor = ""; }}
          >
            <header style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <div style={{ color: "var(--accent)" }}><ServiceIcon name={m.icon} size={28} /></div>
              <span className="mono" style={{ fontSize: 10, color: "var(--fg-soft)", letterSpacing: ".14em" }}>{m.code}</span>
            </header>
            <div style={{ marginTop: "auto" }}>
              <h3 style={{ fontSize: 20, fontWeight: 600, margin: 0, marginBottom: 8, letterSpacing: "-.01em" }}>{m.title}</h3>
              <p style={{ margin: 0, fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.55 }}>{m.desc}</p>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: "var(--gap-2)", borderTop: "1px dashed var(--line-soft)" }}>
              <span className="mono" style={{ fontSize: 11, color: "var(--fg-soft)", letterSpacing: ".08em" }}>{m.stat}</span>
              <span style={{ color: "var(--accent)" }}><IconArrowRight size={16}/></span>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

// ─── 3. WIZARD — Symptoms step ──────────────────────────────────────
const WIZARD_STEPS = [
  { n: 1, label: "Proyecto" },
  { n: 2, label: "Equipo" },
  { n: 3, label: "Trampa" },
  { n: 4, label: "Operación" },
  { n: 5, label: "Síntomas" },
  { n: 6, label: "Línea retorno" },
  { n: 7, label: "Mediciones" },
];

const SYMPTOM_GROUPS = [
  { label: "Visuales / acústicos", items: [
    { id: "leak", text: "Fuga visible de vapor en la trampa o línea aguas abajo" },
    { id: "noise_continuous", text: "Ruido continuo (silbido constante)" },
    { id: "noise_intermittent", text: "Ruido intermitente (golpeteo / tic-tac)" },
    { id: "vibration", text: "Vibración inusual o golpe de ariete" },
    { id: "blowback", text: "Reverso o soplado de vapor por la descarga" },
  ]},
  { label: "Térmicos", items: [
    { id: "cold_body", text: "Cuerpo de la trampa frío respecto a la entrada" },
    { id: "hot_outlet", text: "Descarga con temperatura excesiva" },
    { id: "temp_delta_low", text: "ΔT entre entrada y salida menor al esperado" },
    { id: "ambient_loss", text: "Pérdidas notorias hacia el ambiente" },
  ]},
  { label: "Operación / proceso", items: [
    { id: "process_low", text: "Equipo de proceso no alcanza temperatura objetivo" },
    { id: "cycle_long", text: "Tiempo de ciclo del proceso alargado" },
    { id: "condensate_excess", text: "Tanque de condensados sobre-flujo" },
    { id: "condensate_dry", text: "Línea de condensado seca o sin retorno" },
  ]},
  { label: "Indicadores indirectos", items: [
    { id: "boiler_extra", text: "Caldera trabajando más allá de su carga normal" },
    { id: "make_up_high", text: "Agua de reposición (make-up) elevada" },
    { id: "fuel_spike", text: "Consumo de combustible recientemente incrementado" },
  ]},
];

function ESWizard({ onNext, onBack, variant }) {
  const [selected, setSelected] = React.useState(new Set(["leak", "noise_continuous", "boiler_extra"]));
  const toggle = (id) => {
    setSelected(prev => {
      const n = new Set(prev);
      n.has(id) ? n.delete(id) : n.add(id);
      return n;
    });
  };
  const currentStep = 5;

  return (
    <div data-screen-label="ExpertSteam Wizard" className="container-narrow" style={{ paddingTop: "var(--pad-4)", paddingBottom: "var(--pad-5)" }}>
      {/* Progress rail */}
      <div className="card" style={{ padding: "var(--pad-2)", marginBottom: "var(--gap-4)" }}>
        <div className="mono" style={{
          display: "flex", justifyContent: "space-between", alignItems: "center",
          fontSize: 10, color: "var(--fg-soft)", letterSpacing: ".18em", textTransform: "uppercase",
          marginBottom: 12,
        }}>
          <span>Diagnóstico individual · TR-014</span>
          <span>Paso {currentStep} / {WIZARD_STEPS.length}</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: `repeat(${WIZARD_STEPS.length}, 1fr)`, gap: 6 }}>
          {WIZARD_STEPS.map(s => {
            const isDone = s.n < currentStep;
            const isActive = s.n === currentStep;
            return (
              <div key={s.n}>
                <div style={{
                  height: 3,
                  background: isDone || isActive ? "var(--accent)" : "var(--line)",
                  marginBottom: 6,
                  transition: "background .25s",
                }} />
                <div className="mono" style={{
                  fontSize: 10, letterSpacing: ".08em",
                  color: isActive ? "var(--accent)" : (isDone ? "var(--fg)" : "var(--fg-soft)"),
                  fontWeight: isActive ? 600 : 400,
                }}>
                  {String(s.n).padStart(2,'0')} · {s.label}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Step header */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.3fr) minmax(0, 1fr)", gap: "var(--gap-5)", marginBottom: "var(--gap-4)" }}>
        <div>
          <div className="eyebrow">Paso 05 / Síntomas observados</div>
          <h1 className="display" style={{ fontSize: "clamp(36px, 4vw, 52px)", fontWeight: 400, marginTop: "var(--gap-2)", lineHeight: 1.1 }}>
            ¿Qué se observa <em style={{ fontStyle: variant === "schematic" ? "italic" : "normal", color: "var(--accent)" }}>en planta?</em>
          </h1>
          <p style={{ color: "var(--fg-muted)", marginTop: "var(--gap-2)", lineHeight: 1.6 }}>
            Seleccione todos los síntomas que aplican a la trampa o línea bajo análisis.
            Cada selección modifica el peso de los modos de falla candidatos.
          </p>
        </div>
        <div className="card" style={{ padding: "var(--pad-3)" }}>
          <div className="eyebrow-muted" style={{ marginBottom: 10 }}>Resumen en vivo</div>
          <div style={{ display: "grid", gap: 6, fontSize: 13 }}>
            <Row k="Síntomas" v={String(selected.size).padStart(2, '0')} />
            <Row k="Hipótesis activa" v="F02 · Falla en abierto" hl />
            <Row k="Probabilidad" v="84%" />
            <Row k="Severidad estimada" v="ALTA" sev />
            <Row k="Confianza actual" v="Media" />
          </div>
          <div className="hairline-h" style={{ margin: "12px 0" }} />
          <p style={{ margin: 0, fontSize: 12, color: "var(--fg-muted)" }}>
            El motor recalcula con cada cambio. Continúe al paso 06 para refinar
            la línea de retorno y subir la confianza.
          </p>
        </div>
      </div>

      {/* Symptom groups */}
      <div style={{ display: "grid", gap: "var(--gap-3)" }}>
        {SYMPTOM_GROUPS.map((g, i) => (
          <fieldset key={g.label} style={{ border: 0, padding: 0, margin: 0 }}>
            <legend style={{ marginBottom: "var(--gap-2)", display: "flex", alignItems: "center", gap: 10, width: "100%" }}>
              <span className="mono" style={{ fontSize: 10, color: "var(--fg-soft)", letterSpacing: ".18em" }}>0{i+1}</span>
              <span style={{ fontSize: 14, fontWeight: 600 }}>{g.label}</span>
              <span style={{ flex: 1, height: 1, background: "var(--line-soft)" }} />
              <span className="mono" style={{ fontSize: 10, color: "var(--fg-soft)" }}>
                {g.items.filter(it => selected.has(it.id)).length}/{g.items.length}
              </span>
            </legend>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 8 }}>
              {g.items.map(it => {
                const checked = selected.has(it.id);
                return (
                  <label key={it.id}
                    style={{
                      display: "flex", gap: 12, alignItems: "flex-start",
                      padding: "12px 14px",
                      border: "1px solid",
                      borderColor: checked ? "var(--accent)" : "var(--line)",
                      borderRadius: "var(--card-r)",
                      background: checked ? "var(--accent-soft)" : "var(--card-bg)",
                      cursor: "pointer",
                      transition: "all .15s ease",
                    }}
                  >
                    <input type="checkbox" checked={checked} onChange={() => toggle(it.id)}
                      style={{ accentColor: "var(--accent)", marginTop: 2, flexShrink: 0 }}/>
                    <span style={{ fontSize: 13, color: "var(--fg)", lineHeight: 1.45 }}>{it.text}</span>
                  </label>
                );
              })}
            </div>
          </fieldset>
        ))}
      </div>

      {/* Footer nav */}
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        marginTop: "var(--gap-5)", paddingTop: "var(--gap-3)", borderTop: "1px solid var(--line)",
      }}>
        <button className="btn btn-ghost" onClick={onBack}>
          <IconChevronL size={14}/> Atrás · Operación
        </button>
        <span className="mono" style={{ fontSize: 10, color: "var(--fg-soft)", letterSpacing: ".14em", textTransform: "uppercase" }}>
          Guardado automáticamente · hace 12s
        </span>
        <button className="btn btn-primary" onClick={onNext}>
          Continuar · Línea retorno <IconChevronR size={14}/>
        </button>
      </div>
    </div>
  );
}

function Row({ k, v, hl, sev }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
      <span style={{ color: "var(--fg-muted)", fontSize: 12 }}>{k}</span>
      <span className={hl ? "mono" : "mono"} style={{
        fontWeight: hl ? 600 : 500,
        color: sev ? "var(--critical)" : (hl ? "var(--accent)" : "var(--fg)"),
        fontSize: 13,
      }}>{v}</span>
    </div>
  );
}

// ─── 4. RESULTS PANEL ───────────────────────────────────────────────
function ESResults({ onBack, onPrint, variant }) {
  const isBrutalist = variant === "brutalist";

  const probability = 84;
  const candidates = [
    { code: "F02", name: "Falla en abierto (blow-through)", prob: 84, sev: "ALTA", isPrimary: true },
    { code: "F07", name: "Asiento erosionado", prob: 41, sev: "MEDIA" },
    { code: "F11", name: "Trampa subdimensionada", prob: 23, sev: "MEDIA" },
    { code: "F19", name: "Aislamiento deficiente", prob: 14, sev: "BAJA" },
  ];

  return (
    <div data-screen-label="ExpertSteam Results" className="container-narrow" style={{ paddingTop: "var(--pad-4)", paddingBottom: "var(--pad-5)" }}>
      {/* Header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "var(--gap-3)" }}>
        <button className="btn btn-ghost" onClick={onBack}>
          <IconChevronL size={14}/> Volver al wizard
        </button>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn btn-ghost"><IconDownload size={14}/> Exportar</button>
          <button className="btn btn-primary" onClick={onPrint}><IconPrint size={14}/> Generar reporte</button>
        </div>
      </div>

      <div className="eyebrow">Diagnóstico · TR-014 · Lácteos Andinos</div>
      <h1 className="display" style={{ fontSize: "clamp(40px, 5vw, 64px)", fontWeight: 400, marginTop: "var(--gap-2)", marginBottom: "var(--gap-2)", lineHeight: 1.05 }}>
        Falla más probable:<br/>
        <em style={{ fontStyle: variant === "schematic" ? "italic" : "normal", color: "var(--accent)" }}>
          F02 · Falla en abierto
        </em>
      </h1>

      {/* Top KPI strip */}
      <div className="card" style={{ padding: 0, marginTop: "var(--gap-3)", marginBottom: "var(--gap-4)", overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)" }}>
          <KPICell label="Probabilidad" value={`${probability}%`} caption="Muy alta" accent />
          <KPICell label="Severidad" value="ALTA" caption="Riesgo operativo" />
          <KPICell label="Confianza" value="Media" caption="14 / 20 puntos" />
          <KPICell label="Pérdida estim." value="0.42 t/h" caption="≈ US$ 2.8k/mes" isLast />
        </div>
      </div>

      {/* Probability visualization */}
      <div className="card" style={{ padding: "var(--pad-3)", marginBottom: "var(--gap-3)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "var(--gap-3)" }}>
          <div>
            <div className="eyebrow-muted">Candidatos ponderados</div>
            <h3 style={{ fontSize: 18, fontWeight: 600, margin: "4px 0 0" }}>4 modos de falla evaluados</h3>
          </div>
          <span className="tag">Top 1 confirma diagnóstico</span>
        </div>
        <div style={{ display: "grid", gap: 10 }}>
          {candidates.map(c => (
            <div key={c.code} style={{ display: "grid", gridTemplateColumns: "auto 1fr auto auto", gap: 16, alignItems: "center" }}>
              <span className="mono" style={{ fontSize: 12, color: c.isPrimary ? "var(--accent)" : "var(--fg-soft)", fontWeight: c.isPrimary ? 600 : 400, width: 32 }}>
                {c.code}
              </span>
              <div>
                <div style={{ fontSize: 14, fontWeight: c.isPrimary ? 600 : 500, color: "var(--fg)" }}>{c.name}</div>
                <div style={{
                  height: 4, marginTop: 6,
                  background: "var(--line-soft)",
                  borderRadius: isBrutalist ? 0 : 2, overflow: "hidden",
                }}>
                  <div style={{
                    width: `${c.prob}%`, height: "100%",
                    background: c.isPrimary ? "var(--accent)" : "var(--fg-soft)",
                    borderRadius: isBrutalist ? 0 : 2,
                    transition: "width 1s cubic-bezier(.2,.7,.2,1)",
                  }} />
                </div>
              </div>
              <span className="mono" style={{ fontSize: 13, fontWeight: 600, color: c.isPrimary ? "var(--accent)" : "var(--fg)", width: 44, textAlign: "right" }}>
                {c.prob}%
              </span>
              <span className="mono" style={{
                fontSize: 10, letterSpacing: ".14em", textTransform: "uppercase",
                color: c.sev === "ALTA" ? "var(--critical)" : (c.sev === "MEDIA" ? "var(--warn)" : "var(--fg-muted)"),
                width: 56, textAlign: "right",
              }}>
                {c.sev}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Recommendations + Tests grid */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: "var(--gap-3)", marginBottom: "var(--gap-3)" }}>
        <div className="card" style={{ padding: "var(--pad-3)" }}>
          <div className="eyebrow">Plan de acción</div>
          <h3 style={{ fontSize: 18, fontWeight: 600, margin: "4px 0 var(--gap-2)" }}>Acciones recomendadas</h3>
          <ol style={{ paddingLeft: 0, listStyle: "none", margin: 0, display: "grid", gap: 12 }}>
            {[
              { t: "Aislar la trampa y verificar visualmente fuga de vapor por descarga.", d: "Operación · 15 min" },
              { t: "Si confirma blow-through, sustituir el elemento interno o la trampa completa según marca y serie.", d: "Mantenimiento · 90 min" },
              { t: "Verificar dimensionamiento contra hoja de proceso original.", d: "Ingeniería · 30 min" },
              { t: "Re-medir consumo de planta a las 24 h para cuantificar recuperación.", d: "Operación · 24 h" },
            ].map((step, i) => (
              <li key={i} style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 14, alignItems: "flex-start" }}>
                <span className="mono" style={{
                  width: 28, height: 28, borderRadius: isBrutalist ? 0 : 999,
                  background: "var(--accent)", color: "white",
                  display: "grid", placeItems: "center", fontSize: 12, fontWeight: 600,
                  flexShrink: 0,
                }}>{i+1}</span>
                <div>
                  <div style={{ fontSize: 14, lineHeight: 1.45 }}>{step.t}</div>
                  <div className="mono" style={{ marginTop: 4, fontSize: 11, color: "var(--fg-soft)", letterSpacing: ".08em" }}>
                    {step.d}
                  </div>
                </div>
              </li>
            ))}
          </ol>
        </div>

        <div className="card" style={{ padding: "var(--pad-3)" }}>
          <div className="eyebrow-muted">Pruebas de verificación</div>
          <h3 style={{ fontSize: 16, fontWeight: 600, margin: "4px 0 var(--gap-2)" }}>Ensayos sugeridos</h3>
          <div style={{ display: "grid", gap: 8 }}>
            {[
              { t: "Ultrasonido a la descarga", v: "Espera ≥ 80 dB" },
              { t: "Termografía cuerpo vs salida", v: "ΔT < 10 °C" },
              { t: "Conductividad de condensado", v: "Tendencia ↑" },
              { t: "Estado de empaque" },
            ].map((p, i) => (
              <div key={i} style={{
                display: "grid", gridTemplateColumns: "1fr auto", gap: 8, alignItems: "baseline",
                padding: "8px 0", borderTop: i > 0 ? "1px dashed var(--line-soft)" : "none",
              }}>
                <span style={{ fontSize: 13 }}>{p.t}</span>
                <span className="mono" style={{ fontSize: 11, color: "var(--fg-soft)" }}>{p.v || "—"}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Critical rule applied */}
      <div style={{
        padding: "var(--pad-3)",
        border: "1px solid var(--critical)",
        background: "color-mix(in oklch, var(--critical) 8%, transparent)",
        borderRadius: "var(--card-r)",
        display: "flex", gap: 16, alignItems: "flex-start",
      }}>
        <span style={{ color: "var(--critical)", marginTop: 2 }}><IconAlert size={20}/></span>
        <div style={{ flex: 1 }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--critical)", letterSpacing: ".18em", textTransform: "uppercase", fontWeight: 600 }}>
            Regla crítica activada · C03
          </div>
          <div style={{ fontSize: 14, marginTop: 4, color: "var(--fg)" }}>
            Pérdida estimada {">"} 0.3 t/h y trampa en línea principal — la severidad se eleva automáticamente a <b>ALTA</b>.
            Recomendamos intervención dentro del próximo turno operativo.
          </div>
        </div>
      </div>
    </div>
  );
}

function KPICell({ label, value, caption, accent, isLast }) {
  return (
    <div style={{
      padding: "var(--pad-3)",
      borderRight: isLast ? "none" : "1px solid var(--line-soft)",
    }}>
      <div className="mono" style={{ fontSize: 10, color: "var(--fg-soft)", letterSpacing: ".18em", textTransform: "uppercase" }}>{label}</div>
      <div className="display" style={{
        fontSize: 36, fontWeight: 400, lineHeight: 1.1, marginTop: 6,
        color: accent ? "var(--accent)" : "var(--fg)",
      }}>
        {value}
      </div>
      <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 4 }}>{caption}</div>
    </div>
  );
}

// ─── 5. AUDIT TABLE ─────────────────────────────────────────────────
const AUDIT_TRAPS = [
  { id: "TR-001", area: "Caldera principal", type: "Termodinámica",  app: "Línea principal", state: "OK",       prob: 12, sev: "BAJA",   loss: 0.02 },
  { id: "TR-002", area: "Caldera principal", type: "Balde invertido", app: "Cabezal",         state: "OK",       prob: 18, sev: "BAJA",   loss: 0.04 },
  { id: "TR-014", area: "Pasteurizador L1",  type: "Termostática",    app: "Equipo proceso",  state: "FALLA",    prob: 84, sev: "ALTA",   loss: 0.42, primary: true },
  { id: "TR-015", area: "Pasteurizador L1",  type: "Termostática",    app: "Equipo proceso",  state: "ALERTA",   prob: 56, sev: "MEDIA",  loss: 0.18 },
  { id: "TR-022", area: "Línea 110 mm",      type: "Termodinámica",   app: "Drenaje línea",   state: "OK",       prob: 22, sev: "BAJA",   loss: 0.05 },
  { id: "TR-031", area: "Esterilizador A",   type: "Float & Therm.",  app: "Equipo proceso",  state: "FALLA",    prob: 72, sev: "ALTA",   loss: 0.31 },
  { id: "TR-044", area: "Tanque CIP",        type: "Termostática",    app: "Equipo proceso",  state: "ALERTA",   prob: 48, sev: "MEDIA",  loss: 0.14 },
  { id: "TR-051", area: "Línea 200 mm",      type: "Termodinámica",   app: "Drenaje línea",   state: "OK",       prob: 9,  sev: "BAJA",   loss: 0.01 },
  { id: "TR-067", area: "Marmita 04",        type: "Balde invertido", app: "Equipo proceso",  state: "OK",       prob: 16, sev: "BAJA",   loss: 0.03 },
  { id: "TR-072", area: "Marmita 05",        type: "Balde invertido", app: "Equipo proceso",  state: "FALLA",    prob: 78, sev: "ALTA",   loss: 0.38 },
  { id: "TR-081", area: "Cabezal retorno",   type: "Float & Therm.",  app: "Cabezal",         state: "ALERTA",   prob: 41, sev: "MEDIA",  loss: 0.09 },
  { id: "TR-088", area: "Línea 60 mm",       type: "Termodinámica",   app: "Drenaje línea",   state: "OK",       prob: 14, sev: "BAJA",   loss: 0.02 },
];

const STATE_COLOR = {
  OK:     "var(--good)",
  ALERTA: "var(--warn)",
  FALLA:  "var(--critical)",
};

function ESAudit({ onOpenTrap, variant }) {
  const [filter, setFilter] = React.useState("ALL");
  const [sortBy, setSortBy] = React.useState("prob");
  const isBrutalist = variant === "brutalist";

  let rows = [...AUDIT_TRAPS];
  if (filter !== "ALL") rows = rows.filter(r => r.state === filter);
  rows.sort((a, b) => sortBy === "prob" ? b.prob - a.prob : a.id.localeCompare(b.id));

  const tot = AUDIT_TRAPS.length;
  const failed = AUDIT_TRAPS.filter(r => r.state === "FALLA").length;
  const warn = AUDIT_TRAPS.filter(r => r.state === "ALERTA").length;
  const lossTotal = AUDIT_TRAPS.reduce((acc, r) => acc + (r.state === "FALLA" ? r.loss : 0), 0);

  return (
    <div data-screen-label="ExpertSteam Audit" className="container" style={{ paddingTop: "var(--pad-4)", paddingBottom: "var(--pad-5)" }}>
      {/* Header */}
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: "var(--gap-5)", alignItems: "end", marginBottom: "var(--gap-4)" }}>
        <div>
          <div className="eyebrow">Auditoría · Lácteos Andinos S.A.</div>
          <h1 className="display" style={{ fontSize: "clamp(36px, 4.4vw, 56px)", fontWeight: 400, marginTop: "var(--gap-2)", lineHeight: 1.05 }}>
            Planta completa · <em style={{ fontStyle: variant === "schematic" ? "italic" : "normal", color: "var(--accent)" }}>84 trampas</em>
          </h1>
          <p style={{ color: "var(--fg-muted)", marginTop: "var(--gap-2)", lineHeight: 1.6, maxWidth: 540 }}>
            Visión consolidada del estado de cada trampa, con scoring individual y pérdidas estimadas.
            Filtre por estado o severidad para priorizar la intervención.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", flexWrap: "wrap" }}>
          <button className="btn btn-ghost"><IconUpload size={14}/> Importar Excel</button>
          <button className="btn btn-ghost"><IconDownload size={14}/> Exportar</button>
          <button className="btn btn-primary"><IconPlus size={14}/> Nueva trampa</button>
        </div>
      </div>

      {/* KPI summary strip */}
      <div className="card" style={{ marginBottom: "var(--gap-3)", padding: 0, overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)" }}>
          <KPICell label="Trampas auditadas" value={String(tot)} caption="100% del inventario" />
          <KPICell label="En falla" value={String(failed)} caption={`${Math.round(failed/tot*100)}% del total`} accent />
          <KPICell label="En alerta" value={String(warn)} caption="Requiere seguimiento" />
          <KPICell label="Pérdida total" value={`${lossTotal.toFixed(2)} t/h`} caption="≈ US$ 7.4k / mes" isLast />
        </div>
      </div>

      {/* Filter bar */}
      <div className="card" style={{
        padding: "12px 16px", marginBottom: 0,
        display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12,
        borderBottom: "none", borderTopLeftRadius: "var(--card-r)", borderTopRightRadius: "var(--card-r)",
        borderBottomLeftRadius: 0, borderBottomRightRadius: 0,
      }}>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
          <span className="eyebrow-muted" style={{ marginRight: 6 }}>Filtrar</span>
          {["ALL", "FALLA", "ALERTA", "OK"].map(f => (
            <button key={f}
              onClick={() => setFilter(f)}
              className="mono"
              style={{
                padding: "6px 12px",
                fontSize: 11, letterSpacing: ".12em", textTransform: "uppercase",
                background: filter === f ? "var(--fg)" : "transparent",
                color: filter === f ? "var(--bg)" : "var(--fg-muted)",
                border: "1px solid",
                borderColor: filter === f ? "var(--fg)" : "var(--line)",
                borderRadius: isBrutalist ? 0 : 6,
                cursor: "pointer", transition: "all .15s",
              }}>
              {f === "ALL" ? "Todos" : f}
            </button>
          ))}
        </div>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <button className="btn btn-ghost" onClick={() => setSortBy(sortBy === "prob" ? "id" : "prob")} style={{ fontSize: 11 }}>
            <IconSort size={12}/> Ordenar: {sortBy === "prob" ? "Probabilidad ↓" : "ID"}
          </button>
        </div>
      </div>

      {/* Table */}
      <div className="card" style={{
        padding: 0, overflow: "hidden",
        borderTopLeftRadius: 0, borderTopRightRadius: 0, borderTop: "none",
      }}>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
            <thead>
              <tr className="mono" style={{
                fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase",
                color: "var(--fg-soft)", textAlign: "left",
                background: "var(--bg-soft)",
              }}>
                <th style={cellHead}>ID</th>
                <th style={cellHead}>Área / equipo</th>
                <th style={cellHead}>Tipo de trampa</th>
                <th style={cellHead}>Aplicación</th>
                <th style={cellHead}>Estado</th>
                <th style={{...cellHead, textAlign: "right"}}>Prob.</th>
                <th style={{...cellHead, textAlign: "right"}}>Severidad</th>
                <th style={{...cellHead, textAlign: "right"}}>Pérdida (t/h)</th>
                <th style={cellHead}></th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r, i) => (
                <tr key={r.id}
                  onClick={() => r.primary && onOpenTrap()}
                  style={{
                    borderTop: "1px solid var(--line-soft)",
                    background: r.primary ? "color-mix(in oklch, var(--accent) 5%, transparent)" : "transparent",
                    cursor: r.primary ? "pointer" : "default",
                    transition: "background .12s",
                  }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--bg-soft)"}
                  onMouseLeave={e => e.currentTarget.style.background = r.primary ? "color-mix(in oklch, var(--accent) 5%, transparent)" : "transparent"}
                >
                  <td className="mono" style={{...cell, fontWeight: 600, color: r.primary ? "var(--accent)" : "var(--fg)"}}>
                    {r.id}
                  </td>
                  <td style={cell}>{r.area}</td>
                  <td style={{...cell, color: "var(--fg-muted)"}}>{r.type}</td>
                  <td style={{...cell, color: "var(--fg-muted)"}}>{r.app}</td>
                  <td style={cell}>
                    <span style={{
                      display: "inline-flex", alignItems: "center", gap: 6,
                      fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".08em",
                      color: STATE_COLOR[r.state], fontWeight: 600,
                    }}>
                      <span style={{ width: 6, height: 6, borderRadius: isBrutalist ? 0 : 999, background: STATE_COLOR[r.state] }} />
                      {r.state}
                    </span>
                  </td>
                  <td className="mono" style={{...cell, textAlign: "right", fontWeight: 500}}>
                    {/* mini bar + value */}
                    <div style={{ display: "inline-flex", alignItems: "center", gap: 8, justifyContent: "flex-end", width: "100%" }}>
                      <div style={{ width: 60, height: 4, background: "var(--line-soft)", borderRadius: isBrutalist ? 0 : 2, overflow: "hidden" }}>
                        <div style={{ width: `${r.prob}%`, height: "100%", background: STATE_COLOR[r.state], borderRadius: isBrutalist ? 0 : 2 }}/>
                      </div>
                      <span style={{ minWidth: 36, textAlign: "right" }}>{r.prob}%</span>
                    </div>
                  </td>
                  <td className="mono" style={{...cell, textAlign: "right", fontSize: 11, color: STATE_COLOR[r.state === "OK" ? "OK" : (r.sev === "ALTA" ? "FALLA" : "ALERTA")], letterSpacing: ".08em" }}>
                    {r.sev}
                  </td>
                  <td className="mono" style={{...cell, textAlign: "right", color: r.state === "FALLA" ? "var(--critical)" : "var(--fg)"}}>
                    {r.loss.toFixed(2)}
                  </td>
                  <td style={{...cell, textAlign: "right", color: "var(--fg-soft)"}}>
                    <IconChevronR size={14}/>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <p className="mono" style={{ marginTop: "var(--gap-2)", fontSize: 11, color: "var(--fg-soft)", letterSpacing: ".08em" }}>
        Mostrando {rows.length} de {AUDIT_TRAPS.length} · click en TR-014 para abrir su diagnóstico individual
      </p>
    </div>
  );
}

const cellHead = { padding: "12px 14px", fontWeight: 500 };
const cell = { padding: "12px 14px", verticalAlign: "middle" };

// ─── 6. GUIDES ──────────────────────────────────────────────────────
const GUIDES = [
  { code: "G01", title: "Tipos de trampa de vapor", category: "Fundamentos", time: "8 min", icon: "circuit" },
  { code: "G02", title: "Selección por aplicación", category: "Fundamentos", time: "12 min", icon: "branch" },
  { code: "G03", title: "Sizing — método práctico", category: "Cálculo",     time: "15 min", icon: "gauge" },
  { code: "G04", title: "Diagnóstico de fallas — árbol de decisión", category: "Diagnóstico", time: "10 min", icon: "atom" },
  { code: "G05", title: "Líneas de retorno de condensado", category: "Instalación", time: "14 min", icon: "pipe" },
  { code: "G06", title: "Golpe de ariete — causas y mitigación", category: "Problemas", time: "9 min", icon: "alert" },
  { code: "G07", title: "Aislamiento térmico y pérdidas",  category: "Eficiencia", time: "11 min", icon: "shield" },
  { code: "G08", title: "Tanques flash y recuperación",    category: "Eficiencia", time: "13 min", icon: "droplet" },
  { code: "G09", title: "Auditoría — protocolo CEIA",      category: "Procedimientos", time: "20 min", icon: "clipboard" },
];

function ESGuides({ variant }) {
  const [active, setActive] = React.useState(GUIDES[3]);
  const isBrutalist = variant === "brutalist";

  return (
    <div data-screen-label="ExpertSteam Guides" className="container" style={{ paddingTop: "var(--pad-4)", paddingBottom: "var(--pad-5)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 2fr)", gap: "var(--gap-5)", alignItems: "end", marginBottom: "var(--gap-4)" }}>
        <div>
          <div className="eyebrow">Recursos técnicos · 23 documentos</div>
          <h1 className="display" style={{ fontSize: "clamp(36px, 4.4vw, 56px)", fontWeight: 400, marginTop: "var(--gap-2)", lineHeight: 1.05 }}>
            Guías y <em style={{ fontStyle: variant === "schematic" ? "italic" : "normal", color: "var(--accent)" }}>diagramas técnicos</em>.
          </h1>
        </div>
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", flexWrap: "wrap" }}>
          <div style={{ position: "relative", flex: "1 1 240px", maxWidth: 320 }}>
            <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-soft)" }}>
              <IconSearch size={16}/>
            </span>
            <input className="input" placeholder="Buscar guía o diagrama…" style={{ paddingLeft: 38 }}/>
          </div>
          <button className="btn btn-ghost"><IconFilter size={14}/> Filtros</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.4fr) minmax(0, 1fr)", gap: "var(--gap-3)" }}>
        {/* Guide list */}
        <div style={{ display: "grid", gap: 10 }}>
          {GUIDES.map((g, i) => {
            const isActive = active.code === g.code;
            return (
              <button key={g.code} onClick={() => setActive(g)}
                className="card"
                style={{
                  padding: "var(--pad-2)", textAlign: "left", cursor: "pointer",
                  borderColor: isActive ? "var(--accent)" : "var(--line)",
                  background: isActive ? "var(--accent-soft)" : "var(--card-bg)",
                  display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 16, alignItems: "center",
                  color: "var(--fg)", fontFamily: "inherit",
                  transition: "all .15s ease",
                }}>
                <span className="mono" style={{
                  fontSize: 11, color: isActive ? "var(--accent)" : "var(--fg-soft)",
                  letterSpacing: ".12em", fontWeight: isActive ? 600 : 400,
                  width: 36,
                }}>{g.code}</span>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 600, color: "var(--fg)" }}>{g.title}</div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--fg-soft)", letterSpacing: ".14em", textTransform: "uppercase", marginTop: 4 }}>
                    {g.category} · {g.time}
                  </div>
                </div>
                <span style={{ color: isActive ? "var(--accent)" : "var(--fg-soft)" }}>
                  <IconChevronR size={16}/>
                </span>
              </button>
            );
          })}
        </div>

        {/* Active preview */}
        <div style={{ position: "sticky", top: 80, alignSelf: "start" }}>
          <div className="card" style={{ padding: "var(--pad-3)" }}>
            <div className="mono" style={{
              display: "flex", justifyContent: "space-between",
              fontSize: 10, color: "var(--fg-soft)", letterSpacing: ".14em", textTransform: "uppercase",
              marginBottom: 12,
            }}>
              <span>{active.code} · Vista previa</span>
              <span>{active.time}</span>
            </div>
            <h3 className="display" style={{ fontSize: 26, fontWeight: 400, margin: "0 0 var(--gap-2)", lineHeight: 1.1 }}>
              {active.title}
            </h3>

            {/* Decision tree mock for G04, schematic for others */}
            <div className="card" style={{
              padding: "var(--pad-2)", marginBottom: "var(--gap-2)",
              borderStyle: "dashed",
            }}>
              <svg viewBox="0 0 360 220" style={{ width: "100%", height: "auto", display: "block" }}>
                <defs>
                  <pattern id="grid-guide" width="20" height="20" patternUnits="userSpaceOnUse">
                    <path d="M 20 0 L 0 0 0 20" fill="none" stroke="currentColor" strokeWidth=".3" opacity=".15"/>
                  </pattern>
                </defs>
                <rect width="360" height="220" fill="url(#grid-guide)"/>
                {/* Root */}
                <rect x="140" y="14" width="80" height="28" fill="var(--accent)" stroke="var(--accent)" rx={isBrutalist ? 0 : 3}/>
                <text x="180" y="32" fontSize="10" fill={isBrutalist ? "var(--fg)" : "white"} textAnchor="middle" fontFamily="var(--font-mono)" fontWeight="600">¿Fuga visible?</text>
                {/* Lines */}
                <path d="M180 42 V70 H100 V90" fill="none" stroke="currentColor" strokeWidth="1"/>
                <path d="M180 42 V70 H260 V90" fill="none" stroke="currentColor" strokeWidth="1"/>
                <text x="135" y="63" fontSize="9" fill="currentColor" fontFamily="var(--font-mono)">sí</text>
                <text x="220" y="63" fontSize="9" fill="currentColor" fontFamily="var(--font-mono)">no</text>
                {/* Level 2 */}
                <rect x="60" y="90" width="80" height="26" fill="none" stroke="currentColor" strokeWidth="1" rx={isBrutalist ? 0 : 3}/>
                <text x="100" y="107" fontSize="9" fill="currentColor" textAnchor="middle" fontFamily="var(--font-mono)">¿Continua?</text>
                <rect x="220" y="90" width="80" height="26" fill="none" stroke="currentColor" strokeWidth="1" rx={isBrutalist ? 0 : 3}/>
                <text x="260" y="107" fontSize="9" fill="currentColor" textAnchor="middle" fontFamily="var(--font-mono)">¿Cuerpo frío?</text>
                {/* Branches */}
                <path d="M100 116 V140 H60 V160" fill="none" stroke="currentColor" strokeWidth="1"/>
                <path d="M100 116 V140 H140 V160" fill="none" stroke="currentColor" strokeWidth="1"/>
                <path d="M260 116 V140 H220 V160" fill="none" stroke="currentColor" strokeWidth="1"/>
                <path d="M260 116 V140 H300 V160" fill="none" stroke="currentColor" strokeWidth="1"/>
                {/* Leaves */}
                <rect x="22" y="160" width="76" height="26" fill="var(--accent-soft)" stroke="var(--accent)" strokeWidth=".8" rx={isBrutalist ? 0 : 3}/>
                <text x="60" y="177" fontSize="9" fill="var(--accent)" textAnchor="middle" fontFamily="var(--font-mono)" fontWeight="600">F02 · Abierta</text>
                <rect x="102" y="160" width="76" height="26" fill="none" stroke="currentColor" strokeWidth=".8" rx={isBrutalist ? 0 : 3}/>
                <text x="140" y="177" fontSize="9" fill="currentColor" textAnchor="middle" fontFamily="var(--font-mono)">F07 · Asiento</text>
                <rect x="182" y="160" width="76" height="26" fill="none" stroke="currentColor" strokeWidth=".8" rx={isBrutalist ? 0 : 3}/>
                <text x="220" y="177" fontSize="9" fill="currentColor" textAnchor="middle" fontFamily="var(--font-mono)">F09 · Cerrada</text>
                <rect x="262" y="160" width="76" height="26" fill="none" stroke="currentColor" strokeWidth=".8" rx={isBrutalist ? 0 : 3}/>
                <text x="300" y="177" fontSize="9" fill="currentColor" textAnchor="middle" fontFamily="var(--font-mono)">F11 · Sub-dim.</text>

                <text x="10" y="208" fontSize="8" fill="var(--fg-soft)" fontFamily="var(--font-mono)" letterSpacing=".5">Fig. G04.1 — Árbol de decisión simplificado</text>
              </svg>
            </div>

            <p style={{ fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.55, margin: 0 }}>
              Documento de referencia interna para soporte del diagnóstico en campo.
              Incluye criterios de decisión, ejemplos numéricos y plantillas de inspección.
            </p>

            <div style={{ display: "flex", gap: 8, marginTop: "var(--gap-2)" }}>
              <button className="btn btn-primary" style={{ flex: 1 }}>Abrir documento <IconArrowRight size={14}/></button>
              <button className="btn btn-ghost"><IconDownload size={14}/></button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── 7. PRINTABLE REPORT ────────────────────────────────────────────
function ESReport({ onBack, variant }) {
  return (
    <div data-screen-label="ExpertSteam Report" style={{ background: "var(--bg-soft)", minHeight: "100vh", paddingBottom: "var(--pad-5)" }}>
      <div className="container" style={{ paddingTop: "var(--pad-3)" }}>
        <div className="no-print" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "var(--gap-3)" }}>
          <button className="btn btn-ghost" onClick={onBack}><IconChevronL size={14}/> Volver</button>
          <div style={{ display: "flex", gap: 10 }}>
            <button className="btn btn-ghost"><IconDownload size={14}/> Descargar PDF</button>
            <button className="btn btn-primary" onClick={() => window.print()}><IconPrint size={14}/> Imprimir</button>
          </div>
        </div>

        {/* A4 paper preview */}
        <div style={{
          maxWidth: 880, margin: "0 auto",
          background: "white", color: "#0f172a",
          padding: "56px 64px",
          boxShadow: "0 30px 80px rgba(0,0,0,.18), 0 8px 18px rgba(0,0,0,.08)",
          borderRadius: variant === "brutalist" ? 0 : 4,
        }}>
          {/* Cover */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", borderBottom: "1px solid #cbd5e1", paddingBottom: 28, marginBottom: 32 }}>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: ".22em", textTransform: "uppercase", color: "#d96518", fontWeight: 600 }}>
                CEIA Ingeniería · ExpertSteam Report
              </div>
              <h1 style={{ fontFamily: "var(--font-display)", fontSize: 38, fontWeight: 400, margin: "16px 0 8px", letterSpacing: "-.02em", color: "#0f172a" }}>
                Informe de diagnóstico
              </h1>
              <div style={{ fontSize: 14, color: "#475569" }}>TR-014 · Pasteurizador L1 · Lácteos Andinos S.A.</div>
            </div>
            <div style={{ textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 11, color: "#64748b", lineHeight: 1.6 }}>
              <div>DOC: 2026-014</div>
              <div>REV: A</div>
              <div>FECHA: 20/05/2026</div>
              <div>ING: J. Rodríguez</div>
            </div>
          </div>

          {/* Section 1 — Resumen ejecutivo */}
          <section style={{ marginBottom: 36 }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 700, letterSpacing: ".24em", textTransform: "uppercase", color: "#d96518", marginBottom: 8 }}>
              01 / Resumen ejecutivo
            </div>
            <h2 style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 400, margin: "0 0 16px", color: "#0f172a" }}>
              Falla detectada en trampa de equipo crítico
            </h2>
            <p style={{ fontSize: 13.5, lineHeight: 1.7, color: "#334155", margin: 0 }}>
              La trampa TR-014 (termostática, aplicación equipo de proceso) presenta evidencia clara de
              <b> falla en abierto (F02)</b>. La pérdida estimada de <b>0.42 t/h</b> en operación continua
              representa aproximadamente <b>US$ 2,800 mensuales</b> en costo de combustible, además del
              impacto operativo sobre el proceso de pasteurización.
            </p>

            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginTop: 20 }}>
              {[
                { l: "Modo de falla", v: "F02", c: "Falla en abierto" },
                { l: "Probabilidad",  v: "84%", c: "Muy alta" },
                { l: "Severidad",     v: "ALTA", c: "Riesgo operativo" },
                { l: "Pérdida est.",  v: "0.42 t/h", c: "≈ US$ 2.8k/mes" },
              ].map((m, i) => (
                <div key={i} style={{ padding: 14, border: "1px solid #cbd5e1", borderRadius: 8 }}>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: ".2em", textTransform: "uppercase", color: "#64748b", fontWeight: 700 }}>{m.l}</div>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 26, fontWeight: 400, margin: "8px 0 2px", color: "#0f172a", lineHeight: 1 }}>{m.v}</div>
                  <div style={{ fontSize: 11, color: "#475569" }}>{m.c}</div>
                </div>
              ))}
            </div>
          </section>

          {/* Section 2 — Datos del análisis */}
          <section style={{ marginBottom: 36, paddingTop: 24, borderTop: "1px solid #cbd5e1" }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 700, letterSpacing: ".24em", textTransform: "uppercase", color: "#d96518", marginBottom: 8 }}>
              02 / Datos del análisis
            </div>
            <h2 style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 400, margin: "0 0 16px", color: "#0f172a" }}>Condiciones registradas en planta</h2>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
              <tbody>
                {[
                  ["Ubicación", "Pasteurizador línea 1 · cabezal salida"],
                  ["Tipo de trampa", "Termostática bimetálica · Marca X · DN15"],
                  ["Presión de operación", "8.4 bar(g)"],
                  ["Temperatura de operación", "175 °C"],
                  ["Modo de servicio", "Continuo · 24/7"],
                  ["Última intervención", "Hace 18 meses (cambio de elemento interno)"],
                ].map(([k, v], i) => (
                  <tr key={i} style={{ borderBottom: i === 5 ? "none" : "1px solid #e2e8f0" }}>
                    <td style={{ padding: "10px 0", color: "#64748b", fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: ".08em", textTransform: "uppercase", width: "40%" }}>{k}</td>
                    <td style={{ padding: "10px 0", color: "#0f172a" }}>{v}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </section>

          {/* Section 3 — Plan de acción */}
          <section style={{ marginBottom: 24, paddingTop: 24, borderTop: "1px solid #cbd5e1" }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 700, letterSpacing: ".24em", textTransform: "uppercase", color: "#d96518", marginBottom: 8 }}>
              03 / Plan de acción recomendado
            </div>
            <ol style={{ paddingLeft: 18, margin: 0, fontSize: 13, lineHeight: 1.65, color: "#334155" }}>
              <li style={{ marginBottom: 8 }}>Aislar la trampa y verificar visualmente la fuga por descarga (15 min).</li>
              <li style={{ marginBottom: 8 }}>Sustituir elemento interno o trampa completa según marca/serie (90 min).</li>
              <li style={{ marginBottom: 8 }}>Verificar dimensionamiento contra hoja de proceso (30 min).</li>
              <li>Re-medir consumo a las 24 h para cuantificar recuperación.</li>
            </ol>
          </section>

          <div style={{ marginTop: 36, paddingTop: 14, borderTop: "1px solid #cbd5e1", display: "flex", justifyContent: "space-between", fontFamily: "var(--font-mono)", fontSize: 10, color: "#64748b", letterSpacing: ".12em", textTransform: "uppercase" }}>
            <span>CEIA Ingeniería · ExpertSteam v1.0</span>
            <span>Página 1 de 4</span>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  ESLogin, ESHub, ESWizard, ESResults, ESAudit, ESGuides, ESReport,
});
