/* global React */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ============================================
// Shared: hook d'entrada per scroll + re-play per hover amb debounce
// ============================================
const useReplayOnHover = (duration = 1800) => {
  const ref = useRef(null);
  const [cycle, setCycle] = useState(0);
  const [played, setPlayed] = useState(false);
  const animatingRef = useRef(false);
  const onEnd = useRef(null);

  const play = useCallback(() => {
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduced) { setPlayed(true); return; }
    animatingRef.current = true;
    setPlayed(false);
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        setPlayed(true);
        clearTimeout(onEnd.current);
        onEnd.current = setTimeout(() => { animatingRef.current = false; }, duration + 100);
      });
    });
  }, [duration]);

  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { play(); io.disconnect(); }
      });
    }, { threshold: 0.15, rootMargin: '0px 0px -10% 0px' });
    io.observe(ref.current);
    return () => { io.disconnect(); clearTimeout(onEnd.current); };
  }, [play]);

  const onMouseEnter = () => {
    if (animatingRef.current) return;
    setCycle((c) => c + 1);
    play();
  };

  return { ref, played, cycle, onMouseEnter };
};

// ============================================
// TECH MARQUEE — Technologies we work with
// ============================================
const TECHS = [
  'Claude', 'ChatGPT', 'Gemini', 'Copilot', 'Mistral', 'DeepSeek',
  'Qwen', 'LLaMA', 'Supabase', 'Vercel', 'Mux', 'n8n',
  'Microsoft 365', 'Google Workspace', 'SAP', 'Salesforce'
];
const TechMarquee = () => {
  const [paused, setPaused] = useState(false);
  const items = [...TECHS, ...TECHS];
  return (
    <div className="marquee"
         onMouseEnter={() => setPaused(true)}
         onMouseLeave={() => setPaused(false)}>
      <div className={`marquee-track ${paused ? 'paused' : ''}`}>
        {items.map((t, i) => (
          <span key={i} className="marquee-item">
            {t}
            {i < items.length - 1 && <span className="sep" />}
          </span>
        ))}
      </div>
    </div>
  );
};

// ============================================
// PAIN POINTS — text highlight with scroll
// ============================================
const PainPoints = () => {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const paras = ref.current.querySelectorAll('.pain-p');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => e.target.classList.toggle('is-in', e.isIntersecting));
    }, { threshold: 0.5 });
    paras.forEach((p) => io.observe(p));
    return () => io.disconnect();
  }, []);
  return (
    <section className="section pain-section" id="problema">
      <div className="container-wide">
        <div className="pain-wrap" ref={ref}>
          <p className="pain-eyebrow">Lo que nos dicen los equipos directivos</p>
          <p className="pain-p">
            “Tenemos datos, herramientas y personas capaces, pero seguimos
            <span className="pain-mark"> decidiendo con información incompleta</span>.”
          </p>
          <p className="pain-p">
            Ahí empieza Talos: aclarar qué ordenar, qué automatizar y
            <span className="pain-mark"> dónde hay retorno antes de invertir</span>.
          </p>
        </div>
      </div>
    </section>
  );
};

// ============================================
// S4 — SHOWCASE VISUAL (fondo oscuro, 6 cards)
// ============================================

// Card 1 — Dashboard ejecutivo (animada + hover re-play)
// ============================================
// Shared: footer de card (title + desc + link)
// ============================================
const ShowcaseBody = ({ title, desc, cta }) => (
  <div className="showcase-body">
    <h3 className="showcase-title">{title}</h3>
    <p className="showcase-desc">{desc}</p>
    <span className="showcase-link">{cta} <ArrowRight /></span>
  </div>
);

