// MANUFACTURA · VIDEO DEMOSTRATIVO — 8 ESCENAS · 90 SEGUNDOS
// Escenario: riesgo de falla en activo crítico durante orden prioritaria
// Traducción del video Retail al vocabulario industrial IT/OT

const ManufDemo = () => {
  const [scene, setScene] = React.useState(0);
  const [playing, setPlaying] = React.useState(true);
  const [muted, setMuted] = React.useState(true);
  const scenes = [
    { d: 8,  label: 'Una orden crítica está en producción',           caption: 'La planta opera bajo un plan exigente. Line-4 ejecuta una orden prioritaria en el activo CNC-08.' },
    { d: 10, label: 'Una condición anómala aparece',                  caption: 'Vibración, temperatura y velocidad se desvían de su patrón. El activo aún no se detuvo.' },
    { d: 12, label: 'No es una alarma aislada',                        caption: 'El SDM Manufactura correlaciona la telemetría con historial de fallas, mantenimiento y calidad.' },
    { d: 13, label: 'OMNIX evalúa el impacto operacional',              caption: 'Determina qué orden está en riesgo, qué calidad puede verse afectada y qué alternativas existen.' },
    { d: 14, label: 'Tres alternativas · una decisión gobernada',      caption: 'Compara riesgo, impacto, repuestos, técnicos y cumplimiento del plan antes de recomendar acción.' },
    { d: 13, label: 'Decisión ejecutada entre sistemas',                caption: 'Con aprobación, OMNIX coordina CMMS, MES, APS y QMS. Orden de mantenimiento, secuencia y calidad.' },
    { d: 12, label: 'La operación continúa bajo control',              caption: 'Intervención controlada. Producción reasignada. Riesgo contenido. Downtime pasa de no planificado a planificado.' },
    { d: 8,  label: 'Cada decisión mejora la siguiente',                caption: 'El resultado retroalimenta el modelo. Trazabilidad regulator-ready. Evalúe una operación de Manufactura.' },
  ];
  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 fmtTime = (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' }}>
                Vea cómo OMNIX responde antes de que una anomalía detenga la línea.
              </h2>
            </Reveal>
          </div>
          <Reveal delay={140}>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 18, lineHeight: 1.55, color: '#52557A', margin: 0 }}>
              Escenario simulado. Un activo crítico muestra vibración y temperatura anómalas durante una orden prioritaria.
              OMNIX correlaciona, evalúa alternativas y coordina la respuesta entre CMMS, MES y QMS.
            </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' }}>
              {/* Chrome */}
              <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 · MANUFACTURING 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' }}>
                <ManufSceneStage 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: '#F4024C', textTransform: 'uppercase',
                }}>SIMULATED · scene {scene+1}</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: 24, letterSpacing: '-0.015em', color: '#FFF', marginBottom: 8, lineHeight: 1.15 }}>
                    {scenes[scene].label}
                  </div>
                  <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: '#96A3B5', lineHeight: 1.4, maxWidth: 640 }}>
                    {scenes[scene].caption}
                  </div>
                </div>
              </div>
              {/* Controls */}
              <div style={{ borderTop: '1.5px solid #2E3140', padding: '14px 20px', display: 'flex', alignItems: 'center', gap: 16 }}>
                <button onClick={() => setPlaying((p) => !p)} style={ctrlBtn}>
                  <i data-lucide={playing ? 'pause' : 'play'} width="14" height="14"></i>
                </button>
                <button onClick={() => { setElapsed(0); setScene(0); }} style={ctrlBtn}>
                  <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' }}>
                  {fmtTime(elapsed)} / {fmtTime(totalMs)}
                </span>
                <button onClick={() => setMuted((m) => !m)} style={ctrlBtn}>
                  <i data-lucide={muted ? 'volume-x' : 'volume-2'} width="14" height="14"></i>
                </button>
                <button style={ctrlBtn}>
                  <i data-lucide="captions" width="14" height="14"></i>
                </button>
              </div>
              {/* Chapters */}
              <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', transition: 'all 220ms',
                  }}>{i+1}</button>
                ))}
              </div>
            </div>
          </Reveal>

          {/* Explanation — 6 tarjetas para Manufactura */}
          <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: 15, lineHeight: 1.55, color: '#1E1F26', margin: '0 0 20px' }}>
                Convierte señales IT/OT en decisiones coordinadas entre mantenimiento, producción y calidad — sobre tus sistemas existentes.
              </p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, flex: 1 }}>
                {[
                  { t: 'Señales industriales',   d: 'Vibración, temperatura, velocidad, consumo. Ingesta IT/OT segregada.',           sys: 'SCADA · HIST', res: 'Anomalía detectada',   auto: 'N1' },
                  { t: 'Contexto operacional',    d: 'Historial de fallas, orden en curso, calidad, repuestos y ventana.',              sys: 'MES · ERP',    res: 'Contexto assembled',   auto: 'N1' },
                  { t: 'SDM Manufactura',         d: 'Modelo entrenado sobre activos, modos de falla y procedimientos del cliente.',    sys: 'CORE',         res: 'Razona con reglas',    auto: 'N2' },
                  { t: 'Decisión gobernada',      d: 'Alternativas evaluadas por riesgo, impacto y seguridad. Approval flow activo.',  sys: 'CORTEX',       res: 'Plan priorizado',      auto: 'N3' },
                  { t: 'Ejecución coordinada',    d: 'OT en modo seguro (recomienda). IT ejecuta: CMMS, MES, APS, QMS.',                sys: 'CMMS · MES',   res: 'Acción cross-sistema', auto: 'N3-N4' },
                  { t: 'Impacto y aprendizaje',   d: 'Logs firmados, KPI medidos (OEE, MTTR), reentrenamiento del SDM.',                sys: 'GOV · BI',     res: 'Auditable · learn',    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, display: 'flex', gap: 12, fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.12em' }}>
                        <span style={{ color: '#0050BD' }}>SYS · {c.sys}</span>
                        <span style={{ color: '#96A3B5' }}>→ {c.res}</span>
                      </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: 16, padding: '12px 14px', background: '#FBF3D9', border: '1px solid #B8860B', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.06em', color: '#1E1F26', lineHeight: 1.55 }}>
                Escenario demostrativo. Fuentes, reglas, umbrales, integraciones y niveles de autonomía se configuran según la arquitectura, procesos y gobierno de cada planta.
              </div>
            </div>
          </Reveal>
        </div>

        {/* Enlaces posteriores al video */}
        <Reveal delay={200}>
          <div style={{ marginTop: 32, padding: '20px 24px', border: '1px solid #E4EBF3', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 24, flexWrap: 'wrap' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: '#52557A', textTransform: 'uppercase' }}>
              Para profundizar
            </div>
            <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap' }}>
              <a href="arquitectura.html" style={docLink}>Ver arquitectura OMNIX <i data-lucide="arrow-up-right" width="12" height="12"/></a>
              <a href="ias-propietarias.html" style={docLink}>Explorar SDMs <i data-lucide="arrow-up-right" width="12" height="12"/></a>
              <a href="seguridad.html" style={docLink}>Seguridad y Gobernanza <i data-lucide="arrow-up-right" width="12" height="12"/></a>
              <a href="transferencia.html" style={docLink}>Transferencia de Control <i data-lucide="arrow-up-right" width="12" height="12"/></a>
            </div>
          </div>
        </Reveal>

        <Reveal delay={280}>
          <div style={{ marginTop: 24, padding: '24px 32px', background: '#000', color: '#FFF', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 32, flexWrap: 'wrap' }}>
            <div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: '#F4024C', textTransform: 'uppercase', marginBottom: 8 }}>Siguiente paso</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, letterSpacing: '-0.015em', color: '#FFF' }}>
                Mapeemos una decisión industrial sobre <em>tu</em> operación.
              </div>
            </div>
            <div style={{ display: 'flex', gap: 12 }}>
              <Button variant="primary" icon="arrow-right" href="diagnostico.html">Evaluar una operación de Manufactura</Button>
            </div>
          </div>
        </Reveal>
      </Container>
    </section>
  );
};

