// ENERGÍA · Video demo 90s · Demanda creciente + Generación variable + Activo crítico bajo restricción

const EnergiaDemo = () => {
  const [scene, setScene] = React.useState(0);
  const [playing, setPlaying] = React.useState(true);
  const scenes = [
    { d: 9,  label: 'El sistema opera según el plan',                      cap: 'Generación, demanda, activos y equipos de campo mantienen el equilibrio operacional. Pronósticos dentro del rango habitual.' },
    { d: 11, label: 'Varias condiciones comienzan a converger',             cap: 'Demanda esperada +7% · generación renovable prevista –12% · transformador DIST-N2 muestra desviación térmica y de vibración fuera de patrón histórico.' },
    { d: 13, label: 'Una alarma no explica el impacto',                     cap: 'El SDM de Operaciones Energéticas conecta EMS, historian, EAM, plataforma renovable, meteorología, WMS, WFM y GIS.' },
    { d: 13, label: 'OMNIX identifica qué está en riesgo',                  cap: '4 servicios evaluados · 2 zonas potencialmente afectadas · 1 cliente crítico · flexibilidad de batería disponible · repuesto regional limitado.' },
    { d: 14, label: 'Alternativas evaluadas bajo límites operacionales',    cap: 'Monitoreo reforzado · reprogramar mantenimiento · activar flexibilidad · redistribuir carga vía sistema especializado · despachar cuadrilla · reservar repuesto · contingencia.' },
    { d: 13, label: 'Aprobación humana · plan coordinado',                  cap: 'Operaciones aprueba el plan combinado (flexibilidad + monitoreo reforzado + mantenimiento reprogramado). OMNIX prepara acciones en sistemas autorizados.' },
    { d: 12, label: 'La restricción se mantiene bajo control',              cap: 'Flexibilidad activada por sistema especializado. Activo monitoreado. Intervención reprogramada dentro de ventana segura. Continuidad protegida.' },
    { d: 5,  label: 'Log auditable · KPIs actualizados',                    cap: 'Cada señal, evaluación, aprobación y acción registrada. Trazabilidad completa para auditoría regulatoria y operacional.' },
  ];
  const totalMs = scenes.reduce((s, x) => s + x.d * 1000, 0);
  const [elapsed, setElapsed] = React.useState(0);
  React.useEffect(() => {
    if (!playing) return;
    const step = 100;
    const id = setInterval(() => {
      setElapsed((e) => {
        const next = e + step;
        let acc = 0, s = 0;
        for (let i = 0; i < scenes.length; i++) { acc += scenes[i].d * 1000; if (next < acc) { s = i; break; } s = i; }
        if (next >= totalMs) { setScene(0); return 0; }
        setScene(s); return next;
      });
    }, step);
    return () => clearInterval(id);
  }, [playing, totalMs]);
  const progress = Math.min(100, (elapsed / totalMs) * 100);
  const fmt = (ms) => { const s = Math.floor(ms / 1000); return `${Math.floor(s/60)}:${String(s%60).padStart(2, '0')}`; };

  return (
    <section id="demo" style={{ background: '#FFFFFF', paddingTop: 128, paddingBottom: 128 }}>
      <Container>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, marginBottom: 56, alignItems: 'end' }}>
          <div>
            <Reveal><SectionMeta n="02" label="Demo · 90 segundos"/></Reveal>
            <Reveal delay={80}>
              <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 52, lineHeight: 1.03, letterSpacing: '-0.025em', margin: 0, color: '#000' }}>
                Demanda creciente, generación variable y un activo crítico bajo restricción.
              </h2>
            </Reveal>
          </div>
          <Reveal delay={140}>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 18, lineHeight: 1.55, color: '#52557A', margin: 0 }}>
              Escenario demostrativo con datos sintéticos y red abstracta. OMNIX apoya la coordinación entre operaciones, mantenimiento y campo · las maniobras críticas permanecen en operadores autorizados y sistemas especializados.
            </p>
          </Reveal>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 24 }}>
          <Reveal y={0}>
            <div style={{ border: '1.5px solid #1E1F26', background: '#000', color: '#FFF', overflow: 'hidden' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 20px', borderBottom: '1.5px solid #2E3140', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#96A3B5' }}>
                <span>OMNIX · ENERGY DEMO · SCENE 0{scene+1}/08</span>
                <span style={{ color: '#F4024C', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ width: 6, height: 6, borderRadius: 999, background: '#F4024C' }} className={playing ? 'omnix-blink' : ''}/>
                  {playing ? 'PLAYING' : 'PAUSED'}
                </span>
              </div>
              <div style={{ position: 'relative', aspectRatio: '16 / 10', background: '#0A0B10' }}>
                <EnScene scene={scene}/>
                <div style={{ position: 'absolute', top: 20, left: 20, padding: '8px 14px', background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(8px)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: '#B8860B', textTransform: 'uppercase' }}>[SIMULATED] · [DATOS SINTÉTICOS] · [RED ABSTRACTA]</div>
                <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '20px 32px 24px', background: 'linear-gradient(180deg, transparent, rgba(0,0,0,0.85) 40%)' }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, letterSpacing: '-0.015em', color: '#FFF', marginBottom: 8, lineHeight: 1.15 }}>{scenes[scene].label}</div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: '#96A3B5', lineHeight: 1.4, maxWidth: 640 }}>{scenes[scene].cap}</div>
                </div>
              </div>
              <div style={{ borderTop: '1.5px solid #2E3140', padding: '14px 20px', display: 'flex', alignItems: 'center', gap: 16 }}>
                <button onClick={() => setPlaying(!playing)} style={enCtrl} aria-label={playing ? 'Pausar' : 'Reproducir'}><i data-lucide={playing ? 'pause' : 'play'} width="14" height="14"></i></button>
                <button onClick={() => { setElapsed(0); setScene(0); }} style={enCtrl} aria-label="Reiniciar"><i data-lucide="rotate-ccw" width="14" height="14"></i></button>
                <div style={{ flex: 1, height: 4, background: '#2E3140', position: 'relative' }}>
                  <div style={{ position: 'absolute', inset: 0, right: 'auto', width: `${progress}%`, background: '#F4024C', transition: 'width 100ms linear' }}/>
                </div>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: '#96A3B5', minWidth: 68, textAlign: 'right' }}>{fmt(elapsed)} / {fmt(totalMs)}</span>
                <button style={enCtrl} aria-label="Silenciar"><i data-lucide="volume-x" width="14" height="14"></i></button>
                <button style={enCtrl} aria-label="Subtítulos"><i data-lucide="captions" width="14" height="14"></i></button>
              </div>
              <div style={{ borderTop: '1.5px solid #2E3140', display: 'grid', gridTemplateColumns: `repeat(${scenes.length}, 1fr)` }}>
                {scenes.map((s, i) => (
                  <button key={i} onClick={() => { const before = scenes.slice(0, i).reduce((a, x) => a + x.d * 1000, 0); setElapsed(before); setScene(i); }} style={{ padding: '10px 8px', border: 'none', background: scene === i ? '#F4024C' : '#0A0B10', color: scene === i ? '#FFF' : '#52557A', borderRight: (i < scenes.length - 1) ? '1px solid #2E3140' : 'none', fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', cursor: 'pointer' }} aria-label={`Escena ${i+1}`}>{i+1}</button>
                ))}
              </div>
            </div>
          </Reveal>
          <Reveal delay={100} y={0}>
            <div style={{ border: '1.5px solid #1E1F26', background: '#FAFBFD', padding: 32, height: '100%', display: 'flex', flexDirection: 'column' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', color: '#F4024C', textTransform: 'uppercase', marginBottom: 12 }}>Qué está haciendo OMNIX</div>
              <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.55, color: '#1E1F26', margin: '0 0 20px' }}>
                Convierte convergencia de condiciones (demanda + generación + activo) en un plan coordinado · con evidencia trazable · aprobación humana en decisiones críticas · rollback armado.
              </p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
                {[
                  { t: 'Condición detectada',        d: 'EMS + historian + renovable + meteo · desviación multi-señal.',            sys: 'EMS · SCADA · meteo', auto: 'N1' },
                  { t: 'Impacto contextualizado',     d: 'Servicios, zonas y clientes críticos potencialmente afectados.',           sys: 'OMS · GIS · AMI',     auto: 'N2' },
                  { t: 'Recursos identificados',       d: 'Flexibilidad · repuestos · cuadrillas · ventanas de mantenimiento.',       sys: 'WMS · WFM · EAM',       auto: 'N2' },
                  { t: 'Alternativas evaluadas',       d: '7 alternativas con score de continuidad, riesgo y costo.',                sys: 'CORTEX',                 auto: 'N3' },
                  { t: 'Respuesta coordinada',         d: 'Aprobación de operaciones · acciones vía sistemas especializados.',       sys: 'RUNTIME',                 auto: 'N3-N4' },
                  { t: 'Resultado auditado',           d: 'Log firmado WORM · KPI actualizados · learning al SDM.',                    sys: 'GOV · BI',                auto: '—' },
                ].map((c, i) => (
                  <div key={c.t} style={{ padding: '12px 14px', background: '#FFF', border: '1px solid', borderColor: scene >= i ? '#F4024C' : '#E4EBF3', transition: 'border-color 320ms', display: 'grid', gridTemplateColumns: '22px 1fr 60px', gap: 10, alignItems: 'start' }}>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: scene >= i ? '#F4024C' : '#96A3B5' }}>0{i+1}</span>
                    <div>
                      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13, letterSpacing: '-0.005em', color: '#000', marginBottom: 3 }}>{c.t}</div>
                      <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: '#52557A', lineHeight: 1.4 }}>{c.d}</div>
                      <div style={{ marginTop: 3, fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.14em', color: '#0050BD' }}>SYS · {c.sys}</div>
                    </div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.14em', color: '#1E1F26', textAlign: 'right', paddingTop: 4 }}>{c.auto}</div>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 14, padding: '10px 12px', background: '#FBF3D9', border: '1px solid #B8860B', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.06em', color: '#1E1F26', lineHeight: 1.55 }}>
                Escenario demostrativo. Las maniobras, protecciones, despachos y cambios críticos permanecen bajo responsabilidad de operadores y sistemas autorizados.
              </div>
            </div>
          </Reveal>
        </div>
        <Reveal delay={200}>
          <details style={{ marginTop: 32, padding: '20px 24px', border: '1px solid #E4EBF3', background: '#FAFBFD' }}>
            <summary style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', color: '#F4024C', textTransform: 'uppercase', cursor: 'pointer' }}>Transcripción del video</summary>
            <div style={{ marginTop: 16, fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.7, color: '#1E1F26' }}>
              {scenes.map((s, i) => (
                <p key={i} style={{ margin: '0 0 10px' }}>
                  <strong>Escena {i+1} · {fmt(scenes.slice(0, i).reduce((a, x) => a + x.d * 1000, 0))} — {s.label}.</strong> {s.cap}
                </p>
              ))}
              <p style={{ margin: '16px 0 0', fontStyle: 'italic', color: '#52557A' }}>
                [ESCENARIO DEMOSTRATIVO] · [DATOS SINTÉTICOS] · [RED ABSTRACTA] · [ACTIVOS GENÉRICOS]. Sin uso de topologías, setpoints ni datos operacionales reales.
              </p>
            </div>
          </details>
        </Reveal>
      </Container>
    </section>
  );
};