// ============================================
// Card 1 — Dashboard ejecutivo
// ============================================
const ShowcaseCardDashboard = () => {
  const { ref, played, cycle, onMouseEnter } = useReplayOnHover(1900);
  const [counters, setCounters] = useState({ a: 0, b: 0, c: 0 });
  const rafRef = useRef(null);

  useEffect(() => {
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (!played) { setCounters({ a: 0, b: 0, c: 0 }); return; }
    if (reduced) { setCounters({ a: 847, b: 23, c: 1.2 }); return; }
    const targets = { a: 847, b: 23, c: 1.2 };
    const start = performance.now() + 400;
    const dur = 500;
    cancelAnimationFrame(rafRef.current);
    const tick = (now) => {
      if (now < start) { rafRef.current = requestAnimationFrame(tick); return; }
      const t = Math.min(1, (now - start) / dur);
      const eased = 1 - Math.pow(1 - t, 3);
      setCounters({
        a: Math.round(targets.a * eased),
        b: Math.round(targets.b * eased),
        c: +(targets.c * eased).toFixed(1),
      });
      if (t < 1) rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [played, cycle]);

  return (
    <a href="/gobernanza-de-datos#dashboards"
       ref={ref}
       onMouseEnter={onMouseEnter}
       key={cycle}
       className={`showcase-card ${played ? 'is-in' : ''}`}>
      <div className="showcase-badge">Panel unificado</div>
      <div className="showcase-viz">
        <svg viewBox="0 0 320 180" className="sv-dashboard" aria-hidden="true">
          <g className="sv-el sv-head" style={{ '--d': '0s' }}>
            <line x1="16" y1="18" x2="304" y2="18" stroke="rgba(255,255,255,0.2)" strokeWidth="1" />
            <circle cx="22" cy="13" r="1.8" fill="rgba(255,255,255,0.7)" />
            <circle cx="30" cy="13" r="1.8" fill="rgba(255,255,255,0.7)" />
            <circle cx="38" cy="13" r="1.8" fill="rgba(255,255,255,0.7)" />
            <rect x="258" y="6" width="46" height="14" rx="7" fill="rgba(255,255,255,0.08)" stroke="rgba(255,255,255,0.3)" strokeWidth="1" />
            <text x="281" y="15.5" textAnchor="middle" fontSize="7" fill="rgba(255,255,255,0.85)" fontWeight="500">Q2 2026</text>
          </g>
          <g className="sv-kpis">
            {[0, 1, 2].map((i) => (
              <g key={i} className="sv-el sv-kpi" style={{ '--d': `${0.2 + i * 0.1}s` }}>
                <rect x={16 + i * 98} y="28" width="92" height="36" rx="4" fill="rgba(255,255,255,0.03)" stroke="rgba(255,255,255,0.5)" strokeWidth="1.5" />
                <text x={62 + i * 98} y="48" textAnchor="middle" fontSize="13" fill="#fff" fontWeight="600">
                  {i === 0 ? counters.a : i === 1 ? `${counters.b}%` : `${counters.c}M`}
                </text>
                <text x={62 + i * 98} y="58" textAnchor="middle" fontSize="5.5" fill="rgba(255,255,255,0.55)">
                  {i === 0 ? 'Registros' : i === 1 ? 'Cumplim.' : 'Volumen'}
                </text>
              </g>
            ))}
          </g>
          <g className="sv-chart">
            <line x1="16" y1="150" x2="210" y2="150" stroke="rgba(255,255,255,0.5)" strokeWidth="1"
                  className="sv-el sv-axis" style={{ '--d': '0.7s' }} />
            <polyline className="sv-el sv-line" style={{ '--d': '0.9s' }}
              points="16,135 55,125 90,115 125,100 160,90 205,70"
              fill="none" stroke="rgba(255,255,255,0.85)" strokeWidth="1.5"
              strokeLinecap="round" strokeLinejoin="round" />
            {[{x:16,y:135},{x:55,y:125},{x:90,y:115},{x:125,y:100},{x:160,y:90}].map((pt, i) => (
              <circle key={i} cx={pt.x} cy={pt.y} r="2.4" fill="#fff"
                      className="sv-el sv-dot" style={{ '--d': `${1.2 + i * 0.06}s` }}/>
            ))}
            <circle cx="205" cy="70" r="3.5" fill="#FF4E00"
                    className="sv-el sv-dot-last" style={{ '--d': '1.6s' }}/>
          </g>
          <g className="sv-sources">
            {['ERP', 'CRM', 'Excel'].map((lbl, i) => (
              <g key={lbl} className="sv-el sv-src" style={{ '--d': `${1.4 + i * 0.08}s` }}>
                <circle cx="232" cy={80 + i * 16} r="2.5" fill="none" stroke="rgba(255,255,255,0.7)" strokeWidth="1" />
                <text x="240" y={82.5 + i * 16} fontSize="6.5" fill="rgba(255,255,255,0.7)" fontWeight="500">{lbl}</text>
                <rect x="262" y={78 + i * 16} width="44" height="3" rx="1.5" fill="rgba(255,255,255,0.1)" />
                <rect x="262" y={78 + i * 16} width={(i === 0 ? 40 : i === 1 ? 30 : 20)} height="3" rx="1.5" fill="rgba(255,255,255,0.85)" />
              </g>
            ))}
          </g>
        </svg>
      </div>
      <ShowcaseBody
        title="Datos dispersos"
        desc="ERP, CRM, carpetas y hojas de cálculo convertidos en una sola lectura ejecutiva."
        cta="Ordenar datos" />
    </a>
  );
};

// ============================================
// Card 2 — Captura de facturas (PDF → partícules → camps)
// ============================================
const ShowcaseCardCaptura = () => {
  const { ref, played, cycle, onMouseEnter } = useReplayOnHover(1800);
  // 10 partícules que viatgen d'un centre a posicions finals (3 camps)
  const particles = useMemo(() => {
    const fields = [
      { x: 30, y: 105 }, { x: 115, y: 105 }, { x: 200, y: 105 }, // 3 camps bottom
    ];
    const src = { x: 160, y: 55 };
    const arr = [];
    for (let i = 0; i < 10; i++) {
      const f = fields[i % 3];
      arr.push({
        i, sx: src.x + (i % 3 - 1) * 3, sy: src.y + (Math.floor(i / 3)) * 3,
        dx: f.x + 20 + (i * 7 % 40), dy: f.y - 8 + (i % 2) * 3,
      });
    }
    return arr;
  }, []);

  return (
    <a href="/digitalizacion-de-procesos#captura" ref={ref} onMouseEnter={onMouseEnter}
       key={cycle} className={`showcase-card ${played ? 'is-in' : ''}`}>
      <div className="showcase-badge">Gestión documental</div>
      <div className="showcase-viz">
        <svg viewBox="0 0 320 180" className="sv-captura" aria-hidden="true">
          {/* PDF icon (fades out at T 400ms) */}
          <g className="sv-el sv-pdf" style={{ '--d': '0s' }}>
            <path d="M140 30 L140 78 L180 78 L180 45 L165 30 Z" fill="none" stroke="rgba(255,255,255,0.7)" strokeWidth="1.2" strokeLinejoin="round" />
            <path d="M165 30 L165 45 L180 45" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="1" />
            <line x1="146" y1="54" x2="174" y2="54" stroke="rgba(255,255,255,0.5)" strokeWidth="1" />
            <line x1="146" y1="60" x2="174" y2="60" stroke="rgba(255,255,255,0.5)" strokeWidth="1" />
            <line x1="146" y1="66" x2="168" y2="66" stroke="rgba(255,255,255,0.5)" strokeWidth="1" />
            <text x="160" y="72" textAnchor="middle" fontSize="5" fill="rgba(255,255,255,0.4)" fontWeight="600">PDF</text>
          </g>
          {/* Partícules */}
          {particles.map((p) => (
            <circle key={p.i}
              className="sv-el sv-particle"
              style={{ '--d': `${0.2 + p.i * 0.03}s`, '--tx': `${p.dx - p.sx}px`, '--ty': `${p.dy - p.sy}px` }}
              cx={p.sx} cy={p.sy} r="1.6" fill="rgba(255,255,255,0.9)" />
          ))}
          {/* Camps finals */}
          {[
            { x: 30, label: 'NIF', val: 'B12345' },
            { x: 115, label: 'Fecha', val: '15/03' },
            { x: 200, label: 'Total', val: '1.240 €', accent: true },
          ].map((f, i) => (
            <g key={f.label} className="sv-el sv-field" style={{ '--d': `${0.6 + i * 0.08}s` }}>
              <rect x={f.x} y="100" width="90" height="36" rx="4"
                    fill="rgba(255,255,255,0.03)"
                    stroke={f.accent ? '#FF4E00' : 'rgba(255,255,255,0.5)'}
                    strokeWidth={f.accent ? '1.5' : '1'} />
              <text x={f.x + 8} y="112" fontSize="6" fill="rgba(255,255,255,0.55)" fontWeight="500">{f.label}</text>
              <text x={f.x + 8} y="126" fontSize="9.5" fill={f.accent ? '#FF4E00' : '#fff'} fontWeight="600">{f.val}</text>
            </g>
          ))}
          {/* Pulse al camp taronja */}
          <circle className="sv-el sv-pulse-accent" cx="245" cy="118" r="3" fill="#FF4E00"
                  style={{ '--d': '0.85s' }} />
        </svg>
      </div>
      <ShowcaseBody
        title="Control de facturas y albaranes"
        desc="Digitaliza papel, captura datos, valida importes y deja tus documentos accesibles sin perseguir archivadores."
        cta="Controlar facturas y albaranes" />
    </a>
  );
};

// ============================================
// Card 3 — Agente IA (chat conversation)
// ============================================
const ShowcaseCardAgente = () => {
  const { ref, played, cycle, onMouseEnter } = useReplayOnHover(1800);
  return (
    <a href="/ia-aplicada#agentes" ref={ref} onMouseEnter={onMouseEnter}
       key={cycle} className={`showcase-card ${played ? 'is-in' : ''}`}>
      <div className="showcase-badge">Agente interno</div>
      <div className="showcase-viz">
        <svg viewBox="0 0 320 180" className="sv-agente" aria-hidden="true">
          {/* User bubble (dreta) */}
          <g className="sv-el sv-msg-user" style={{ '--d': '0s' }}>
            <rect x="140" y="20" width="160" height="30" rx="14" fill="rgba(0,60,112,0.35)" stroke="rgba(255,255,255,0.15)" strokeWidth="1" />
            <text x="153" y="39" fontSize="8.5" fill="rgba(255,255,255,0.9)" fontWeight="400">¿Qué dice la política de gasto?</text>
          </g>
          {/* Typing indicator */}
          <g className="sv-el sv-typing" style={{ '--d': '0.35s' }}>
            <rect x="20" y="60" width="50" height="20" rx="10" fill="rgba(255,255,255,0.06)" stroke="rgba(255,255,255,0.15)" strokeWidth="1" />
            <circle cx="32" cy="70" r="2" fill="rgba(255,255,255,0.7)" className="sv-typing-dot" style={{ '--i': 0 }}/>
            <circle cx="42" cy="70" r="2" fill="rgba(255,255,255,0.7)" className="sv-typing-dot" style={{ '--i': 1 }}/>
            <circle cx="52" cy="70" r="2" fill="rgba(255,255,255,0.7)" className="sv-typing-dot" style={{ '--i': 2 }}/>
          </g>
          {/* Agent bubble */}
          <g className="sv-el sv-msg-agent" style={{ '--d': '0.65s' }}>
            <rect x="20" y="90" width="260" height="52" rx="12" fill="rgba(255,255,255,0.08)" stroke="rgba(255,255,255,0.2)" strokeWidth="1" />
            {/* Reveal mask for text */}
            <g className="sv-agent-text" style={{ '--d': '0.75s' }}>
              <text x="32" y="107" fontSize="8.5" fill="rgba(255,255,255,0.9)">Según la política</text>
              <rect x="115" y="100" width="40" height="10" rx="2" fill="rgba(255,78,0,0.25)" stroke="#FF4E00" strokeWidth="0.8" className="sv-highlight" style={{ '--d': '0.95s' }}/>
              <text x="118" y="108" fontSize="8" fill="#FF4E00" fontWeight="600" className="sv-el sv-highlight-text" style={{ '--d': '1s' }}>v2.3 §4</text>
              <text x="32" y="122" fontSize="8.5" fill="rgba(255,255,255,0.9)">la respuesta es sí,</text>
              <text x="32" y="135" fontSize="8.5" fill="rgba(255,255,255,0.7)">con aprobación de dirección.</text>
            </g>
          </g>
        </svg>
      </div>
      <ShowcaseBody
        title="Conocimiento atrapado"
        desc="Un agente interno responde con tus reglas, políticas, criterios y precedentes."
        cta="Liberar conocimiento" />
    </a>
  );
};

// ============================================
// Card 4 — Simulación (wireframe 3D rotating)
// ============================================
const ShowcaseCardSimulacion = () => {
  const { ref, played, cycle, onMouseEnter } = useReplayOnHover(1800);
  return (
    <a href="/simulacion-y-formacion-inmersiva#simulacion" ref={ref} onMouseEnter={onMouseEnter}
       key={cycle} className={`showcase-card ${played ? 'is-in' : ''}`}>
      <div className="showcase-badge">Simulación segura</div>
      <div className="showcase-viz">
        <div className="sv-sim-wrap">
          <svg viewBox="0 0 320 180" className={`sv-sim ${played ? 'is-in' : ''}`} aria-hidden="true">
            {/* Cub wireframe isomètric-ish */}
            <g stroke="rgba(255,255,255,0.85)" strokeWidth="1.2" fill="none" strokeLinejoin="round">
              {/* Back face */}
              <path className="sv-el sv-cube-back" style={{ '--d': '0s' }} d="M100 40 L220 40 L220 120 L100 120 Z" opacity="0.5" />
              {/* Front face (shifted) */}
              <path className="sv-el sv-cube-front" style={{ '--d': '0.1s' }} d="M80 60 L200 60 L200 140 L80 140 Z" />
              {/* Connect corners */}
              <path className="sv-el sv-cube-edges" style={{ '--d': '0.2s' }} d="M100 40 L80 60 M220 40 L200 60 M220 120 L200 140 M100 120 L80 140" />
              {/* Grid intern */}
              <path className="sv-el sv-cube-grid" style={{ '--d': '0.4s' }} d="M140 60 L140 140 M170 60 L170 140 M80 90 L200 90 M80 115 L200 115" strokeWidth="0.6" opacity="0.4" />
            </g>
            {/* Nodes interns */}
            {[
              { x: 115, y: 85 }, { x: 155, y: 110 }, { x: 180, y: 75 },
            ].map((n, i) => (
              <circle key={i} cx={n.x} cy={n.y} r="2" fill="rgba(255,255,255,0.9)"
                      className="sv-el sv-node-in" style={{ '--d': `${0.3 + i * 0.08}s` }}/>
            ))}
            {/* Alert dots vèrtexs: 2 blancs + 1 taronja */}
            <circle cx="200" cy="60" r="3" fill="#FF4E00" className="sv-el sv-alert sv-alert-accent" style={{ '--d': '0.65s' }}/>
            <circle cx="80" cy="140" r="2.5" fill="#fff" className="sv-el sv-alert" style={{ '--d': '0.8s' }}/>
            <circle cx="220" cy="120" r="2.5" fill="#fff" className="sv-el sv-alert" style={{ '--d': '0.95s' }}/>
          </svg>
        </div>
      </div>
      <ShowcaseBody
        title="Formación crítica"
        desc="Simulación y práctica para situaciones donde equivocarse en real sale caro."
        cta="Entrenar situaciones críticas" />
    </a>
  );
};

// ============================================
// Card 5 — Circuito automatizado (nodes + fletxes)
// ============================================
const ShowcaseCardCircuito = () => {
  const { ref, played, cycle, onMouseEnter } = useReplayOnHover(2000);
  const nodes = [
    { x: 40,  y: 90, label: '1', ic: 'mail' },
    { x: 115, y: 90, label: '2', ic: 'doc' },
    { x: 190, y: 90, label: '3', ic: 'gear' },
    { x: 265, y: 90, label: '4', ic: 'check' },
  ];
  const Icon = ({ kind }) => {
    const p = { fill: 'none', stroke: '#fff', strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round' };
    if (kind === 'mail') return <g {...p}><rect x="-6" y="-4" width="12" height="8" rx="1"/><path d="M-6 -4 L0 1 L6 -4" /></g>;
    if (kind === 'doc')  return <g {...p}><path d="M-4 -6 L3 -6 L5 -4 L5 6 L-4 6 Z"/><path d="M-2 -2 h5 M-2 1 h5 M-2 4 h3"/></g>;
    if (kind === 'gear') return <g {...p}><circle r="2.5"/><path d="M0 -5 v2 M0 3 v2 M-5 0 h2 M3 0 h2 M-3.5 -3.5 l1.4 1.4 M2.1 2.1 l1.4 1.4 M-3.5 3.5 l1.4 -1.4 M2.1 -2.1 l1.4 -1.4"/></g>;
    return <g {...p} stroke="#FF4E00"><path d="M-4 0 L-1 3 L5 -3"/></g>;
  };

  return (
    <a href="/digitalizacion-de-procesos#procesos" ref={ref} onMouseEnter={onMouseEnter}
       key={cycle} className={`showcase-card ${played ? 'is-in' : ''}`}>
      <div className="showcase-badge">Flujo de proceso</div>
      <div className="showcase-viz">
        <svg viewBox="0 0 320 180" className="sv-circuito" aria-hidden="true">
          {/* Fletxes entre nodes */}
          {[0, 1, 2].map((i) => (
            <g key={i} className="sv-el sv-arrow" style={{ '--d': `${0.15 + i * 0.22}s` }}>
              <line x1={nodes[i].x + 14} y1={nodes[i].y} x2={nodes[i + 1].x - 14} y2={nodes[i + 1].y}
                    stroke="rgba(255,255,255,0.7)" strokeWidth="1.2" />
              <path d={`M${nodes[i + 1].x - 18} ${nodes[i + 1].y - 3} L${nodes[i + 1].x - 14} ${nodes[i + 1].y} L${nodes[i + 1].x - 18} ${nodes[i + 1].y + 3}`}
                    fill="none" stroke="rgba(255,255,255,0.7)" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" />
            </g>
          ))}
          {/* Nodes */}
          {nodes.map((n, i) => (
            <g key={i} className={`sv-el sv-node ${i === 3 ? 'sv-node-final' : ''}`}
               style={{ '--d': `${i * 0.22}s` }}>
              <circle cx={n.x} cy={n.y} r="14"
                      fill="rgba(255,255,255,0.06)"
                      stroke={i === 3 ? '#FF4E00' : 'rgba(255,255,255,0.7)'}
                      strokeWidth={i === 3 ? '1.6' : '1.2'} />
              <g transform={`translate(${n.x} ${n.y})`}>
                <Icon kind={n.ic} />
              </g>
            </g>
          ))}
          {/* Pulse halo final */}
          <circle cx="265" cy="90" r="14" fill="none" stroke="#FF4E00" strokeWidth="1.5"
                  className="sv-el sv-halo" style={{ '--d': '0.95s' }}/>
        </svg>
      </div>
      <ShowcaseBody
        title="Procesos manuales"
        desc="Validaciones, tareas y traspasos encadenados sin cuellos de botella."
        cta="Automatizar circuitos" />
    </a>
  );
};

// ============================================
// Card 6 — Trazabilidad blockchain (blocs cadascun amb hash)
// ============================================
const ShowcaseCardBlockchain = () => {
  const { ref, played, cycle, onMouseEnter } = useReplayOnHover(2200);
  const hashes = ['0x7a3f…e2c1', '0x9b2d…4f8a', '0xc1e5…9d3b', '0x4a8f…6e2d'];
  return (
    <a href="/gobernanza-de-datos#blockchain" ref={ref} onMouseEnter={onMouseEnter}
       key={cycle} className={`showcase-card ${played ? 'is-in' : ''}`}>
      <div className="showcase-badge">Registro auditable</div>
      <div className="showcase-viz">
        <svg viewBox="0 0 320 180" className="sv-chain" aria-hidden="true">
          {/* 4 blocs horitzontals */}
          {hashes.map((h, i) => {
            const x = 14 + i * 76;
            const isFinal = i === 3;
            return (
              <g key={i}>
                {/* Link entre blocs */}
                {i > 0 && (
                  <line className="sv-el sv-chain-link"
                        style={{ '--d': `${0.2 + (i - 1) * 0.22}s` }}
                        x1={x - 10} y1="90" x2={x} y2="90"
                        stroke="rgba(255,255,255,0.5)" strokeWidth="1" strokeDasharray="2 2" />
                )}
                <g className={`sv-el sv-block ${isFinal ? 'sv-block-final' : ''}`}
                   style={{ '--d': `${i * 0.22}s` }}>
                  <rect x={x} y="60" width="68" height="60" rx="3"
                        fill="rgba(255,255,255,0.05)"
                        stroke={isFinal ? '#FF4E00' : 'rgba(255,255,255,0.7)'}
                        strokeWidth={isFinal ? '1.5' : '1'} />
                  <text x={x + 6} y="75" fontSize="5.5" fill="rgba(255,255,255,0.5)" fontWeight="500">BLOCK #{i + 1}</text>
                  <text x={x + 6} y="92" fontSize="8" fill="rgba(255,255,255,0.9)" fontFamily="ui-monospace, Menlo, monospace" fontWeight="500">{h}</text>
                  <line x1={x + 6} y1="100" x2={x + 62} y2="100" stroke="rgba(255,255,255,0.15)" strokeWidth="0.8" />
                  <text x={x + 6} y="112" fontSize="5" fill="rgba(255,255,255,0.4)">prev →</text>
                  {isFinal && (
                    <g className="sv-el sv-checksum" style={{ '--d': '1s' }}>
                      <circle cx={x + 54} cy="75" r="4" fill="#FF4E00" />
                      <path d={`M${x + 51} 75 L${x + 53} 77 L${x + 57} 73`} stroke="#fff" strokeWidth="1.2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
                    </g>
                  )}
                </g>
              </g>
            );
          })}
        </svg>
      </div>
      <ShowcaseBody
        title="Documentos sin trazabilidad"
        desc="Cada documento, firma y cambio con registro verificable y auditable."
        cta="Asegurar trazabilidad" />
    </a>
  );
};

const ShowcaseCardSignal = ({ href, badge, title, desc, cta, mode }) => {
  const { ref, played, cycle, onMouseEnter } = useReplayOnHover(1600);
  const isSlow = mode === 'slow';
  const isApproval = mode === 'approval';

  return (
    <a href={href} ref={ref} onMouseEnter={onMouseEnter}
       key={cycle} className={`showcase-card ${played ? 'is-in' : ''}`}>
      <div className="showcase-badge">{badge}</div>
      <div className="showcase-viz">
        <svg viewBox="0 0 320 180" className="sv-signal" aria-hidden="true">
          <g className="sv-el sv-head" style={{ '--d': '0s' }}>
            <line x1="34" y1="90" x2="286" y2="90" stroke="rgba(255,255,255,0.18)" strokeWidth="1" />
          </g>
          {[0, 1, 2, 3, 4].map((i) => {
            const x = 44 + i * 58;
            const y = isSlow ? 116 - i * 11 : isApproval ? (i === 3 ? 116 : 82) : 88 + Math.sin(i) * 22;
            const active = isApproval ? i === 3 : i === 4;
            return (
              <g key={i} className="sv-el sv-signal-node" style={{ '--d': `${0.12 + i * 0.12}s` }}>
                {i > 0 && (
                  <line x1={x - 58} y1={isSlow ? 116 - (i - 1) * 11 : isApproval ? ((i - 1) === 3 ? 116 : 82) : 88 + Math.sin(i - 1) * 22}
                        x2={x} y2={y}
                        stroke={active ? '#FF4E00' : 'rgba(255,255,255,0.5)'}
                        strokeWidth={active ? '1.6' : '1'}
                        strokeLinecap="round" />
                )}
                <circle cx={x} cy={y} r={active ? 9 : 7}
                        fill={active ? 'rgba(255,78,0,0.16)' : 'rgba(255,255,255,0.06)'}
                        stroke={active ? '#FF4E00' : 'rgba(255,255,255,0.72)'}
                        strokeWidth={active ? '1.6' : '1'} />
                {mode === 'attention' && i < 4 && (
                  <path d={`M${x - 8} ${y + 22} h${24 + i * 6}`} stroke="rgba(255,255,255,0.36)" strokeWidth="3" strokeLinecap="round" />
                )}
                {isApproval && i === 3 && (
                  <path d={`M${x - 4} ${y} l3 4 l8 -9`} stroke="#FF4E00" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round" />
                )}
              </g>
            );
          })}
          {isSlow && (
            <g className="sv-el sv-checksum" style={{ '--d': '0.9s' }}>
              <rect x="202" y="46" width="72" height="24" rx="12" fill="rgba(255,78,0,0.14)" stroke="#FF4E00" />
              <text x="238" y="62" textAnchor="middle" fontSize="8" fill="#FF4E00" fontWeight="700">alerta</text>
            </g>
          )}
        </svg>
      </div>
      <ShowcaseBody title={title} desc={desc} cta={cta} />
    </a>
  );
};

const ShowcaseVisual = () => (
  <section className="showcase-section" id="capacidades">
    <div className="container-wide">
      <div className="showcase-head">
        <h2 className="showcase-h2">Del desorden a un sistema que trabaja.</h2>
        <p className="showcase-sub">Entra por el problema que reconoces hoy; la hoja de ruta viene después.</p>
      </div>
      <div className="showcase-grid">
        <ShowcaseCardDashboard />
        <ShowcaseCardCircuito />
        <ShowcaseCardBlockchain />
        <ShowcaseCardAgente />
        <ShowcaseCardSignal
          href="/ia-aplicada#analitica"
          badge="Señales de alerta"
          title="Decisiones lentas"
          desc="Paneles, alertas y criterios para decidir antes de que el problema se haga grande."
          cta="Detectar antes"
          mode="slow" />
        <ShowcaseCardSimulacion />
        <ShowcaseCardCaptura />
        <ShowcaseCardSignal
          href="/digitalizacion-de-procesos#documental"
          badge="Archivo físico"
          title="Digitalización documental"
          desc="Escaneo, OCR, clasificación e indexación para convertir papel acumulado en información gobernable."
          cta="Digitalizar archivo físico"
          mode="slow" />
        <ShowcaseCardSignal
          href="/digitalizacion-de-procesos#captura"
          badge="OCR y validación"
          title="Captura documental"
          desc="Lectura y validación de facturas, albaranes y documentos repetitivos."
          cta="Capturar y validar documentos"
          mode="approval" />
      </div>
    </div>
  </section>
);

// ============================================
// PILLARS — S5 Cuatro ámbitos (Apple-like doors)
// ============================================
const PillarIcon = ({ kind, color }) => {
  const common = { width: 40, height: 40, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (kind === 'shield') return (
    <svg {...common}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
  );
  if (kind === 'workflow') return (
    <svg {...common}><rect x="3" y="3" width="8" height="8" rx="1"/><rect x="13" y="13" width="8" height="8" rx="1"/><path d="M7 11v4h8"/></svg>
  );
  if (kind === 'sparkles') return (
    <svg {...common}><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/><path d="M20 3v4"/><path d="M22 5h-4"/><path d="M4 17v2"/><path d="M5 18H3"/></svg>
  );
  // headset
  return (
    <svg {...common}><path d="M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H4a1 1 0 0 1-1-1v-6a9 9 0 0 1 18 0v6a1 1 0 0 1-1 1h-2a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"/></svg>
  );
};

const AREAS = [
  { id: 'gobernanza',   icon: 'shield',   badge: 'Primer criterio',   title: 'Si los datos no son fiables',      desc: 'Empezamos por saber dónde está la información, quién accede, qué reglas aplican y qué puede automatizarse con seguridad.', href: '/gobernanza-de-datos', cta: 'Ordenar datos dispersos' },
  { id: 'digitalizacion', icon: 'workflow', badge: 'Segundo criterio',        title: 'Si el proceso depende de perseguir personas', desc: 'Digitalizamos documentos, capturas y aprobaciones para que el trabajo avance con responsables y estados claros.', href: '/digitalizacion-de-procesos', cta: 'Digitalizar procesos manuales' },
  { id: 'ia',           icon: 'sparkles', badge: 'Tercer criterio',            title: 'Si ya hay contexto para aplicar IA',              desc: 'Diseñamos agentes, alertas y automatizaciones cuando existen datos, reglas y validación humana suficiente.', href: '/ia-aplicada', cta: 'Aplicar IA con criterio' },
  { id: 'inmersiva',    icon: 'headset',  badge: 'Cuando hay adopción crítica',     title: 'Si el equipo necesita practicar antes de cambiar',       desc: 'Creamos simulación y formación aplicada para procesos donde aprender solo con teoría no basta.', href: '/simulacion-y-formacion-inmersiva', cta: 'Entrenar decisiones críticas' },
];

const PillarsSection = () => {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const cards = ref.current.querySelectorAll('.area-card');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => e.target.classList.toggle('is-in', e.isIntersecting));
    }, { threshold: 0.18 });
    cards.forEach((card) => io.observe(card));
    return () => io.disconnect();
  }, []);

  return (
    <section className="areas-section" id="metodologia" ref={ref}>
      <div className="container-wide">
        <div className="areas-head">
          <p className="eyebrow areas-eyebrow">Ruta de decisión</p>
          <h2>Primero diagnóstico. Después módulos.</h2>
          <p>No todas las empresas necesitan lo mismo. El diagnóstico decide por dónde empezar, qué dejar para después y qué no merece inversión.</p>
        </div>
        <div className="areas-grid">
          {AREAS.map((a) => (
            <a key={a.id} href={a.href} className="area-card">
              <div className="area-icon"><PillarIcon kind={a.icon} color="#003C70" /></div>
              <span className="area-badge">{a.badge}</span>
              <h3 className="area-title">{a.title}</h3>
              <p className="area-desc">{a.desc}</p>
              <span className="area-cta">{a.cta} <ArrowRight /><span className="area-cta-underline" /></span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
};

// ============================================
// SERVICES
// ============================================
const SERVICES = [
  { title: 'Diagnóstico estratégico', tag: 'Punto de partida', desc: 'Analizamos tus datos, procesos y equipo. Identificamos dónde estás, qué te frena y qué tiene mayor impacto potencial. Resultado: una hoja de ruta clara y priorizada.', featured: true,
    cta: 'Solicitar diagnóstico', href: '/diagnostico' },
  { title: 'Gobernanza y soberanía de datos', tag: 'Ámbito · Gobernanza', desc: 'Estructuramos tu información, definimos accesos y políticas de datos, y dejamos preparada la trazabilidad avanzada cuando la integridad o la soberanía lo justifican.',
    cta: 'Auditar gobernanza de datos', href: '/gobernanza-de-datos' },
  { title: 'Digitalización documental y procesos', tag: 'Ámbito · Digitalización', desc: 'Digitalizamos papel, aplicamos OCR, clasificamos documentos y automatizamos circuitos administrativos que hoy consumen horas de trabajo manual.',
    cta: 'Digitalizar documentos y procesos', href: '/digitalizacion-de-procesos' },
  { title: 'Implantación de IA', tag: 'Ámbito · IA aplicada', desc: 'Agentes inteligentes, modelos adaptados a tus datos y automatizaciones que aprenden. Sobre la base que hemos construido juntos.',
    cta: 'Aplicar IA con control humano', href: '/ia-aplicada' },
  { title: 'Inmersión aplicada', tag: 'Ámbito · Inmersión', desc: 'Formación de alto impacto, simulación de riesgo y virtualización de procesos. Donde la práctica sustituye la teoría y el error no tiene coste real.',
    cta: 'Diseñar formación inmersiva', href: '/simulacion-y-formacion-inmersiva' },
  { title: 'Formación y acompañamiento', tag: 'Transversal', desc: 'Tu equipo aprende a trabajar con las nuevas herramientas. No dependes de nosotros para siempre — te preparamos para que vueles solo.',
    cta: 'Solicitar diagnóstico', href: '/diagnostico' },
];

const ServiceIcon = ({ i }) => {
  const icons = [
    <path key="0" d="M12 2 L3 7 v10 l9 5 9-5 V7 Z M12 2 v20 M3 7 l18 10 M21 7 L3 17" strokeLinejoin="round" />,
    <><rect key="a" x="3" y="4" width="18" height="16" rx="2" /><path key="b" d="M7 9 h10 M7 13 h6 M15 13 l2 2 -2 2" strokeLinecap="round" /></>,
    <><rect key="a" x="4" y="4" width="6" height="6" rx="1" /><rect key="b" x="14" y="4" width="6" height="6" rx="1" /><rect key="c" x="9" y="14" width="6" height="6" rx="1" /><path key="d" d="M7 10 v2 h10 v-2 M12 14 v-2" strokeLinecap="round" /></>,
    <><circle key="a" cx="12" cy="12" r="3" /><path key="b" d="M12 4 v3 M12 17 v3 M4 12 h3 M17 12 h3 M6.3 6.3 l2.1 2.1 M15.6 15.6 l2.1 2.1 M6.3 17.7 l2.1 -2.1 M15.6 8.4 l2.1 -2.1" strokeLinecap="round" /></>,
    <><circle key="a" cx="12" cy="12" r="9" /><path key="b" d="M3 12 h18 M12 3 a14 14 0 0 1 0 18 M12 3 a14 14 0 0 0 0 18" /></>,
    <><path key="a" d="M4 19 V9 L12 4 L20 9 V19 H4 Z" /><path key="b" d="M9 19 v-6 h6 v6" /></>,
  ];
  return (
    <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
      {icons[i]}
    </svg>
  );
};

const ServicesSection = () => {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const cards = ref.current.querySelectorAll('.service-card');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e, i) => {
        if (e.isIntersecting) {
          setTimeout(() => e.target.classList.add('is-in'), i * 60);
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12 });
    cards.forEach((c) => io.observe(c));
    return () => io.disconnect();
  }, []);

  return (
    <section className="section" id="servicios">
      <div className="container-wide">
        <div className="section-head">
          <p className="eyebrow">Nuestros servicios</p>
          <h2>Diseñados para cada fase de tu <span className="accent">transformación</span>.</h2>
        </div>
        <div className="services-grid" ref={ref}>
          {SERVICES.map((s, i) => (
            <div key={i} className={`service-card ${s.featured ? 'featured' : ''}`}>
              {s.featured && <div className="service-pill">Punto de partida</div>}
              <div className="service-icon"><ServiceIcon i={i} /></div>
              <div className="service-tag">{s.tag}</div>
              <h3>{s.title}</h3>
              <p>{s.desc}</p>
              <a
                href={s.pending ? '#' : s.href}
                {...(s.pending ? { 'data-pending': 'true' } : {})}
                className="service-link"
              >
                {s.cta} <ArrowRight />
              </a>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ============================================
// TRUST SECTION — Por qué Talos puede ejecutarlo
// ============================================
const TRUST_ITEMS = [
  {
    label: 'Responsables visibles',
    title: 'Hablas con quien decide.',
    desc: 'La conversación no se delega en perfiles sin criterio. El diagnóstico, la propuesta y la entrega tienen responsables claros.',
  },
  {
    label: 'Capacidad técnica',
    title: 'Podemos bajar a producción.',
    desc: 'Talos combina consultoría, programación, integración y soporte para que las decisiones no se queden en una presentación.',
  },
  {
    label: 'Criterio de negocio',
    title: 'No todo se automatiza.',
    desc: 'Antes de proponer tecnología, medimos retorno, esfuerzo, adopción y riesgo operativo. Si no hay caso, lo decimos.',
  },
  {
    label: 'Validación humana',
    title: 'El control no desaparece.',
    desc: 'Cada módulo deja trazabilidad, responsables y puntos de revisión para que el equipo mantenga criterio sobre el sistema.',
  },
];

const TrustSection = () => (
  <section className="trust-section" id="confianza">
    <div className="container-wide trust-grid">
      <div className="trust-copy">
        <p className="eyebrow">Por qué Talos</p>
        <h2>Consultoría cercana con capacidad de implantación técnica.</h2>
        <p>Hablas con responsables. Detrás hay capacidad técnica y consultiva para ejecutar: diagnóstico, programación, integración, formación y acompañamiento.</p>
      </div>
      <div className="trust-cards">
        {TRUST_ITEMS.map((item) => (
          <article className="trust-card" key={item.label}>
            <span>{item.label}</span>
            <h3>{item.title}</h3>
            <p>{item.desc}</p>
          </article>
        ))}
      </div>
    </div>
  </section>
);

// ============================================
// SECTORS
// ============================================
const SECTORS = [
  {
    title: 'Facturas que se revisan a mano',
    scenario: 'Horas perdidas comprobando importes, vencimientos y albaranes.',
    path: 'Digitalización',
    href: '/digitalizacion-de-procesos#captura',
    cta: 'Digitalizar facturas y albaranes',
  },
  {
    title: 'Digitalización documental',
    scenario: 'Escaneo, OCR, clasificación e indexación de archivos físicos para convertir papel acumulado en información buscable y gobernable.',
    path: 'Archivo físico',
    href: '/digitalizacion-de-procesos#documental',
    cta: 'Digitalizar archivo físico',
  },
  {
    title: 'Captura documental',
    scenario: 'Lectura y validación de facturas, albaranes y documentos repetitivos.',
    path: 'OCR y validación',
    href: '/digitalizacion-de-procesos#captura',
    cta: 'Capturar y validar documentos',
  },
  {
    title: 'Datos críticos repartidos en Excels',
    scenario: 'Nadie mira la misma versión cuando hay que decidir rápido.',
    path: 'Gobernanza',
    href: '/gobernanza-de-datos',
    cta: 'Centralizar datos críticos',
  },
  {
    title: 'Expedientes sin trazabilidad clara',
    scenario: 'Cuesta demostrar quién hizo qué, cuándo y con qué criterio.',
    path: 'Gobernanza',
    href: '/gobernanza-de-datos#trazabilidad',
    cta: 'Asegurar trazabilidad documental',
  },
  {
    title: 'Consultas internas repetidas',
    scenario: 'El equipo responde lo mismo una y otra vez sin una fuente común.',
    path: 'IA',
    href: '/ia-aplicada#agentes',
    cta: 'Resolver consultas internas con IA',
  },
  {
    title: 'Reporting directivo que llega tarde',
    scenario: 'Los datos aparecen cuando la decisión ya se ha tomado.',
    path: 'IA',
    href: '/ia-aplicada#analitica',
    cta: 'Anticipar decisiones con datos',
  },
  {
    title: 'Formación de riesgo difícil de practicar',
    scenario: 'El error real sale caro y la teoría no prepara suficiente.',
    path: 'Inmersión',
    href: '/simulacion-y-formacion-inmersiva',
    cta: 'Entrenar situaciones críticas',
  },
  {
    title: 'Conocimiento atrapado en personas clave',
    scenario: 'La empresa depende de memoria, criterio y disponibilidad individual.',
    path: 'IA',
    href: '/ia-aplicada#conocimiento',
    cta: 'Liberar conocimiento interno',
  },
];

const SectorIcon = ({ i }) => {
  const icons = [
    <><rect key="a" x="3" y="10" width="18" height="10" rx="1" /><path key="b" d="M7 10 V6 h10 v4 M10 14 h4" strokeLinecap="round" /></>,
    <><path key="a" d="M4 20 V10 l8 -6 8 6 v10 Z" /><path key="b" d="M9 20 v-6 h6 v6 M4 10 l8 -6 8 6" strokeLinejoin="round" /></>,
    <><rect key="a" x="3" y="4" width="18" height="16" rx="1" /><path key="b" d="M7 8 h10 M7 12 h10 M7 16 h6" strokeLinecap="round" /></>,
    <><circle key="a" cx="12" cy="8" r="4" /><path key="b" d="M4 20 c0-4 4-6 8-6 s8 2 8 6" /></>,
    /* Sanidad — HeartPulse */
    <><path key="a" d="M20.42 11.5 a5 5 0 0 0 -8.42 -5 a5 5 0 0 0 -8.42 5" strokeLinecap="round" strokeLinejoin="round" /><path key="b" d="M3.75 13 H7 l2 -3 3 6 2 -4 1.5 2 H20.25" strokeLinecap="round" strokeLinejoin="round" /><path key="c" d="M12 20 c-2 -1.5 -5.3 -3.7 -7.2 -6 M12 20 c2 -1.5 5.3 -3.7 7.2 -6" strokeLinecap="round" /></>,
    /* Financiero — ShieldCheck */
    <><path key="a" d="M12 22 s8 -4 8 -10 V5 l-8 -3 -8 3 v7 c0 6 8 10 8 10 z" strokeLinejoin="round" /><path key="b" d="M8.5 12 l2.5 2.5 L15.5 9.5" strokeLinecap="round" strokeLinejoin="round" /></>,
  ];
  return <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">{icons[i % icons.length]}</svg>;
};

const SectorsSection = () => {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const cards = ref.current.querySelectorAll('.sector-card');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e, i) => {
        if (e.isIntersecting) {
          setTimeout(() => e.target.classList.add('is-in'), i * 80);
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12 });
    cards.forEach((c) => io.observe(c));
    return () => io.disconnect();
  }, []);

  return (
    <section className="section bg-muted" id="sectores">
      <div className="container-wide">
        <div className="section-head">
          <p className="eyebrow eyebrow--sentence">Casos de uso</p>
          <h2>Problemas reales que podemos <span className="accent">ordenar.</span></h2>
          <p>Microcasos para reconocer dónde puede empezar el diagnóstico.</p>
        </div>
        <div className="sectors-grid" ref={ref}>
          {SECTORS.map((s, i) => (
            <a key={i} className="sector-card microcase-card" href={s.href}>
              <div className="sector-head">
                <div className="ico"><SectorIcon i={i} /></div>
                <h3>{s.title}</h3>
              </div>
              <div className="sector-body">
                <div className="sector-block sector-scenario">
                  <p>{s.scenario}</p>
                </div>
                <div className="microcase-foot">
                  <span>{s.path}</span>
                  <span>{s.cta} <ArrowRight /></span>
                </div>
              </div>
            </a>
          ))}
        </div>
        <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--muted-fg)', marginTop: 40 }}>
          Casos representativos. Cada implantación se adapta al contexto real de la empresa.
        </p>
      </div>
    </section>
  );
};

// ============================================
// TEAM SECTION — Quién está detrás
// ============================================
const TeamSection = () => {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current) return;
    const cards = ref.current.querySelectorAll('.area-card');
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => e.target.classList.toggle('is-in', e.isIntersecting));
    }, { threshold: 0.18 });
    cards.forEach((card) => io.observe(card));
    return () => io.disconnect();
  }, []);

  return (
    <section className="areas-section" id="equipo-home" ref={ref}>
      <div className="container-wide">
        <div className="areas-head">
          <p className="eyebrow areas-eyebrow">Equipo</p>
          <h2>Hablas con responsables. Detrás hay capacidad para ejecutar.</h2>
          <p>Talos no es una caja negra ni una marca sin interlocutores. Entendemos tu empresa contigo, traducimos el problema a una hoja de ruta y bajamos a implantación cuando el caso lo justifica.</p>
        </div>
        <div className="areas-grid team-grid-3">
          <a href="/equipo" className="area-card">
            <span className="area-badge">Estrategia y adopción</span>
            <h3 className="area-title">Criterio antes de herramienta</h3>
            <p className="area-desc">La dirección del proyecto mantiene foco en negocio, impacto real, comunicación con comité directivo y adopción interna.</p>
            <span className="area-cta">Ver dirección estratégica <ArrowRight /><span className="area-cta-underline" /></span>
          </a>
          <a href="/equipo" className="area-card">
            <span className="area-badge">Procesos y organización</span>
            <h3 className="area-title">La operativa marca el diseño</h3>
            <p className="area-desc">Cada módulo parte de cómo trabaja la organización hoy: responsables, fricciones, aprobaciones, documentación y riesgos.</p>
            <span className="area-cta">Ver análisis operativo <ArrowRight /><span className="area-cta-underline" /></span>
          </a>
          <a href="/equipo" className="area-card">
            <span className="area-badge">Tecnología y entrega</span>
            <h3 className="area-title">Implantación con capacidad detrás</h3>
            <p className="area-desc">La arquitectura, integración y desarrollo se sostienen con equipos técnicos y consultivos ya operativos.</p>
            <span className="area-cta">Ver capacidad de implantación <ArrowRight /><span className="area-cta-underline" /></span>
          </a>
        </div>
        <div style={{ textAlign: 'center', marginTop: 32 }}>
          <a href="/equipo" className="btn btn-ghost">Ver responsables y capacidad operativa <ArrowRight /></a>
        </div>
      </div>
    </section>
  );
};