const ctrlBtn = {
  width: 32, height: 32, border: '1px solid #2E3140', background: '#0A0B10',
  color: '#FFF', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
};
const docLink = {
  fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', color: '#F4024C',
  textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6,
  textTransform: 'uppercase',
};

// ─── SCENE STAGE ────────────────────────────────────────────
const ManufSceneStage = ({ scene }) => (
  <div style={{ position: 'absolute', inset: 0 }}>
    {scene === 0 && <MfScene0Line/>}
    {scene === 1 && <MfScene1Anomaly/>}
    {scene === 2 && <MfScene2Correlation/>}
    {scene === 3 && <MfScene3Impact/>}
    {scene === 4 && <MfScene4Alternatives/>}
    {scene === 5 && <MfScene5Execute/>}
    {scene === 6 && <MfScene6Recovery/>}
    {scene === 7 && <MfScene7Outro/>}
  </div>
);

// SCENE 0 — Línea operando, orden prioritaria
const MfScene0Line = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <MfSceneGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">LINE-4 · SHIFT 3 · WORK ORDER WO-8402</text>
    {/* Line schematic — 5 stations */}
    <g transform="translate(80, 220)">
      {[0, 1, 2, 3, 4].map((i) => (
        <g key={i} transform={`translate(${i * 140}, 0)`}>
          <rect x="0" y="-40" width="100" height="80" fill="#0A0B10" stroke={i === 2 ? '#F4024C' : '#2E3140'} strokeWidth={i === 2 ? 2 : 1.5}/>
          <text x="50" y="-4" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill={i === 2 ? '#F4024C' : '#96A3B5'}>ST-0{i+1}</text>
          <text x="50" y="12" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="700" fontSize="12" fill="#FFF">
            {['LOAD', 'MILL', 'CNC-08', 'INSP', 'PACK'][i]}
          </text>
          {i === 2 && (
            <text x="50" y="26" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="8" letterSpacing="0.14em" fill="#F4024C">CRITICAL</text>
          )}
          {/* Conveyor arrows */}
          {i < 4 && (
            <FlowPath d={`M 100 0 L 140 0`} stroke="#0F5132" strokeWidth={1.5} particleColor="#0F5132" particleSize={3} duration={2}/>
          )}
        </g>
      ))}
    </g>
    {/* Order card */}
    <g transform="translate(80, 380)">
      <rect x="0" y="0" width="200" height="60" fill="#0A0B10" stroke="#F4024C" strokeWidth="1.25"/>
      <text x="12" y="20" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.18em" fill="#F4024C">PRIORITY · WO-8402</text>
      <text x="12" y="38" fontFamily="var(--font-display)" fontWeight="700" fontSize="15" fill="#FFF">Batch #A-2029 · 4.500 units</text>
      <text x="12" y="52" fontFamily="var(--font-mono)" fontSize="9" fill="#96A3B5">due 18:00 · progress 42%</text>
    </g>
    {/* KPIs on right */}
    <g transform="translate(560, 380)">
      <text x="0" y="10" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.18em" fill="#96A3B5">CURRENT · SHIFT</text>
      <text x="0" y="34" fontFamily="var(--font-display)" fontWeight="800" fontSize="32" fill="#0F5132" letterSpacing="-0.02em">OEE 82.1%</text>
      <text x="0" y="52" fontFamily="var(--font-mono)" fontSize="10" fill="#96A3B5">on plan</text>
    </g>
  </svg>
);

