/* eslint-disable */
/* global React, ReactDOM, useLang, LangProvider, WhatsAppFloat */
/* home.jsx — Teramot Home V2 (relanzamiento, foco Finanzas / P&CdG).
   Recreación del handoff de diseño "Teramot Home V2" (ver
   /Users/facundoortega/.claude/plans/replicated-dazzling-badger.md para el
   contexto completo). Nav y footer son propios de esta página (no
   chrome.jsx) — el resto del sitio no cambia. Mantiene el toggle ES/EN vía
   el useLang() global (i18n.jsx) por consistencia con el resto del sitio,
   aunque no está en el diseño original. */

const { useState: useStateHome, useEffect: useEffectHome, useRef: useRefHome, useCallback: useCallbackHome } = React;

/* ── Scroll reveal genérico (mismo idiom que el resto del sitio: chrome.jsx,
   agro.jsx, etc.) — no el motor de reveal más elaborado del handoff. ── */
const useScrollReveal = (rootRef) => {
  useEffectHome(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const root = rootRef.current;
    if (!root) return;
    const groups = [];
    root.querySelectorAll('section, footer').forEach((sec) => {
      const wrap = sec.firstElementChild && sec.children.length === 1 ? sec.firstElementChild : sec;
      // Drawer/overlay are fixed-position overlays, not in-flow content —
      // reveal-in would fight their own open/close transform.
      const kids = Array.from(wrap.children).filter((el) => (
        el.nodeType === 1 && !el.classList.contains('tm-drawer') && !el.classList.contains('tm-drawer-overlay')
      ));
      if (kids.length) groups.push(kids);
    });
    const io = new IntersectionObserver((entries) => {
      entries.forEach((en) => {
        if (en.isIntersecting) {
          en.target.classList.add('rv-in');
          io.unobserve(en.target);
        }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.08 });
    groups.forEach((kids) => kids.forEach((el, i) => {
      el.classList.add('rv');
      el.style.transitionDelay = Math.min(i, 4) * 70 + 'ms';
      io.observe(el);
    }));
    return () => io.disconnect();
  }, []);
};

/* Smooth anchor scroll — duración proporcional a la distancia, easing
   cubic-bezier(0.16,1,0.3,1), igual que el handoff. */
const makeBezier = (p1x, p1y, p2x, p2y) => {
  const cx = 3 * p1x, bx = 3 * (p2x - p1x) - cx, ax = 1 - cx - bx;
  const cy = 3 * p1y, by = 3 * (p2y - p1y) - cy, ay = 1 - cy - by;
  const sx = (t) => ((ax * t + bx) * t + cx) * t;
  const dx = (t) => (3 * ax * t + 2 * bx) * t + cx;
  return (x) => {
    let t = x;
    for (let i = 0; i < 6; i++) {
      const e = sx(t) - x, d = dx(t);
      if (Math.abs(e) < 1e-5 || Math.abs(d) < 1e-6) break;
      t -= e / d;
    }
    return ((ay * t + by) * t + cy) * t;
  };
};

const useSmoothAnchors = (hostRef) => {
  useEffectHome(() => {
    const root = hostRef.current || document;
    const ease = makeBezier(0.16, 1, 0.3, 1);
    let raf = 0;
    const stop = () => { if (raf) cancelAnimationFrame(raf); raf = 0; };
    const glide = (to) => {
      stop();
      const from = window.scrollY;
      const dist = to - from;
      if (Math.abs(dist) < 2) return;
      const dur = Math.min(1500, Math.max(650, Math.abs(dist) * 0.55));
      const t0 = performance.now();
      const step = (now) => {
        const p = Math.min(1, (now - t0) / dur);
        window.scrollTo(0, from + dist * ease(p));
        if (p < 1) raf = requestAnimationFrame(step); else raf = 0;
      };
      raf = requestAnimationFrame(step);
    };
    const onClick = (e) => {
      const a = e.target.closest && e.target.closest('a[href^="#"]');
      if (!a) return;
      const id = a.getAttribute('href').slice(1);
      if (!id) return;
      const target = document.getElementById(id);
      if (!target) return;
      e.preventDefault();
      if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
        window.scrollTo(0, target.getBoundingClientRect().top + window.scrollY);
        return;
      }
      glide(Math.max(0, target.getBoundingClientRect().top + window.scrollY - 24));
    };
    root.addEventListener('click', onClick);
    ['wheel', 'touchstart', 'keydown'].forEach((ev) => window.addEventListener(ev, stop, { passive: true }));
    return () => {
      stop();
      root.removeEventListener('click', onClick);
      ['wheel', 'touchstart', 'keydown'].forEach((ev) => window.removeEventListener(ev, stop));
    };
  }, []);
};

/* Hero mouse-parallax sobre los layers con data-depth. */
const useHeroParallax = (artRef) => {
  useEffectHome(() => {
    const el = artRef.current;
    if (!el) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const layers = Array.from(el.querySelectorAll('[data-depth]'));
    layers.forEach((l) => {
      const release = () => {
        l.style.animation = 'none';
        l.style.opacity = '1';
        l.style.transform = 'translate3d(0, 0, 0) scale(1)';
      };
      l.addEventListener('animationend', release, { once: true });
    });
    let raf = 0;
    const apply = (dx, dy, lift) => {
      layers.forEach((l) => {
        const d = parseFloat(l.dataset.depth) || 0;
        const x = (-dx * d * 18).toFixed(2);
        const y = (-dy * d * 14).toFixed(2);
        l.style.transform = `translate3d(${x}px, ${y}px, 0) scale(${(1 + d * 0.01 * lift).toFixed(4)})`;
      });
    };
    const move = (e) => {
      const r = el.getBoundingClientRect();
      const dx = (e.clientX - (r.left + r.width / 2)) / r.width;
      const dy = (e.clientY - (r.top + r.height / 2)) / r.height;
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => apply(dx, dy, 1));
    };
    const leave = () => { cancelAnimationFrame(raf); apply(0, 0, 0); };
    el.addEventListener('mousemove', move);
    el.addEventListener('mouseleave', leave);
    return () => {
      cancelAnimationFrame(raf);
      el.removeEventListener('mousemove', move);
      el.removeEventListener('mouseleave', leave);
    };
  }, []);
};

/* ── NAV + HERO ──────────────────────────────────────────────── */

