// SECCIÓN 3 · SELECTOR DE CASO DEMOSTRATIVO — 4 tabs (4 dominios)
// Cada tab reproduce un video corto propio con escenas SVG

const MineriaDemo = () => {
  const [tab, setTab] = React.useState(0);
  const [scene, setScene] = React.useState(0);
  const [playing, setPlaying] = React.useState(true);

  const tabs = [
    { l: 'Mantenimiento', k: 'MANTENIMIENTO',   color: '#F4024C' },
    { l: 'Relaves',        k: 'RELAVES',          color: '#0050BD' },
    { l: 'Logística',      k: 'LOGÍSTICA',        color: '#B00238' },
    { l: 'Sist. expertos', k: 'SISTEMAS EXPERTOS',color: '#B8860B' },
  ];

  const stories = [
    // 0 · Mantenimiento
    {
      title: 'Anomalía en sistema de transporte crítico',
      scenes: [
        { d: 8,  label: 'La operación cumple el plan',              cap: 'Un sistema crítico mantiene el flujo de mineral hacia la planta.' },
        { d: 10, label: 'Una condición se desvía',                   cap: 'Vibración, temperatura y corriente se alejan del patrón normal.' },
        { d: 12, label: 'Una alerta no explica el impacto',         cap: 'OMNIX combina telemetría con historial, mantenimiento y conocimiento experto.' },
        { d: 13, label: 'Contexto operacional completo',            cap: 'Evalúa plan, stockpile, repuestos, técnicos y capacidad alternativa.' },
        { d: 14, label: 'Alternativas evaluadas bajo restricciones', cap: 'Compara riesgo, producción, personal y cumplimiento del plan.' },
        { d: 13, label: 'Decisión aprobada y coordinada',            cap: 'El responsable autoriza. OMNIX coordina CMMS · ERP · planificación.' },
        { d: 12, label: 'De anomalía a respuesta controlada',        cap: 'Intervención planificada y trazable, no parada reactiva.' },
        { d: 8,  label: 'Cada decisión mejora la siguiente',         cap: 'Log firmado · aprendizaje del SDM · Evalúe una operación minera.' },
      ],
      sys: ['SCADA · Historian', 'Condition Monitoring', 'CMMS · EAM', 'ERP', 'Planificación', 'SDM Confiabilidad'],
      decision: 'Intervención programada dentro de ventana operacional aprobada',
      autonomy: 'N3 (asistida) → N4 en casos recurrentes',
      kpi: 'MTBF · MTTR · Disponibilidad · Cumplimiento del plan',
    },
    // 1 · Relaves
    {
      title: 'Tendencia instrumental que requiere revisión',
      scenes: [
        { d: 8,  label: 'Vigilancia continua',                        cap: 'Piezómetros, deformación, filtraciones y balance hídrico se monitorean permanentemente.' },
        { d: 10, label: 'Una tendencia se desvía',                    cap: 'Combinación de señales fuera de rango histórico · dato de calidad marginal.' },
        { d: 12, label: 'OMNIX reconcilia fuentes',                    cap: 'Correlaciona instrumentación, inspecciones y balance de agua. Verifica integridad.' },
        { d: 13, label: 'Contexto e historial',                        cap: 'Consulta observaciones de terreno, precipitaciones y condiciones de operación recientes.' },
        { d: 14, label: 'Apertura de investigación',                    cap: 'Solicita revisión al responsable técnico. Aumenta frecuencia de monitoreo.' },
        { d: 13, label: 'Escalamiento gobernado',                      cap: 'Notifica cadena de responsables · reúne evidencia · agenda inspección.' },
        { d: 12, label: 'Decisión técnica del responsable',             cap: 'La responsabilidad geotécnica permanece en roles autorizados por la compañía.' },
        { d: 8,  label: 'Trazabilidad completa',                       cap: 'Cada paso registrado · evidencia disponible para auditoría y revisión profesional.' },
      ],
      sys: ['Piezometría · deformación', 'Balance hídrico', 'Estaciones meteo', 'Inspecciones', 'Gestión documental', 'SDM Relaves'],
      decision: 'Apertura de investigación · escalamiento a responsable · frecuencia reforzada',
      autonomy: 'N1 – N2 · aprobación humana obligatoria en decisiones críticas',
      kpi: 'Tiempo desviación → revisión · completitud datos · trazabilidad',
      caution: 'OMNIX acelera detección, investigación, coordinación y documentación. La responsabilidad técnica permanece en los roles autorizados.',
    },
    // 2 · Logística
    {
      title: 'Restricción amenaza ventana de embarque',
      scenes: [
        { d: 8,  label: 'Programa de embarque activo',                 cap: 'Un compromiso de embarque debe cumplirse en una ventana portuaria específica.' },
        { d: 10, label: 'Una restricción aparece',                      cap: 'Cierre de ruta, indisponibilidad de flota o restricción portuaria detectada.' },
        { d: 12, label: 'OMNIX evalúa impacto en cadena',              cap: 'Cruza producción, inventarios, calidad, capacidad ferroviaria y compromisos.' },
        { d: 13, label: 'Alternativas por SLA y costo',                  cap: 'Recalcula prioridades, evalúa reprogramación de rutas y capacidad alternativa.' },
        { d: 14, label: 'Decisión coordinada mina-puerto',              cap: 'Ajusta secuencia, reasigna transporte, modifica ventanas dentro de reglas.' },
        { d: 13, label: 'Ejecución cross-sistema',                       cap: 'Actualiza WMS, TMS, programa ferroviario y notifica áreas comerciales.' },
        { d: 12, label: 'Impacto medido',                                cap: 'Embarque protegido dentro de compromiso. Costo extra minimizado.' },
        { d: 8,  label: 'De mina a puerto, una decisión',                cap: 'Sin reprogramaciones manuales · sin llamadas cross-área.' },
      ],
      sys: ['FMS · despacho', 'WMS · stockpiles', 'TMS · rutas', 'Ferrocarril · puerto', 'Compromisos comerciales', 'SDM Logística'],
      decision: 'Reprogramación coordinada · reasignación de transporte · modificación de ventana',
      autonomy: 'N3 · aprobación de logística en cambios comerciales',
      kpi: 'OTIF · tiempo mina-puerto · cumplimiento embarques · demoras',
    },
    // 3 · Sistemas expertos
    {
      title: 'Recomendaciones expertas contradictorias',
      scenes: [
        { d: 8,  label: 'Múltiples sistemas expertos activos',           cap: 'APC, mantenimiento predictivo, geometalurgia y energía operan concurrentemente.' },
        { d: 10, label: 'Recomendaciones divergentes',                   cap: 'APC propone +throughput · condition monitoring anticipa riesgo · geomet marca mayor dureza.' },
        { d: 12, label: 'OMNIX normaliza contexto',                       cap: 'Recibe recomendaciones, unifica escalas temporales y evalúa compatibilidad.' },
        { d: 13, label: 'Identifica conflicto',                            cap: 'Detecta objetivos locales incompatibles con el objetivo global de la operación.' },
        { d: 14, label: 'Jerarquía de objetivos aplicada',                cap: 'Aplica prioridad: seguridad · continuidad · plan · costo · dentro de restricciones.' },
        { d: 13, label: 'Propuesta consolidada',                          cap: 'Genera decisión única con fundamento explícito de cómo se resolvió el conflicto.' },
        { d: 12, label: 'Aprobación operacional',                         cap: 'El responsable operacional autoriza y la decisión se registra con evidencia.' },
        { d: 8,  label: 'No reemplaza · coordina',                        cap: 'Los sistemas expertos siguen operando. OMNIX evalúa el impacto completo.' },
      ],
      sys: ['APC', 'Mantto. predictivo', 'Geometalurgia', 'Energía', 'Planificación', 'SDM Orquestación'],
      decision: 'Respuesta consolidada que balancea throughput, riesgo activo, dureza y disponibilidad',
      autonomy: 'N3 · N4 en escenarios recurrentes con guardrails',
      kpi: 'Adherencia al plan · estabilidad operacional · conflictos resueltos · decisiones auditadas',
    },
  ];

  const story = stories[tab];
  const totalMs = story.scenes.reduce((s, x) => s + x.d * 1000, 0);
  const [elapsed, setElapsed] = React.useState(0);

  // Reset al cambiar de tab
  React.useEffect(() => { setScene(0); setElapsed(0); setPlaying(true); }, [tab]);

  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 < story.scenes.length; i++) {
          acc += story.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, tab]);

  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: 48, alignItems: 'end' }}>
          <div>
            <Reveal><SectionMeta n="02" label="Demostraciones por dominio"/></Reveal>
            <Reveal delay={80}>
              <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 52, lineHeight: 1.03, letterSpacing: '-0.025em', margin: 0, color: '#000' }}>
                Elija un dominio · vea la decisión coordinada.
              </h2>
            </Reveal>
          </div>
          <Reveal delay={140}>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 17, lineHeight: 1.55, color: '#52557A', margin: 0 }}>
              Cada dominio muestra su propio ciclo: señal → contexto → alternativas → decisión → ejecución. Escenario simulado.
            </p>
          </Reveal>
        </div>

        {/* Tab selector — 4 dominios */}
        <Reveal>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, marginBottom: 24, border: '1.5px solid #1E1F26' }}>
            {tabs.map((t, i) => (
              <button key={t.k} onClick={() => setTab(i)} style={{
                padding: '18px 20px', border: 'none', textAlign: 'left', cursor: 'pointer',
                background: tab === i ? '#000' : '#FFF',
                color: tab === i ? '#FFF' : '#1E1F26',
                borderRight: (i < 3) ? '1px solid #E4EBF3' : 'none',
                transition: 'all 220ms',
              }}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: tab === i ? t.color : '#96A3B5', marginBottom: 6, textTransform: 'uppercase' }}>
                  DOMINIO 0{i+1}
                </div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16, letterSpacing: '-0.005em' }}>{t.l}</div>
              </button>
            ))}
          </div>
        </Reveal>

        <div style={{ display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 24 }}>
          {/* Video */}
          <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 · {tabs[tab].k} · SCENE 0{scene+1}/0{story.scenes.length}</span>
              <span style={{ color: tabs[tab].color, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <span style={{ width: 6, height: 6, borderRadius: 999, background: tabs[tab].color }} className={playing ? 'omnix-blink' : ''}/>
                {playing ? 'PLAYING' : 'PAUSED'}
              </span>
            </div>
            <div style={{ position: 'relative', aspectRatio: '16 / 10', background: '#0A0B10' }}>
              <MineriaSceneStage tab={tab} 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: tabs[tab].color, textTransform: 'uppercase',
              }}>SIMULATED · {tabs[tab].k}</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 }}>
                  {story.scenes[scene].label}
                </div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: '#96A3B5', lineHeight: 1.4, maxWidth: 620 }}>
                  {story.scenes[scene].cap}
                </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: tabs[tab].color, 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 style={ctrlBtn}>
                <i data-lucide="volume-x" width="14" height="14"></i>
              </button>
              <button style={ctrlBtn}>
                <i data-lucide="captions" width="14" height="14"></i>
              </button>
            </div>
            <div style={{ borderTop: '1.5px solid #2E3140', display: 'grid', gridTemplateColumns: `repeat(${story.scenes.length}, 1fr)` }}>
              {story.scenes.map((s, i) => (
                <button key={i} onClick={() => {
                  const before = story.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 ? tabs[tab].color : '#0A0B10',
                  color: scene === i ? '#FFF' : '#52557A',
                  borderRight: (i < story.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>

          {/* Panel de contexto por dominio */}
          <div style={{ border: '1.5px solid #1E1F26', background: '#FAFBFD', padding: 28, display: 'flex', flexDirection: 'column', gap: 18 }}>
            <div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: tabs[tab].color, textTransform: 'uppercase', marginBottom: 6 }}>
                CASO · {tabs[tab].k}
              </div>
              <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, letterSpacing: '-0.015em', color: '#000', margin: 0, lineHeight: 1.2 }}>
                {story.title}
              </h3>
            </div>

            <div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: '#96A3B5', textTransform: 'uppercase', marginBottom: 8 }}>Sistemas conectados</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {story.sys.map((s) => (
                  <span key={s} style={{
                    padding: '4px 8px', border: `1px solid ${tabs[tab].color}`, color: tabs[tab].color,
                    fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.08em',
                  }}>{s}</span>
                ))}
              </div>
            </div>

            <div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: '#96A3B5', textTransform: 'uppercase', marginBottom: 6 }}>Decisión coordinada</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: '#1E1F26', lineHeight: 1.5 }}>{story.decision}</div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: '#96A3B5', textTransform: 'uppercase', marginBottom: 4 }}>Nivel de autonomía</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: tabs[tab].color, fontWeight: 500 }}>{story.autonomy}</div>
              </div>
              <div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: '#96A3B5', textTransform: 'uppercase', marginBottom: 4 }}>KPI impactado</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: '#1E1F26', lineHeight: 1.4 }}>{story.kpi}</div>
              </div>
            </div>

            {story.caution && (
              <div style={{ padding: '12px 14px', background: '#FBF3D9', border: '1px solid #B8860B', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.06em', color: '#1E1F26', lineHeight: 1.55, marginTop: 'auto' }}>
                <strong style={{ color: '#B8860B', letterSpacing: '0.14em', textTransform: 'uppercase' }}>PRECAUCIÓN · </strong>
                {story.caution}
              </div>
            )}

            <div style={{ marginTop: story.caution ? 0 : 'auto', paddingTop: 16, borderTop: '1px solid #E4EBF3' }}>
              <Button variant="ghost" icon="arrow-right" href={
                tab === 0 ? 'mineria-mantenimiento.html' :
                tab === 1 ? 'mineria-relaves.html' :
                tab === 2 ? 'mineria-logistica.html' :
                             'mineria-sistemas-expertos.html'
              }>Ver dominio completo</Button>
            </div>
          </div>
        </div>
      </Container>
    </section>
  );
};

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