// SCENE 1 — Anomalía: vibración, temp, velocidad
const MfScene1Anomaly = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <MfSceneGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">CNC-08 · TELEMETRY · LAST 20 min</text>
    {/* 3 traces */}
    {[
      { l: 'VIBRATION · mm/s',   c: '#EA384C', d: 'M 80 240 L 200 235 L 300 230 L 400 210 L 500 175 L 600 140 L 700 120', anom: [600, 140] },
      { l: 'TEMPERATURE · °C',   c: '#B8860B', d: 'M 80 330 L 200 328 L 300 325 L 400 315 L 500 295 L 600 275 L 700 260', anom: [600, 275] },
      { l: 'SPEED · rpm',         c: '#0050BD', d: 'M 80 400 L 200 400 L 300 398 L 400 395 L 500 390 L 600 385 L 700 382', anom: null },
    ].map((tr, i) => (
      <g key={tr.l} transform={`translate(0, ${i * 8})`}>
        <text x="80" y={90 + i * 90} fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill={tr.c}>{tr.l}</text>
        <line x1="80" y1={230 + i * 45} x2="740" y2={230 + i * 45} stroke="#2E3140" strokeWidth="0.5" strokeDasharray="3 3"/>
        <DrawLine d={tr.d} stroke={tr.c} strokeWidth={2} duration={1500}/>
        {tr.anom && (
          <>
            <circle cx={tr.anom[0]} cy={tr.anom[1]} r="6" fill={tr.c}>
              <animate attributeName="r" values="6;10;6" dur="1.2s" repeatCount="indefinite"/>
            </circle>
            <text x={tr.anom[0] + 12} y={tr.anom[1] + 4} fontFamily="var(--font-mono)" fontSize="10" fill={tr.c}>+2.8σ</text>
          </>
        )}
      </g>
    ))}
    <text x="80" y="470" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#EA384C">DEVIATION DETECTED · ISO 10816 · ZONE C</text>
  </svg>
);