// ============================================
// CTA FINAL
// ============================================
const CTAFinal = () => (
  <section className="cta-final" id="contacto">
    <div className="inner">
      <p className="eyebrow">Siguiente paso</p>
      <h2>Antes de invertir en tecnología, aclaremos dónde está el <span className="cta-accent">retorno</span>.</h2>
      <p className="lead">Explícanos el contexto. Revisamos datos, procesos y prioridades para proponerte el siguiente paso razonable. Hablas siempre con uno de los consultores responsables, no con un comercial.</p>
      <div className="cta-row">
          <a className="btn btn-primary" href="/diagnostico">Solicita tu diagnóstico <ArrowRight /></a>
          <a className="btn btn-ghost" href="/contacto">Hablar con el equipo</a>
      </div>
    </div>
  </section>
);

// ============================================
// FOOTER
// ============================================
const Footer = () => (
  <footer className="footer">
    <div className="container-wide">
      <div className="footer-grid">
        <div className="footer-brand">
          <div className="mark"><TalosLogoHorizontal variant="white" height={96} /></div>
          <p>Consultoría tecnológica para empresas e instituciones que necesitan criterio antes que herramientas. Responsables visibles al frente y capacidad operativa contrastada detrás.</p>
          <div className="footer-contact-card" aria-label="Contacto directo">
            <a href="mailto:info@talostech.es">info@talostech.es</a>
            <a href="tel:+34652885269">652.885.269</a>
          </div>
        </div>
        <div className="footer-col">
          <h4>Servicios</h4>
          <ul>
            <li><a href="/gobernanza-de-datos">Gobernanza de datos</a></li>
            <li><a href="/digitalizacion-de-procesos">Digitalización</a></li>
            <li><a href="/ia-aplicada">IA aplicada</a></li>
            <li><a href="/simulacion-y-formacion-inmersiva">Inmersión</a></li>
            <li><a href="/diagnostico">Diagnóstico</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>Empresa</h4>
          <ul>
            <li><a href="/metodologia">Metodología</a></li>
            <li><a href="/equipo">Equipo</a></li>
            <li><a href="/contacto">Contacto</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>Legal</h4>
          <ul>
            <li><a href="/aviso-legal">Aviso legal</a></li>
            <li><a href="/privacidad">Privacidad</a></li>
            <li><a href="/cookies">Cookies</a></li>
          </ul>
        </div>
      </div>
    </div>
    <div className="footer-bottom">
      <div className="wrap">
        <span>© 2026 Talos Technology. Todos los derechos reservados.</span>
        <span>Estrategia y consultoría en datos, procesos e inteligencia artificial.</span>
      </div>
    </div>
  </footer>
);

Object.assign(window, {
  TechMarquee, PainPoints, ShowcaseVisual, PillarsSection,
  ServicesSection, SectorsSection, TrustSection, TeamSection,
  CTAFinal, Footer
});