const enCtrl = { width: 32, height: 32, border: '1px solid #2E3140', background: '#0A0B10', color: '#FFF', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' };

const EnScene = ({ scene }) => (
  <div style={{ position: 'absolute', inset: 0 }}>
    {scene === 0 && <EnSc0/>}
    {scene === 1 && <EnSc1/>}
    {scene === 2 && <EnSc2/>}
    {scene === 3 && <EnSc3/>}
    {scene === 4 && <EnSc4/>}
    {scene === 5 && <EnSc5/>}
    {scene === 6 && <EnSc6/>}
    {scene === 7 && <EnSc7/>}
  </div>
);

const EnGrid = () => (
  <g stroke="#2E3140" strokeWidth="0.5" opacity="0.4">
    {Array.from({length: 17}).map((_, i) => <line key={`v${i}`} x1={i*50} y1="0" x2={i*50} y2="500"/>)}
    {Array.from({length: 11}).map((_, i) => <line key={`h${i}`} x1="0" y1={i*50} x2="800" y2={i*50}/>)}
  </g>
);

const EnSc0 = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <EnGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">SISTEMA · GENERACIÓN + TRANSMISIÓN + DISTRIBUCIÓN · NOMINAL</text>
    {[
      { x: 90,  y: 140, k: 'GEN·SOLAR',  c: '#B8860B' },
      { x: 90,  y: 300, k: 'GEN·EÓLICA', c: '#0F5132' },
      { x: 300, y: 220, k: 'SUB·TRANS',  c: '#0050BD' },
      { x: 500, y: 150, k: 'DIST·N1',    c: '#0F5132' },
      { x: 500, y: 290, k: 'DIST·N2',    c: '#0F5132' },
      { x: 690, y: 220, k: 'STORAGE',    c: '#0050BD' },
    ].map((n) => (
      <g key={n.k} transform={`translate(${n.x}, ${n.y})`}>
        <rect x="-58" y="-24" width="116" height="48" fill="#0A0B10" stroke={n.c} strokeWidth="1.5"/>
        <text y="-4" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" fill="#FFF">{n.k}</text>
        <text y="14" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill={n.c}>nominal</text>
      </g>
    ))}
    {[[148,140,242,220],[148,300,242,220],[358,220,442,150],[358,220,442,290],[558,150,632,220],[558,290,632,220]].map((r, i) => (
      <FlowPath key={i} d={`M ${r[0]} ${r[1]} L ${r[2]} ${r[3]}`} stroke="#96A3B5" strokeWidth={0.75} particleColor="#0050BD" particleSize={2.5} duration={2.6 + i * 0.15}/>
    ))}
    <g transform="translate(80, 430)">
      <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">DEMANDA</text>
      <text x="0" y="34" fontFamily="var(--font-display)" fontWeight="800" fontSize="32" fill="#F4024C" letterSpacing="-0.02em">4820 MW</text>
      <text x="200" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">RENOVABLE</text>
      <text x="200" y="34" fontFamily="var(--font-mono)" fontSize="24" fill="#B8860B">1240 MW</text>
      <text x="410" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">SAIDI (min)</text>
      <text x="410" y="34" fontFamily="var(--font-mono)" fontSize="24" fill="#0F5132">38.2</text>
      <text x="600" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">SISTEMAS</text>
      <text x="600" y="34" fontFamily="var(--font-mono)" fontSize="18" fill="#FFF">conectados</text>
    </g>
  </svg>
);

