// OMNIX CORE — Fábrica de cognición · entrena SDMs
const CoreHero = () => (
  <section style={{ background: '#FFFFFF', paddingTop: 88, paddingBottom: 88, position: 'relative', overflow: 'hidden' }}>
    <div style={{
      position: 'absolute', inset: 0,
      backgroundImage: 'linear-gradient(#E4EBF3 1px, transparent 1px), linear-gradient(90deg, #E4EBF3 1px, transparent 1px)',
      backgroundSize: '80px 80px', opacity: 0.5, pointerEvents: 'none',
      maskImage: 'radial-gradient(ellipse at 85% 45%, #000 0%, transparent 55%)',
      WebkitMaskImage: 'radial-gradient(ellipse at 85% 45%, #000 0%, transparent 55%)',
    }}/>
    <Container>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, alignItems: 'center', position: 'relative' }}>
        <div>
          <Reveal>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
              <a href="arquitectura.html" style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', color: '#52557A', textDecoration: 'none', textTransform: 'uppercase' }}>← Arquitectura</a>
              <span style={{ color: '#96A3B5' }}>/</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', color: '#F4024C', textTransform: 'uppercase' }}>Motor 02 · CORE</span>
            </div>
          </Reveal>
          <Reveal delay={80}>
            <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 76, lineHeight: 0.98, letterSpacing: '-0.03em', margin: '0 0 20px', color: '#000' }}>
              OMNIX <span style={{ color: '#F4024C' }}>Core</span>.
            </h1>
          </Reveal>
          <Reveal delay={140}>
            <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 26, lineHeight: 1.25, color: '#1E1F26', margin: '0 0 24px', maxWidth: 500 }}>
              La fábrica donde tu inteligencia se construye.
            </div>
          </Reveal>
          <Reveal delay={200}>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 18, lineHeight: 1.55, color: '#52557A', maxWidth: 500, margin: '0 0 32px' }}>
              Entrena Specialized Domain Models (SDMs) &lt; 20B parámetros sobre tus datos, tus reglas
              y tu conocimiento experto. Fine-tuning continuo con feedback operacional. Cero llamadas
              a modelos externos.
            </p>
          </Reveal>
          <Reveal delay={260}>
            <div style={{ display: 'flex', gap: 12 }}>
              <Button variant="primary" icon="arrow-right" href="diagnostico.html">Construye tu SDM</Button>
              <Button variant="ghost" href="arquitectura-runtime.html" icon="arrow-right">Siguiente: Runtime</Button>
            </div>
          </Reveal>
        </div>

        <Reveal delay={200} y={0}>
          <CoreTrainingViz/>
        </Reveal>
      </div>
    </Container>
  </section>
);

