/* eslint-disable */
const { useState, useEffect, useRef, useCallback, Fragment } = React;

/* ============ Reveal hook (IntersectionObserver) ============ */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.in)");
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            e.target.style.opacity = "1";
            e.target.style.transform = "translateY(0)";
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.06, rootMargin: "0px 0px -40px 0px" }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

/* ============ Animated number ============ */
function CountUp({ to, suffix = "", duration = 1600 }) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let started = false;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started) {
          started = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(Math.round(eased * to));
            if (t < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
          io.unobserve(el);
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [to]);
  return <span ref={ref}>{val}<span className="suffix">{suffix}</span></span>;
}

/* ============ Icons ============ */
const Icon = {
  Arrow: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" />
    </svg>
  ),
  Menu: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <line x1="3" y1="7" x2="21" y2="7" /><line x1="3" y1="17" x2="21" y2="17" />
    </svg>
  ),
  Close: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}>
      <line x1="6" y1="6" x2="18" y2="18" /><line x1="18" y1="6" x2="6" y2="18" />
    </svg>
  ),
  Ship: (p) => (
    <svg width="38" height="38" viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" {...p}>
      <path d="M8 44h48l-6 12H14z" /><path d="M16 44V28h32v16" /><path d="M22 28V18h20v10" /><line x1="32" y1="10" x2="32" y2="28" /><path d="M4 44c5 4 11 4 16 0s11 4 16 0 11 4 16 0" />
    </svg>
  ),
  Truck: (p) => (
    <svg width="38" height="38" viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="6" y="20" width="32" height="24" /><path d="M38 26h12l6 8v10H38z" /><circle cx="18" cy="48" r="5" /><circle cx="46" cy="48" r="5" />
    </svg>
  ),
  Shield: (p) => (
    <svg width="38" height="38" viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" {...p}>
      <path d="M32 6L10 14v18c0 14 10 24 22 28 12-4 22-14 22-28V14z" /><polyline points="22,32 30,40 44,24" />
    </svg>
  ),
  Handshake: (p) => (
    <svg width="38" height="38" viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M4 28l6-8h14l4 4-10 10-4-2-6 4z" /><path d="M60 28l-6-8H40l-4 4 10 10 4-2 6 4z" /><path d="M22 32l8-6 6 4 4-4 4 4-12 12-6-2-8-4z" /><line x1="30" y1="34" x2="36" y2="40" />
    </svg>
  ),
  Plane: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M22 12l-9 9-1.5-7.5L4 12l18-8z" />
    </svg>
  ),
  Spark: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 2v6M12 16v6M2 12h6M16 12h6M5 5l4 4M15 15l4 4M5 19l4-4M15 9l4-4" />
    </svg>
  ),
  Layers: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round" {...p}>
      <polygon points="12 2 2 7 12 12 22 7 12 2" /><polyline points="2 17 12 22 22 17" /><polyline points="2 12 12 17 22 12" />
    </svg>
  ),
  Scale: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round" {...p}>
      <line x1="12" y1="3" x2="12" y2="21" /><path d="M3 9l4-6 4 6" /><path d="M13 9l4-6 4 6" /><path d="M3 9c0 2 2 4 4 4s4-2 4-4" /><path d="M13 9c0 2 2 4 4 4s4-2 4-4" />
    </svg>
  ),
  Award: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round" {...p}>
      <circle cx="12" cy="8" r="6" /><polyline points="8 13 7 22 12 19 17 22 16 13" />
    </svg>
  ),
  Heart: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round" {...p}>
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
    </svg>
  ),
  Brain: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round" {...p}>
      <path d="M9 3a3 3 0 0 0-3 3v1a3 3 0 0 0-2 5 3 3 0 0 0 0 4 3 3 0 0 0 2 5v1a3 3 0 0 0 6 0V3a3 3 0 0 0-3 0z" /><path d="M15 3a3 3 0 0 1 3 3v1a3 3 0 0 1 2 5 3 3 0 0 1 0 4 3 3 0 0 1-2 5v1a3 3 0 0 1-6 0V3a3 3 0 0 1 3 0z" />
    </svg>
  ),
  LegalDoc: (p) => (
    /* Certidumbre jurídica: documento con sello/firma de aprobación */
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <polyline points="14 2 14 8 20 8" />
      <line x1="8" y1="13" x2="13" y2="13" />
      <line x1="8" y1="17" x2="11" y2="17" />
      <circle cx="16.5" cy="17.5" r="2.6" />
      <path d="M15.1 18l1 1 2-2.6" />
    </svg>
  ),
  Lightbulb: (p) => (
    /* Somos especialistas: foco/idea */
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M9 18h6" />
      <path d="M10 21h4" />
      <path d="M12 3a6 6 0 0 0-4 10.5c.8.8 1.5 1.5 1.5 2.5v1h5v-1c0-1 .7-1.7 1.5-2.5A6 6 0 0 0 12 3z" />
      <line x1="12" y1="8" x2="12" y2="12" />
      <line x1="10.2" y1="10" x2="13.8" y2="10" />
    </svg>
  ),
  Pin: (p) => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round" {...p}>
      <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" />
    </svg>
  ),
  Phone: (p) => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13 1 .37 1.96.72 2.88a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.2-1.27a2 2 0 0 1 2.11-.45c.92.35 1.88.59 2.88.72A2 2 0 0 1 22 16.92z" />
    </svg>
  ),
  Mail: (p) => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" /><polyline points="22,6 12,13 2,6" />
    </svg>
  ),
  Pin2: (p) => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" />
    </svg>
  ),
  /* ── Trade / Logistics icons for cintillo ── */
  CustomsClear: (p) => (
    /* Despacho aduanal: documento con sello oficial */
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
      <polyline points="14 2 14 8 20 8"/>
      <circle cx="12" cy="15" r="2.5"/>
      <line x1="8" y1="12" x2="11" y2="12"/>
      <line x1="13" y1="12" x2="16" y2="12"/>
    </svg>
  ),
  SemiTruck: (p) => (
    /* Flete nacional: camión articulado / tractor-trailer */
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="1" y="8" width="13" height="9" rx="1"/>
      <path d="M14 10h4.5l2.5 3v4h-7V10z"/>
      <circle cx="5.5" cy="19.5" r="1.5"/>
      <circle cx="18.5" cy="19.5" r="1.5"/>
      <line x1="14" y1="14" x2="21" y2="14"/>
      <line x1="1" y1="13" x2="14" y2="13"/>
    </svg>
  ),
  PortCrane: (p) => (
    /* Maniobra fuera de puerto: grúa portuaria */
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <line x1="10" y1="2" x2="10" y2="18"/>
      <line x1="10" y1="2" x2="22" y2="6"/>
      <line x1="22" y1="6" x2="22" y2="11"/>
      <rect x="19" y="11" width="5" height="3.5" rx="0.5"/>
      <line x1="21" y1="14.5" x2="21" y2="17"/>
      <line x1="3" y1="18" x2="21" y2="18"/>
      <line x1="6" y1="18" x2="6" y2="22"/>
      <line x1="16" y1="18" x2="16" y2="22"/>
    </svg>
  ),
  Custody: (p) => (
    /* Custodia: escudo con radar/satélite */
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 2L4 5v6c0 5 3.5 9 8 11 4.5-2 8-6 8-11V5z"/>
      <circle cx="12" cy="11" r="2"/>
      <path d="M9 11a3 3 0 0 1 6 0"/>
      <path d="M7 11a5 5 0 0 1 10 0"/>
    </svg>
  ),
  CargoCover: (p) => (
    /* Seguro de carga: caja con paraguas protector */
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 2C8 2 5 4.7 5 8h14c0-3.3-3-6-7-6z"/>
      <line x1="8" y1="8" x2="8" y2="13"/>
      <path d="M8 13a2 2 0 0 0 4 0"/>
      <line x1="12" y1="8" x2="12" y2="13"/>
      <line x1="16" y1="8" x2="16" y2="12"/>
      <rect x="4" y="16" width="16" height="6" rx="1.5"/>
      <line x1="9" y1="16" x2="9" y2="22"/>
      <line x1="15" y1="16" x2="15" y2="22"/>
    </svg>
  ),
  Linkedin: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M20.5 2h-17A1.5 1.5 0 0 0 2 3.5v17A1.5 1.5 0 0 0 3.5 22h17a1.5 1.5 0 0 0 1.5-1.5v-17A1.5 1.5 0 0 0 20.5 2zM8 19H5v-9h3zM6.5 8.25A1.75 1.75 0 1 1 8.3 6.5a1.78 1.78 0 0 1-1.8 1.75zM19 19h-3v-4.74c0-1.42-.6-1.93-1.38-1.93A1.74 1.74 0 0 0 13 14.19a.66.66 0 0 0 0 .14V19h-3v-9h2.9v1.3a3.11 3.11 0 0 1 2.7-1.4c1.55 0 3.36.86 3.36 3.66z" />
    </svg>
  ),
  Facebook: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" {...p}>
      <path d="M22 12a10 10 0 1 0-11.56 9.88v-7H8v-2.88h2.44V9.74c0-2.41 1.44-3.74 3.64-3.74a14.93 14.93 0 0 1 2.16.19v2.36h-1.21c-1.2 0-1.58.75-1.58 1.51v1.81h2.69l-.43 2.88h-2.26v7A10 10 0 0 0 22 12z" />
    </svg>
  ),
  Instagram: (p) => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <rect x="2" y="2" width="20" height="20" rx="5" /><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z" /><line x1="17.5" y1="6.5" x2="17.5" y2="6.5" />
    </svg>
  ),
};