const EnSc1 = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <EnGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#EA384C">CONVERGENCIA DE CONDICIONES · DEMANDA ↑ · RENOVABLE ↓ · DIST-N2 DEGRADADO</text>
    {[
      { x: 60, y: 130, l: 'DEMANDA', val: '+7%', c: '#EA384C', arrow: '↑' },
      { x: 60, y: 260, l: 'RENOVABLE', val: '−12%', c: '#B8860B', arrow: '↓' },
      { x: 60, y: 390, l: 'DIST-N2', val: 'DEGRADED', c: '#EA384C', arrow: '⚠' },
    ].map((r, i) => (
      <g key={r.l} transform={`translate(${r.x}, ${r.y})`}>
        <rect x="0" y="-30" width="240" height="60" fill="#0A0B10" stroke={r.c} strokeWidth="1.5"/>
        <text x="20" y="-8" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.18em" fill={r.c}>{r.l}</text>
        <text x="20" y="18" fontFamily="var(--font-display)" fontWeight="800" fontSize="20" fill="#FFF">{r.val} <tspan fill={r.c}>{r.arrow}</tspan></text>
      </g>
    ))}
    <g transform="translate(500, 250)">
      <circle r="70" fill="none" stroke="#EA384C" strokeWidth="1" opacity="0.4">
        <animate attributeName="r" values="60;80;60" dur="1.6s" repeatCount="indefinite"/>
      </circle>
      <rect x="-100" y="-50" width="200" height="100" fill="#0A0B10" stroke="#EA384C" strokeWidth="2"/>
      <text y="-16" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#EA384C">CONVERGENCIA</text>
      <text y="10" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="800" fontSize="16" fill="#FFF">3 condiciones</text>
      <text y="32" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" fill="#96A3B5">próximas 4h</text>
    </g>
  </svg>
);