// Visualización: pipeline de entrenamiento SDM con métricas vivas
const CoreTrainingViz = () => {
  const [epoch, setEpoch] = React.useState(3);
  const [loss, setLoss] = React.useState(0.284);
  const [accuracy, setAccuracy] = React.useState(87.4);
  React.useEffect(() => {
    const id = setInterval(() => {
      setEpoch((e) => e + 1);
      setLoss((l) => Math.max(0.05, l * (0.94 + Math.random() * 0.05)));
      setAccuracy((a) => Math.min(99, a + Math.random() * 0.6));
    }, 1400);
    return () => clearInterval(id);
  }, []);
  return (
    <div style={{ border: '1.5px solid #1E1F26', background: '#FAFBFD' }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', padding: '14px 20px',
        borderBottom: '1.5px solid #1E1F26',
        fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: '#52557A',
      }}>
        <span>CORE · TRAINING RUN #4082</span>
        <span style={{ color: '#F4024C', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: '#F4024C' }} className="omnix-blink"/>
          EPOCH {epoch}
        </span>
      </div>
      {/* Loss curve animada */}
      <div style={{ padding: 24 }}>
        <LossCurve epoch={epoch} loss={loss}/>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginTop: 24 }}>
          <div style={{ padding: '14px 16px', border: '1px solid #E4EBF3', background: '#FFF' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.14em', color: '#96A3B5', marginBottom: 6 }}>LOSS</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 18, color: '#F4024C', fontWeight: 500 }}>
              <SpringNumber to={loss} decimals={4}/>
            </div>
          </div>
          <div style={{ padding: '14px 16px', border: '1px solid #E4EBF3', background: '#FFF' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.14em', color: '#96A3B5', marginBottom: 6 }}>ACCURACY</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 18, color: '#0F5132', fontWeight: 500 }}>
              <SpringNumber to={accuracy} suffix="%" decimals={1}/>
            </div>
          </div>
          <div style={{ padding: '14px 16px', border: '1px solid #E4EBF3', background: '#FFF' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.14em', color: '#96A3B5', marginBottom: 6 }}>GPU · IN-VPC</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 18, color: '#000', fontWeight: 500 }}>8 × A100</div>
          </div>
        </div>
      </div>
      <div style={{
        borderTop: '1.5px solid #1E1F26', padding: '14px 20px',
        display: 'flex', justifyContent: 'space-between',
        fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#52557A',
      }}>
        <span>SDM: <span style={{ color: '#F4024C' }}>banco-fraud-v3.4.2</span></span>
        <span>Params: 14.2B · Domain: banking</span>
      </div>
    </div>
  );
};

// Loss curve descendente animada
const LossCurve = ({ epoch, loss }) => {
  const points = React.useMemo(() => {
    // Genera una curva de pérdida decreciente basada en el epoch actual
    const arr = [];
    const n = Math.min(30, epoch);
    for (let i = 0; i < n; i++) {
      const x = (i / 29) * 520;
      const decay = Math.exp(-i / 8);
      const noise = Math.sin(i * 1.3) * 0.05;
      const y = 20 + (1 - decay + noise) * 100;
      arr.push([x, Math.min(140, y)]);
    }
    return arr;
  }, [epoch]);
  const d = points.length > 0 ? 'M ' + points.map(([x, y]) => `${x} ${y}`).join(' L ') : '';
  return (
    <svg viewBox="0 0 520 160" style={{ width: '100%', height: 160, display: 'block' }}>
      {/* Grid */}
      <g stroke="#E4EBF3" strokeWidth="0.5">
        {Array.from({length: 5}).map((_, i) => <line key={i} x1="0" y1={i*40} x2="520" y2={i*40}/>)}
        {Array.from({length: 11}).map((_, i) => <line key={i} x1={i*52} y1="0" x2={i*52} y2="160"/>)}
      </g>
      {/* Curve */}
      <path d={d} fill="none" stroke="#F4024C" strokeWidth="1.5"/>
      {/* Area */}
      <path d={d + ` L 520 160 L 0 160 Z`} fill="url(#loss-grad)" opacity="0.15"/>
      <defs>
        <linearGradient id="loss-grad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#F4024C"/>
          <stop offset="100%" stopColor="#F4024C" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {/* Last point */}
      {points.length > 0 && (
        <circle cx={points[points.length - 1][0]} cy={points[points.length - 1][1]} r="4" fill="#F4024C">
          <animate attributeName="r" values="4;7;4" dur="1s" repeatCount="indefinite"/>
        </circle>
      )}
      {/* Labels */}
      <text x="4" y="14" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.14em" fill="#96A3B5">LOSS OVER EPOCHS</text>
    </svg>
  );
};

const CoreLifecycle = () => {
  const phases = [
    { n: '01', k: 'DATASET',    t: 'Curación', d: 'Sobre vectores de Ingest. Balanceo, sampling, splits temporales, holdouts.' },
    { n: '02', k: 'ARCHITECT',  t: 'Diseño', d: 'Selección de arquitectura base optimizada para el dominio: tabular, sequence, multi-modal.' },
    { n: '03', k: 'TRAIN',      t: 'Entrenamiento', d: 'Fine-tuning con feedback experto. GPU cluster dentro del perímetro cliente.' },
    { n: '04', k: 'EVAL',       t: 'Evaluación', d: 'Métricas de negocio (no de paper). Backtesting sobre casos históricos reales.' },
    { n: '05', k: 'GATE',       t: 'Governance', d: 'Approval flow ejecutivo. Model risk review. Firma criptográfica del artefacto.' },
    { n: '06', k: 'DEPLOY',     t: 'Publicación', d: 'A Runtime en modo sombra primero, luego canary, luego producción total.' },
  ];
  return (
    <section style={{ background: '#FAFBFD', paddingTop: 128, paddingBottom: 128, borderTop: '1.5px solid #E4EBF3', borderBottom: '1.5px solid #E4EBF3' }}>
      <Container>
        <Reveal><SectionMeta n="01" label="Lifecycle SDM"/></Reveal>
        <Reveal delay={80}>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 52, lineHeight: 1.03, letterSpacing: '-0.025em', margin: '0 0 56px', color: '#000', maxWidth: 900 }}>
            Seis fases entre datos crudos y modelo en producción.
          </h2>
        </Reveal>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
          {phases.map((p, i) => (
            <SlideIn key={p.n} direction="up" delay={i * 90}>
              <MagneticHover strength={3}>
                <div style={{
                  background: '#FFF', border: '1px solid #E4EBF3', padding: 28, minHeight: 200,
                  display: 'flex', flexDirection: 'column', gap: 12,
                  transition: 'border-color 220ms',
                }}
                onMouseEnter={(e) => e.currentTarget.style.borderColor = '#F4024C'}
                onMouseLeave={(e) => e.currentTarget.style.borderColor = '#E4EBF3'}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.18em', color: '#F4024C' }}>{p.n}</span>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.18em', color: '#96A3B5' }}>{p.k}</span>
                  </div>
                  <h4 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, letterSpacing: '-0.015em', color: '#000', margin: 0, lineHeight: 1.15 }}>
                    {p.t}
                  </h4>
                  <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.55, color: '#52557A', margin: 0 }}>
                    {p.d}
                  </p>
                </div>
              </MagneticHover>
            </SlideIn>
          ))}
        </div>
      </Container>
    </section>
  );
};