// SCENE 2 — Correlación con historial
const MfScene2Correlation = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <MfSceneGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">SDM MANUFACTURING · CORRELATION</text>
    {/* Historical failures on a timeline */}
    <text x="80" y="100" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#F4024C">SIMILAR CONDITIONS · LAST 24 MONTHS</text>
    <line x1="80" y1="130" x2="720" y2="130" stroke="#2E3140" strokeWidth="1"/>
    {[
      { x: 140, k: 'F1', d: 'bearing fault', c: '#EA384C' },
      { x: 240, k: 'F2', d: 'alignment',     c: '#B8860B' },
      { x: 380, k: 'F3', d: 'bearing fault', c: '#EA384C' },
      { x: 520, k: 'F4', d: 'alignment',     c: '#B8860B' },
      { x: 640, k: 'F5', d: 'bearing fault', c: '#EA384C' },
      { x: 700, k: 'CURRENT', d: 'match: bearing (0.87)', c: '#F4024C', big: true },
    ].map((e, i) => (
      <g key={i}>
        {e.big && <circle cx={e.x} cy={130} r="14" fill="none" stroke={e.c} strokeWidth="1.5"><animate attributeName="r" values="10;18;10" dur="1.4s" repeatCount="indefinite"/></circle>}
        <circle cx={e.x} cy={130} r={e.big ? 6 : 4} fill={e.c}/>
        <text x={e.x} y={155} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.06em" fill={e.c}>{e.k}</text>
        <text x={e.x} y={168} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="8" fill="#96A3B5">{e.d}</text>
      </g>
    ))}
    {/* Match analysis */}
    <g transform="translate(80, 220)">
      <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#F4024C">FAILURE MODE ANALYSIS</text>
      {[
        { l: 'Bearing degradation',   score: 0.87, c: '#EA384C' },
        { l: 'Misalignment',            score: 0.42, c: '#B8860B' },
        { l: 'Imbalance',               score: 0.28, c: '#0050BD' },
        { l: 'Loose fastener',          score: 0.11, c: '#96A3B5' },
      ].map((m, i) => (
        <g key={m.l} transform={`translate(0, ${30 + i * 32})`}>
          <text x="0" y="12" fontFamily="var(--font-body)" fontSize="13" fill="#FFF">{m.l}</text>
          <rect x="240" y="4" width="360" height="10" fill="#2E3140"/>
          <rect x="240" y="4" width={m.score * 360} height="10" fill={m.c}>
            <animate attributeName="width" from="0" to={m.score * 360} dur="0.9s" begin={`${i * 0.15}s`} fill="freeze"/>
          </rect>
          <text x="620" y="13" fontFamily="var(--font-mono)" fontSize="11" fill={m.c}>{(m.score * 100).toFixed(0)}%</text>
        </g>
      ))}
    </g>
    <text x="80" y="470" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#F4024C">HYPOTHESIS: bearing degradation · 24-72h to failure</text>
  </svg>
);

// SCENE 3 — Impacto operacional
const MfScene3Impact = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <MfSceneGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">OPERATIONAL IMPACT ASSESSMENT</text>
    <text x="80" y="90" fontFamily="var(--font-display)" fontWeight="700" fontSize="22" fill="#FFF" letterSpacing="-0.015em">
      Si CNC-08 falla · <tspan fill="#EA384C">consecuencias</tspan>
    </text>
    {[
      { l: 'ORDEN WO-8402',        v: 'Interrumpida',            c: '#EA384C', d: '58% incompleta · SLA 18:00' },
      { l: 'LOTE #A-2029',          v: 'Retención probable',      c: '#B8860B', d: 'inspección QMS reforzada' },
      { l: 'DOWNTIME PROYECTADO',   v: '6 – 8 horas',              c: '#EA384C', d: 'sin planificación' },
      { l: 'PLAN DIARIO',           v: '−1.240 unidades',         c: '#EA384C', d: 'schedule adherence 68%' },
      { l: 'MTTR ESTIMADO',         v: '4 – 6 horas',              c: '#B8860B', d: 'sin repuesto en sitio' },
      { l: 'LÍNEA ALTERNATIVA',      v: 'Line-2 · 70% capacidad',  c: '#0F5132', d: 'disponible en 40 min' },
    ].map((k, i) => (
      <g key={k.l} transform={`translate(${80 + (i % 3) * 220}, ${140 + Math.floor(i / 3) * 130})`}>
        <rect x="0" y="0" width="200" height="110" fill="#0A0B10" stroke="#2E3140" strokeWidth="1"/>
        <text x="14" y="22" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.14em" fill="#96A3B5">{k.l}</text>
        <text x="14" y="58" fontFamily="var(--font-display)" fontWeight="800" fontSize="20" fill={k.c} letterSpacing="-0.015em">{k.v}</text>
        <text x="14" y="82" fontFamily="var(--font-mono)" fontSize="10" fill="#96A3B5">{k.d}</text>
      </g>
    ))}
  </svg>
);