const EnSc2 = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <EnGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">SDM OPERACIONES ENERGÉTICAS · MULTI-SIGNAL CONTEXT</text>
    {['EMS · pronóstico demanda', 'Historian · desviación activo', 'Renovable · pronóstico ajustado', 'Meteorología · nubosidad', 'EAM · estado transformador', 'WMS · repuesto regional', 'WFM · cuadrillas disponibles', 'AMI · consumo clientes'].map((s, i) => (
      <g key={s} transform={`translate(60, ${100 + i * 40})`}>
        <rect x="0" y="-14" width="240" height="28" fill="#0A0B10" stroke="#0050BD" strokeWidth="1"/>
        <text x="12" y="4" fontFamily="var(--font-mono)" fontSize="11" fill="#FFF">{s}</text>
        <FlowPath d={`M 240 0 L 400 0 L 460 130`} stroke="#96A3B5" strokeWidth={0.5} particleColor="#F4024C" particleSize={2} duration={2.2 + i * 0.15}/>
      </g>
    ))}
    <g transform="translate(590, 250)">
      <circle r="70" fill="none" stroke="#F4024C" strokeWidth="1" opacity="0.3">
        <animate attributeName="r" values="60;76;60" dur="2.4s" repeatCount="indefinite"/>
      </circle>
      <rect x="-64" y="-44" width="128" height="88" fill="#000" stroke="#F4024C" strokeWidth="2"/>
      <text y="-12" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="800" fontSize="14" fill="#FFF">SDM</text>
      <text y="8" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="700" fontSize="12" fill="#F4024C">ENERGY-OPS</text>
      <text y="30" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.14em" fill="#96A3B5">v0.4-demo</text>
    </g>
  </svg>
);