// SCENE STAGE — 4 tabs × 8 escenas = 32 escenas. Simplifico usando componentes por tab.
const MineriaSceneStage = ({ tab, scene }) => {
  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      {tab === 0 && <MaintScenes scene={scene}/>}
      {tab === 1 && <TailingsScenes scene={scene}/>}
      {tab === 2 && <LogisticsScenes scene={scene}/>}
      {tab === 3 && <ExpertScenes scene={scene}/>}
    </div>
  );
};

// ─── TAB 0 · MANTENIMIENTO (8 escenas) ────────────────────
const MaintScenes = ({ scene }) => {
  const SceneWrap = ({ children }) => (
    <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}>
      <MnSceneGrid/>
      {children}
    </svg>
  );
  if (scene === 0) return (
    <SceneWrap>
      <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">MINE-TO-PLANT · SHIFT 3 · SYSTEM 47</text>
      <g transform="translate(80, 220)">
        {['MINA', 'CHANC', 'CORREA', 'MOLINO', 'PLANTA'].map((l, i) => (
          <g key={l} transform={`translate(${i * 140}, 0)`}>
            <rect x="0" y="-30" width="100" height="60" fill="#0A0B10" stroke={l === 'CORREA' ? '#F4024C' : '#0F5132'} strokeWidth={l === 'CORREA' ? 2 : 1.5}/>
            <text x="50" y="4" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="700" fontSize="12" fill="#FFF">{l}</text>
            {l === 'CORREA' && <text x="50" y="20" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="8" letterSpacing="0.14em" fill="#F4024C">CRITICAL</text>}
            {i < 4 && <FlowPath d={`M 100 0 L 140 0`} stroke="#0F5132" strokeWidth={1.5} particleColor="#0F5132" particleSize={3} duration={2}/>}
          </g>
        ))}
      </g>
      <g transform="translate(80, 350)">
        <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">FLOW · t/h</text>
        <text x="0" y="30" fontFamily="var(--font-display)" fontWeight="800" fontSize="30" fill="#0F5132" letterSpacing="-0.02em">4.820</text>
        <text x="150" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">TARGET</text>
        <text x="150" y="30" fontFamily="var(--font-mono)" fontSize="20" fill="#96A3B5">4.900</text>
      </g>
    </SceneWrap>
  );
  if (scene === 1) return (
    <SceneWrap>
      <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">CORREA-47 · TELEMETRY · L15 min</text>
      {[
        { l: 'VIBRACIÓN · mm/s', c: '#EA384C', d: 'M 80 200 L 200 195 L 320 190 L 440 175 L 560 145 L 680 115 L 720 105', anom: [680, 115] },
        { l: 'TEMPERATURA · °C',  c: '#B8860B', d: 'M 80 290 L 200 288 L 320 285 L 440 275 L 560 260 L 680 245 L 720 240', anom: [680, 245] },
        { l: 'CORRIENTE · A',     c: '#0050BD', d: 'M 80 380 L 200 380 L 320 378 L 440 373 L 560 366 L 680 358 L 720 355', anom: null },
      ].map((tr, i) => (
        <g key={tr.l}>
          <text x="80" y={90 + i * 90} fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill={tr.c}>{tr.l}</text>
          <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;11;6" dur="1.2s" repeatCount="indefinite"/></circle>}
        </g>
      ))}
    </SceneWrap>
  );
  if (scene === 2) return (
    <SceneWrap>
      <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">SDM CONFIABILIDAD · CROSS-SOURCE</text>
      {['SCADA · Historian', 'Condition Monitoring', 'CMMS · fallas', 'Sistema experto'].map((s, i) => (
        <g key={s} transform={`translate(80, ${120 + i * 60})`}>
          <rect x="0" y="-14" width="200" 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 200 0 L 340 0 L 380 200 L 440 200`} stroke="#96A3B5" strokeWidth={0.75} particleColor="#0050BD" particleSize={2.5} duration={2.2 + i * 0.15}/>
        </g>
      ))}
      <g transform="translate(500, 260)">
        <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="-50" y="-50" width="100" height="100" fill="#000" stroke="#F4024C" strokeWidth="2"/>
        <text y="-6" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="800" fontSize="14" fill="#FFF">SDM</text>
        <text y="14" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="700" fontSize="12" fill="#F4024C">CONFIABILIDAD</text>
      </g>
    </SceneWrap>
  );
  if (scene === 3) return (
    <SceneWrap>
      <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">OPERATIONAL CONTEXT · IMPACT ASSESSMENT</text>
      {[
        { l: 'PLAN', v: '4.900 t/h', c: '#0050BD' },
        { l: 'STOCKPILE',v: '18h buffer', c: '#0F5132' },
        { l: 'REPUESTO',   v: 'en sitio', c: '#0F5132' },
        { l: 'TÉCNICOS',    v: '2/turno',  c: '#B8860B' },
        { l: 'LÍNEA ALT.',  v: 'Correa-46', c: '#0F5132' },
        { l: 'PRODUCCIÓN RIESGO', v: '−1.200 t', c: '#EA384C' },
      ].map((k, i) => (
        <g key={k.l} transform={`translate(${80 + (i % 3) * 220}, ${120 + Math.floor(i / 3) * 140})`}>
          <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="60" fontFamily="var(--font-display)" fontWeight="800" fontSize="22" fill={k.c} letterSpacing="-0.015em">{k.v}</text>
        </g>
      ))}
    </SceneWrap>
  );
  if (scene === 4) return (
    <SceneWrap>
      <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">ALTERNATIVAS · RESTRICCIONES APLICADAS</text>
      {[
        { k: 'MONITOR',       t: 'Continuar con monitoreo reforzado',    r: 68, sel: false },
        { k: 'REDUCE',        t: 'Reducir carga -15%',                    r: 40, sel: false },
        { k: 'INTERVENE',     t: 'Intervenir en ventana (2h)',            r: 15, sel: true },
        { k: 'DIVERT',        t: 'Redirigir flujo temporalmente',         r: 20, sel: false },
        { k: 'STOP',          t: 'Detener controladamente',                r: 8,  sel: false },
      ].map((o, i) => (
        <g key={o.k} transform={`translate(80, ${100 + i * 60})`}>
          {o.sel && <rect x="-8" y="-24" width="656" height="52" fill="#F4024C" opacity="0.08"/>}
          {o.sel && <rect x="-8" y="-24" width="4" height="52" fill="#F4024C"/>}
          <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill={o.sel ? '#F4024C' : '#96A3B5'}>0{i+1} · {o.k}</text>
          <text x="0" y="20" fontFamily="var(--font-display)" fontWeight="700" fontSize="14" fill="#FFF">{o.t}</text>
          <rect x="480" y="10" width="160" height="8" fill="#2E3140"/>
          <rect x="480" y="10" width={o.r * 1.6} height="8" fill={o.r > 40 ? '#EA384C' : '#0F5132'}><animate attributeName="width" from="0" to={o.r * 1.6} dur="0.9s" begin={`${i * 0.12}s`} fill="freeze"/></rect>
          <text x="480" y="34" fontFamily="var(--font-mono)" fontSize="10" fill="#96A3B5">risk {o.r}%</text>
          {o.sel && <text x="650" y="0" textAnchor="end" fontFamily="var(--font-mono)" fontSize="10" fill="#F4024C">SELECTED</text>}
        </g>
      ))}
    </SceneWrap>
  );
  if (scene === 5) return (
    <SceneWrap>
      <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">APPROVED · EXECUTING CROSS-SYSTEM</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: 'CMMS', a: 'crea WO-M-8291', x: 130, y: 130 },
        { s: 'ERP',  a: 'reserva repuesto', x: 670, y: 130 },
        { s: 'PLAN', a: 'ventana confirmada', x: 130, y: 380 },
        { s: 'OPS',  a: 'notifica supervisor', 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="-72" y="-24" width="144" height="48" fill="#0A0B10" stroke="#0F5132" strokeWidth="1.5"/>
            <text x="-60" y="-4" fontFamily="var(--font-display)" fontWeight="800" fontSize="14" fill="#FFF">{s.s}</text>
            <text x="-60" y="14" fontFamily="var(--font-mono)" fontSize="9" fill="#0F5132">✓ {s.a}</text>
          </g>
        </g>
      ))}
    </SceneWrap>
  );
  if (scene === 6) return (
    <SceneWrap>
      <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">IMPACT · CONTROLLED INTERVENTION</text>
      {[
        { l: 'DOWNTIME', v: 'PLANIF', s: '2h vs 8h reactivo', c: '#F4024C', x: 80, y: 140 },
        { l: 'PRODUCCIÓN PROT.', v: '92%', s: 'plan cubierto', c: '#0F5132', x: 260, y: 140 },
        { l: 'MTTR', v: '−4h', s: 'vs escenario reactivo', c: '#0F5132', x: 440, y: 140 },
        { l: 'COSTO', v: '−58%', s: 'vs emergencia', c: '#0050BD', 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.v}</text>
          <text x="12" y="82" fontFamily="var(--font-mono)" fontSize="9" fill="#96A3B5">{k.s}</text>
        </g>
      ))}
      <g transform="translate(80, 300)">
        <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#F4024C">DECISION TRACE · #MN-2029-c8f1 · signed</text>
        {['input: correa-47 · vib=8.2mm/s · temp=+9°C', 'sdm.reliability-v3.2 · conf=0.89', 'policy match · approval flow · maintenance-manager', 'exec: cmms + erp + plan + ops · 5 sistemas · 112ms'].map((l, i) => (
          <text key={i} x="0" y={22 + i * 20} fontFamily="var(--font-mono)" fontSize="11" fill="#FFF"><tspan fill="#52557A">{`0${i+1}  `}</tspan>{l}</text>
        ))}
      </g>
    </SceneWrap>
  );
  return (
    <SceneWrap>
      <g transform="translate(400, 200)">
        <text textAnchor="middle" fontFamily="var(--font-display)" fontWeight="800" fontSize="64" fill="#FFF" letterSpacing="-0.03em" y="0">OMNIX</text>
        <text y="28" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.22em" fill="#F4024C">CONFIABILIDAD MINERA</text>
      </g>
      <g transform="translate(400, 300)">
        <text textAnchor="middle" fontFamily="var(--font-serif)" fontStyle="italic" fontSize="20" fill="#96A3B5" y="0">
          Cada decisión mejora la siguiente.
        </text>
      </g>
      <g transform="translate(400, 380)">
        <rect x="-140" y="-24" width="280" height="48" fill="#F4024C"/>
        <text textAnchor="middle" fontFamily="var(--font-body)" fontWeight="600" fontSize="15" fill="#FFF" y="6">Evalúe una operación minera</text>
      </g>
    </SceneWrap>
  );
};

// ─── TAB 1 · RELAVES (8 escenas) ────────────────────
const TailingsScenes = ({ scene }) => {
  const SW = ({ children }) => <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}><MnSceneGrid/>{children}</svg>;
  if (scene === 0) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">TAILINGS FACILITY · CONTINUOUS MONITORING</text>
    <g transform="translate(80, 200)">
      {['PIEZO', 'DEFORM', 'FILTR', 'CAUDAL', 'METEO', 'INSPEC'].map((k, i) => (
        <g key={k} transform={`translate(${i * 110}, 0)`}>
          <rect x="0" y="-24" width="90" height="48" fill="#0A0B10" stroke="#0050BD" strokeWidth="1.25"/>
          <text x="45" y="0" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="10" fill="#FFF" letterSpacing="0.06em">{k}</text>
          <circle cx="10" cy="14" r="3" fill="#0F5132"><animate attributeName="opacity" values="1;0.3;1" dur="1.6s" repeatCount="indefinite"/></circle>
          <text x="16" y="17" fontFamily="var(--font-mono)" fontSize="8" fill="#0F5132">nominal</text>
        </g>
      ))}
    </g>
    <text x="80" y="340" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">6 fuentes · monitoreo continuo · data quality ok</text>
  </SW>;
  if (scene === 1) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">DEVIATION DETECTED · MULTI-SIGNAL</text>
    {[
      { l: 'PIEZO-04', c: '#EA384C', d: 'M 80 200 L 220 202 L 340 205 L 460 208 L 580 218 L 700 232', hi: true },
      { l: 'BALANCE H₂O', c: '#B8860B', d: 'M 80 290 L 220 292 L 340 295 L 460 298 L 580 305 L 700 315', hi: true },
    ].map((tr, i) => (
      <g key={tr.l}>
        <text x="80" y={90 + i * 100} fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill={tr.c}>{tr.l}</text>
        <DrawLine d={tr.d} stroke={tr.c} strokeWidth={2} duration={1500}/>
        {tr.hi && <circle cx="700" cy={i === 0 ? 232 : 315} r="7" fill={tr.c}><animate attributeName="r" values="6;10;6" dur="1.2s" repeatCount="indefinite"/></circle>}
      </g>
    ))}
    <text x="80" y="430" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#B8860B">
      COMBINED SIGNALS · REVIEW REQUIRED · not conclusive · engineering assessment needed
    </text>
  </SW>;
  if (scene === 2) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">SDM RELAVES · DATA RECONCILIATION</text>
    {['Piezometría', 'Deformación', 'Balance hídrico', 'Inspecciones', 'Meteorología', 'Historial'].map((s, i) => (
      <g key={s} transform={`translate(80, ${120 + i * 44})`}>
        <rect x="0" y="-14" width="180" height="28" fill="#0A0B10" stroke="#0050BD" strokeWidth="0.75"/>
        <text x="12" y="4" fontFamily="var(--font-mono)" fontSize="10" fill="#FFF">{s}</text>
        <text x="170" y="4" textAnchor="end" fontFamily="var(--font-mono)" fontSize="9" fill="#0F5132">✓ verified</text>
        <FlowPath d={`M 180 0 L 340 0 L 400 130`} stroke="#96A3B5" strokeWidth={0.5} particleColor="#0050BD" particleSize={2} duration={2.4 + i * 0.15}/>
      </g>
    ))}
    <g transform="translate(500, 260)">
      <circle r="60" fill="none" stroke="#0050BD" strokeWidth="1" opacity="0.3"><animate attributeName="r" values="50;68;50" dur="2.4s" repeatCount="indefinite"/></circle>
      <rect x="-50" y="-40" width="100" height="80" fill="#000" stroke="#0050BD" strokeWidth="2"/>
      <text y="-6" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="800" fontSize="14" fill="#FFF">SDM</text>
      <text y="14" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="700" fontSize="12" fill="#0050BD">RELAVES</text>
    </g>
  </SW>;
  if (scene === 3) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">CONTEXT · L30 DAYS</text>
    {[
      { l: 'PRECIPITACIÓN', v: '+42%', s: 'vs promedio estacional', c: '#B8860B' },
      { l: 'DEPOSICIÓN', v: 'nominal', s: 'dentro de plan', c: '#0F5132' },
      { l: 'INSPECCIONES', v: '2 pend.', s: 'zona norte', c: '#B8860B' },
      { l: 'BOMBAS AGUA', v: 'op ok', s: '4/4 disponibles', c: '#0F5132' },
    ].map((k, i) => (
      <g key={k.l} transform={`translate(${80 + (i % 2) * 340}, ${120 + Math.floor(i / 2) * 140})`}>
        <rect x="0" y="0" width="300" height="110" fill="#0A0B10" stroke="#2E3140" strokeWidth="1"/>
        <text x="14" y="22" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">{k.l}</text>
        <text x="14" y="60" fontFamily="var(--font-display)" fontWeight="800" fontSize="26" fill={k.c} letterSpacing="-0.02em">{k.v}</text>
        <text x="14" y="86" fontFamily="var(--font-mono)" fontSize="10" fill="#96A3B5">{k.s}</text>
      </g>
    ))}
  </SW>;
  if (scene === 4) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">INVESTIGATION OPENED · NO AUTONOMOUS ACTION</text>
    <g transform="translate(80, 140)">
      {[
        { i: '01', a: 'Aumentar frecuencia monitoreo · piezo-04' },
        { i: '02', a: 'Reunir historial inspecciones L30 días · zona norte' },
        { i: '03', a: 'Solicitar revisión ingeniero geotécnico responsable' },
        { i: '04', a: 'Coordinar inspección en terreno · próximas 24h' },
        { i: '05', a: 'Notificar cadena responsables · Superintendente Relaves + HSEC' },
        { i: '06', a: 'Documentar antecedentes · abrir investigación #INV-4082' },
      ].map((s, i) => (
        <g key={s.i} transform={`translate(0, ${i * 44})`}>
          <text x="0" y="4" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.14em" fill="#0050BD">STEP {s.i}</text>
          <text x="70" y="4" fontFamily="var(--font-body)" fontSize="13" fill="#FFF">{s.a}</text>
          <i data-lucide="check" width="14" height="14" x="620" y="-8" style={{ color: '#0F5132' }}/>
        </g>
      ))}
    </g>
  </SW>;
  if (scene === 5) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">ESCALATION · GOVERNED</text>
    <g transform="translate(80, 130)">
      {[
        { r: 'Superintendente Relaves',      t: '10:42', s: 'notified' },
        { r: 'HSEC · seguridad operacional',  t: '10:43', s: 'notified' },
        { r: 'Ingeniero responsable',         t: '10:44', s: 'reviewing' },
        { r: 'Gerencia de faena',              t: '10:47', s: 'informed' },
      ].map((s, i) => (
        <g key={s.r} transform={`translate(0, ${i * 60})`}>
          <rect x="0" y="0" width="640" height="48" fill="#0A0B10" stroke="#0050BD" strokeWidth="1"/>
          <text x="16" y="20" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.14em" fill="#0050BD">ROL · 0{i+1}</text>
          <text x="16" y="38" fontFamily="var(--font-display)" fontWeight="700" fontSize="14" fill="#FFF">{s.r}</text>
          <text x="520" y="20" fontFamily="var(--font-mono)" fontSize="10" fill="#96A3B5">{s.t}</text>
          <text x="520" y="38" fontFamily="var(--font-mono)" fontSize="10" fill="#0F5132">✓ {s.s}</text>
        </g>
      ))}
    </g>
  </SW>;
  if (scene === 6) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">TECHNICAL DECISION · BY AUTHORIZED ROLES</text>
    <g transform="translate(80, 120)">
      <rect x="0" y="0" width="640" height="240" fill="#0A0B10" stroke="#B8860B" strokeWidth="1.5"/>
      <text x="20" y="30" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.18em" fill="#B8860B">PRECAUCIÓN</text>
      <text x="20" y="62" fontFamily="var(--font-display)" fontWeight="700" fontSize="18" fill="#FFF">
        La responsabilidad técnica geotécnica permanece
      </text>
      <text x="20" y="86" fontFamily="var(--font-display)" fontWeight="700" fontSize="18" fill="#FFF">
        en los roles autorizados por la compañía.
      </text>
      <text x="20" y="130" fontFamily="var(--font-body)" fontSize="13" fill="#96A3B5">OMNIX acelera:</text>
      {['Detección de desviaciones combinadas', 'Reconciliación de fuentes de información', 'Coordinación de investigaciones', 'Documentación y trazabilidad de evidencia'].map((it, i) => (
        <g key={it} transform={`translate(20, ${150 + i * 20})`}>
          <text x="10" y="10" fontFamily="var(--font-mono)" fontSize="10" fill="#0050BD">→</text>
          <text x="30" y="10" fontFamily="var(--font-body)" fontSize="12" fill="#FFF">{it}</text>
        </g>
      ))}
    </g>
  </SW>;
  return <SW>
    <g transform="translate(400, 200)">
      <text textAnchor="middle" fontFamily="var(--font-display)" fontWeight="800" fontSize="64" fill="#FFF" letterSpacing="-0.03em">OMNIX</text>
      <text y="28" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.22em" fill="#0050BD">RELAVES · GOBERNANZA</text>
    </g>
    <g transform="translate(400, 300)">
      <text textAnchor="middle" fontFamily="var(--font-serif)" fontStyle="italic" fontSize="18" fill="#96A3B5" y="0">
        Acelera la investigación y el escalamiento.
      </text>
      <text textAnchor="middle" fontFamily="var(--font-serif)" fontStyle="italic" fontSize="18" fill="#96A3B5" y="26">
        La decisión técnica permanece en los responsables autorizados.
      </text>
    </g>
    <g transform="translate(400, 400)">
      <rect x="-160" y="-24" width="320" height="48" fill="#0050BD"/>
      <text textAnchor="middle" fontFamily="var(--font-body)" fontWeight="600" fontSize="15" fill="#FFF" y="6">Evaluar un flujo de vigilancia</text>
    </g>
  </SW>;
};

// ─── TAB 2 · LOGÍSTICA (8 escenas) ────────────────────
const LogisticsScenes = ({ scene }) => {
  const SW = ({ children }) => <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}><MnSceneGrid/>{children}</svg>;
  if (scene === 0) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">MINE-TO-PORT · SHIPMENT WINDOW · MV-4082</text>
    <g transform="translate(80, 200)">
      {['MINA', 'PLANTA', 'STOCK', 'FFCC', 'PUERTO'].map((l, i) => (
        <g key={l} transform={`translate(${i * 140}, 0)`}>
          <rect x="0" y="-30" width="100" height="60" fill="#0A0B10" stroke="#0F5132" strokeWidth="1.5"/>
          <text x="50" y="4" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="700" fontSize="12" fill="#FFF">{l}</text>
          {i < 4 && <FlowPath d={`M 100 0 L 140 0`} stroke="#0F5132" strokeWidth={1.5} particleColor="#B00238" particleSize={3} duration={2.2}/>}
        </g>
      ))}
    </g>
    <g transform="translate(80, 350)">
      <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#B00238">EMBARQUE COMPROMETIDO</text>
      <text x="0" y="28" fontFamily="var(--font-display)" fontWeight="800" fontSize="28" fill="#FFF" letterSpacing="-0.02em">MV-4082 · 48h window · 68% cumplido</text>
    </g>
  </SW>;
  if (scene === 1) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">RESTRICCIÓN DETECTADA</text>
    <g transform="translate(80, 140)">
      <rect x="0" y="0" width="640" height="80" fill="#EA384C" opacity="0.12"/>
      <rect x="0" y="0" width="4" height="80" fill="#EA384C"/>
      <text x="20" y="30" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.18em" fill="#EA384C">ALERTA · CIERRE DE RUTA</text>
      <text x="20" y="56" fontFamily="var(--font-display)" fontWeight="700" fontSize="18" fill="#FFF">Ruta principal · corte 12h · impacto embarque MV-4082</text>
    </g>
    <g transform="translate(80, 260)">
      <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">IMPACTO PROYECTADO SIN INTERVENCIÓN</text>
      {[
        { l: 'CAMIONES DEMORADOS', v: '18 unid' },
        { l: 'TIEMPO EXTRA MINA-PUERTO', v: '+9h' },
        { l: 'RIESGO EMBARQUE', v: 'ALTO' },
      ].map((r, i) => (
        <g key={r.l} transform={`translate(${i * 220}, 30)`}>
          <text x="0" y="16" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.14em" fill="#96A3B5">{r.l}</text>
          <text x="0" y="46" fontFamily="var(--font-display)" fontWeight="700" fontSize="20" fill="#EA384C">{r.v}</text>
        </g>
      ))}
    </g>
  </SW>;
  if (scene === 2) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">SDM LOGÍSTICA · CROSS-DOMAIN EVAL</text>
    {[
      { s: 'Inventario stockpile',    v: '72k t · 3 nodos', c: '#0F5132' },
      { s: 'Programa ferroviario',    v: '2 trenes · ok',    c: '#0F5132' },
      { s: 'Ventana portuaria',        v: '48h · fija',        c: '#B8860B' },
      { s: 'Camiones disponibles',    v: '42/58',              c: '#B8860B' },
      { s: 'Ruta alternativa',         v: '+3h · viable',     c: '#0F5132' },
      { s: 'Restricción de mezcla',    v: 'ok',                c: '#0F5132' },
    ].map((r, i) => (
      <g key={r.s} transform={`translate(80, ${120 + i * 46})`}>
        <rect x="0" y="-14" width="640" height="34" fill="#0A0B10" stroke="#2E3140" strokeWidth="1"/>
        <text x="16" y="8" fontFamily="var(--font-mono)" fontSize="10" fill="#FFF">{r.s}</text>
        <text x="620" y="8" textAnchor="end" fontFamily="var(--font-mono)" fontSize="11" fill={r.c}>{r.v}</text>
      </g>
    ))}
  </SW>;
  if (scene === 3) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">ALTERNATIVAS · SLA + COST</text>
    {[
      { k: 'REROUTE',       t: 'Ruta alternativa + tren extra',  cost: 62, sla: 92, sel: true },
      { k: 'PRIORITIZE',    t: 'Priorizar carga MV-4082',          cost: 40, sla: 78, sel: false },
      { k: 'RESCHEDULE',    t: 'Renegociar ventana portuaria',    cost: 28, sla: 45, sel: false },
    ].map((o, i) => (
      <g key={o.k} transform={`translate(80, ${120 + i * 90})`}>
        {o.sel && <rect x="-8" y="-24" width="656" height="72" fill="#B00238" opacity="0.12"/>}
        {o.sel && <rect x="-8" y="-24" width="4" height="72" fill="#B00238"/>}
        <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.14em" fill={o.sel ? '#B00238' : '#96A3B5'}>0{i+1} · {o.k}</text>
        <text x="0" y="22" fontFamily="var(--font-display)" fontWeight="700" fontSize="16" fill="#FFF">{o.t}</text>
        <text x="360" y="4" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.14em" fill="#B8860B">COST +{o.cost}%</text>
        <text x="360" y="22" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.14em" fill="#0F5132">SLA {o.sla}%</text>
        <rect x="480" y="10" width="120" height="6" fill="#2E3140"/>
        <rect x="480" y="10" width={o.sla * 1.2} height="6" fill="#0F5132"><animate attributeName="width" from="0" to={o.sla * 1.2} dur="0.9s" begin={`${i * 0.15}s`} fill="freeze"/></rect>
        {o.sel && <text x="640" y="0" textAnchor="end" fontFamily="var(--font-mono)" fontSize="10" fill="#B00238">SELECTED</text>}
      </g>
    ))}
  </SW>;
  if (scene === 4) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">COORDINATED EXECUTION</text>
    <g transform="translate(400, 250)">
      <rect x="-44" y="-44" width="88" height="88" fill="#B00238" stroke="#B00238" 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">LOGÍSTICA</text>
    </g>
    {[
      { s: 'WMS',    a: 'reorganiza stockpiles',        x: 130, y: 130 },
      { s: 'TMS',    a: 'ajusta ruta · dispatch',        x: 670, y: 130 },
      { s: 'FFCC',   a: 'agenda tren extra',              x: 130, y: 380 },
      { s: 'PUERTO', a: 'confirma ventana MV-4082',     x: 670, y: 380 },
    ].map((s) => (
      <g key={s.s}>
        <FlowPath d={`M 400 250 L ${s.x} ${s.y}`} stroke="#B00238" strokeWidth={1.5} particleColor="#B00238" particleSize={4} duration={1.4} pulseWidth/>
        <g transform={`translate(${s.x}, ${s.y})`}>
          <rect x="-80" y="-24" width="160" height="48" fill="#0A0B10" stroke="#0F5132" strokeWidth="1.5"/>
          <text x="-68" y="-4" fontFamily="var(--font-display)" fontWeight="800" fontSize="14" fill="#FFF">{s.s}</text>
          <text x="-68" y="14" fontFamily="var(--font-mono)" fontSize="9" fill="#0F5132">✓ {s.a}</text>
        </g>
      </g>
    ))}
  </SW>;
  if (scene === 5) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">RESULT · SHIPMENT PROTECTED</text>
    {[
      { l: 'MV-4082', v: '100%', s: 'cargado a tiempo', c: '#0F5132' },
      { l: 'OTIF',    v: '+18pt', s: 'vs mes anterior', c: '#0F5132' },
      { l: 'CICLO M→P', v: '−22%', s: 'tiempo total', c: '#0050BD' },
      { l: 'COSTO EXTRA', v: '+62%', s: 'aceptable · dentro plan', c: '#B8860B' },
    ].map((k, i) => (
      <g key={k.l} transform={`translate(${80 + (i % 2) * 340}, ${120 + Math.floor(i / 2) * 140})`}>
        <rect x="0" y="0" width="300" height="110" fill="#0A0B10" stroke="#2E3140" strokeWidth="1"/>
        <text x="14" y="22" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">{k.l}</text>
        <text x="14" y="60" fontFamily="var(--font-display)" fontWeight="800" fontSize="26" fill={k.c} letterSpacing="-0.02em">{k.v}</text>
        <text x="14" y="86" fontFamily="var(--font-mono)" fontSize="10" fill="#96A3B5">{k.s}</text>
      </g>
    ))}
  </SW>;
  if (scene === 6) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">AUDIT TRAIL · #LOG-2029-e4f2</text>
    <g transform="translate(80, 120)">
      {['input: route-closure · MV-4082 window at risk', 'sdm.logistics-v2.4 · reroute (cost+62%, sla+15%)', 'policy match · commercial approval · logistics-manager', 'exec: wms + tms + ffcc + port · 4 systems · 88ms', 'result: shipment 100% · signed WORM · 10y retention'].map((l, i) => (
        <text key={i} x="0" y={20 + i * 24} fontFamily="var(--font-mono)" fontSize="12" fill="#FFF"><tspan fill="#52557A">{`0${i+1}  `}</tspan>{l}</text>
      ))}
    </g>
  </SW>;
  return <SW>
    <g transform="translate(400, 200)">
      <text textAnchor="middle" fontFamily="var(--font-display)" fontWeight="800" fontSize="64" fill="#FFF" letterSpacing="-0.03em">OMNIX</text>
      <text y="28" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.22em" fill="#B00238">LOGÍSTICA MINA-PUERTO</text>
    </g>
    <g transform="translate(400, 300)">
      <text textAnchor="middle" fontFamily="var(--font-serif)" fontStyle="italic" fontSize="20" fill="#96A3B5">De mina a puerto, una decisión coordinada.</text>
    </g>
    <g transform="translate(400, 400)">
      <rect x="-140" y="-24" width="280" height="48" fill="#B00238"/>
      <text textAnchor="middle" fontFamily="var(--font-body)" fontWeight="600" fontSize="15" fill="#FFF" y="6">Mapear una disrupción logística</text>
    </g>
  </SW>;
};

// ─── TAB 3 · SISTEMAS EXPERTOS (8 escenas) ────────────────────
const ExpertScenes = ({ scene }) => {
  const SW = ({ children }) => <svg viewBox="0 0 800 500" style={{ width: '100%', height: '100%' }}><MnSceneGrid/>{children}</svg>;
  if (scene === 0) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">EXPERT SYSTEMS · MULTIPLE ACTIVE</text>
    {[
      { s: 'APC',            o: 'throughput ↑',   c: '#0F5132' },
      { s: 'CONDITION',      o: 'risk ↑',          c: '#EA384C' },
      { s: 'GEOMET',         o: 'harder ore',      c: '#B8860B' },
      { s: 'ENERGY',         o: 'peak constraint', c: '#B8860B' },
    ].map((e, i) => (
      <g key={e.s} transform={`translate(${80 + (i % 2) * 340}, ${130 + Math.floor(i / 2) * 140})`}>
        <rect x="0" y="0" width="300" height="110" fill="#0A0B10" stroke={e.c} strokeWidth="1.5"/>
        <text x="14" y="24" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill={e.c}>SISTEMA · {e.s}</text>
        <text x="14" y="66" fontFamily="var(--font-display)" fontWeight="800" fontSize="22" fill="#FFF" letterSpacing="-0.02em">{e.o}</text>
        <text x="14" y="88" fontFamily="var(--font-mono)" fontSize="9" fill="#96A3B5">recomendación activa</text>
      </g>
    ))}
  </SW>;
  if (scene === 1) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">DIVERGENT RECOMMENDATIONS DETECTED</text>
    <g transform="translate(80, 120)">
      {[
        { s: 'APC',       r: 'aumentar throughput +4%',        d: 'objetivo local: producción'  },
        { s: 'CONDITION', r: 'reducir carga -6%',                d: 'objetivo local: proteger activo' },
        { s: 'GEOMET',    r: 'ajustar setpoint molienda',      d: 'objetivo local: recuperación' },
        { s: 'ENERGY',    r: 'limitar consumo próximas 2h',    d: 'objetivo local: peak cost' },
      ].map((e, i) => (
        <g key={e.s} transform={`translate(0, ${i * 60})`}>
          <rect x="0" y="0" width="640" height="48" fill="#0A0B10" stroke="#EA384C" strokeWidth="1"/>
          <text x="16" y="20" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#B8860B">{e.s}</text>
          <text x="16" y="38" fontFamily="var(--font-display)" fontWeight="600" fontSize="13" fill="#FFF">{e.r}</text>
          <text x="620" y="30" textAnchor="end" fontFamily="var(--font-mono)" fontSize="10" fill="#96A3B5">{e.d}</text>
        </g>
      ))}
    </g>
    <text x="80" y="400" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.14em" fill="#EA384C">4 objetivos locales · potencialmente incompatibles</text>
  </SW>;
  if (scene === 2) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">NORMALIZATION · SHARED CONTEXT</text>
    {['APC', 'CONDITION', 'GEOMET', 'ENERGY'].map((s, i) => (
      <g key={s} transform={`translate(80, ${120 + i * 60})`}>
        <rect x="0" y="-14" width="140" height="28" fill="#0A0B10" stroke="#B8860B" strokeWidth="1"/>
        <text x="12" y="4" fontFamily="var(--font-mono)" fontSize="11" fill="#FFF">{s}</text>
        <FlowPath d={`M 140 0 L 340 0 L 400 130`} stroke="#96A3B5" strokeWidth={0.75} particleColor="#B8860B" particleSize={2.5} duration={2.4 + i * 0.15}/>
      </g>
    ))}
    <g transform="translate(500, 240)">
      <circle r="72" fill="none" stroke="#B8860B" strokeWidth="1" opacity="0.3"><animate attributeName="r" values="60;80;60" dur="2.4s" repeatCount="indefinite"/></circle>
      <rect x="-56" y="-56" width="112" height="112" fill="#000" stroke="#B8860B" strokeWidth="2"/>
      <text y="-14" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="800" fontSize="14" fill="#FFF">SDM</text>
      <text y="4" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="700" fontSize="12" fill="#B8860B">ORQUESTA-</text>
      <text y="18" textAnchor="middle" fontFamily="var(--font-display)" fontWeight="700" fontSize="12" fill="#B8860B">CIÓN</text>
    </g>
  </SW>;
  if (scene === 3) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">CONFLICT DETECTION</text>
    <g transform="translate(80, 120)">
      <rect x="0" y="0" width="640" height="120" fill="#EA384C" opacity="0.08"/>
      <rect x="0" y="0" width="4" height="120" fill="#EA384C"/>
      <text x="20" y="30" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.18em" fill="#EA384C">CONFLICTO IDENTIFICADO</text>
      <text x="20" y="60" fontFamily="var(--font-display)" fontWeight="700" fontSize="16" fill="#FFF">APC (+throughput) × CONDITION (-carga) = incompatible en horizonte 4h</text>
      <text x="20" y="90" fontFamily="var(--font-body)" fontSize="13" fill="#96A3B5">Impacto global: si se aplican ambas → riesgo activo elevado sin ganancia neta de plan.</text>
    </g>
    <g transform="translate(80, 280)">
      <text x="0" y="0" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">JERARQUÍA DE OBJETIVOS APLICADA</text>
      {['1. Seguridad', '2. Continuidad operacional', '3. Cumplimiento del plan', '4. Costo'].map((h, i) => (
        <text key={h} x={i * 160} y="30" fontFamily="var(--font-mono)" fontSize="11" fill="#B8860B" letterSpacing="0.14em">{h}</text>
      ))}
    </g>
  </SW>;
  if (scene === 4) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">CONSOLIDATED RESPONSE</text>
    <g transform="translate(80, 120)">
      <rect x="0" y="0" width="640" height="240" fill="#0A0B10" stroke="#B8860B" strokeWidth="1.5"/>
      <text x="20" y="30" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.18em" fill="#B8860B">PROPUESTA CONSOLIDADA</text>
      {[
        { l: 'THROUGHPUT',   v: '+1.8%',        s: 'conservador · dentro de límites activo' },
        { l: 'CARGA CORREA', v: 'mantiene',      s: 'protege ventana intervención' },
        { l: 'SETPOINT MOLINO', v: 'ajusta',   s: 'según geomet · viable' },
        { l: 'ENERGÍA',      v: 'diferir 2h',   s: 'aplicar restricción energía' },
      ].map((r, i) => (
        <g key={r.l} transform={`translate(20, ${60 + i * 40})`}>
          <text x="0" y="12" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">{r.l}</text>
          <text x="200" y="12" fontFamily="var(--font-display)" fontWeight="700" fontSize="14" fill="#F4024C">{r.v}</text>
          <text x="330" y="12" fontFamily="var(--font-body)" fontSize="12" fill="#FFF">· {r.s}</text>
        </g>
      ))}
    </g>
  </SW>;
  if (scene === 5) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">APPROVAL · OPERATIONS MANAGER</text>
    <g transform="translate(80, 140)">
      <rect x="0" y="0" width="640" height="220" fill="#0A0B10" stroke="#0F5132" strokeWidth="1.5"/>
      <text x="20" y="30" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.18em" fill="#0F5132">APROBADO</text>
      <text x="20" y="60" fontFamily="var(--font-display)" fontWeight="700" fontSize="18" fill="#FFF">Superintendente de Operaciones · 14:28</text>
      <text x="20" y="88" fontFamily="var(--font-body)" fontSize="13" fill="#96A3B5">Fundamento explícito registrado. Alternativas rechazadas y motivo. Cadena de decisión trazable.</text>
      <text x="20" y="130" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#B8860B">EJECUCIÓN AUTORIZADA · SISTEMAS NOTIFICADOS</text>
      <text x="20" y="160" fontFamily="var(--font-mono)" fontSize="11" fill="#FFF">APC · Condition · Geomet · Energy · Planificación → coordinated</text>
      <text x="20" y="185" fontFamily="var(--font-mono)" fontSize="11" fill="#0F5132">✓ signed · WORM · #ORQ-2029-b6a4</text>
    </g>
  </SW>;
  if (scene === 6) return <SW>
    <text x="80" y="60" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.18em" fill="#96A3B5">IMPACT · NET RESULT</text>
    {[
      { l: 'CONFLICTOS',  v: 'resuelto', s: '4→0 recomendaciones', c: '#0F5132' },
      { l: 'THROUGHPUT',  v: '+1.8%',    s: 'sin riesgo activo',   c: '#0F5132' },
      { l: 'ESTABILIDAD', v: '+22%',     s: 'menos oscilaciones',   c: '#0050BD' },
      { l: 'DECISIÓN AUD.', v: '100%',   s: 'trazable · firmada',   c: '#0F5132' },
    ].map((k, i) => (
      <g key={k.l} transform={`translate(${80 + (i % 2) * 340}, ${120 + Math.floor(i / 2) * 140})`}>
        <rect x="0" y="0" width="300" height="110" fill="#0A0B10" stroke="#2E3140" strokeWidth="1"/>
        <text x="14" y="22" fontFamily="var(--font-mono)" fontSize="10" letterSpacing="0.14em" fill="#96A3B5">{k.l}</text>
        <text x="14" y="60" fontFamily="var(--font-display)" fontWeight="800" fontSize="24" fill={k.c} letterSpacing="-0.02em">{k.v}</text>
        <text x="14" y="86" fontFamily="var(--font-mono)" fontSize="10" fill="#96A3B5">{k.s}</text>
      </g>
    ))}
  </SW>;
  return <SW>
    <g transform="translate(400, 200)">
      <text textAnchor="middle" fontFamily="var(--font-display)" fontWeight="800" fontSize="60" fill="#FFF" letterSpacing="-0.03em">OMNIX</text>
      <text y="28" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" letterSpacing="0.22em" fill="#B8860B">ORQUESTACIÓN EXPERTA</text>
    </g>
    <g transform="translate(400, 300)">
      <text textAnchor="middle" fontFamily="var(--font-serif)" fontStyle="italic" fontSize="18" fill="#96A3B5" y="0">
        No reemplaza la experiencia. La coordina.
      </text>
    </g>
    <g transform="translate(400, 400)">
      <rect x="-160" y="-24" width="320" height="48" fill="#B8860B"/>
      <text textAnchor="middle" fontFamily="var(--font-body)" fontWeight="600" fontSize="15" fill="#FFF" y="6">Evaluar sistemas expertos</text>
    </g>
  </SW>;
};

const MnSceneGrid = () => (
  <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, { MineriaDemo });