// SCENE 4 — 3 alternativas
const MfScene4Alternatives = () => {
  const options = [
    { k: 'MONITOR',   t: 'Continuar con mayor monitoreo',       a: 30, r: 78, s: 40, sel: false },
    { k: 'INTERVENE', t: 'Reducir velocidad · intervenir en ventana', a: 78, r: 22, s: 85, sel: true },
    { k: 'TRANSFER',  t: 'Transferir a Line-2 · detener CNC-08',  a: 92, r: 8,  s: 65, sel: false },
  ];
  return (
    <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
      <MfSceneGrid/>
      <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">DEEP THINK · GOVERNED ALTERNATIVES</text>
      <text x="80" y="90" fontFamily="var(--font-display)" fontWeight="700" fontSize="20" fill="#FFF" letterSpacing="-0.015em">3 alternativas · una decisión gobernada</text>
      <g transform="translate(80, 130)">
        <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">ACCIÓN</text>
        <text x="330" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#0F5132">PLAN PROTECTED</text>
        <text x="475" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#EA384C">RISK</text>
        <text x="590" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#0050BD">SAFETY</text>
      </g>
      {options.map((o, i) => (
        <g key={o.k} transform={`translate(80, ${170 + i * 90})`}>
          {o.sel && <rect x="-8" y="-24" width="656" height="72" fill="#F4024C" opacity="0.08"/>}
          {o.sel && <rect x="-8" y="-24" width="4" height="72" fill="#F4024C"/>}
          <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.14em" fill={o.sel ? '#F4024C' : '#96A3B5'}>0{i+1} · {o.k}</text>
          <text x="0" y="22" fontFamily="var(--font-display)" fontWeight="700" fontSize="15" fill="#FFF" letterSpacing="-0.01em">{o.t}</text>
          {[
            { x: 310, v: o.a, c: '#0F5132' },
            { x: 460, v: o.r, c: '#EA384C' },
            { x: 580, v: o.s, c: '#0050BD' },
          ].map((b, j) => (
            <g key={j}>
              <rect x={b.x} y="10" width="120" height="6" fill="#2E3140"/>
              <rect x={b.x} y="10" width={b.v * 1.2} height="6" fill={b.c}>
                <animate attributeName="width" from="0" to={b.v * 1.2} dur="0.9s" begin={`${i * 0.15}s`} fill="freeze"/>
              </rect>
              <text x={b.x} y="34" fontFamily="var(--font-mono)" fontSize="10" fill="#96A3B5">{b.v}%</text>
            </g>
          ))}
          {o.sel && <text x="660" y="12" textAnchor="end" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#F4024C">SELECTED</text>}
        </g>
      ))}
      <text x="80" y="470" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">POLICY MATCH · GUARDRAILS · REQUIRES MAINTENANCE APPROVAL</text>
    </svg>
  );
};

// SCENE 5 — Ejecución cross-sistemas
const MfScene5Execute = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <MfSceneGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">RUNTIME · CROSS-SYSTEM EXECUTION · APPROVED</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" letterSpacing="0.18em" fill="#FFF">RUNTIME</text>
    </g>
    {[
      { sys: 'CMMS', action: 'create WO-M-9241 · priority high',  x: 130, y: 130, delay: 0    },
      { sys: 'ERP',  action: 'reserve bearing #B-4082',            x: 670, y: 130, delay: 0.25 },
      { sys: 'MES',  action: 'schedule maintenance window',         x: 130, y: 380, delay: 0.5  },
      { sys: 'APS',  action: 'transfer WO-8402 → Line-2 (part.)',    x: 400, y: 420, delay: 0.75 },
      { sys: 'QMS',  action: 'reinforced inspection · batch #A-2029',x: 670, y: 380, delay: 1.0  },
    ].map((s, i) => (
      <g key={s.sys}>
        <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="-92" y="-24" width="184" height="48" fill="#0A0B10" stroke="#0F5132" strokeWidth="1.5"/>
          <text x="-80" y="-4" fontFamily="var(--font-display)" fontWeight="800" fontSize="14" fill="#FFF">{s.sys}</text>
          <text x="-80" y="14" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.06em" fill="#0F5132">✓ {s.action}</text>
        </g>
      </g>
    ))}
    <text x="80" y="480" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#0F5132">
      ✓ TX #MF-2029-b4c1 · APPROVED by maintenance-manager · 5 systems · 128ms · signed WORM
    </text>
  </svg>
);