const EnSc3 = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <EnGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">RECURSOS Y RIESGOS IDENTIFICADOS</text>
    <text x="80" y="90" fontFamily="var(--font-display)" fontWeight="700" fontSize="20" fill="#FFF">Alcance evaluado · sistema completo</text>
    {[
      { k: 'SERVICIOS EN RIESGO',   n: '4', v: 'Zonas de distribución potencialmente afectadas',      c: '#EA384C' },
      { k: 'CLIENTES CRÍTICOS',      n: '1', v: 'Hospital · notificación proactiva sugerida',           c: '#B8860B' },
      { k: 'FLEXIBILIDAD DISPONIBLE', n: '85 MWh', v: 'Batería regional · capacidad autorizada',        c: '#0F5132' },
      { k: 'CUADRILLAS · REPUESTOS',  n: '2·1', v: 'Cuadrillas + 1 repuesto regional · lead time 8h',    c: '#0050BD' },
    ].map((r, i) => (
      <g key={r.k} transform={`translate(80, ${130 + i * 70})`}>
        <rect x="0" y="0" width="640" height="58" fill="#0A0B10" stroke={r.c} strokeWidth="1.5"/>
        <text x="20" y="22" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.18em" fill={r.c}>{r.k}</text>
        <text x="20" y="46" fontFamily="var(--font-display)" fontWeight="800" fontSize="20" fill="#FFF">{r.n}</text>
        <text x="130" y="46" fontFamily="var(--font-body)" fontSize="13" fill="#96A3B5">{r.v}</text>
      </g>
    ))}
    <text x="80" y="470" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#F4024C">→ EVALUAR COMBINACIÓN ÓPTIMA · SIGUIENTE PASO</text>
  </svg>
);