const CoreComparison = () => {
  const [mode, setMode] = React.useState(0);
  const dimensionRows = [
    { d: 'Ubicación de datos',    sdm: 'Tu VPC · on-prem',       llm: 'API pública compartida' },
    { d: 'Parámetros',            sdm: '< 20B',                   llm: '500B – 2T' },
    { d: 'Consumo · inferencia',  sdm: '~13 W',                   llm: '~690 W' },
    { d: 'Velocidad relativa',    sdm: 'hasta 50× más rápido',    llm: 'base' },
    { d: 'Costo por decisión',    sdm: 'hasta 30× menor',         llm: 'base' },
    { d: 'Reentrenamiento',       sdm: 'A demanda · en tu VPC',   llm: 'Cuando el proveedor decide' },
    { d: 'Auditabilidad',         sdm: 'Determinística · logs',   llm: 'Caja negra' },
  ];
  const costRows = [
    { d: 'Costo por 1M decisiones',  sdm: 'USD ~40',              llm: 'USD ~150 - 500' },
    { d: 'Consumo energético',        sdm: '~13 W · inferencia',   llm: '~690 W · inferencia' },
    { d: 'Infra requerida',           sdm: '1× GPU media · VPC',   llm: 'Cluster A100/H100' },
    { d: 'Facturación',               sdm: 'CAPEX · sin token-tax', llm: 'OPEX · por token' },
    { d: 'Elasticidad de costo',      sdm: 'Predecible · fijo',    llm: 'Variable · imprevisible' },
    { d: 'Costo de re-entrenar',      sdm: 'Marginal · in-house',  llm: 'No aplica · caja negra' },
    { d: 'TCO a 24 meses',            sdm: 'hasta 30× menor',      llm: 'base' },
  ];
  const rows = mode === 0 ? dimensionRows : costRows;
  const sdmHeader = mode === 0 ? 'OMNIX · SDM' : 'OMNIX · SDM (costo)';
  const llmHeader = mode === 0 ? 'LLM GENÉRICO' : 'LLM GENÉRICO (costo)';
  const firstColHeader = mode === 0 ? 'DIMENSIÓN' : 'PARTIDA';
  return (
    <section style={{ background: '#FFFFFF', paddingTop: 128, paddingBottom: 128 }}>
      <Container>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', marginBottom: 48, flexWrap: 'wrap', gap: 20 }}>
          <div>
            <Reveal><SectionMeta n="02" label="SDM vs LLM genérico"/></Reveal>
            <Reveal delay={80}>
              <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 52, lineHeight: 1.03, letterSpacing: '-0.025em', margin: 0, color: '#000', maxWidth: 720 }}>
                No es un LLM con otro nombre.
              </h2>
            </Reveal>
          </div>
          <Reveal delay={140}>
            <SegmentedTabs tabs={[{l: 'Dimensiones'}, {l: 'Costo'}]} active={mode} onChange={setMode}/>
          </Reveal>
        </div>

        <div style={{ border: '1.5px solid #1E1F26' }}>
          <div style={{
            display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr',
            background: '#000', color: '#FFF',
            padding: '18px 24px',
            fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase',
          }}>
            <div>{firstColHeader}</div>
            <div style={{ color: '#F4024C' }}>{sdmHeader}</div>
            <div style={{ color: '#96A3B5' }}>{llmHeader}</div>
          </div>
          {rows.map((r, i) => (
            <SlideIn key={`${mode}-${r.d}`} direction="right" delay={i * 60}>
              <div style={{
                display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr',
                padding: '20px 24px', borderTop: '1px solid #E4EBF3',
                background: i % 2 === 0 ? '#FFF' : '#FAFBFD',
              }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 15, color: '#1E1F26' }}>{r.d}</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: '#F4024C', fontWeight: 500 }}>{r.sdm}<ValidateMark/></div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: '#96A3B5' }}>{r.llm}</div>
              </div>
            </SlideIn>
          ))}
        </div>
      </Container>
    </section>
  );
};

Object.assign(window, { CoreHero, CoreTrainingViz, CoreLifecycle, CoreComparison });