// SCENE 6 — Impacto / recovery panel
const MfScene6Recovery = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <MfSceneGrid/>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">IMPACT · AUDITED · SHIFT 3</text>
    <text x="80" y="90" fontFamily="var(--font-display)" fontWeight="700" fontSize="22" fill="#FFF" letterSpacing="-0.015em">Downtime NO planificado → intervención planificada</text>
    {[
      { l: 'RIESGO DE FALLA',    b: '0.87 → 0.12',   sub: 'downgrade tras intervención', c: '#0F5132', x: 80,  y: 140 },
      { l: 'DOWNTIME',           b: 'PLANIFICADO',    sub: '90 min · en ventana',          c: '#F4024C', x: 260, y: 140 },
      { l: 'ORDEN WO-8402',      b: 'PROTEGIDA',      sub: '86% · vía Line-2',              c: '#0050BD', x: 440, y: 140 },
      { l: 'MTTR PROYECTADO',    b: '−4 horas',       sub: 'vs escenario reactivo',        c: '#B8860B', x: 620, y: 140 },
    ].map((k) => (
      <g key={k.l} transform={`translate(${k.x}, ${k.y})`}>
        <rect x="0" y="0" width="160" height="100" fill="#0A0B10" stroke="#2E3140" strokeWidth="1"/>
        <text x="12" y="20" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.14em" fill="#96A3B5">{k.l}</text>
        <text x="12" y="58" fontFamily="var(--font-display)" fontWeight="800" fontSize="22" fill={k.c} letterSpacing="-0.015em">{k.b}</text>
        <text x="12" y="82" fontFamily="var(--font-mono)" fontSize="9" fill="#96A3B5">{k.sub}</text>
      </g>
    ))}
    <g transform="translate(80, 280)">
      <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#F4024C">DECISION TRACE · #MF-2029-b4c1</text>
      {[
        'input: cnc-08 · vib=8.6mm/s · temp=+11°C · rpm=−4%',
        'sdm.mfg-asset-v3.7 · bearing-fault-hypothesis · conf=0.87',
        'policy.saf_03: match · guardrail.ot_read_only: pass',
        'action: reduce-speed + create-wo + transfer-partial',
        'systems: CMMS.create · ERP.reserve · MES.schedule · APS.transfer · QMS.reinforce',
        'autonomy: N3 · approved by maintenance-manager · signed · WORM',
      ].map((line, i) => (
        <text key={i} x="0" y={26 + i * 22} fontFamily="var(--font-mono)" fontSize="11" fill="#FFF">
          <tspan fill="#52557A">{`0${i+1}  `}</tspan>{line}
        </text>
      ))}
    </g>
  </svg>
);

// SCENE 7 — Outro
const MfScene7Outro = () => (
  <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
    <MfSceneGrid/>
    <g transform="translate(400, 200)">
      <text textAnchor="middle" fontFamily="var(--font-display)" fontWeight="800" fontSize="68" fill="#FFF" letterSpacing="-0.03em" y="0">OMNIX</text>
      <text y="30" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.24em" fill="#F4024C">COGNITIVE OPERATIONS · MANUFACTURING</text>
    </g>
    <g transform="translate(400, 300)">
      <text textAnchor="middle" fontFamily="var(--font-serif)" fontStyle="italic" fontSize="22" fill="#96A3B5" letterSpacing="-0.01em" y="0">
        Cada decisión mejora la siguiente.
      </text>
    </g>
    <g transform="translate(400, 380)">
      <rect x="-160" y="-24" width="320" height="48" fill="#F4024C"/>
      <text textAnchor="middle" fontFamily="var(--font-body)" fontWeight="600" fontSize="16" fill="#FFF" letterSpacing="-0.005em" y="6">Evalúe una operación de Manufactura</text>
    </g>
  </svg>
);

const MfSceneGrid = () => (
  <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>
);

Object.assign(window, { ManufDemo });