const EnSc4 = () => {
  const opts = [
    { k: 'MONITOR',     t: 'Monitoreo reforzado · mantener plan',      cont: 62, risk: 48, cost: 8,   sel: false },
    { k: 'FLEX+MAINT',   t: 'Flex batería + reprogramar mantenimiento', cont: 94, risk: 18, cost: 22,  sel: true },
    { k: 'REDISTR',     t: 'Redistribuir carga via ADMS',              cont: 88, risk: 32, cost: 14,  sel: false },
    { k: 'CREW+PART',   t: 'Despachar cuadrilla + reservar repuesto',   cont: 76, risk: 26, cost: 34,  sel: false },
    { k: 'CONTINGENCY', t: 'Preparar plan de contingencia',             cont: 82, risk: 22, cost: 42,  sel: false },
    { k: 'ESCALATE',    t: 'Escalar a centro superior',                 cont: 80, risk: 30, cost: 28,  sel: false },
    { k: 'FULL-EMERG',  t: 'Contingencia total',                        cont: 96, risk: 12, cost: 78,  sel: false },
  ];
  return (
    <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
      <EnGrid/>
      <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">DEEP THINK · ALTERNATIVAS COMPARADAS</text>
      <g transform="translate(80, 100)">
        <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">ACCIÓN</text>
        <text x="360" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#0F5132">CONTINUIDAD</text>
        <text x="490" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#B8860B">RIESGO</text>
        <text x="620" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#EA384C">COSTO</text>
      </g>
      {opts.map((o, i) => (
        <g key={o.k} transform={`translate(80, ${132 + i * 46})`}>
          {o.sel && <rect x="-8" y="-14" width="656" height="36" fill="#F4024C" opacity="0.08"/>}
          {o.sel && <rect x="-8" y="-14" width="4" height="36" fill="#F4024C"/>}
          <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.14em" fill={o.sel ? '#F4024C' : '#96A3B5'}>0{i+1} · {o.k}</text>
          <text x="0" y="15" fontFamily="var(--font-display)" fontWeight="700" fontSize="12" fill="#FFF">{o.t}</text>
          {[{ x: 360, v: o.cont, c: '#0F5132' }, { x: 480, v: o.risk, c: '#B8860B' }, { x: 610, v: o.cost, c: '#EA384C' }].map((b, j) => (
            <g key={j}>
              <rect x={b.x} y="4" width="80" height="6" fill="#2E3140"/>
              <rect x={b.x} y="4" width={Math.min(80, b.v * 0.8)} height="6" fill={b.c}>
                <animate attributeName="width" from="0" to={Math.min(80, b.v * 0.8)} dur="0.9s" begin={`${i * 0.08}s`} fill="freeze"/>
              </rect>
              <text x={b.x} y="22" fontFamily="var(--font-mono)" fontSize="10" fill={b.c}>{b.v}%</text>
            </g>
          ))}
          {o.sel && <text x="660" y="0" textAnchor="end" fontFamily="var(--font-mono)" fontSize="10" fill="#F4024C">SELECTED</text>}
        </g>
      ))}
      <text x="80" y="470" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#B8860B">REQUIERE APROBACIÓN · OPERACIONES · MANIOBRAS VÍA SISTEMAS ESPECIALIZADOS</text>
    </svg>
  );
};

const EnSc5 = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <EnGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">APPROVAL FLOW · CADENA DE RESPONSABILIDAD</text>
    {[
      { r: 'ANÁLISIS OPERACIONAL',      s: '✓ Centro de Control · alternativa FLEX+MAINT validada',      t: '14:12' },
      { r: 'VALIDACIÓN ACTIVOS',         s: '✓ Ing. de Activos · ventana segura para reprogramación', t: '14:18' },
      { r: 'COORDINACIÓN CAMPO',         s: '✓ Field · cuadrilla disponible para movimiento',           t: '14:24' },
      { r: 'AUTORIZACIÓN OPERACIONES',    s: '✓ Jefe de Turno · dentro de umbral · sin maniobras críticas', t: '14:31' },
    ].map((n, i) => (
      <g key={n.r} transform={`translate(80, ${110 + i * 78})`}>
        <rect x="0" y="0" width="640" height="60" fill="#0A0B10" stroke="#0F5132" strokeWidth="1.5"/>
        <text x="20" y="24" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#0F5132">{n.r}</text>
        <text x="20" y="46" fontFamily="var(--font-body)" fontSize="13" fill="#FFF">{n.s}</text>
        <text x="620" y="34" textAnchor="end" fontFamily="var(--font-mono)" fontSize="11" fill="#96A3B5">{n.t}</text>
      </g>
    ))}
    <text x="80" y="450" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#0050BD">✓ CADENA COMPLETA · 4 ROLES · TRACE #EN-c9d4 · signed WORM</text>
  </svg>
);