/* ============ NAVBAR ============ */
function Nav({ onOpenDrawer }) {
  const [scrolled, setScrolled] = useState(false);
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      setScrolled(y > 60);
      const h = document.documentElement.scrollHeight - window.innerHeight;
      setProgress(h > 0 ? (y / h) * 100 : 0);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const links = [
    ["#hero", "Inicio"],
    ["#servicios", "Servicios"],
    ["#beneficios", "Beneficios"],
    ["#cobertura", "Cobertura"],
    ["#nosotros", "Nosotros"],
    ["#certs", "Certificaciones"],
  ];
  return (
    <header className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="container nav-inner">
        <a href="#hero" className="nav-logo" aria-label="Injoy Agencia Aduanal">
          <img src="assets/logo-color.svg" alt="Injoy" className="logo-color" />
          <img src="assets/logo-white.svg" alt="Injoy" className="logo-white" />
        </a>
        <nav className="nav-links">
          {links.map(([h, l]) => <a key={h} href={h}>{l}</a>)}
        </nav>
        <a href="#contacto" className="nav-cta">
          Hagamos equipo <Icon.Arrow />
        </a>
        <button className="hamburger" onClick={onOpenDrawer} aria-label="Abrir menú">
          <Icon.Menu />
        </button>
      </div>
      <div className="scroll-progress" style={{ width: progress + "%" }} />
    </header>
  );
}

function Drawer({ open, onClose }) {
  const links = [
    ["#hero", "Inicio"], ["#servicios", "Servicios"], ["#beneficios", "Beneficios"],
    ["#cobertura", "Cobertura"], ["#nosotros", "Nosotros"], ["#certs", "Certificaciones"], ["#contacto", "Contacto"],
  ];
  return (
    <div className={`drawer ${open ? "open" : ""}`} aria-hidden={!open}>
      <div className="drawer-top">
        <img src="assets/logo-color.svg" style={{ height: 48 }} alt="" />
        <button onClick={onClose} style={{ color: "white" }} aria-label="Cerrar"><Icon.Close /></button>
      </div>
      <div className="drawer-links">
        {links.map(([h, l]) => <a key={h} href={h} onClick={onClose}>{l}</a>)}
      </div>
      <a href="#contacto" className="drawer-cta" onClick={onClose}>Hagamos equipo</a>
    </div>
  );
}

/* ============ HERO ============ */
function Hero() {
  const isoRef = useRef(null);
  useEffect(() => {
    const onMove = (e) => {
      if (!isoRef.current) return;
      const x = (e.clientX / window.innerWidth - 0.5) * 18;
      const y = (e.clientY / window.innerHeight - 0.5) * 14;
      isoRef.current.style.transform = `translate(${x}px, ${y}px)`;
    };
    window.addEventListener("mousemove", onMove);
    return () => window.removeEventListener("mousemove", onMove);
  }, []);
  return (
    <section className="hero" id="hero">
      <div className="hero-bg">
        <video className="hero-video" autoPlay muted loop playsInline preload="auto">
          <source src="uploads/INJOYVIDEO.mp4" type="video/mp4" />
        </video>
      </div>
      <div className="hero-grain" />
      <div className="hero-iso" ref={isoRef}>
        <img src="assets/isotype-white.svg" alt="" />
      </div>
      <div className="container hero-inner">
        <div className="hero-eyebrow reveal">
          <span className="pulse" />
          <span>desde 2007</span>
        </div>
        <h1 className="hero-title-display reveal delay-1">
          <span className="hero-display-line">AGENCIA</span>
          <span className="hero-display-line">ADUAN<em className="accent">A</em>L</span>
        </h1>
        <p className="hero-sub reveal delay-3">
          Más de 19 años transformando el comercio exterior en México.
        </p>
        <div className="hero-actions reveal delay-4">
          <a href="#contacto" className="btn btn-primary">Cotizar mi despacho <Icon.Arrow /></a>
          <a href="#servicios" className="btn btn-ghost">Conoce nuestros servicios <Icon.Arrow /></a>
        </div>
      </div>

      <div className="container hero-meta">
        <div className="hero-meta-block">
          <span>Patentes directas</span>
          <strong>1880 · Bojalil</strong>
        </div>
        <div className="hero-meta-block" style={{ textAlign: "center" }}>
          <span>Certificados</span>
          <strong>OEA · ISO 9001:2015</strong>
        </div>
        <div className="hero-meta-block" style={{ textAlign: "right" }}>
          <span>Cobertura</span>
          <strong>8 aduanas nacionales</strong>
        </div>
      </div>

      <div className="scroll-indicator" />
    </section>
  );
}