const HomeHero = ({ artRef }) => {
  const { lang, setLang, c } = useLang();
  useHeroParallax(artRef);
  const [drawerOpen, setDrawerOpen] = useStateHome(false);

  /* Smooth ES/EN content swap — View Transitions crossfades the whole
     page (old snapshot out, new content in) instead of an instant text
     swap. Falls back to a plain setLang where unsupported. */
  const changeLang = useCallbackHome((next) => {
    if (next === lang) return;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (!reduce && document.startViewTransition) {
      const transition = document.startViewTransition(() => setLang(next));
      // Clicking again before a transition settles aborts it — expected,
      // but the browser otherwise reports it as an unhandled rejection.
      transition.ready.catch(() => {});
      transition.finished.catch(() => {});
    } else {
      setLang(next);
    }
  }, [lang, setLang]);

  useEffectHome(() => {
    document.body.style.overflow = drawerOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [drawerOpen]);

  useEffectHome(() => {
    if (!drawerOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setDrawerOpen(false); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [drawerOpen]);

  /* Swipe-to-close — same idiom as chrome.jsx's NavBar drawer. */
  const touchStartXRef = useRefHome(0);
  const touchDeltaXRef = useRefHome(0);
  const onDrawerTouchStart = useCallbackHome((e) => {
    touchStartXRef.current = e.touches[0].clientX;
    touchDeltaXRef.current = 0;
  }, []);
  const onDrawerTouchMove = useCallbackHome((e) => {
    touchDeltaXRef.current = e.touches[0].clientX - touchStartXRef.current;
  }, []);
  const onDrawerTouchEnd = useCallbackHome(() => {
    if (touchDeltaXRef.current > 60) setDrawerOpen(false);
    touchDeltaXRef.current = 0;
  }, []);

  return (
    <section className="tm-home-hero">
      <div className="tm-home-hero-nav">
        <a href="#" className="tm-home-hero-nav-logo" aria-label="Teramot home">
          <img src="brand/teramot-logo-on-dark.svg" alt="Teramot" />
        </a>
        <nav className="tm-home-hero-nav-links">
          <a href="#producto">{c.home2.nav.links[0]}</a>
          <a href="#como-funciona">{c.home2.nav.links[1]}</a>
          <a href="#integraciones">{c.home2.nav.links[2]}</a>
          <a href="#seguridad">{c.home2.nav.links[3]}</a>
        </nav>
        <div className="tm-home-hero-nav-actions">
          <div className={`tm-lang tm-home-lang-toggle ${lang === 'en' ? 'is-en' : ''}`} role="group" aria-label="Language">
            <button type="button" aria-current={lang === 'es' ? 'true' : 'false'} onClick={() => changeLang('es')}>ES</button>
            <button type="button" aria-current={lang === 'en' ? 'true' : 'false'} onClick={() => changeLang('en')}>EN</button>
          </div>
          <a href={c.links.app} className="tm-home-video-link">{c.home2.nav.login}</a>
          <a href={c.links.call} target="_blank" rel="noopener noreferrer" className="tm-home-btn tm-home-btn-md tm-home-btn-white">{c.home2.demo} <i className="ph ph-arrow-right" /></a>
        </div>
        <button
          type="button"
          className="tm-home-hero-hamburger"
          aria-label={c.home2.nav.openMenu}
          aria-expanded={drawerOpen}
          onClick={() => setDrawerOpen(true)}
        >
          <span /><span /><span />
        </button>
      </div>

      <div className={`tm-drawer-overlay ${drawerOpen ? 'is-open' : ''}`} onClick={() => setDrawerOpen(false)} />
      <div
        className={`tm-drawer ${drawerOpen ? 'is-open' : ''}`}
        aria-hidden={!drawerOpen}
        onTouchStart={onDrawerTouchStart}
        onTouchMove={onDrawerTouchMove}
        onTouchEnd={onDrawerTouchEnd}
      >
        <div className="tm-drawer-header">
          <a href="#" className="tm-home-hero-nav-logo" aria-label="Teramot home" onClick={() => setDrawerOpen(false)}>
            <img src="brand/teramot-logo.png" alt="Teramot" />
          </a>
          <button className="tm-drawer-close" aria-label={c.home2.nav.closeMenu} onClick={() => setDrawerOpen(false)}>
            <i className="ph-bold ph-x" />
          </button>
        </div>
        <nav className="tm-drawer-links">
          <a className="tm-nav-link" href="#producto" onClick={() => setDrawerOpen(false)}>{c.home2.nav.links[0]}</a>
          <a className="tm-nav-link" href="#como-funciona" onClick={() => setDrawerOpen(false)}>{c.home2.nav.links[1]}</a>
          <a className="tm-nav-link" href="#integraciones" onClick={() => setDrawerOpen(false)}>{c.home2.nav.links[2]}</a>
          <a className="tm-nav-link" href="#seguridad" onClick={() => setDrawerOpen(false)}>{c.home2.nav.links[3]}</a>
          <a className="tm-nav-link" href={c.links.app} onClick={() => setDrawerOpen(false)}>{c.home2.nav.login}</a>
        </nav>
        <div className="tm-drawer-actions">
          <a className="tm-btn tm-btn-primary tm-btn-lg" href={c.links.call} target="_blank" rel="noopener noreferrer" onClick={() => setDrawerOpen(false)}>{c.home2.demo} <i className="ph ph-arrow-right" /></a>
        </div>
        <div className="tm-drawer-lang">
          <div className="tm-lang" role="group" aria-label="Language">
            <button type="button" aria-current={lang === 'es' ? 'true' : 'false'} onClick={() => changeLang('es')}>ES</button>
            <button type="button" aria-current={lang === 'en' ? 'true' : 'false'} onClick={() => changeLang('en')}>EN</button>
          </div>
        </div>
      </div>

      <div className="tm-home-hero-content">
        <div className="tm-home-hero-copy">
          <h1>{c.home2.hero.h1Pre}<span className="tm-home-text-mint">{c.home2.hero.h1Highlight}</span>{c.home2.hero.h1Post}</h1>
          <p>{c.home2.hero.sub}</p>
          <div className="tm-home-hero-actions">
            <a href={c.links.call} target="_blank" rel="noopener noreferrer" className="tm-home-btn tm-home-btn-lg tm-home-btn-white">{c.home2.demo} <i className="ph ph-arrow-right" /></a>
            <a href={c.links.app} className="tm-home-btn tm-home-btn-lg tm-home-btn-ghost-light"><i className="ph ph-arrow-right" /> {c.home2.video}</a>
          </div>
          <p className="tm-home-hero-finePrint">{c.home2.hero.finePrint}</p>
        </div>

        <div ref={artRef} className="tm-home-hero-art">
          <div data-depth="0.25" className="tm-home-hero-art-glow" />
          <img src="assets/home/mockup-01.svg" alt={c.home2.hero.artAlt} data-depth="0.6" className="tm-home-hero-art-mockup" />
          <img src="assets/home/chart-01.svg" alt="" data-depth="1.4" className="tm-home-hero-art-chart1" />
          <picture>
            <source srcSet="assets/home/girl-hero-v3.avif" type="image/avif" />
            <source srcSet="assets/home/girl-hero-v3.webp" type="image/webp" />
            <img src="assets/home/girl-hero-v3.png" alt="" data-depth="0.9" className="tm-home-hero-art-girl" />
          </picture>
          <img src="assets/home/chart-02.svg" alt="" data-depth="1.8" className="tm-home-hero-art-chart2" />
        </div>
      </div>
    </section>
  );
};

/* ── CLIENTES ────────────────────────────────────────────────── */

const CLIENTES_LOGOS = [
  { src: 'brand/clients/coca-cola.png', alt: 'The Coca-Cola Company', h: 40 },
  { src: 'brand/clients/johnson-johnson.png', alt: 'Johnson & Johnson', h: 15 },
  { src: 'brand/clients/sancor-seguros.png', alt: 'Grupo Sancor Seguros', h: 38 },
  { src: 'brand/clients/bcr.png', alt: 'Bolsa de Comercio de Rosario', h: 38 },
  { src: 'brand/clients/la-segunda.svg', alt: 'La Segunda', h: 27 },
  { src: 'brand/clients/cubo-itau.webp', alt: 'Cubo Itaú', h: 32 },
  { src: 'brand/clients/endeavor.png', alt: 'Endeavor', h: 19 },
  { src: 'brand/clients/digital-house.png', alt: 'Digital House', h: 29 },
  { src: 'brand/clients/sullair.svg', alt: 'Sullair', h: 21 },
];

const ClientesSection = () => {
  const { c } = useLang();
  const track = [...CLIENTES_LOGOS, ...CLIENTES_LOGOS];
  return (
    <div className="tm-home-clientes">
      <div className="tm-home-clientes-inner">
        <p className="tm-home-clientes-label">{c.home2.clientes.label}</p>
        <div className="tm-home-marquee">
          <div className="tm-home-marquee-track">
            {track.map((logo, i) => (
              <img key={logo.alt + i} src={logo.src} alt={logo.alt} style={{ height: logo.h }} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

/* ── PROBLEMA ────────────────────────────────────────────────── */

const PROBLEM_ICONS = ['clock-countdown', 'table', 'user-focus', 'chart-line-down'];

/* Inlinea problem.svg en runtime para poder animar cada parte por separado.
   La categorización por posición (sources/flows/core/report) es agnóstica al
   contenido exacto del SVG — se basa en el bounding box de cada elemento. */
const useProblemIllustration = (hostRef) => {
  useEffectHome(() => {
    const host = hostRef.current;
    if (!host) return;
    let cancelled = false;
    (async () => {
      let markup;
      try {
        markup = await (await fetch('assets/home/problem.svg')).text();
      } catch (err) {
        return;
      }
      if (cancelled) return;
      host.innerHTML = markup;
      const svg = host.querySelector('svg');
      if (!svg) return;
      svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
      svg.style.width = '100%';
      svg.style.height = '100%';
      svg.style.display = 'block';

      const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      const nodes = Array.from(svg.children).filter((el) => el.tagName !== 'defs');
      const sources = [], flows = [], core = [], report = [];
      nodes.forEach((el) => {
        let bb;
        try { bb = el.getBBox(); } catch (e) { return; }
        if (bb.width >= 700) return;
        el.style.transformBox = 'fill-box';
        el.style.transformOrigin = 'center';
        const cx = bb.x + bb.width / 2;
        if (el.getAttribute('stroke-dasharray')) flows.push(el);
        else if (cx < 220) sources.push({ el, y: bb.y });
        else if (cx < 500) core.push(el);
        else report.push(el);
      });
      sources.sort((a, b) => a.y - b.y);
      const hide = (el) => { el.style.opacity = '0'; };
      sources.forEach((s) => hide(s.el));
      flows.forEach(hide); core.forEach(hide); report.forEach(hide);

      const ease = 'cubic-bezier(0.2, 0, 0, 1)';
      const play = () => {
        sources.forEach(({ el }, i) => {
          el.animate([{ opacity: 0, transform: 'translateX(-18px)' }, { opacity: 1, transform: 'translateX(0)' }],
            { duration: 520, delay: 120 + i * 110, easing: ease, fill: 'forwards' });
        });
        flows.forEach((el, i) => {
          el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 420, delay: 560 + i * 90, easing: ease, fill: 'forwards' });
          el.animate([{ strokeDashoffset: 0 }, { strokeDashoffset: -16 }], { duration: 900, delay: 560, iterations: Infinity, easing: 'linear' });
        });
        core.forEach((el) => {
          el.animate([{ opacity: 0, transform: 'scale(.92)' }, { opacity: 1, transform: 'scale(1)' }],
            { duration: 620, delay: 900, easing: ease, fill: 'forwards' });
        });
        report.forEach((el, i) => {
          el.animate([{ opacity: 0, transform: 'translateY(10px)' }, { opacity: 1, transform: 'translateY(0)' }],
            { duration: 560, delay: 1200 + Math.min(i, 18) * 45, easing: ease, fill: 'forwards' });
        });
        const disc = core.find((el) => (el.getAttribute('fill') || '').toUpperCase() === '#91DFC8');
        if (disc) {
          disc.animate([{ transform: 'scale(1)' }, { transform: 'scale(1.12)' }, { transform: 'scale(1)' }],
            { duration: 2400, delay: 1600, iterations: Infinity, easing: 'cubic-bezier(0.4, 0, 0.6, 1)' });
        }
      };

      if (reduce) {
        [...sources.map((s) => s.el), ...flows, ...core, ...report].forEach((el) => { el.style.opacity = '1'; });
        return;
      }
      if (!('IntersectionObserver' in window)) { play(); return; }
      let played = false;
      const playOnce = () => { if (played) return; played = true; play(); };
      const io = new IntersectionObserver((entries) => {
        entries.forEach((entry) => { if (entry.isIntersecting) { playOnce(); io.disconnect(); } });
      }, { threshold: 0.35 });
      io.observe(host);
      const guard = setInterval(() => {
        if (played) { clearInterval(guard); return; }
        const r = host.getBoundingClientRect();
        if (r.height && r.top < window.innerHeight * 0.9 && r.bottom > 0) {
          playOnce(); io.disconnect(); clearInterval(guard);
        }
      }, 250);
      host._cleanup = () => { io.disconnect(); clearInterval(guard); };
    })();
    return () => { cancelled = true; if (host._cleanup) host._cleanup(); };
  }, []);
};

const ProblemaSection = () => {
  const { c } = useLang();
  const problemRef = useRefHome(null);
  useProblemIllustration(problemRef);
  return (
    <section id="producto" className="tm-home-problema">
      <div className="tm-home-container">
        <div style={{ textAlign: 'center', marginBottom: 36 }}>
          <span className="tm-home-eyebrow-chip"><span className="tm-home-eyebrow-dot" /> {c.home2.problema.eyebrow}</span>
        </div>
        <p className="tm-home-problema-statement">{c.home2.problema.statementPre}<span className="tm-home-text-blue">{c.home2.problema.statementHighlight}</span>{c.home2.problema.statementPost}</p>
        <div ref={problemRef} className="tm-home-problema-illo" />
        <div className="tm-home-card-grid">
          {c.home2.problema.cards.map((card, i) => (
            <div className="tm-home-card" key={card.title}>
              <div className="tm-home-card-icon"><i className={`ph ph-${PROBLEM_ICONS[i]}`} /></div>
              <h4>{card.title}</h4>
              <p>{card.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ── CÓMO FUNCIONA ───────────────────────────────────────────── */

const HOW_STEP_IMGS = ['teramot-connect-data', 'teramot-schema', 'teramot-dashboard', 'teramot-sync'];
const HOW_STEP_NUMS = ['01', '02', '03', '04'];

/* ── INTEGRACIONES / DIFERENCIALES / ANTES-DESPUÉS ──────────────
   (construidas por un subagente a partir del handoff, líneas 389-536;
   contenido verificado línea por línea contra la fuente.) ── */

const INTEGRATION_LOGOS = [
  { src: 'brand/integrations/sap.png', alt: 'SAP', height: 30, labelKey: 'erp' },
  { src: 'brand/integrations/netsuite.png', alt: 'Oracle NetSuite', height: 28, labelKey: 'erp' },
  { src: 'brand/integrations/dynamics.png', alt: 'Microsoft Dynamics', height: 28, labelKey: 'erp' },
  { src: 'brand/integrations/odoo.png', alt: 'Odoo', height: 24, labelKey: 'erp' },
  { src: 'brand/integrations/tango.png', alt: 'Tango Gestión', height: 38, labelKey: 'erpLatam' },
  { src: 'brand/integrations/softland.png', alt: 'Softland', height: 24, labelKey: 'erpLatam' },
  { src: 'brand/integrations/bejerman.png', alt: 'Bejerman', height: 22, labelKey: 'erpLatam' },
  { src: 'brand/integrations/excel.png', alt: 'Excel', height: 30, labelKey: 'planillas' },
  { src: 'brand/integrations/google-sheets.png', alt: 'Google Sheets', height: 46, labelKey: 'planillas' },
  { src: 'brand/integrations/power-bi.png', alt: 'Power BI', height: 36, labelKey: 'bi' },
  { src: 'brand/integrations/tableau.png', alt: 'Tableau', height: 22, labelKey: 'bi' },
  { src: 'brand/integrations/snowflake.svg', alt: 'Snowflake', height: 34, labelKey: 'dataWarehouse' },
];

const IntegracionesSection = () => {
  const { c } = useLang();
  const t = c.home2.integraciones;
  return (
    <section id="integraciones" className="tm-home-integrations">
      <div className="tm-home-integrations-container">
        <div className="tm-home-integrations-header">
          <span className="tm-home-integrations-eyebrow">
            <span className="tm-home-integrations-eyebrow-dot" /> {t.eyebrow}
          </span>
          <h2 className="tm-home-integrations-heading">{t.heading}</h2>
          <p className="tm-home-integrations-lede">{t.lede}</p>
        </div>

        <div className="tm-home-integrations-grid">
          {INTEGRATION_LOGOS.map((logo, i) => (
            <div key={i} className="tm-home-integration-card">
              <img src={logo.src} alt={logo.alt} className="tm-home-integration-logo" style={{ height: logo.height }} />
              <small className="tm-home-integration-label">{t.labels[logo.labelKey]}</small>
            </div>
          ))}
        </div>

        <div className="tm-home-integrations-cta">
          <a href="#integraciones-todas" className="tm-home-btn tm-home-btn-md tm-home-btn-outline-blue">
            {t.ctaAll} <i className="ph ph-arrow-right" />
          </a>
        </div>
      </div>
    </section>
  );
};

const DIFERENCIALES_ICONS = ['ph ph-graph', 'ph ph-shield-check', 'ph ph-lightning', 'ph ph-sparkle'];

const DiferencialesSection = () => {
  const { c } = useLang();
  const t = c.home2.diferenciales;
  return (
    <section className="tm-home-diff">
      <div className="tm-home-diff-container">
        <div className="tm-home-diff-header">
          <span className="tm-home-diff-eyebrow">
            <span className="tm-home-diff-eyebrow-dot" /> {t.eyebrow}
          </span>
          <h2 className="tm-home-diff-heading">{t.heading}</h2>
          <p className="tm-home-diff-lede">{t.lede}</p>
        </div>

        <div className="tm-home-diff-grid">
          {t.items.map((item, i) => (
            <div key={item.title} className="tm-home-diff-card">
              <div className="tm-home-diff-card-icon"><i className={`${DIFERENCIALES_ICONS[i]} tm-home-diff-card-icon-glyph`} /></div>
              <div className="tm-home-diff-card-kicker">{item.kicker}</div>
              <h3 className="tm-home-diff-card-title">{item.title}</h3>
              <p className="tm-home-diff-card-body">{item.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const AntesDespuesSection = () => {
  const { c } = useLang();
  const t = c.home2.antesDespues;
  return (
    <section className="tm-home-before-after">
      <div className="tm-home-before-after-container">
        <div className="tm-home-before-after-header">
          <span className="tm-home-before-after-eyebrow">
            <span className="tm-home-before-after-eyebrow-dot" /> {t.eyebrow}
          </span>
          <h2 className="tm-home-before-after-heading">{t.heading}</h2>
        </div>

        <div className="tm-home-before-after-grid">
          <div className="tm-home-before-after-card tm-home-before-after-card--before">
            <h4 className="tm-home-before-after-card-title">{t.beforeTitle}</h4>
            <div className="tm-home-before-after-list">
              {t.before.map((text, i) => (
                <div key={i} className="tm-home-before-after-item">
                  <i className="ph-bold ph-x tm-home-before-after-icon tm-home-before-after-icon--x" />
                  {text}
                </div>
              ))}
            </div>
          </div>
          <div className="tm-home-before-after-card tm-home-before-after-card--after">
            <h4 className="tm-home-before-after-card-title">{t.afterTitle}</h4>
            <div className="tm-home-before-after-list">
              {t.after.map((text, i) => (
                <div key={i} className="tm-home-before-after-item">
                  <i className="ph-bold ph-check tm-home-before-after-icon tm-home-before-after-icon--check" />
                  {text}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

/* ── CASOS DE USO (scroll-pinned) ────────────────────────────── */

const CASE_COUNT = 4;

const RAIL_ICONS = ['magnifying-glass', 'database', 'chart-line', 'clock-counter-clockwise'];
const CASE_ACTION_ICONS = ['download-simple', 'sliders-horizontal', 'funnel', 'plus'];
/* Estado/badge color per row — internal styling hook, not user-visible text,
   so it stays in code rather than the i18n copy tree. */
const CASE2_KINDS = ['green', 'neutral', 'low', 'low'];
/* Fake source-table identifiers for the ad-hoc query mockup — technical
   strings, not translated. */
const CASE3_SOURCES = ['erp.ventas_v2', 'sheets.gastos_cc', 'erp.stock_dep'];

const CaseMockupShell = ({ title, actionIcon, actionLabel, children }) => (
  <div className="tm-home-case-mockup-frame">
    <div className="tm-home-case-mockup-card">
      <div className="tm-home-case-mockup-rail">
        <span className="tm-home-case-mockup-rail-logo"><img src="brand/teramot-mark.svg" alt="Teramot" /></span>
        {RAIL_ICONS.map((icon) => (
          <span className="tm-home-case-mockup-rail-icon" key={icon}><i className={`ph ph-${icon}`} /></span>
        ))}
        <span className="tm-home-case-mockup-rail-avatar">MG</span>
      </div>
      <div className="tm-home-case-mockup-body-wrap">
        <div className="tm-home-case-mockup-topbar">
          <span className="tm-home-case-mockup-version"><i className="ph-fill ph-sparkle" />Teramot v2.6<i className="ph-bold ph-caret-down" /></span>
          <span className="tm-home-case-mockup-title">{title}</span>
          <span className="tm-home-case-mockup-action"><i className={`ph-bold ph-${actionIcon}`} />{actionLabel}</span>
        </div>
        <div className="tm-home-case-mockup-body">{children}</div>
      </div>
    </div>
  </div>
);

const Case0Body = ({ t }) => (
  <>
    <div className="tm-home-mock-toprow">
      <span className="tm-home-mock-toprow-label">{t.topLabel}</span>
      <span className="tm-home-mock-badge tm-home-mock-badge-green">{t.badge}</span>
    </div>
    <div data-mock-body className="tm-home-mock-checklist">
      {t.rows.map(([label, time]) => (
        <div className="tm-home-mock-check-row" key={label}>
          <i data-anim="check" className="ph-fill ph-check-circle" />
          <span>{label}</span>
          <span>{time}</span>
        </div>
      ))}
      <div className="tm-home-mock-total-row">
        <span className="tm-home-mock-toprow-label">{t.totalLabel}</span>
        <span>{t.totalValue}</span>
      </div>
    </div>
  </>
);

const Case1Body = ({ t }) => (
  <>
    <div className="tm-home-mock-toprow">
      <span className="tm-home-mock-toprow-label">{t.topLabel}</span>
      <span className="tm-home-mock-badge tm-home-mock-badge-neutral">{t.badge}</span>
    </div>
    <div data-mock-body className="tm-home-mock-bars">
      <div className="tm-home-mock-bar-row">
        <div className="tm-home-mock-bar-row-head"><span>{t.realLabel}</span><span>$ 58.2M</span></div>
        <div className="tm-home-mock-bar-track"><div data-anim="bar" className="tm-home-mock-bar-fill" style={{ width: '74%', background: '#5B6478' }} /></div>
      </div>
      <div className="tm-home-mock-bar-row">
        <div className="tm-home-mock-bar-row-head"><span>{t.budgetLabel}</span><span>$ 61.0M</span></div>
        <div className="tm-home-mock-bar-track"><div data-anim="bar" className="tm-home-mock-bar-fill" style={{ width: '82%', background: '#C6CBD8' }} /></div>
      </div>
      <div className="tm-home-mock-bar-row">
        <div className="tm-home-mock-bar-row-head"><span>{t.forecastLabel}</span><span style={{ color: '#2E7A64' }}>$ 64.4M</span></div>
        <div className="tm-home-mock-bar-track"><div data-anim="bar live" className="tm-home-mock-bar-fill" style={{ width: '96%', background: '#7bc1ad' }} /></div>
      </div>
      <div className="tm-home-mock-footnote">
        <i className="ph-bold ph-trend-up" />
        <span>{t.footnotePre}<b>{t.footnoteBold}</b>{t.footnotePost}</span>
      </div>
    </div>
  </>
);

const Case2Body = ({ t }) => (
  <>
    <div className="tm-home-mock-toprow">
      <span className="tm-home-mock-toprow-label">{t.topLabel}</span>
      <span className="tm-home-mock-badge tm-home-mock-badge-neutral">{t.badge}</span>
    </div>
    <div data-mock-body>
      <div className="tm-home-mock-table-head"><span>{t.headSku}</span><span style={{ textAlign: 'right' }}>{t.headMargin}</span><span style={{ textAlign: 'right' }}>{t.headStatus}</span></div>
      {t.rows.map(([sku, margin, estado], i) => {
        const kind = CASE2_KINDS[i];
        return (
          <div className="tm-home-mock-table-row" key={sku}>
            <span>{sku}</span>
            <span>{margin}</span>
            <span>
              <span
                data-anim={kind === 'low' ? 'chip' : undefined}
                className={
                  kind === 'green' ? 'tm-home-mock-badge tm-home-mock-badge-green'
                  : kind === 'low' ? 'tm-home-mock-badge-low'
                  : 'tm-home-mock-badge tm-home-mock-badge-neutral'
                }
              >{estado}</span>
            </span>
          </div>
        );
      })}
      <div className="tm-home-mock-alert">
        <i className="ph-bold ph-warning-circle" />
        <span>{t.alert}</span>
      </div>
    </div>
  </>
);

const Case3Body = ({ t }) => (
  <>
    <div className="tm-home-mock-toprow">
      <span className="tm-home-mock-toprow-label">{t.topLabel}</span>
      <span className="tm-home-mock-badge tm-home-mock-badge-green">{t.badge}</span>
    </div>
    <div data-mock-body className="tm-home-mock-queries">
      {t.rows.map(([q, value, who], i) => (
        <div className="tm-home-mock-query" key={q}>
          <div className="tm-home-mock-query-q">{q}</div>
          <div className="tm-home-mock-query-meta">
            <span className="tm-home-mock-query-value">{value}</span>
            <span className="tm-home-mock-query-src">{CASE3_SOURCES[i]}</span>
            <span className="tm-home-mock-query-who">{who}</span>
          </div>
        </div>
      ))}
    </div>
  </>
);

const CASE_BODIES = [Case0Body, Case1Body, Case2Body, Case3Body];

const CaseMockup = ({ idx, casos }) => {
  const Body = CASE_BODIES[idx];
  const mockKeys = ['case0', 'case1', 'case2', 'case3'];
  const t = casos.mockups[mockKeys[idx]];
  return (
    <CaseMockupShell title={casos.items[idx].tag} actionIcon={CASE_ACTION_ICONS[idx]} actionLabel={t.actionLabel}>
      <Body t={t} />
    </CaseMockupShell>
  );
};

const useCaseScrollPin = ({ casesRef, caseShotRef, caseTitleRef, caseDescRef, caseListRef, activeCase, setActiveCase, targetCase, setTargetCase }) => {
  const activeRef = useRefHome(activeCase);
  const targetRef = useRefHome(targetCase);
  const busyRef = useRefHome(false);
  const tokenRef = useRefHome(0);
  const timerRef = useRefHome(null);
  activeRef.current = activeCase;
  targetRef.current = targetCase;

  const caseLayers = useCallbackHome(() => {
    const list = caseListRef.current;
    const bullets = list ? Array.from(list.children) : [];
    return {
      shot: caseShotRef.current,
      text: [caseTitleRef.current, caseDescRef.current].filter(Boolean),
      bullets,
      all: [caseShotRef.current, caseTitleRef.current, caseDescRef.current, ...bullets].filter(Boolean),
    };
  }, []);

  const resetCaseLayers = useCallbackHome(() => {
    caseLayers().all.forEach((el) => el.getAnimations().forEach((a) => a.cancel()));
  }, [caseLayers]);

  const animateMockBody = useCallbackHome((shot) => {
    const body = shot.querySelector('[data-mock-body]');
    if (!body) return;
    const softOut = 'cubic-bezier(0.22, 1, 0.36, 1)';
    Array.from(body.children).forEach((row, i) => {
      row.animate(
        [{ opacity: 0, transform: 'translate3d(0, 10px, 0)' }, { opacity: 1, transform: 'translate3d(0,0,0)' }],
        { duration: 420, delay: 120 + i * 80, easing: softOut, fill: 'both' }
      );
    });
    shot.querySelectorAll('[data-anim="check"]').forEach((el, i) => {
      el.animate(
        [{ transform: 'scale(.6)', opacity: 0 }, { transform: 'scale(1.14)', opacity: 1, offset: 0.7 }, { transform: 'scale(1)', opacity: 1 }],
        { duration: 420, delay: 180 + i * 80, easing: 'cubic-bezier(0.34, 1.4, 0.64, 1)', fill: 'both' }
      );
    });
    shot.querySelectorAll('[data-anim~="bar"]').forEach((el, i) => {
      el.animate([{ transform: 'scaleX(0)' }, { transform: 'scaleX(1)' }], { duration: 700, delay: 200 + i * 90, easing: softOut, fill: 'both' });
      if (el.dataset.anim.indexOf('live') > -1) {
        el.animate([{ opacity: 0.85 }, { opacity: 1 }], { duration: 620, delay: 900, easing: 'ease-in-out', fill: 'both', direction: 'alternate', iterations: 2 });
      }
    });
    shot.querySelectorAll('[data-anim="chip"]').forEach((el, i) => {
      el.animate([{ opacity: 0, transform: 'scale(.9)' }, { opacity: 1, transform: 'scale(1)' }], { duration: 320, delay: 480 + i * 80, easing: softOut, fill: 'both' });
    });
  }, []);

  const enterCase = useCallbackHome((dir, token) => {
    if (token !== tokenRef.current) { resetCaseLayers(); return; }
    const layers = caseLayers();
    resetCaseLayers();
    const soft = 'cubic-bezier(0.16, 1, 0.3, 1)';
    if (layers.shot) {
      layers.shot.animate(
        [{ opacity: 0, transform: 'translate3d(0, 20px, 0)' }, { opacity: 1, transform: 'translate3d(0,0,0)' }],
        { duration: 500, easing: 'cubic-bezier(0.22, 1, 0.36, 1)', fill: 'both' }
      );
      animateMockBody(layers.shot);
    }
    layers.text.forEach((el, i) => {
      el.animate(
        [{ opacity: 0, transform: `translate3d(${dir * 22}px, 10px, 0)`, filter: 'blur(4px)' }, { opacity: 1, transform: 'translate3d(0,0,0)', filter: 'blur(0)' }],
        { duration: 700, delay: 90 + i * 90, easing: soft, fill: 'both' }
      );
    });
    layers.bullets.forEach((el, i) => {
      el.animate(
        [{ opacity: 0, transform: `translate3d(${dir * 16}px, 8px, 0)` }, { opacity: 1, transform: 'translate3d(0,0,0)' }],
        { duration: 620, delay: 300 + i * 80, easing: soft, fill: 'both' }
      );
    });
  }, [caseLayers, resetCaseLayers, animateMockBody]);

  const reconcileCase = useCallbackHome(() => {
    if (busyRef.current) return;
    if (activeRef.current === targetRef.current) return;
    runCaseTransition(targetRef.current);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function runCaseTransition(idx) {
    const from = activeRef.current;
    if (from === idx) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      activeRef.current = idx;
      setActiveCase(idx);
      reconcileCase();
      return;
    }
    const token = ++tokenRef.current;
    busyRef.current = true;
    const dir = idx > from ? 1 : -1;
    const layers = caseLayers();
    resetCaseLayers();
    const easeOut = 'cubic-bezier(0.45, 0, 0.55, 1)';
    let last = null;
    layers.all.forEach((el, i) => {
      last = el.animate(
        [{ opacity: 1, transform: 'translate3d(0,0,0)', filter: 'blur(0)' },
         { opacity: 0, transform: `translate3d(${-dir * 26}px, ${-dir * 6}px, 0)`, filter: 'blur(5px)' }],
        { duration: 260, delay: i * 18, easing: easeOut, fill: 'forwards' }
      );
    });
    let done = false;
    const swap = () => {
      if (done) return;
      done = true;
      clearTimeout(timerRef.current);
      if (token !== tokenRef.current) { busyRef.current = false; return; }
      activeRef.current = idx;
      setActiveCase(idx);
      busyRef.current = false;
      enterCase(dir, token);
      reconcileCase();
    };
    timerRef.current = setTimeout(swap, 420);
    if (last) last.finished.then(swap).catch(swap);
    else swap();
  }

  useEffectHome(() => {
    const el = casesRef.current;
    if (!el) return;
    let box = { top: 0, height: 0 };
    const measure = () => { box = { top: el.offsetTop, height: el.offsetHeight }; };
    const read = () => {
      const track = box.height - window.innerHeight;
      if (track <= 0) return;
      const p = (window.scrollY - box.top) / track;
      const idx = Math.max(0, Math.min(CASE_COUNT - 1, Math.floor(p * CASE_COUNT)));
      if (idx !== targetRef.current) {
        targetRef.current = idx;
        setTargetCase(idx);
        reconcileCase();
      } else {
        reconcileCase();
      }
    };
    let raf = 0;
    const loop = () => { read(); raf = requestAnimationFrame(loop); };
    const restart = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(loop); };
    const onResize = () => { measure(); read(); };
    const events = ['scroll', 'wheel', 'touchmove', 'keydown', 'visibilitychange'];
    events.forEach((n) => window.addEventListener(n, read, { passive: true }));
    window.addEventListener('resize', onResize);
    measure();
    read();
    raf = requestAnimationFrame(loop);
    const timer = setInterval(read, 100);
    let io = null;
    if ('IntersectionObserver' in window) {
      io = new IntersectionObserver(() => { measure(); restart(); read(); }, { threshold: [0, 0.01, 0.5, 1] });
      io.observe(el);
    }
    return () => {
      cancelAnimationFrame(raf);
      clearInterval(timer);
      clearTimeout(timerRef.current);
      events.forEach((n) => window.removeEventListener(n, read));
      window.removeEventListener('resize', onResize);
      if (io) io.disconnect();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const goToCase = useCallbackHome((i) => {
    const el = casesRef.current;
    if (!el) { setActiveCase(i); setTargetCase(i); return; }
    const track = el.offsetHeight - window.innerHeight;
    // Below 1024px the section isn't pinned (height:auto, no scroll
    // track) — scrollTo would land on the same spot for every pill, so
    // switch cases directly instead of relying on scroll position.
    if (track <= 0) {
      setTargetCase(i);
      runCaseTransition(i);
      return;
    }
    const top = el.offsetTop + (track * i) / (CASE_COUNT - 1);
    window.scrollTo({ top, behavior: 'smooth' });
  }, []);

  return { goToCase };
};

const CasosDeUsoSection = () => {
  const casesRef = useRefHome(null);
  const caseShotRef = useRefHome(null);
  const caseTitleRef = useRefHome(null);
  const caseDescRef = useRefHome(null);
  const caseListRef = useRefHome(null);
  const [activeCase, setActiveCase] = useStateHome(0);
  const [targetCase, setTargetCase] = useStateHome(0);

  const { goToCase } = useCaseScrollPin({
    casesRef, caseShotRef, caseTitleRef, caseDescRef, caseListRef,
    activeCase, setActiveCase, targetCase, setTargetCase,
  });

  const { c } = useLang();
  const casos = c.home2.casos;
  const active = casos.items[activeCase];

  return (
    <section ref={casesRef} className="tm-home-casos">
      <div className="tm-home-casos-sticky">
        <div className="tm-home-container">
          <div className="tm-home-casos-head">
            <span className="tm-home-casos-eyebrow">{casos.eyebrow}</span>
            <h2 className="tm-home-casos-heading">{casos.heading}</h2>
          </div>

          <div className="tm-home-casos-pillnav">
            {casos.items.map((item, i) => (
              <button
                key={item.tag}
                type="button"
                className={`tm-home-casos-pill ${targetCase === i ? 'is-active' : ''}`}
                onClick={() => goToCase(i)}
              >{item.tag}</button>
            ))}
          </div>

          <div className="tm-home-casos-panel">
            <div ref={caseShotRef} className="tm-home-casos-shot">
              <CaseMockup idx={activeCase} casos={casos} />
            </div>
            <div className="tm-home-casos-text">
              <h3 ref={caseTitleRef}>{active.title}</h3>
              <p ref={caseDescRef}>{active.desc}</p>
              <div ref={caseListRef} className="tm-home-casos-bullets">
                {active.bullets.map((b) => (
                  <div className="tm-home-casos-bullet" key={b}><i className="ph-fill ph-check-circle" />{b}</div>
                ))}
              </div>
            </div>
          </div>

          <div className="tm-home-casos-dots">
            {casos.items.map((item, i) => (
              <span key={item.tag} className={`tm-home-casos-dot ${targetCase === i ? 'is-active' : ''}`} />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

/* ── PRENSA ──────────────────────────────────────────────────────
   Las 3 fotos reales (Forbes/Yahoo/Cronista) no vienen en el handoff —
   bloque neutro #F3F4F6 en su lugar, tal como indica el propio README.
   Los links de las notas usan href="#" hasta tener las URLs reales. ── */

/* Mismos links/imágenes que la home productiva actual (press.jsx): la
   imagen es un screenshot OG obtenido en runtime via microlink.io (no hay
   asset local), y el logo del medio viene de Clearbit por dominio. */
const PRESS_ITEMS = [
  {
    name: 'Forbes Argentina',
    domain: 'forbesargentina.com',
    headlineEs: 'Estos físicos del Balseiro crearon Teramot para hacer posible la IA empresarial',
    headlineEn: 'Balseiro physicists built Teramot to make enterprise AI possible',
    url: 'https://www.forbesargentina.com/daily-cover/estos-fisicos-e-ingenieros-balseiro-crearon-teramot-transformar-big-data-smart-data-hacer-posible-ia-empresarial-n55631',
    imageFrom: 'https://www.lacapital.com.ar/negocios/invirtieron-us-1-millon-crear-un-software-que-procesa-datos-tiempo-record-n10144070.html',
  },
  {
    name: 'Yahoo Finance',
    domain: 'yahoo.com',
    headlineEs: 'Físicos argentinos del Balseiro cierran una ronda de US$ 2,1 millones',
    headlineEn: 'Argentine physicists close a US$2.1M seed round',
    url: 'https://es-us.finanzas.yahoo.com/noticias/f%C3%ADsicos-ingenieros-balseiro-crearon-teramot-083500932.html',
  },
  {
    name: 'El Cronista',
    domain: 'cronista.com',
    headlineEs: 'Es argentino, descubrió el talón de Aquiles de la IA y ayuda a empresas de cuatro países',
    headlineEn: "He found AI's Achilles' heel — and now helps companies across four countries",
    url: 'https://www.cronista.com/infotechnology/entreprenerds/es-argentino-descubrio-el-talon-de-aquiles-de-la-ia-y-ahora-ayuda-a-empresas-de-cuatro-paises/',
  },
];

const PressCard = ({ name, domain, headlineEs, headlineEn, url, imageFrom, readNote }) => {
  const { lang } = useLang();
  const headline = lang === 'en' ? headlineEn : headlineEs;
  const [ogImage, setOgImage] = useStateHome(null);
  const [loading, setLoading] = useStateHome(true);
  const [logoFailed, setLogoFailed] = useStateHome(false);

  useEffectHome(() => {
    const fetchUrl = imageFrom || url;
    fetch(`https://api.microlink.io?url=${encodeURIComponent(fetchUrl)}`)
      .then((r) => r.json())
      .then((data) => {
        const img = data?.data?.image?.url;
        if (img && img.startsWith('http')) setOgImage(img);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  return (
    <a href={url} target="_blank" rel="noopener noreferrer" className="tm-home-press-card">
      <div className="tm-home-press-card-image">
        {loading ? (
          <div className="tm-home-press-card-skeleton" />
        ) : ogImage ? (
          <img src={ogImage} alt={headline} className="tm-home-press-card-img" />
        ) : (
          <div className="tm-home-press-card-nophoto"><span>{name}</span></div>
        )}
      </div>
      <div className="tm-home-press-card-content">
        <div className="tm-home-press-card-source">
          {!logoFailed && (
            <img
              src={`https://logo.clearbit.com/${domain}`}
              alt=""
              className="tm-home-press-card-source-logo"
              onError={() => setLogoFailed(true)}
            />
          )}
          <span className="tm-home-press-card-outlet">{name}</span>
        </div>
        <h3 className="tm-home-press-card-headline">{headline}</h3>
        <span className="tm-home-press-card-cta">
          {readNote} <i className="ph-bold ph-arrow-right" />
        </span>
      </div>
    </a>
  );
};

const PrensaSection = () => {
  const { c } = useLang();
  const t = c.home2.prensa;
  return (
    <section id="prensa" className="tm-home-prensa">
      <div className="tm-home-prensa-container">
        <div className="tm-home-prensa-header">
          <span className="tm-home-eyebrow-chip">
            <span className="tm-home-eyebrow-dot" />
            {t.eyebrow}
          </span>
          <h2 className="tm-home-prensa-title">
            {t.headingPre}<span className="tm-home-text-blue">{t.headingHighlight}</span>{t.headingPost}
          </h2>
          <p className="tm-home-prensa-lede">{t.lede}</p>
        </div>

        <div className="tm-home-press-grid">
          {PRESS_ITEMS.map((item) => (
            <PressCard key={item.name} {...item} readNote={t.readNote} />
          ))}
        </div>

        <div className="tm-home-press-more-wrap">
          <a href="medios.html" className="tm-home-press-more">
            {t.viewAll} <i className="ph ph-arrow-right" />
          </a>
        </div>
      </div>
    </section>
  );
};

/* ── SEGURIDAD ───────────────────────────────────────────────── */

const useSoc2Diagram = (hostRef) => {
  useEffectHome(() => {
    const host = hostRef.current;
    if (!host) return;
    const q = (sel) => host.querySelector(`[data-soc="${sel}"]`);
    const nodeIn = q('node-in'), nodeOut = q('node-out'), lineIn = q('line-in'), lineOut = q('line-out');
    const badge = q('badge'), badgeImg = q('badge-img'), label = q('gov-label');
    const glowHost = q('glow');
    const glow = glowHost && glowHost.firstElementChild;
    const dots = Array.from(host.querySelectorAll('[data-soc-dot]'));
    const particles = q('particles');
    const tip = q('tooltip');
    if (!nodeIn || !nodeOut || !lineIn || !lineOut || !badge || !glow) return;
    const ease = 'cubic-bezier(0.22, 1, 0.36, 1)';
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    const onEnter = () => {
      tip.style.opacity = '1'; tip.style.transform = 'translate(-50%, 0)';
      glow.animate([{ opacity: 0.72 }, { opacity: 1 }], { duration: 260, easing: ease, fill: 'forwards' });
    };
    const onLeave = () => {
      tip.style.opacity = '0'; tip.style.transform = 'translate(-50%, 4px)';
      glow.animate([{ opacity: 1 }, { opacity: 0.72 }], { duration: 260, easing: ease, fill: 'forwards' });
    };
    badge.addEventListener('mouseenter', onEnter);
    badge.addEventListener('mouseleave', onLeave);
    /* Touch has no hover — without this, the tooltip is unreachable
       on phones/tablets. Tap toggles it; a second tap (or tapping
       elsewhere) closes it early, otherwise it auto-hides. */
    let tipHideTimer = 0;
    let tipShown = false;
    const onBadgeTap = (e) => {
      e.stopPropagation();
      clearTimeout(tipHideTimer);
      if (tipShown) { onLeave(); tipShown = false; return; }
      onEnter(); tipShown = true;
      tipHideTimer = setTimeout(() => { onLeave(); tipShown = false; }, 2500);
    };
    const onDocTap = (e) => {
      if (badge.contains(e.target)) return; // the badge's own tap handler already toggles it
      if (tipShown) { onLeave(); tipShown = false; clearTimeout(tipHideTimer); }
    };
    badge.addEventListener('click', onBadgeTap);
    document.addEventListener('touchstart', onDocTap);

    [lineIn, lineOut].forEach((l) => {
      const len = l.getTotalLength();
      l.style.strokeDasharray = len;
      l.style.strokeDashoffset = len;
    });

    const fadeUp = (el, delay) => el.animate(
      [{ opacity: 0, transform: 'translateY(6px)' }, { opacity: 1, transform: 'translateY(0)' }],
      { duration: 600, delay, easing: ease, fill: 'both' }
    );
    const draw = (l, delay) => l.animate(
      [{ strokeDashoffset: l.getTotalLength() }, { strokeDashoffset: 0 }],
      { duration: 1000, delay, easing: ease, fill: 'both' }
    );

    const play = () => {
      fadeUp(nodeIn, 100);
      draw(lineIn, 500);
      badge.animate([{ opacity: 0, transform: 'scale(.9)' }, { opacity: 1, transform: 'scale(1)' }], { duration: 700, delay: 800, easing: ease, fill: 'both' });
      if (badgeImg) badgeImg.animate([{ opacity: 0, transform: 'scale(.9)' }, { opacity: 1, transform: 'scale(1)' }], { duration: 700, delay: 800, easing: ease, fill: 'both' });
      if (label) label.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 500, delay: 900, easing: ease, fill: 'both' });
      draw(lineOut, 1000);
      fadeUp(nodeOut, 1300);
      if (particles) particles.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 400, delay: 1600, easing: ease, fill: 'both' });
      dots.forEach((dot, i) => {
        const pair = Math.floor(i / 2);
        const within = i % 2;
        dot.animate(
          [{ transform: 'translateX(0px)', opacity: 0, offset: 0 }, { opacity: 1, offset: 0.15 }, { opacity: 1, offset: 0.85 }, { transform: `translateX(${dot.dataset.dx || 142}px)`, opacity: 0, offset: 1 }],
          { duration: 2400, delay: 1600 + within * 800 + pair * 200, iterations: Infinity, easing: 'linear' }
        );
      });
      glow.animate(
        [{ opacity: 0.72, transform: 'scale(1)' }, { opacity: 1, transform: 'scale(1.06)' }, { opacity: 0.72, transform: 'scale(1)' }],
        { duration: 3000, delay: 1600, iterations: Infinity, easing: 'ease-in-out' }
      );
    };

    if (reduce) {
      [nodeIn, nodeOut, badge, badgeImg, label, particles].forEach((el) => { if (el) el.style.opacity = '1'; });
      [lineIn, lineOut].forEach((l) => { l.style.strokeDashoffset = 0; });
      return () => {
        badge.removeEventListener('mouseenter', onEnter);
        badge.removeEventListener('mouseleave', onLeave);
        badge.removeEventListener('click', onBadgeTap);
        document.removeEventListener('touchstart', onDocTap);
        clearTimeout(tipHideTimer);
      };
    }
    let fired = false;
    let socObserver = null;
    const fire = () => {
      if (fired) return;
      fired = true;
      clearInterval(socTimer);
      if (socObserver) socObserver.disconnect();
      play();
    };
    if ('IntersectionObserver' in window) {
      socObserver = new IntersectionObserver((entries) => { entries.forEach((entry) => { if (entry.isIntersecting) fire(); }); }, { threshold: 0.3 });
      socObserver.observe(host);
    }
    const check = () => {
      const r = host.getBoundingClientRect();
      if (r.top < window.innerHeight * 0.85 && r.bottom > 0) fire();
    };
    const socTimer = setInterval(check, 150);
    check();

    return () => {
      badge.removeEventListener('mouseenter', onEnter);
      badge.removeEventListener('mouseleave', onLeave);
      badge.removeEventListener('click', onBadgeTap);
      document.removeEventListener('touchstart', onDocTap);
      clearTimeout(tipHideTimer);
      clearInterval(socTimer);
      if (socObserver) socObserver.disconnect();
    };
  }, []);
};

const SECURITY_ICONS = ['shield-check', 'lock-key', 'clock-counter-clockwise'];

const SeguridadSection = () => {
  const { c } = useLang();
  const t = c.home2.seguridad;
  const d = t.diagram;
  const socRef = useRefHome(null);
  useSoc2Diagram(socRef);
  return (
    <section id="seguridad" className="tm-home-seguridad">
      <div className="tm-home-container">
        <div className="tm-home-section-head">
          <span className="tm-home-eyebrow-chip"><span className="tm-home-eyebrow-dot" /> {t.eyebrow}</span>
          <h2>{t.headingPre}<span className="tm-home-text-blue">{t.headingHighlight}</span></h2>
          <p>{t.lede}</p>
        </div>

        <div ref={socRef} className="tm-home-soc2-diagram">
          <div className="tm-home-soc2-inner">
            <svg viewBox="0 -48 820 240" width="820" height="240" fill="none" role="img" aria-label={d.ariaLabel}>
              <g data-soc="node-in" opacity="0">
                <rect x="40" y="26" width="124" height="92" rx="16" fill="#FFFFFF" stroke="#E6E9F5" strokeWidth="2" />
                <circle cx="58" cy="44" r="3.5" fill="#DCE0F6" /><circle cx="70" cy="44" r="3.5" fill="#E7EAF9" />
                <rect x="56" y="60" width="60" height="9" rx="4.5" fill="#E1E5FD" />
                <rect x="56" y="76" width="88" height="9" rx="4.5" fill="#EEF0FE" />
                <rect x="56" y="92" width="44" height="9" rx="4.5" fill="#EEF0FE" />
                <circle cx="140" cy="64" r="7" fill="#C8CEF8" />
                <text x="102" y="140" textAnchor="middle" fontSize="12" fontWeight="700" fill="#0B0F14">{d.dataIn}</text>
                <text x="102" y="157" textAnchor="middle" fontSize="10.5" fill="#6b7280">{d.subIn}</text>
              </g>
              <path id="soc2-path-in" data-soc="line-in" d="M176 72 H318" stroke="#D8DEEC" strokeWidth="2" strokeLinecap="round" />
              <defs>
                <radialGradient id="soc2-glow" cx="50%" cy="50%" r="50%">
                  <stop offset="0%" stopColor="#5A6DF3" stopOpacity=".34" />
                  <stop offset="55%" stopColor="#5A6DF3" stopOpacity=".16" />
                  <stop offset="100%" stopColor="#5A6DF3" stopOpacity="0" />
                </radialGradient>
              </defs>
              <g data-soc="glow">
                <circle cx="410" cy="72" r="112" fill="url(#soc2-glow)" style={{ transformBox: 'fill-box', transformOrigin: 'center' }} />
              </g>
              <g data-soc="badge" opacity="0" style={{ cursor: 'pointer', transformBox: 'fill-box', transformOrigin: 'center' }}>
                <rect x="318" y="20" width="184" height="104" rx="52" fill="#FFFFFF" stroke="#E6E9F5" strokeWidth="2" />
              </g>
              <text data-soc="gov-label" opacity="0" x="410" y="150" textAnchor="middle" fontSize="10.5" fontWeight="700" letterSpacing="1" fill="#253DE5">{d.govLabel}</text>
              <path id="soc2-path-out" data-soc="line-out" d="M502 72 H646" stroke="#253DE5" strokeWidth="2" strokeLinecap="round" />
              <g data-soc="node-out" opacity="0">
                <rect x="656" y="26" width="124" height="92" rx="16" fill="#FFFFFF" stroke="#E6E9F5" strokeWidth="2" />
                <rect x="672" y="44" width="92" height="56" rx="12" fill="#EAF8F2" />
                <circle cx="700" cy="72" r="14" fill="#91DFC8" />
                <path d="M694 72l4.5 4.5 9-10" stroke="#0B0F14" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
                <rect x="722" y="66" width="30" height="6" rx="3" fill="#DCF1E8" />
                <rect x="722" y="78" width="20" height="6" rx="3" fill="#DCF1E8" />
                <text x="718" y="140" textAnchor="middle" fontSize="12" fontWeight="700" fill="#0B0F14">{d.dataOut}</text>
                <text x="718" y="157" textAnchor="middle" fontSize="10.5" fill="#253DE5">{d.subOut}</text>
              </g>
              <g data-soc="particles" opacity="0">
                <circle data-soc-dot="" data-dx="142" cx="176" cy="72" r="3.5" fill="#5A6DF3" />
                <circle data-soc-dot="" data-dx="142" cx="176" cy="72" r="3.5" fill="#5A6DF3" />
                <circle data-soc-dot="" data-dx="144" cx="502" cy="72" r="3.5" fill="#253DE5" />
                <circle data-soc-dot="" data-dx="144" cx="502" cy="72" r="3.5" fill="#253DE5" />
              </g>
            </svg>
            <img data-soc="badge-img" src="brand/soc2-type2.png" alt="SOC 2 Type II Certified" className="tm-home-soc2-badge-img" />
          </div>
          <div data-soc="tooltip" className="tm-home-soc2-tooltip">{d.tooltip}</div>
        </div>

        <div className="tm-home-card-grid">
          {t.cards.map((card, i) => (
            <div className="tm-home-card" key={card.title}>
              <div className="tm-home-card-icon"><i className={`ph ph-${SECURITY_ICONS[i]}`} /></div>
              <h4>{card.title}</h4>
              <p>{card.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const ComoFuncionaSection = () => {
  const { c } = useLang();
  return (
    <section id="como-funciona" className="tm-home-comofunciona">
      <div className="tm-home-container">
        <div className="tm-home-section-head">
          <span className="tm-home-eyebrow-chip"><span className="tm-home-eyebrow-dot" /> {c.home2.comoFunciona.eyebrow}</span>
          <h2>{c.home2.comoFunciona.heading}</h2>
          <p>{c.home2.comoFunciona.lede}</p>
        </div>
        <div className="tm-home-step-grid">
          {c.home2.comoFunciona.steps.map((s, i) => (
            <div className="tm-home-card" key={s.title}>
              <div className="tm-home-step-shot"><img src={`assets/home/${HOW_STEP_IMGS[i]}.svg`} alt={s.alt} /></div>
              <div className="tm-home-step-num">{HOW_STEP_NUMS[i]}</div>
              <h4 className="tm-home-step-title">{s.title}</h4>
              <p>{s.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* ── FAQ ─────────────────────────────────────────────────────── */

/* Acordeón exclusivo con animación de altura — misma easing que el resto
   de las animaciones WAAPI del sitio (SOC2, ilustración de "Problema").
   Reemplaza el toggle nativo instantáneo de <details> por uno animado; la
   exclusividad (abrir uno cierra el resto) se maneja a mano para poder
   animar también el que se cierra, algo que el atributo nativo `name`
   no permite (cierra a los otros de forma instantánea, sin transición). */
const FAQ_EASE = 'cubic-bezier(0.22, 1, 0.36, 1)';

const useFaqAccordion = (listRef) => {
  useEffectHome(() => {
    const list = listRef.current;
    if (!list) return;
    const items = Array.from(list.querySelectorAll('.tm-home-faq-item'));
    const anims = new Map();
    let current = items.find((d) => d.hasAttribute('open')) || null;

    const currentPx = (el) => parseFloat(getComputedStyle(el).height) || 0;

    const runTo = (details, targetPx, onDone) => {
      const answer = details.querySelector('.tm-home-faq-answer');
      const prev = anims.get(details);
      const fromPx = prev ? currentPx(answer) : (targetPx > 0 ? 0 : answer.scrollHeight);
      if (prev) prev.cancel();
      answer.style.overflow = 'hidden';
      const anim = answer.animate(
        [{ height: `${fromPx}px`, opacity: fromPx === 0 ? 0 : 1 },
         { height: `${targetPx}px`, opacity: targetPx === 0 ? 0 : 1 }],
        { duration: targetPx === 0 ? 240 : 320, easing: FAQ_EASE }
      );
      anims.set(details, anim);
      anim.onfinish = () => { anims.delete(details); answer.style.overflow = ''; if (onDone) onDone(); };
      anim.oncancel = () => { anims.delete(details); };
    };

    const openItem = (details) => {
      details.open = true;
      runTo(details, details.querySelector('.tm-home-faq-answer').scrollHeight);
    };
    const closeItem = (details) => {
      runTo(details, 0, () => { details.open = false; });
    };

    const onClick = (e) => {
      const summary = e.target.closest('.tm-home-faq-summary');
      const details = summary && summary.closest('.tm-home-faq-item');
      if (!details || !items.includes(details)) return;
      e.preventDefault();

      if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
        if (current && current !== details) current.open = false;
        details.open = current === details ? !details.open : true;
        current = details.open ? details : null;
        return;
      }

      if (current === details) { closeItem(details); current = null; return; }
      if (current) closeItem(current);
      openItem(details);
      current = details;
    };

    list.addEventListener('click', onClick);
    return () => {
      list.removeEventListener('click', onClick);
      anims.forEach((a) => a.cancel());
    };
  }, []);
};

const FaqSection = () => {
  const { c } = useLang();
  const t = c.home2.faq;
  const listRef = useRefHome(null);
  useFaqAccordion(listRef);
  return (
  <section id="faqs" className="tm-home-faq">
    <div className="tm-home-faq-container">
      <div className="tm-home-faq-grid">
        <aside className="tm-home-faq-aside">
          <span className="tm-home-eyebrow-chip"><span className="tm-home-eyebrow-dot" /> {t.eyebrow}</span>
          <h2 className="tm-home-faq-heading">{t.headingPre}<span className="tm-home-text-blue">{t.headingHighlight}</span></h2>
          <p className="tm-home-faq-subcopy">{t.subcopy}</p>
          <div className="tm-home-faq-support-card">
            <div className="tm-home-faq-support-title">{t.supportTitle}</div>
            <p className="tm-home-faq-support-copy">{t.supportCopy}</p>
            <a href={c.links.call} target="_blank" rel="noopener noreferrer" className="tm-home-faq-support-link">{c.home2.demo} <i className="ph-bold ph-arrow-right" /></a>
          </div>
        </aside>

        <div className="tm-home-faq-list" ref={listRef}>
          {t.items.map((item, i) => (
            <details key={i} className="tm-home-faq-item" open={i === 0 ? true : undefined}>
              <summary className="tm-home-faq-summary">
                <span className="tm-home-faq-question">{item.q}</span>
                <span className="tm-home-faq-icon"><i className="ph-bold ph-plus" /></span>
              </summary>
              <p className="tm-home-faq-answer" dangerouslySetInnerHTML={{ __html: item.a }} />
            </details>
          ))}
        </div>
      </div>
    </div>
  </section>
  );
};

/* ── CTA FINAL ───────────────────────────────────────────────── */

const CtaFinalSection = () => {
  const { c } = useLang();
  const t = c.home2.ctaFinal;
  return (
    <section id="demo" className="tm-home-cta-final">
      <div className="tm-home-cta-final-container">
        <h2 className="tm-home-cta-final-heading">{t.heading}</h2>
        <p className="tm-home-cta-final-copy">{t.copy}</p>
        <div className="tm-home-cta-final-actions">
          <a href={c.links.call} target="_blank" rel="noopener noreferrer" className="tm-home-btn tm-home-btn-lg tm-home-cta-final-btn-primary">{c.home2.demo} <i className="ph ph-arrow-right" /></a>
          <a href={c.links.app} className="tm-home-btn tm-home-btn-lg tm-home-cta-final-btn-secondary"><i className="ph ph-arrow-right" /> {c.home2.video}</a>
        </div>
        <p className="tm-home-cta-final-fineprint">{t.finePrint}</p>
      </div>
    </section>
  );
};

/* ── FOOTER (propio de esta página, no chrome.jsx) ──────────────
   8 links del sitemap resueltos contra rutas reales existentes;
   Privacidad/Términos apuntan a los mismos PDFs externos que ya usa
   el footer compartido (i18n.jsx) — no hay página local para esos temas. ── */

const HomeFooter = () => {
  const { c } = useLang();
  const t = c.home2.footer;
  return (
    <footer className="tm-home-footer">
      <div className="tm-home-footer-container">
        <div className="tm-home-footer-brandrow">
          <div className="tm-home-footer-brand">
            <img src="brand/teramot-logo-on-dark.svg" alt="Teramot" className="tm-home-footer-logo" />
            <p className="tm-home-footer-tagline">{t.tagline}</p>
          </div>
          <div className="tm-home-footer-soc2">
            <img src="brand/soc2-type2.png" alt="" className="tm-home-footer-soc2-img" />
          </div>
        </div>

        <div className="tm-home-footer-map">
          <div className="tm-home-footer-col">
            <h5 className="tm-home-footer-col-title">{t.colTitles.producto}</h5>
            <div className="tm-home-footer-col-links">
              <a href="pricing.html" className="tm-home-footer-link">{t.links.precios}<i className="ph-bold ph-arrow-right" /></a>
              <a href="specialists.html" className="tm-home-footer-link">{t.links.especialistas}<i className="ph-bold ph-arrow-right" /></a>
            </div>
          </div>
          <div className="tm-home-footer-col">
            <h5 className="tm-home-footer-col-title">{t.colTitles.recursos}</h5>
            <div className="tm-home-footer-col-links">
              <a href="tutorials.html" className="tm-home-footer-link">{t.links.tutoriales}<i className="ph-bold ph-arrow-right" /></a>
              <a href="docs.html" className="tm-home-footer-link">{t.links.documentacion}<i className="ph-bold ph-arrow-right" /></a>
            </div>
          </div>
          <div className="tm-home-footer-col">
            <h5 className="tm-home-footer-col-title">{t.colTitles.empresa}</h5>
            <div className="tm-home-footer-col-links">
              <a href="mission.html" className="tm-home-footer-link">{t.links.mision}<i className="ph-bold ph-arrow-right" /></a>
              <a href="blog.html" className="tm-home-footer-link">{t.links.blog}<i className="ph-bold ph-arrow-right" /></a>
              <a href="partners.html" className="tm-home-footer-link">{t.links.partners}<i className="ph-bold ph-arrow-right" /></a>
            </div>
          </div>
          <div className="tm-home-footer-col">
            <h5 className="tm-home-footer-col-title">{t.colTitles.legal}</h5>
            <div className="tm-home-footer-col-links">
              <a href="https://teramot-documentation.s3.us-east-1.amazonaws.com/public/Teramot+-+Website+Privacy+Policy+1.1.pdf" target="_blank" rel="noopener" className="tm-home-footer-link">{t.links.privacidad}<i className="ph-bold ph-arrow-right" /></a>
              <a href="https://teramot-documentation.s3.us-east-1.amazonaws.com/public/Teramot+Website+Terms+of+Use.pdf" target="_blank" rel="noopener" className="tm-home-footer-link">{t.links.terminos}<i className="ph-bold ph-arrow-right" /></a>
            </div>
          </div>
        </div>

        <div className="tm-home-footer-bottom">
          <span>{t.copyright}</span>
          <a href="https://www.linkedin.com/company/teramot/" target="_blank" rel="noopener" className="tm-home-footer-social" aria-label="LinkedIn">
            <i className="ph-fill ph-linkedin-logo" />
          </a>
        </div>
      </div>
    </footer>
  );
};

/* ── ROOT ────────────────────────────────────────────────────── */

const HomeApp = () => {
  const hostRef = useRefHome(null);
  const artRef = useRefHome(null);
  useScrollReveal(hostRef);
  useSmoothAnchors(hostRef);
  return (
    <LangProvider>
      <div ref={hostRef} className="tm-home">
        <HomeHero artRef={artRef} />
        <ClientesSection />
        <ProblemaSection />
        <ComoFuncionaSection />
        <CasosDeUsoSection />
        <IntegracionesSection />
        <DiferencialesSection />
        <AntesDespuesSection />
        <PrensaSection />
        <SeguridadSection />
        <FaqSection />
        <CtaFinalSection />
        <HomeFooter />
        <WhatsAppFloat />
      </div>
    </LangProvider>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<HomeApp />);