const EnSc6 = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <EnGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">EJECUCIÓN COORDINADA · VÍA SISTEMAS AUTORIZADOS</text>
    <g transform="translate(400, 250)">
      <circle r="52" fill="none" stroke="#F4024C" strokeWidth="1" opacity="0.4">
        <animate attributeName="r" values="44;58;44" dur="1.6s" repeatCount="indefinite"/>
      </circle>
      <rect x="-44" y="-44" width="88" height="88" fill="#F4024C" stroke="#F4024C" strokeWidth="2"/>
      <text y="-6" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="800" fontSize="14" fill="#FFF">OMNIX</text>
      <text y="16" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" fill="#FFF">RUNTIME</text>
    </g>
    {[
      { s: 'ADMS',    a: 'flexibilidad batería activada',           x: 130, y: 130 },
      { s: 'EAM',      a: 'mantenimiento reprogramado ventana segura', x: 670, y: 130 },
      { s: 'WFM',       a: 'cuadrilla en standby',                     x: 130, y: 380 },
      { s: 'OMS',       a: 'notificación proactiva cliente crítico',   x: 670, y: 380 },
    ].map((s) => (
      <g key={s.s}>
        <FlowPath d={`M 400 250 L ${s.x} ${s.y}`} stroke="#F4024C" strokeWidth={1.5} particleColor="#F4024C" particleSize={4} duration={1.4} pulseWidth/>
        <g transform={`translate(${s.x}, ${s.y})`}>
          <rect x="-96" y="-24" width="192" height="48" fill="#0A0B10" stroke="#0F5132" strokeWidth="1.5"/>
          <text x="-82" y="-4" fontFamily="var(--font-display)" fontWeight="800" fontSize="14" fill="#FFF">{s.s}</text>
          <text x="-82" y="14" fontFamily="var(--font-mono)" fontSize="9" fill="#0F5132">✓ {s.a}</text>
        </g>
      </g>
    ))}
    <text x="80" y="480" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#0F5132">✓ TX #EN-c9d4 · 4 sistemas · signed WORM · reversible · sin maniobras críticas autónomas</text>
  </svg>
);

const EnSc7 = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <EnGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">DECISION TRACE · AUDITORÍA REGULATORIA COMPLETA</text>
    <g transform="translate(80, 100)">
      <rect x="0" y="0" width="680" height="360" fill="#0A0B10" stroke="#F4024C" strokeWidth="1.5"/>
      <text x="20" y="30" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.18em" fill="#F4024C">TRACE · #EN-c9d4 · signed WORM · retention según código de red aplicable</text>
      {[
        'timestamp:   2026-11-14 14:12:32.104 local',
        'system:      grid-abstract (topología no publicada)',
        'sdm:         sdm.energy-operations-v0.4',
        'signals:     EMS · historian · renovable · meteo · EAM · WMS · WFM',
        'convergence: demand +7% · renewable −12% · DIST-N2 degraded',
        'impact:      4 zonas · 1 cliente crítico',
        'options:     7 evaluated · continuity-scored',
        'selected:    option 02 · FLEX+MAINT · continuity 94% · risk 18%',
        'approval:    jefe de turno · dentro de umbral · sin maniobras críticas',
        'systems:     ADMS · EAM · WFM · OMS',
        'result:      flex activada · mantenimiento reprogramado · notificación',
        'reversible:  yes · ventana 6h',
        'evidence:    signed WORM · datos sintéticos en demo',
      ].map((line, i) => (
        <text key={i} x="20" y={60 + i * 22} fontFamily="var(--font-mono)" fontSize="11" fill="#FFF">
          <tspan fill="#52557A">{`0${i+1}  `}</tspan>{line}
        </text>
      ))}
    </g>
  </svg>
);

Object.assign(window, { EnergiaDemo });