/* ============ SERVICIOS CINTILLO (home strip) ============ */
function ServiciosCintillo() {
  const items = [
    { icon: Icon.CustomsClear, t: "Despacho aduanal",          s: "Importación · Exportación" },
    { icon: Icon.SemiTruck,    t: "Flete nacional",             s: "Contenedores · Hazmat · Refrigerados" },
    { icon: Icon.PortCrane,    t: "Maniobra fuera de puerto",   s: "Almacén · Cross dock · Trinca" },
    { icon: Icon.CargoCover,   t: "Seguro de carga",            s: "Cobertura total de mercancía" },
  ];
  return (
    <section className="servicios-cintillo" aria-label="Servicios principales">
      <div className="container">
        <div className="cintillo-grid">
          {items.map((it, i) => {
            const I = it.icon;
            return (
              <a href="#servicios" className="cintillo-item reveal" style={{ transitionDelay: `${i*80}ms` }} key={i}>
                <div className="cintillo-icon"><I /></div>
                <div className="cintillo-text">
                  <div className="cintillo-title">{it.t}</div>
                  <div className="cintillo-sub">{it.s}</div>
                </div>
              </a>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ============ FORELAND MAP — MapLibre GL + Deck.gl ============ */
function ForelandDeckMap() {
  const containerRef = useRef(null);

  useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    if (typeof maplibregl === "undefined" || typeof deck === "undefined") return;

    const MAG = [211, 39, 124];
    const GRN = [120, 190, 32];
    const YEL = [242, 194, 0];

    const ports = [
      { name: "Veracruz",        coords: [-96.13, 19.17], c: MAG },
      { name: "Altamira",        coords: [-97.93, 22.40], c: MAG },
      { name: "Manzanillo",      coords: [-104.32, 19.04], c: MAG },
      { name: "Lázaro Cárdenas", coords: [-102.20, 17.95], c: MAG },
      { name: "AICM",            coords: [-99.07, 19.43], c: GRN },
      { name: "AIFA",            coords: [-99.01, 19.74], c: GRN },
      { name: "Guadalajara",     coords: [-103.31, 20.52], c: GRN },
      { name: "Nuevo Laredo",    coords: [-99.50, 27.50],  c: YEL },
    ];

    const arcs = [
      { from: [-96.13,19.17],   to: [121.47,31.23],  c: MAG }, // Veracruz → Shanghai
      { from: [-96.13,19.17],   to: [4.14,51.95],    c: MAG }, // → Rotterdam
      { from: [-97.93,22.40],   to: [9.99,53.55],    c: MAG }, // Altamira → Hamburg
      { from: [-104.32,19.04],  to: [103.82,1.35],   c: MAG }, // Manzanillo → Singapur
      { from: [-104.32,19.04],  to: [139.76,35.68],  c: MAG }, // → Tokio
      { from: [-102.20,17.95],  to: [18.42,-33.92],  c: MAG }, // Lázaro → Cape Town
      { from: [-96.13,19.17],   to: [-58.4,-34.6],   c: MAG }, // → Buenos Aires
      { from: [-99.07,19.43],   to: [-3.70,40.42],   c: GRN }, // AICM → Madrid
      { from: [-99.01,19.74],   to: [8.68,50.11],    c: GRN }, // AIFA → Frankfurt
      { from: [-99.07,19.43],   to: [-80.19,25.77],  c: GRN }, // AICM → Miami
      { from: [-103.31,20.52],  to: [-118.41,33.94], c: GRN }, // GDL → LAX
      { from: [-99.50,27.50],   to: [-96.80,32.78],  c: YEL }, // Laredo → Dallas
      { from: [-99.50,27.50],   to: [-87.63,41.88],  c: YEL }, // → Chicago
    ];

    const map = new maplibregl.Map({
      container: el,
      style: "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",
      center: [-30, 22],
      zoom: 1.65,
      pitch: 0,
      bearing: 0,
      attributionControl: false,
      logoPosition: "bottom-right",
    });

    let overlay = null;
    let animId = null;
    let t = 0;

    const buildLayers = (pulse) => [
      new deck.ArcLayer({
        id: "arcs",
        data: arcs,
        getSourcePosition: d => d.from,
        getTargetPosition: d => d.to,
        getSourceColor: d => [...d.c, 210],
        getTargetColor: d => [...d.c, 40],
        getWidth: 1.6,
        getHeight: 0.42,
        widthMinPixels: 1.2,
        widthMaxPixels: 2.8,
        pickable: false,
      }),
      new deck.ScatterplotLayer({
        id: "dots",
        data: ports,
        getPosition: d => d.coords,
        getFillColor: d => [...d.c, 230],
        getLineColor: [255, 255, 255, 220],
        getRadius: 100000,
        radiusMinPixels: 4,
        radiusMaxPixels: 9,
        stroked: true,
        lineWidthMinPixels: 1.5,
        pickable: true,
        getTooltip: d => d.name,
      }),
      new deck.ScatterplotLayer({
        id: "pulse",
        data: ports,
        getPosition: d => d.coords,
        getFillColor: [0, 0, 0, 0],
        getLineColor: d => [...d.c, Math.round(130 * (1 - pulse * 0.7))],
        getRadius: 120000 + 160000 * pulse,
        radiusMinPixels: 5 + 12 * pulse,
        radiusMaxPixels: 24,
        stroked: true,
        lineWidthMinPixels: 0.9,
        pickable: false,
      }),
    ];

    map.on("load", () => {
      if (!deck.MapboxOverlay) return;

      overlay = new deck.MapboxOverlay({ interleaved: false, layers: buildLayers(0) });
      map.addControl(overlay);

      const tick = () => {
        t = (t + 0.022) % (Math.PI * 2);
        const pulse = (1 + Math.sin(t)) / 2;
        if (overlay) overlay.setProps({ layers: buildLayers(pulse) });
        animId = requestAnimationFrame(tick);
      };
      tick();
    });

    const ro = new ResizeObserver(() => map.resize());
    ro.observe(el);

    return () => {
      if (animId) cancelAnimationFrame(animId);
      ro.disconnect();
      try { map.remove(); } catch (e) {}
    };
  }, []);

  return <div ref={containerRef} className="foreland-deck" />;
}

function ForelandMap() {
  return (
    <div className="foreland">
      <div className="foreland-regions">
        <span className="foreland-regions-label">Foreland</span>
        <span className="foreland-regions-list">Europa · Asia · Medio Oriente · América del Norte · África Occidental · El Caribe</span>
      </div>

      <div className="foreland-map">
        <ForelandDeckMap />
      </div>

      {/* Legend */}
      <div className="foreland-legend">
        <div className="leg-row">
          <span className="leg-dot" style={{ background: "#D3277C" }} />
          <span><strong>Marítimas</strong> · Veracruz, Altamira, Manzanillo, Lázaro Cárdenas</span>
        </div>
        <div className="leg-row">
          <span className="leg-dot" style={{ background: "#78BE20" }} />
          <span><strong>Aéreas</strong> · AICM, AIFA, GDL</span>
        </div>
        <div className="leg-row">
          <span className="leg-dot" style={{ background: "#F2C200" }} />
          <span><strong>Fronteriza</strong> · Nuevo Laredo, Tamps.</span>
        </div>
      </div>
    </div>
  );
}

function Pin({ x, y, color, label, align }) {
  const dx = align === "left" ? -8 : 8;
  const anchor = align === "left" ? "end" : "start";
  return (
    <g>
      <circle cx={x} cy={y} r="3.5" fill={color} stroke="white" strokeWidth="1" />
      <circle cx={x} cy={y} r="7" fill="none" stroke={color} strokeOpacity=".35" />
      <text x={x + dx} y={y + 3} textAnchor={anchor}
            fill="white" fontFamily="ui-sans-serif, sans-serif" fontSize="8" letterSpacing="1.5">
        {label}
      </text>
    </g>
  );
}

/* ============ QUÉ HACEMOS ============ */
function QueHacemos() {
  return (
    <section className="qh section-pad" id="que-hacemos">
      <img src="assets/deco-green.png" className="qh-deco tl" alt="" />
      <img src="assets/deco-magenta.png" className="qh-deco br" alt="" />
      <div className="container qh-grid">
        <div>
          <div className="eyebrow eyebrow-line reveal">Qué hacemos</div>
          <h2 className="h-section reveal delay-1" style={{ marginTop: 22 }}>
            Desde cualquier origen.<br />
            Cobertura estratégica<br />
            <span className="serif-it" style={{ color: "var(--gray)" }}>en las aduanas clave de México.</span>
          </h2>
          <p className="lead reveal delay-2" style={{ marginTop: 28 }}>
            Operamos importaciones y exportaciones en las aduanas más importantes de México. Conocemos los sectores, anticipamos los riesgos y acompañamos cada operación con un equipo que entiende que detrás de cada contenedor hay una empresa que necesita avanzar.
          </p>

          <div className="patente-card reveal delay-3">
            <div className="patente-seal" aria-hidden="true">
              <img src="uploads/calidad.svg" alt="" />
            </div>
            <div className="patente-body">
              <div className="patente-label">Patente del socio fundador</div>
              <div className="patente-year"><em>1880</em></div>
              <div className="patente-name">Salvador Bojalil Puente</div>
              <p>
                Otorgada por sustitución en 2022. En 1994 le fue concedida a su antecesor y padre, <span>Salvador Antonio Bojalil Zacarías</span>, con autorización <span>3492</span> para operar en las aduanas de Puebla, Nuevo Laredo, Altamira y Veracruz.
              </p>
            </div>
          </div>
        </div>

        <div className="reveal delay-2">
          <ForelandMap />
        </div>
      </div>
    </section>
  );
}

/* ============ STATS strip ============ */
function Stats() {
  const items = [
    { to: 18, suffix: "+", label: "Años de experiencia" },
    { to: 8, suffix: "", label: "Aduanas operadas" },
    { to: 4, suffix: "", label: "Servicios core" },
    { to: 100, suffix: "%", label: "Operaciones certificadas" },
  ];
  return (
    <section className="stats" aria-label="Cifras Injoy">
      <div className="container">
        <div className="stats-grid">
          {items.map((s, i) => (
            <div className="stat reveal" style={{ transitionDelay: `${i*80}ms` }} key={i}>
              <div className="stat-num"><CountUp to={s.to} suffix={s.suffix} /></div>
              <div className="stat-label">{s.label}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============ HISTORIA ============ */
/* ============ NOSOTROS — Historia · Valores ============ */
function Nosotros() {
  const vs = [
    { t: "Aspiración efectiva", d: "Nos movemos hacia las mejores prácticas conociendo a profundidad los sectores a los que servimos." },
    { t: "Compromiso", d: "Desarrollamos las operaciones de comercio exterior de nuestros clientes al margen de la normatividad a través de un equipo especializado enfocado en maximizar la eficacia en cada operación." },
    { t: "Dedicación", d: "Amamos lo que hacemos, no nos vemos en ningún otro sector." },
    { t: "Humanidad", d: "Construimos relaciones empáticas y auténticas basadas en la comprensión y el respeto. Creamos una sinergia justa, cercana y consciente." },
  ];

  return (
    <section className="nosotros" id="nosotros">
      {/* ── Bloque Historia ── */}
      <div className="nosotros-historia section-pad" id="historia">
        <div className="container historia-grid">
          <div>
            <div className="eyebrow eyebrow-line on-dark reveal" style={{ color: "var(--green-soft)" }}>Historia</div>
            <h2 className="h-section reveal delay-1" style={{ marginTop: 22, color: "white" }}>
              HIST<span className="accent">O</span>RIA<br />
              <span className="serif-it" style={{ color: "rgba(255,255,255,.55)", fontSize: ".6em" }}>de una patente con alma.</span>
            </h2>
            <p className="body reveal delay-2">
              Injoy nació con la visión de transformar los servicios aduanales en México, ofreciendo una experiencia eficiente, humana y ágil. Con más de 18 años en el sector, hemos crecido gracias a la confianza de nuestros clientes y al esfuerzo constante por innovar y profesionalizar nuestro trabajo.
            </p>

            <div className="future-label reveal delay-3">NUESTRO FUTURO</div>
            <blockquote className="quote reveal delay-4">
              "Entregar un servicio que transforme la experiencia con la que se vive hoy el comercio exterior desde el despacho aduanal."
            </blockquote>
          </div>

          <div className="historia-image reveal delay-3">
            <img src="assets/injoy-barco.png" alt="Injoy — barco contenedor" />
          </div>
        </div>

        <div className="container team-gallery-wrap">
          <div className="team-gallery-label reveal">Equipo Injoy · Veracruz</div>
          <div className="team-gallery">
            <div className="team-photo reveal delay-1">
              <img src="uploads/FOTOS%20EQUIPO/8AA22B27-862E-45D9-90A4-D0E5B753ACF2_1_102_a.jpeg" alt="Equipo Injoy" loading="lazy" />
            </div>
            <div className="team-photo reveal delay-2">
              <img src="uploads/FOTOS%20EQUIPO/IMG_3591.jpg" alt="Equipo Injoy en operación" loading="lazy" />
            </div>
            <div className="team-photo reveal delay-3">
              <img src="uploads/FOTOS%20EQUIPO/IMG_3599.jpg" alt="Equipo Injoy en oficina" loading="lazy" />
            </div>
          </div>
        </div>
      </div>

      {/* ── Bloque Valores (diseño original — slide oscuro con foto + lista) ── */}
      <div className="valores section-pad" id="valores">
        <div className="valores-bg" />
        <div className="container valores-inner">
          <div className="valores-text">
            <div className="eyebrow on-dark reveal" style={{ display: "inline-block", color: "var(--green-soft)" }}>Nosotros</div>
            <h2 className="h-section reveal delay-1" style={{ marginTop: 18 }}>
              VAL<span className="accent">O</span>RES
            </h2>
            <p className="lead on-dark reveal delay-2" style={{ marginTop: 24 }}>
              La diferencia de Injoy no está en el trámite, está en la gente. Un equipo entrenado para diagnosticar, proponer y resolver con cercanía.
            </p>
          </div>

          <div className="valores-grid">
            <div className="valor-image reveal delay-2">
              <div style={{ aspectRatio: "4/5", overflow: "hidden", borderRadius: 8, boxShadow: "0 30px 80px -30px rgba(0,0,0,.5)" }}>
                <img src="assets/team-portrait.jpg" alt="Equipo Injoy" loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", filter: "saturate(.9) contrast(1.05)" }} />
              </div>
            </div>
            <div className="valores-list">
              {vs.map((v, i) => (
                <div className="valor reveal" style={{ transitionDelay: `${i*120}ms` }} key={i}>
                  <div className="valor-title">{v.t.toUpperCase()}</div>
                  <p className="valor-desc">{v.d}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ SERVICIOS ============ */
function Servicios() {
  const services = [
    {
      n: "01",
      icon: Icon.Ship,
      title: "Flete internacional",
      sub: "Marítimo · Aéreo · Terrestre",
      desc: "Organizamos el transporte internacional de tu mercancía por la vía más eficiente.",
      bullets: [
        "Flete marítimo FCL y LCL",
        "Flete aéreo internacional",
        "Transporte terrestre internacional",
        "Selección de la mejor ruta según tu operación",
      ],
    },
    {
      n: "02",
      icon: Icon.CargoCover,
      title: "Seguro de mercancías y de contenedor",
      sub: "Cobertura todo riesgo",
      desc: "Protegemos tu carga ante cualquier eventualidad durante todo el trayecto.",
      bullets: [
        "Pólizas todo riesgo",
        "Cobertura nacional e internacional",
        "Protección de mercancía y contenedor",
        "Asesoría personalizada para cada operación",
      ],
    },
    {
      n: "03",
      icon: Icon.PortCrane,
      title: "Maniobras en patio de contenedores",
      sub: "Almacén propio · Cross dock · Trinca",
      desc: "Realizamos maniobras seguras y eficientes en nuestro patio especializado.",
      bullets: [
        "Carga y descarga de contenedores",
        "Revisión física de mercancía",
        "Estiba y desestiba",
        "Consolidación y desconsolidación",
        "Personal y equipo especializado",
      ],
    },
    {
      n: "04",
      icon: Icon.CustomsClear,
      title: "Despacho aduanal en México",
      sub: "Importación · Exportación · Servicio core",
      desc: "Gestionamos tus operaciones de importación y exportación con cumplimiento total.",
      bullets: [
        "Importación y exportación",
        "Trámites aduanales",
        "Cumplimiento normativo",
        "Clasificación arancelaria",
        "Asesoría en regulaciones y restricciones",
      ],
    },
    {
      n: "05",
      icon: Icon.SemiTruck,
      title: "Transporte nacional en unidades propias",
      sub: "Cobertura nacional · Monitoreo 24/7",
      desc: "Trasladamos tu mercancía a cualquier punto del país con unidades propias.",
      bullets: [
        "Cobertura nacional",
        "Unidades propias y monitoreadas",
        "Entregas seguras y puntuales",
        "Capacidad para carga seca, refrigerada y sobredimensionada",
      ],
    },
    {
      n: "06",
      icon: Icon.Custody,
      title: "Custodia armada y monitoreo satelital",
      sub: "Física · Virtual · Grado aeroespacial",
      desc: "Brindamos seguridad integral a tu mercancía con tecnología y personal altamente capacitado.",
      bullets: [
        "Custodia física armada y desarmada",
        "Monitoreo virtual satelital 24/7",
        "Dispositivos de alta seguridad",
        "Tecnología grado aeroespacial",
        "Reportes e información en tiempo real",
      ],
    },
  ];
  return (
    <section className="servicios section-pad" id="servicios">
      <div className="container">
        <div className="servicios-header">
          <div>
            <div className="eyebrow eyebrow-line reveal">Qué ofrecemos</div>
            <h2 className="h-section reveal delay-1" style={{ marginTop: 18 }}>
              SERV<span className="accent">I</span>CIOS
            </h2>
          </div>
          <p className="lead reveal delay-2">
            Soluciones logísticas y aduanales integrales para que tu mercancía llegue segura, a tiempo y en cumplimiento.
          </p>
        </div>

        <div className="servicios-grid">
          {services.map((s, i) => {
            const I = s.icon;
            return (
              <article className="service reveal" style={{ transitionDelay: `${i*100}ms` }} key={s.n}>
                <div className="service-top">
                  <div className="service-num">{s.n}</div>
                  <div className="service-icon-wrap"><I /></div>
                </div>
                <div className="service-body">
                  <div className="service-title">{s.title}</div>
                  <div className="service-sub">{s.sub}</div>
                  <p className="service-desc">{s.desc}</p>
                  <ul className="service-bullets">
                    {s.bullets.map((b, j) => (
                      <li key={j}>
                        <svg viewBox="0 0 16 16" aria-hidden="true">
                          <path d="M3 8.5l3 3 7-7" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round" />
                        </svg>
                        <span>{b}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              </article>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ============ BENEFICIOS ============ */
function Beneficios() {
  const bs = [
    { icon: Icon.Spark, t: "Eficiencia operativa", d: "Resultados. Superamos los estándares de la industria." },
    { icon: Icon.Layers, t: "Soluciones a la medida", d: "Flexibilidad. Adecuamos nuestra logística a su operación." },
    { icon: Icon.LegalDoc, t: "Certidumbre jurídica", d: "Sociedades inscritas en ANAM. Materialidad en las operaciones." },
    { icon: Icon.Award, t: "Certificados", d: "Procesos confiables, mayor control operativo y un servicio aduanal consistente que reduce riesgos." },
    { icon: Icon.Heart, t: "Calidez en el trato", d: "Compromiso. Nuestro personal hace la diferencia." },
    { icon: Icon.Lightbulb, t: "Somos especialistas", d: "Diagnosticamos, proponemos y solucionamos." },
    { icon: Icon.Pin, t: "Cobertura nacional", d: "Presencia en las aduanas más importantes del país: marítimas, aéreas y de frontera." },
  ];
  return (
    <section className="beneficios section-pad" id="beneficios">
      <div className="container">
        <div className="beneficios-header">
          <div className="eyebrow on-dark reveal" style={{ display: "inline-block", color: "var(--green-soft)" }}>Por qué Injoy</div>
          <h2 className="h-section reveal delay-1" style={{ marginTop: 18 }}>
            BENEF<span className="accent">I</span>CIOS
          </h2>
        </div>
        <div className="beneficios-grid">
          {bs.map((b, i) => {
            const I = b.icon;
            return (
              <div className="benefit reveal" style={{ transitionDelay: `${i*70}ms` }} key={i}>
                <div className="benefit-num">{String(i+1).padStart(2, "0")} / 07</div>
                <div className="benefit-icon"><I /></div>
                <div className="benefit-title">{b.t}</div>
                <div className="benefit-desc">{b.d}</div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ============ TIMELINE ============ */
function Timeline() {
  const events = [
    {
      year: "1994", color: "magenta", icon: "plane",
      title: "Fundación",
      text: "Fundación de la agencia aduanal Salvador Bojalil Zacarías. Volkswagen y Autotek se convierten en los principales clientes. Somos los primeros en importar el Antonov, el avión más grande del mundo, de fabricación rusa."
    },
    {
      year: "1996", color: "green", icon: "building",
      title: "Autorización de Aduana Adicional",
      text: "Se obtiene autorización para operar una aduana adicional, ampliando la presencia en Veracruz."
    },
    {
      year: "2005", color: "magenta", icon: "crane",
      title: "Autorización de aduana adicional",
      text: "Nueva autorización para operar una aduana adicional, extendiendo cobertura a Altamira, Tamaulipas."
    },
    {
      year: "2007", color: "magenta", icon: "person",
      title: "Constitución de Injoy Agencia Aduanal",
      text: "Autorización de Sociedad ante la Administración General de Aduanas. Inicio formal de operaciones de Injoy."
    },
    {
      year: "2022", color: "green", icon: "patent",
      title: "Patente 1880",
      text: "Obtención de la patente 1880 por el Lic. Salvador Bojalil Puente."
    },
    {
      year: "2023", color: "green", icon: "person",
      title: "Nos reinventamos",
      text: "Renovación integral de la operación e identidad: nueva estructura, nuevo organigrama y consolidación del equipo directivo."
    },
  ];

  const Icons = {
    plane: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M22 12l-9 9-1.5-7.5L4 12l18-8z"/></svg>,
    building: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"><rect x="3" y="9" width="18" height="12"/><path d="M3 9l9-6 9 6"/><rect x="9" y="13" width="3" height="4"/><rect x="14" y="13" width="3" height="4"/></svg>,
    crane: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round"><path d="M5 21V5l14-2v6"/><path d="M5 9h14"/><path d="M12 9v12"/><rect x="9" y="17" width="6" height="4"/></svg>,
    person: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round"><circle cx="12" cy="8" r="4"/><path d="M4 22c0-4.4 3.6-8 8-8s8 3.6 8 8"/></svg>,
    office: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round"><rect x="3" y="7" width="8" height="14"/><rect x="13" y="3" width="8" height="18"/><line x1="5" y1="11" x2="9" y2="11"/><line x1="5" y1="15" x2="9" y2="15"/><line x1="15" y1="7" x2="19" y2="7"/><line x1="15" y1="11" x2="19" y2="11"/><line x1="15" y1="15" x2="19" y2="15"/></svg>,
    docs: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round"><rect x="6" y="3" width="14" height="18" rx="1"/><path d="M6 7H4v15h13"/><line x1="10" y1="9" x2="16" y2="9"/><line x1="10" y1="13" x2="16" y2="13"/><line x1="10" y1="17" x2="14" y2="17"/></svg>,
    patent: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round"><circle cx="12" cy="9" r="6"/><polyline points="8 14 7 22 12 19 17 22 16 14"/></svg>,
  };

  return (
    <section className="timeline section-pad" id="timeline">
      <div className="container">
        <div className="timeline-header">
          <div className="eyebrow eyebrow-line reveal">Nuestra trayectoria</div>
          <h2 className="h-section reveal delay-1" style={{ marginTop: 18 }}>
            L<span className="accent">Í</span>NEA DEL TIEMPO
          </h2>
          <p className="lead reveal delay-2" style={{ marginTop: 22 }}>
            Tres décadas construyendo confianza, una patente que pasó de padre a hijo y un equipo que ha hecho del despacho aduanal un oficio con alma.
          </p>
        </div>

        <div className="timeline-wrap">
          <svg className="timeline-path" viewBox="0 0 1200 360" preserveAspectRatio="none" aria-hidden="true">
            <defs>
              <linearGradient id="tlGrad" x1="0" x2="1" y1="0" y2="0">
                <stop offset="0%"  stopColor="#D3277C" />
                <stop offset="55%" stopColor="#D3277C" />
                <stop offset="55%" stopColor="#78BE20" />
                <stop offset="100%" stopColor="#78BE20" />
              </linearGradient>
              <marker id="tlArrow" viewBox="0 0 12 12" refX="6" refY="6" markerWidth="9" markerHeight="9" orient="auto-start-reverse">
                <path d="M0,0 L12,6 L0,12 L4,6 z" fill="#78BE20" />
              </marker>
            </defs>
            <path
              d="M 20 320 C 180 320, 240 220, 380 200 S 600 120, 720 170 S 940 110, 1180 40"
              fill="none" stroke="url(#tlGrad)" strokeWidth="5" strokeLinecap="round"
              markerEnd="url(#tlArrow)"
            />
          </svg>

          <div className="timeline-grid">
            {events.map((e, i) => (
              <div className={`tl-card tl-${e.color} ${i % 2 === 0 ? "tl-up" : "tl-down"} reveal`} style={{ transitionDelay: `${i*80}ms` }} key={i}>
                <div className="tl-marker" aria-hidden="true" />
                <div className="tl-head">
                  <span className="tl-year">{e.year}</span>
                  <span className="tl-icon">{Icons[e.icon]}</span>
                </div>
                <div className="tl-title">{e.title}</div>
                <p className="tl-text">{e.text}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ MARQUEE ============ */
function Marquee() {
  const items = ["Veracruz", "Altamira", "Manzanillo", "Lázaro Cárdenas", "AICM", "AIFA", "GDL", "Nuevo Laredo", "Confianza", "Experiencia", "18 años", "OEA", "ISO 9001:2015"];
  const Row = () => (
    <span>
      {items.map((t, i) => (
        <span key={i} className="m-item">{t}<span className="dot" /></span>
      ))}
    </span>
  );
  return (
    <div className="marquee" aria-hidden="true">
      <div className="marquee-track">
        <Row /><Row />
      </div>
    </div>
  );
}

/* ============ COBERTURA / MAPA ============ */
const PINS = [
  { name: "Veracruz",        type: "maritima", lat: 19.174,  lng: -96.134,  op: "Marítima" },
  { name: "Altamira",        type: "maritima", lat: 22.407,  lng: -97.927,  op: "Marítima" },
  { name: "Manzanillo",      type: "maritima", lat: 19.052,  lng: -104.318, op: "Marítima" },
  { name: "Lázaro Cárdenas", type: "maritima", lat: 17.958,  lng: -102.189, op: "Marítima" },
  { name: "AICM",            type: "aerea",    lat: 19.436,  lng: -99.072,  op: "Aérea · CDMX" },
  { name: "AIFA",            type: "aerea",    lat: 19.756,  lng: -99.015,  op: "Aérea · Edomex" },
  { name: "GDL",             type: "aerea",    lat: 20.522,  lng: -103.311, op: "Aérea · Guadalajara" },
  { name: "Nuevo Laredo",    type: "frontera", lat: 27.477,  lng: -99.515,  op: "Frontera · Tamps." },
];

const PIN_COLORS = { maritima: "#D3277C", aerea: "#78BE20", frontera: "#2A6FDB" };

function makeMarkerIcon(color) {
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="28" height="36" viewBox="0 0 28 36">
    <circle cx="14" cy="14" r="13" fill="${color}" stroke="white" stroke-width="2.5" opacity=".95"/>
    <circle cx="14" cy="14" r="6" fill="white"/>
    <line x1="14" y1="27" x2="14" y2="35" stroke="${color}" stroke-width="2.5" stroke-linecap="round"/>
  </svg>`;
  return L.divIcon({
    html: svg,
    className: "",
    iconSize: [28, 36],
    iconAnchor: [14, 35],
    popupAnchor: [0, -36],
  });
}

function LeafletMap() {
  const mapRef = useRef(null);
  const instanceRef = useRef(null);

  useEffect(() => {
    if (instanceRef.current) return;
    const map = L.map(mapRef.current, {
      center: [23.5, -102.5],
      zoom: 5,
      zoomControl: false,
      scrollWheelZoom: false,
      attributionControl: false,
    });

    L.tileLayer("https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png", {
      subdomains: "abcd",
      maxZoom: 19,
    }).addTo(map);

    // Subtle country/state border overlay
    L.tileLayer("https://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}{r}.png", {
      subdomains: "abcd",
      maxZoom: 19,
      opacity: 0.5,
    }).addTo(map);

    L.control.zoom({ position: "bottomright" }).addTo(map);
    L.control.attribution({ position: "bottomright", prefix: false })
      .addAttribution('© <a href="https://carto.com/">CARTO</a>')
      .addTo(map);

    PINS.forEach((p) => {
      L.marker([p.lat, p.lng], { icon: makeMarkerIcon(PIN_COLORS[p.type]) })
        .addTo(map)
        .bindPopup(
          `<strong style="font-family:sans-serif;font-size:13px">${p.name}</strong><br>
           <span style="font-family:sans-serif;font-size:12px;color:#666">${p.op}</span>`
        );
    });

    instanceRef.current = map;
    return () => { map.remove(); instanceRef.current = null; };
  }, []);

  return <div ref={mapRef} className="leaflet-map" />;
}

function Cobertura() {
  return (
    <section className="cobertura section-pad" id="cobertura">
      <div className="container cobertura-grid">
        <div>
          <div className="eyebrow eyebrow-line reveal">Misión & Cobertura</div>
          <h2 className="h-section reveal delay-1" style={{ marginTop: 18 }}>
            MISI<span className="accent">Ó</span>N
          </h2>
          <p className="mision-text reveal delay-2">
            "Generar sinergia para maquilar los despachos de importación y exportación en las aduanas con un alto nivel de eficiencia y seguridad en la cadena de suministro."
          </p>
          <div className="legend reveal delay-3">
            <div className="legend-item"><span className="legend-dot" style={{ background: "var(--magenta)" }} /> Marítimas · Veracruz, Altamira, Manzanillo, Lázaro Cárdenas</div>
            <div className="legend-item"><span className="legend-dot" style={{ background: "var(--green)" }} /> Aéreas · AICM, AIFA, GDL</div>
            <div className="legend-item"><span className="legend-dot" style={{ background: "#2A6FDB" }} /> Frontera · Nuevo Laredo, Tamps.</div>
          </div>
        </div>

        <div className="map-wrap reveal delay-2">
          <LeafletMap />
        </div>
      </div>
    </section>
  );
}

/* ============ CERTIFICACIONES ============ */
function Certs() {
  return (
    <section className="certs section-pad-sm" id="certs">
      <div className="container">
        <div className="eyebrow eyebrow-line reveal" style={{ display: "inline-flex" }}>Avales</div>
        <h2 className="h-section reveal delay-1" style={{ marginTop: 18 }}>
          CERTIF<span className="accent">I</span>CACIONES
        </h2>
        <p className="lead reveal delay-2" style={{ margin: "20px auto 0" }}>
          Avalados por los más altos estándares internacionales de comercio exterior y gestión de calidad.
        </p>

        <div className="certs-grid">
          <div className="cert reveal delay-2">
            <div className="cert-logo-wrap cert-grayscale">
              <img src="uploads/cropped-Nuevo-logo-OEA-5.png" alt="OEA — Operador Económico Autorizado México" />
            </div>
            <div className="cert-title">Operador Económico Autorizado</div>
            <div className="cert-sub">Certificación SAT / OEA · Cadena de suministro segura</div>
          </div>
          <div className="cert reveal delay-3">
            <div className="cert-logo-wrap cert-grayscale">
              <img src="uploads/Logo iso 9001.png" alt="MB Certification ISO 9001:2015" />
            </div>
            <div className="cert-title">MB Certification · ISO 9001:2015</div>
            <div className="cert-sub">Sistemas de gestión de calidad</div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============ MANIFESTO ============ */
function Manifesto() {
  return (
    <section className="manifesto section-pad">
      <div className="manifesto-bg" />
      <div className="container manifesto-inner">
        <img src="assets/isotype-white.svg" alt="" className="manifesto-iso reveal" />
        <h2 className="reveal delay-1">
          La diferencia entre cruzar<br />
          y avanzar, es hacerlo con <span className="accent">certeza.</span>
        </h2>
        <div className="manifesto-sig reveal delay-2">— Injoy Agencia Aduanal</div>
      </div>
    </section>
  );
}

/* ============ CONTACTO ============ */
function Contacto() {
  const [data, setData] = useState({ nombre: "", empresa: "", email: "", telefono: "", tipo: "", aduana: "", mensaje: "" });
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const set = (k) => (e) => setData({ ...data, [k]: e.target.value });
  const submit = async (e) => {
    e.preventDefault();
    setSending(true);
    setError("");
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          access_key: "27f39efb-4600-4534-b1c5-60130d7bcb66",
          subject: `Nueva cotización · ${data.nombre || "sin nombre"}${data.empresa ? " (" + data.empresa + ")" : ""}`,
          from_name: "Injoy · Sitio web",
          to: "contacto@injoy.mx",
          nombre: data.nombre,
          empresa: data.empresa,
          email: data.email,
          telefono: data.telefono,
          tipo_operacion: data.tipo,
          aduana_interes: data.aduana,
          mensaje: data.mensaje,
        }),
      });
      const json = await res.json();
      if (json.success) {
        setSent(true);
      } else {
        setError(json.message || "No pudimos enviar tu mensaje. Intenta de nuevo o escríbenos a contacto@injoy.mx");
      }
    } catch (err) {
      setError("Error de conexión. Escríbenos directo a contacto@injoy.mx");
    } finally {
      setSending(false);
    }
  };

  return (
    <section className="contacto section-pad" id="contacto">
      <div className="container">
        <div style={{ maxWidth: 760, marginBottom: 60 }}>
          <div className="eyebrow eyebrow-line reveal">Contacto</div>
          <h2 className="h-section reveal delay-1" style={{ marginTop: 18 }}>
            HAGAMOS <span className="accent">EQUIPO</span>
          </h2>
          <p className="lead reveal delay-2" style={{ marginTop: 22 }}>
            Cuéntanos qué necesitas mover. Te respondemos con propuesta, tiempos y un agente operador asignado en menos de 24 horas hábiles.
          </p>
        </div>

        <div className="contacto-grid">
          <form onSubmit={submit} className="reveal">
            <div className="fields-row">
              <div className="field"><label>Nombre completo</label><input value={data.nombre} onChange={set("nombre")} required /></div>
              <div className="field"><label>Empresa</label><input value={data.empresa} onChange={set("empresa")} /></div>
            </div>
            <div className="fields-row">
              <div className="field"><label>Email corporativo</label><input type="email" value={data.email} onChange={set("email")} required /></div>
              <div className="field"><label>Teléfono</label><input value={data.telefono} onChange={set("telefono")} /></div>
            </div>
            <div className="fields-row">
              <div className="field">
                <label>Tipo de operación</label>
                <select value={data.tipo} onChange={set("tipo")}>
                  <option value="">Selecciona</option>
                  <option>Importación marítima</option>
                  <option>Exportación marítima</option>
                  <option>Aérea</option>
                  <option>Frontera</option>
                </select>
              </div>
              <div className="field">
                <label>Aduana de interés</label>
                <select value={data.aduana} onChange={set("aduana")}>
                  <option value="">Selecciona</option>
                  <option>Veracruz</option><option>Altamira</option>
                  <option>Manzanillo</option><option>Lázaro Cárdenas</option>
                  <option>AICM</option><option>AIFA</option><option>GDL</option>
                  <option>Nuevo Laredo</option>
                </select>
              </div>
            </div>
            <div className="field"><label>Mensaje</label><textarea value={data.mensaje} onChange={set("mensaje")} rows="3" /></div>
            <button type="submit" className="btn btn-primary" style={{ marginTop: 12 }} disabled={sent || sending}>
              {sent ? "¡Recibido! Te contactamos pronto." : sending ? "Enviando..." : "Enviar cotización"} <Icon.Arrow />
            </button>
            {error && <div style={{ marginTop: 12, color: "#c0392b", fontSize: 14 }}>{error}</div>}
          </form>

          <aside className="contact-aside reveal delay-2">
            <h3>Habla con Injoy</h3>
            <div className="contact-item">
              <div className="ic"><Icon.Phone /></div>
              <div>
                <div className="lbl">Teléfono</div>
                <div className="val">+52 56 3962 4670</div>
              </div>
            </div>
            <div className="contact-item">
              <div className="ic"><Icon.Mail /></div>
              <div>
                <div className="lbl">Email</div>
                <div className="val">contacto@injoy.mx</div>
              </div>
            </div>
            <div className="contact-item">
              <div className="ic"><Icon.Pin2 /></div>
              <div>
                <div className="lbl">Oficinas</div>
                <div className="val">Veracruz, México</div>
              </div>
            </div>

          </aside>
        </div>
      </div>
    </section>
  );
}

/* ============ FOOTER ============ */
function Footer() {
  return (
    <footer className="footer">
      <img src="assets/isotype-white.svg" className="footer-iso" alt="" />
      <div className="container footer-grid">
        <div>
          <img src="assets/logo-white.svg" alt="Injoy" className="footer-logo" />
          <p className="footer-tag">Tu socio en comercio exterior desde 2007. Una sinergia justa entre rigor técnico y trato humano.</p>
          <div className="social">
            <a href="https://www.linkedin.com/company/injoy-agencia-aduanal/" target="_blank" rel="noopener noreferrer" aria-label="LinkedIn"><Icon.Linkedin /></a>
            <a href="https://www.facebook.com/InjoyServices/"             target="_blank" rel="noopener noreferrer" aria-label="Facebook"><Icon.Facebook /></a>
            <a href="https://www.instagram.com/injoyagenciaduanal/"       target="_blank" rel="noopener noreferrer" aria-label="Instagram"><Icon.Instagram /></a>
          </div>
        </div>
        <div className="footer-col">
          <h4>Navegación</h4>
          <ul>
            <li><a href="#hero">Inicio</a></li>
            <li><a href="#servicios">Servicios</a></li>
            <li><a href="#beneficios">Beneficios</a></li>
            <li><a href="#cobertura">Cobertura</a></li>
            <li><a href="#nosotros">Nosotros</a></li>
            <li><a href="#certs">Certificaciones</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>Contacto</h4>
          <ul>
            <li>+52 56 3962 4670</li>
            <li>contacto@injoy.mx</li>
            <li>Veracruz, México</li>
            <li style={{ marginTop: 12, color: "var(--green-soft)" }}>OEA · ISO 9001:2015</li>
          </ul>
        </div>
      </div>
      <div className="container footer-bottom">
        <div>© 2026 Injoy Agencia Aduanal. Todos los derechos reservados.</div>
        <div style={{ display: "flex", gap: 24 }}>
          <a href="#">Aviso de privacidad</a>
          <a href="#">Términos y condiciones</a>
        </div>
        <div style={{ width: "100%", paddingTop: 8, borderTop: "1px solid rgba(255,255,255,.06)", textAlign: "center", fontSize: 11.5, color: "rgba(255,255,255,.35)" }}>
          Diseñado por <a href="https://sintergica.ai/" target="_blank" rel="noopener noreferrer" style={{ color: "rgba(255,255,255,.55)", textDecoration: "none", transition: "color .2s" }} onMouseEnter={e => e.target.style.color="white"} onMouseLeave={e => e.target.style.color="rgba(255,255,255,.55)"}>Sintérgica AI</a>
        </div>
      </div>
    </footer>
  );
}

/* ============ LOADER ============ */
function Loader({ done }) {
  return (
    <div className={`loader ${done ? "hide" : ""}`} aria-hidden={done}>
      <svg className="loader-iso" viewBox="40 8 75 40">
        <path className="b b1" fill="#D3277C" d="M102.83,39.83c-6.61,7.43-17.21,9.54-23.68,4.72-6.46-4.83-6.35-14.76.27-22.19,6.61-7.43,17.2-9.54,23.67-4.71,6.46,4.82,6.34,14.76-.27,22.19Z"/>
        <path className="b b2" fill="#78BE20" d="M63.77,27.05c6.02,4.96,8.58,11.54,5.73,14.68-2.86,3.14-10.04,1.66-16.07-3.31-6.01-4.96-8.57-11.54-5.72-14.68,2.85-3.14,10.04-1.66,16.06,3.31Z"/>
        <path className="b b3" fill="#78BE20" d="M74.17,16.81c.91,4.02-.26,8.14-2.62,9.2-2.36,1.06-5.01-1.34-5.91-5.36-.91-4.02.26-8.14,2.62-9.2,2.36-1.06,5.01,1.34,5.91,5.36Z"/>
      </svg>
    </div>
  );
}

/* ============ WhatsApp Floating Button ============ */
function WhatsAppBtn() {
  return (
    <a
      href="https://wa.me/525639624670"
      target="_blank"
      rel="noopener noreferrer"
      className="wa-btn"
      aria-label="Contactar por WhatsApp"
    >
      <svg width="26" height="26" viewBox="0 0 24 24" fill="currentColor">
        <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51a12.8 12.8 0 0 0-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413Z"/>
      </svg>
    </a>
  );
}

/* ============ APP ============ */
function App() {
  const [drawer, setDrawer] = useState(false);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    const t = setTimeout(() => setLoaded(true), 900);
    return () => clearTimeout(t);
  }, []);

  useReveal();

  return (
    <div>
      <Loader done={loaded} />
      <Nav onOpenDrawer={() => setDrawer(true)} />
      <Drawer open={drawer} onClose={() => setDrawer(false)} />
      <main>
        <Hero />
        <ServiciosCintillo />
        <QueHacemos />
        <Servicios />
        <Nosotros />
        <Timeline />
        <Marquee />
        <Beneficios />
        <Cobertura />
        <Certs />
        <Manifesto />
        <Contacto />
        <Stats />
      </main>
      <Footer />
      <WhatsAppBtn />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
