// Landing page Enfoque Ambiental - recreación exacta del diseño aprobado
const { useState: uS, useEffect: uE, useRef: uR } = React;

// Hooks
function useScroll() {
  const [y, setY] = uS(0);
  uE(() => {
    const fn = () => setY(window.scrollY);
    window.addEventListener("scroll", fn, { passive: true });
    return () => window.removeEventListener("scroll", fn);
  }, []);
  return y;
}
function useInView(ref, th = 0.3) {
  const [seen, setSeen] = uS(false);
  uE(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(([e]) => e.isIntersecting && setSeen(true), {
      threshold: th,
    });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return seen;
}
function CountUp({ to, prefix = "", suffix = "", duration = 1800 }) {
  const ref = uR();
  const seen = useInView(ref, 0.5);
  const [val, setVal] = uS(0);
  uE(() => {
    if (!seen) return;
    const start = performance.now();
    let raf;
    const tick = (t) => {
      const p = Math.min((t - start) / duration, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(to * eased);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [seen]);
  return <span ref={ref}>{prefix}{Math.round(val)}{suffix}</span>;
}

// ===================== Translations =====================
const T = {
  es: {
    nav: [["INICIO","#hero"],["SERVICIOS","servicios.html"],["PROYECTOS","#proj"],["EXPERIENCIA","#exp"],["BLOG","blog.html"],["CONTACTO","#footer"]],
    hero: {
      t1: "INGENIERÍA",
      t2: "SOSTENIBLE,",
      t3: "INTEGRAL",
      t4: "Y DE CALIDAD",
      sub: "Ofrecemos soluciones ambientales y geoespaciales basadas en datos, tecnología y experiencia, para la toma de decisiones responsables y el desarrollo sostenible.",
      cta: "CONOCE NUESTROS SERVICIOS",
    },
    serv: {
      kicker: "NUESTROS SERVICIOS",
      title1: "Soluciones integrales para cada etapa",
      title2: "de tus proyectos ambientales y territoriales",
      items: [
        { ic: "layers", n: "GEOMÁTICA Y\nGEOINFORMACIÓN", d: "Levantamiento, procesamiento y análisis de información geoespacial con tecnología de vanguardia." },
        { ic: "pin", n: "ESTUDIOS Y GESTIÓN\nAMBIENTAL", d: "Elaboración de estudios ambientales y apoyo en la gestión de permisos y licenciamiento." },
        { ic: "leaf", n: "MONITOREO Y\nSEGUIMIENTO", d: "Monitoreo ambiental, social y predial con enfoque en calidad, trazabilidad y cumplimiento normativo." },
        { ic: "chart", n: "SISTEMAS DE\nINFORMACIÓN (SIG)", d: "Diseño e implementación de soluciones SIG para análisis espacial y gestión de datos." },
        { ic: "doc", n: "CONSULTORÍA Y\nGESTIÓN INTEGRAL", d: "Acompañamiento técnico y estratégico en proyectos ambientales y de desarrollo territorial." },
        { ic: "helmet", n: "INGENIERÍA Y DISEÑO\nDE PROYECTOS", d: "Diseño y formulación de proyectos ambientales e infraestructura sostenible." },
      ],
    },
    exp: {
      kicker: "NUESTRA EXPERIENCIA",
      title1: "Más de 20 años generando",
      title2: "confianza y resultados",
      title3: "que dejan huella.",
      sub: "Durante más de 20 años hemos convertido retos ambientales y sanitarios en soluciones sostenibles para comunidades, municipios y empresas a lo largo de Colombia — en gestión de residuos sólidos, saneamiento básico, interventoría ambiental y estudios de impacto, hoy potenciados con tecnología de drones. Rigor técnico, cumplimiento y resultados que perduran.",
      stats: [
        { n: 24, suf: "+", l: "PROYECTOS\nEJECUTADOS" },
        { n: 20, suf: "+", l: "AÑOS DE\nEXPERIENCIA" },
        { n: 3, suf: "+", l: "DEPARTAMENTOS\nDE COBERTURA" },
        { n: 100, suf: "%", l: "COMPROMISO\nY CALIDAD" },
      ],
    },
    proj: {
      kicker: "PROYECTOS DESTACADOS",
      title1: "Nuestra experiencia",
      title2: "en proyectos ejecutados",
      seeAll: "VER TODOS LOS PROYECTOS →",
      countLbl: "",
      items: [
        { t: "Estudio de Impacto Ambiental", s: "Proyecto vial · Colombia", k: "valley", cta: "VER PROYECTO" },
        { t: "Monitoreo Ambiental con Drones", s: "Seguimiento de cierres · Santander", k: "drone", cta: "VER PROYECTO" },
        { t: "Levantamiento Geoespacial LiDAR", s: "Generación de modelos de elevación", k: "lidar", cta: "VER PROYECTO" },
        { t: "Gestión Ambiental y Permisos", s: "Licenciamiento y permisos ambientales", k: "landfill", cta: "VER PROYECTO" },
      ],
    },
    cta: {
      q: "¿TIENES UN PROYECTO EN MENTE?",
      t1: "Hablemos sobre cómo",
      t2: "podemos ayudarte",
      btn: "CONTÁCTANOS",
    },
    foot: {
      desc: "Ingeniería sostenible, integral y de calidad.",
      h1: "ENLACES",
      h2: "SERVICIOS",
      h3: "CONTACTO",
      l1: ["Inicio", "Nosotros", "Servicios", "Proyectos", "Blog", "Contacto"],
      l2: ["Geomática y Geoinformación", "Estudios y Gestión Ambiental", "Monitoreo y Seguimiento", "Sistemas de Información (SIG)", "Consultoría y Gestión Integral", "Ingeniería y Diseño de Proyectos"],
      c: ["+57 304 620 5305", "info@enfoqueambiental.com.co", "Cartagena de Indias, Bolívar", "Colombia"],
      r: "© 2026 Enfoque Ambiental S.A.S. Todos los derechos reservados.",
      pp: "Política de privacidad",
      tc: "Términos y condiciones",
    },
  },
  en: {
    nav: [["HOME","#hero"],["SERVICES","servicios.html"],["PROJECTS","#proj"],["EXPERIENCE","#exp"],["BLOG","blog.html"],["CONTACT","#footer"]],
    hero: {
      t1: "SUSTAINABLE",
      t2: "ENGINEERING,",
      t3: "INTEGRAL",
      t4: "AND RIGOROUS",
      sub: "We deliver environmental and geospatial solutions grounded in data, technology and experience — for responsible decision-making and sustainable development.",
      cta: "EXPLORE OUR SERVICES",
    },
    serv: {
      kicker: "OUR SERVICES",
      title1: "Integral solutions for every stage",
      title2: "of your environmental and territorial projects",
      items: [
        { ic: "layers", n: "GEOMATICS &\nGEOINFORMATION", d: "Acquisition, processing and analysis of geospatial information with state-of-the-art technology." },
        { ic: "pin", n: "ENVIRONMENTAL\nSTUDIES", d: "Environmental impact studies and support with permits and licensing." },
        { ic: "leaf", n: "MONITORING &\nFOLLOW-UP", d: "Environmental, social and land monitoring with focus on quality, traceability and compliance." },
        { ic: "chart", n: "GIS\nSYSTEMS", d: "Design and implementation of GIS solutions for spatial analysis and data management." },
        { ic: "doc", n: "CONSULTING &\nINTEGRAL MANAGEMENT", d: "Technical and strategic support for environmental and territorial development projects." },
        { ic: "helmet", n: "ENGINEERING &\nPROJECT DESIGN", d: "Design and formulation of environmental projects and sustainable infrastructure." },
      ],
    },
    exp: {
      kicker: "OUR EXPERIENCE",
      title1: "Over 20 years building",
      title2: "trust and results that",
      title3: "leave a mark.",
      sub: "We have participated in more than 20 projects across Colombia in infrastructure, energy, oil & gas, mining, agribusiness and public sector.",
      stats: [
        { n: 24, suf: "+", l: "PROJECTS\nDELIVERED" },
        { n: 20, suf: "+", l: "YEARS OF\nEXPERIENCE" },
        { n: 3, suf: "+", l: "DEPARTMENTS\nCOVERED" },
        { n: 100, suf: "%", l: "COMMITMENT\n& QUALITY" },
      ],
    },
    proj: {
      kicker: "FEATURED PROJECTS",
      title1: "Our experience",
      title2: "in delivered projects",
      seeAll: "VIEW ALL PROJECTS →",
      countLbl: "",
      items: [
        { t: "Environmental Impact Study", s: "Road project · Colombia", k: "valley", cta: "VIEW PROJECT" },
        { t: "Drone Environmental Monitoring", s: "Closure follow-up · Santander", k: "drone", cta: "VIEW PROJECT" },
        { t: "LiDAR Geospatial Survey", s: "Elevation model generation", k: "lidar", cta: "VIEW PROJECT" },
        { t: "Environmental Permitting", s: "Licensing & environmental permits", k: "landfill", cta: "VIEW PROJECT" },
      ],
    },
    cta: { q: "HAVE A PROJECT IN MIND?", t1: "Let's talk about how", t2: "we can help you", btn: "GET IN TOUCH" },
    foot: {
      desc: "Sustainable engineering, integral and rigorous.",
      h1: "LINKS", h2: "SERVICES", h3: "CONTACT",
      l1: ["Home", "About", "Services", "Projects", "Blog", "Contact"],
      l2: ["Geomatics & Geoinformation", "Environmental Studies", "Monitoring & Follow-up", "GIS Systems", "Integral Consulting", "Engineering & Project Design"],
      c: ["+57 304 620 5305", "info@enfoqueambiental.com.co", "Cartagena de Indias, Bolívar", "Colombia"],
      r: "© 2026 Enfoque Ambiental S.A.S. All rights reserved.",
      pp: "Privacy policy", tc: "Terms & conditions",
    },
  },
};

// ===================== Service icons =====================
function Icon({ kind, size = 44, color = "#0B1D2E", accent = "#4CAF50" }) {
  const s = size;
  if (kind === "layers") return (
    <svg viewBox="0 0 50 50" width={s} height={s} fill="none" stroke={color} strokeWidth="2">
      <path d="M 25 6 L 44 16 L 25 26 L 6 16 Z" fill={accent} fillOpacity="0.2"/>
      <path d="M 25 18 L 44 28 L 25 38 L 6 28 Z" stroke={accent}/>
      <path d="M 25 30 L 44 40 L 25 44 Q 25 44 6 40 L 25 30 Z"/>
    </svg>
  );
  if (kind === "pin") return (
    <svg viewBox="0 0 50 50" width={s} height={s} fill="none" stroke={color} strokeWidth="2">
      <path d="M 25 6 C 17 6 11 12 11 20 C 11 30 25 44 25 44 C 25 44 39 30 39 20 C 39 12 33 6 25 6 Z"/>
      <circle cx="25" cy="20" r="5" stroke={accent}/>
    </svg>
  );
  if (kind === "leaf") return (
    <svg viewBox="0 0 50 50" width={s} height={s} fill="none" stroke={color} strokeWidth="2">
      <path d="M 10 40 C 10 24 24 10 40 10 C 40 26 26 40 10 40 Z"/>
      <path d="M 10 40 L 30 20" stroke={accent}/>
    </svg>
  );
  if (kind === "chart") return (
    <svg viewBox="0 0 50 50" width={s} height={s} fill="none" stroke={color} strokeWidth="2">
      <line x1="6" y1="44" x2="44" y2="44"/>
      <rect x="10" y="28" width="6" height="16"/>
      <rect x="20" y="20" width="6" height="24" stroke={accent}/>
      <rect x="30" y="12" width="6" height="32"/>
    </svg>
  );
  if (kind === "doc") return (
    <svg viewBox="0 0 50 50" width={s} height={s} fill="none" stroke={color} strokeWidth="2">
      <path d="M 12 6 L 32 6 L 40 14 L 40 44 L 12 44 Z"/>
      <path d="M 32 6 L 32 14 L 40 14"/>
      <line x1="18" y1="22" x2="34" y2="22" stroke={accent}/>
      <line x1="18" y1="28" x2="34" y2="28"/>
      <line x1="18" y1="34" x2="28" y2="34"/>
    </svg>
  );
  if (kind === "helmet") return (
    <svg viewBox="0 0 50 50" width={s} height={s} fill="none" stroke={color} strokeWidth="2">
      <path d="M 8 32 C 8 22 15 14 25 14 C 35 14 42 22 42 32 L 42 36 L 8 36 Z"/>
      <line x1="8" y1="36" x2="42" y2="36"/>
      <path d="M 25 14 L 25 22" stroke={accent}/>
      <path d="M 18 16 L 18 28 M 32 16 L 32 28"/>
    </svg>
  );
  return null;
}

// ===================== Hero scenery =====================
function HeroScene() {
  return <img src="img/hero.jpg" className="ea-hero-photo" alt="Relleno Sanitario Loma de los Cocos — Enfoque Ambiental S.A.S"/>;
}

// ===================== NAV =====================
function Nav({ t, lang, setLang }) {
  const [active, setActive] = uS(0);
  const [open, setOpen] = uS(false);
  return (
    <nav className="ea-nav">
      <div className="ea-nav-inner">
        <window.LogoFull width={170}/>
        <div className={`ea-nav-mid ${open ? "ea-nav-open" : ""}`}>
          {t.nav.map((n, i) => (
            <a key={i} href={n[1]} className={i === active ? "active" : ""} onClick={() => { setActive(i); setOpen(false); }}>
              {n[0]}
            </a>
          ))}
        </div>
        <div style={{display:"flex",gap:12,alignItems:"center"}}>
          <button className="ea-lang" onClick={() => setLang(lang === "es" ? "en" : "es")}>
            <span className={lang === "es" ? "act" : ""}>ES</span>
            <span className="sl">/</span>
            <span className={lang === "en" ? "act" : ""}>EN</span>
          </button>
          <button className="ea-hamburger" onClick={() => setOpen(!open)} aria-label="Menú">
            <span/><span/><span/>
          </button>
        </div>
      </div>
      {open && (
        <div className="ea-nav-mobile">
          {t.nav.map((n, i) => (
            <a key={i} href={n[1]} onClick={() => setOpen(false)}>{n[0]}</a>
          ))}
        </div>
      )}
    </nav>
  );
}

// ===================== HERO =====================
function Hero({ t }) {
  const y = useScroll();
  return (
    <section className="ea-hero" id="hero">
      <img
        src="img/hero.jpg"
        className="ea-hero-bg"
        alt="Relleno Sanitario Loma de los Cocos"
        style={{ transform: `translateY(${y * 0.12}px)` }}
      />
      <div className="ea-hero-overlay"/>
      <div className="ea-hero-content">
        <div className="ea-hero-side-bar"/>
        <div className="ea-hero-text">
          <h1>
            <span>{t.hero.t1}</span><br/>
            <span>{t.hero.t2}</span><br/>
            <span className="green">{t.hero.t3}</span><br/>
            <span className="green">{t.hero.t4}</span>
          </h1>
          <p>{t.hero.sub}</p>
          <a href="#serv" className="ea-btn ea-btn-hero">
            {t.hero.cta} <span className="ea-arrow">→</span>
          </a>
        </div>
      </div>
    </section>
  );
}

// ===================== SERVICES =====================
function Services({ t }) {
  return (
    <section className="ea-serv" id="serv">
      <div className="ea-serv-head">
        <div className="ea-kicker green-kicker">{t.serv.kicker}</div>
        <h2>{t.serv.title1}<br/>{t.serv.title2}</h2>
      </div>
      <div className="ea-serv-grid">
        {t.serv.items.map((it, i) => (
          <div key={i} className="ea-serv-card">
            <div className="ea-serv-ic">
              <Icon kind={it.ic} size={48}/>
            </div>
            <h3>{it.n.split("\n").map((l, j) => <span key={j}>{l}<br/></span>)}</h3>
            <p>{it.d}</p>
          </div>
        ))}
      </div>
    </section>
  );
}

// ===================== EXPERIENCE (dark) =====================
function Experience({ t }) {
  return (
    <section className="ea-exp" id="exp">
      <div className="ea-exp-grid">
        <div className="ea-exp-text">
          <div className="ea-kicker green-kicker">{t.exp.kicker}</div>
          <h2>{t.exp.title1}<br/>{t.exp.title2}<br/>{t.exp.title3}</h2>
          <p>{t.exp.sub}</p>
        </div>
        <div className="ea-exp-stats">
          {t.exp.stats.map((s, i) => (
            <div key={i} className="ea-exp-stat">
              <div className="ea-exp-stat-ic">
                {i === 0 && <svg viewBox="0 0 40 40" width="40" height="40" fill="none" stroke="#4CAF50" strokeWidth="1.8"><circle cx="14" cy="14" r="5"/><circle cx="28" cy="14" r="5"/><path d="M 6 32 C 6 26 10 22 14 22 C 18 22 22 26 22 32"/><path d="M 20 32 C 20 26 24 22 28 22 C 32 22 36 26 36 32"/></svg>}
                {i === 1 && <svg viewBox="0 0 40 40" width="40" height="40" fill="none" stroke="#4CAF50" strokeWidth="1.8"><rect x="8" y="14" width="24" height="20" rx="1"/><path d="M 14 14 L 14 10 L 26 10 L 26 14"/><line x1="8" y1="22" x2="32" y2="22"/></svg>}
                {i === 2 && <svg viewBox="0 0 40 40" width="40" height="40" fill="none" stroke="#4CAF50" strokeWidth="1.8"><path d="M 20 6 C 13 6 8 11 8 18 C 8 26 20 36 20 36 C 20 36 32 26 32 18 C 32 11 27 6 20 6 Z"/><circle cx="20" cy="18" r="4"/></svg>}
                {i === 3 && <svg viewBox="0 0 40 40" width="40" height="40" fill="none" stroke="#4CAF50" strokeWidth="1.8"><circle cx="20" cy="16" r="9"/><path d="M 14 24 L 12 36 L 20 32 L 28 36 L 26 24"/></svg>}
              </div>
              <div className="ea-exp-stat-num">+<CountUp to={s.n}/>{s.suf === "%" ? "%" : ""}</div>
              <div className="ea-exp-stat-l">{s.l.split("\n").map((l, j) => <span key={j}>{l}<br/></span>)}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ===================== PROJECTS carousel =====================
const RUP_PROJECTS = [
  { proj: "Levantamiento ortofotogramétrico del relleno sanitario Loma de los Cocos", entity: "CARIBE VERDE S.A. E.S.P.", date: "Feb 2026", cat: "Geomática" },
  { proj: "Interventoría técnica, ambiental, administrativa, jurídica y financiera para los estudios y diseños del relleno sanitario regional de la subregión sur, en el municipio de El Banco, Magdalena", entity: "AGUAS DEL MAGDALENA S.A. E.S.P.", date: "2025", cat: "Interventoría" },
  { proj: "Actualización del PGIRS, Plan de emergencia y contingencia de acueducto y alcantarillado y PUEAA del municipio de Ariguaní", entity: "Municipio de Ariguaní, Magdalena", date: "2020", cat: "PGIRS" },
  { proj: "Rehabilitación de acueductos rurales, lavado y desinfección de tanques y redes en el municipio de María La Baja", entity: "Municipio de María La Baja, Bolívar", date: "2019", cat: "Acueductos" },
  { proj: "Interventoría a la construcción del relleno sanitario regional de Bosconia, Cesar", entity: "Aguas del Cesar S.A. E.S.P.", date: "2016", cat: "Interventoría" },
  { proj: "Actualización del PGIRS del municipio de Barranco de Loba", entity: "Municipio de Barranco de Loba, Bolívar", date: "2016", cat: "PGIRS" },
  { proj: "Diagnóstico del acueducto, lavado y desinfección de redes del municipio de Barranco de Loba", entity: "Municipio de Barranco de Loba, Bolívar", date: "2016", cat: "Acueductos" },
  { proj: "Actualización del PGIRS del municipio de Becerril", entity: "Municipio de Becerril, Cesar", date: "2015", cat: "PGIRS" },
  { proj: "Actualización del PGIRS del municipio de Arjona", entity: "Municipio de Arjona, Bolívar", date: "2015", cat: "PGIRS" },
  { proj: "Diseños y Estudio de Impacto Ambiental del relleno sanitario de Becerril, Cesar", entity: "Municipio de Becerril, Cesar", date: "2014", cat: "EIA" },
  { proj: "Actualización del PGIRS del Distrito Turístico y Cultural de Cartagena de Indias", entity: "D.T. y C. Cartagena de Indias", date: "2014", cat: "PGIRS" },
  { proj: "Diseño y estudio de relleno sanitario para Bioger Colombia", entity: "Bioger Colombia S.A. E.S.P.", date: "2013", cat: "Diseño" },
  { proj: "Interventoría a la construcción del relleno sanitario regional de San Jacinto, Bolívar", entity: "Municipio de San Jacinto, Bolívar", date: "2012", cat: "Interventoría" },
  { proj: "Diseño del relleno sanitario regional de San Jacinto, Bolívar y elaboración del Estudio de Impacto Ambiental", entity: "Municipio de San Jacinto, Bolívar", date: "2011", cat: "EIA" },
  { proj: "Seguimiento y control a los factores de riesgo en salud y medio ambiente (acueductos, residuos sólidos, alcantarillados y residuos hospitalarios) en el Departamento de Bolívar", entity: "Departamento de Bolívar", date: "2009", cat: "Monitoreo" },
  { proj: "Seguimiento y control a los factores de riesgo en salud y medio ambiente (acueductos, residuos sólidos, alcantarillados y residuos hospitalarios) en el Departamento de Bolívar", entity: "Departamento de Bolívar", date: "2008", cat: "Monitoreo" },
  { proj: "Seguimiento y control a los factores de riesgo en salud y medio ambiente (acueductos, residuos sólidos, alcantarillados y residuos hospitalarios) en el Departamento de Bolívar", entity: "Departamento de Bolívar", date: "2007", cat: "Monitoreo" },
  { proj: "Interventoría al servicio integral de aseo del Distrito de Cartagena de Indias", entity: "Alcaldía Mayor de Cartagena", date: "2006", cat: "Interventoría" },
  { proj: "Seguimiento y control a los factores de riesgo en salud y medio ambiente en el Departamento de Bolívar", entity: "Departamento de Bolívar", date: "2004", cat: "Monitoreo" },
  { proj: "Educación comunitaria y control del dengue en el Departamento de Bolívar", entity: "Departamento de Bolívar", date: "2003", cat: "Salud pública" },
  { proj: "Elaboración del PGIRSH de la ESE Hospital Local Cartagena de Indias", entity: "ESE Hospital Local Cartagena de Indias", date: "2003", cat: "PGIRSH" },
  { proj: "Elaboración del PGIRSH de la ESE Hospital Local de San Jacinto, Bolívar", entity: "ESE Hospital Local de San Jacinto, Bolívar", date: "2003", cat: "PGIRSH" },
];

function ProjectChip({ p }) {
  return (
    <div className="ea-mq-card">
      <div className="ea-mq-top">
        <span className="ea-mq-cat">{p.cat}</span>
        <span className="ea-mq-date">{p.date}</span>
      </div>
      <h4>{p.proj}</h4>
      <div className="ea-mq-entity">
        <span className="ea-mq-pin">●</span>{p.entity}
      </div>
    </div>
  );
}

function MarqueeTrack({ items, direction }) {
  const wrapRef = uR(null);
  const trackRef = uR(null);
  const stateRef = uR({ pos: null, dragging: false, lastX: 0, halfW: 0, raf: null });

  uE(() => {
    const wrap = wrapRef.current;
    const track = trackRef.current;
    const s = stateRef.current;
    const speed = 0.7;

    s.halfW = track.scrollWidth / 2;
    s.pos = direction === 'right' ? -s.halfW : 0;

    const tick = () => {
      if (!s.dragging) {
        s.pos += direction === 'left' ? -speed : speed;
        if (direction === 'left' && s.pos <= -s.halfW) s.pos += s.halfW;
        if (direction === 'right' && s.pos >= 0) s.pos -= s.halfW;
      }
      track.style.transform = `translate3d(${s.pos}px,0,0)`;
      s.raf = requestAnimationFrame(tick);
    };
    s.raf = requestAnimationFrame(tick);

    const onStart = (x) => { s.dragging = true; s.lastX = x; wrap.style.cursor = 'grabbing'; };
    const onMove = (x) => {
      if (!s.dragging) return;
      s.pos += x - s.lastX;
      s.lastX = x;
      if (s.pos <= -s.halfW) s.pos += s.halfW;
      if (s.pos > 0) s.pos -= s.halfW;
    };
    const onEnd = () => { s.dragging = false; wrap.style.cursor = 'grab'; };

    const onMD = (e) => { e.preventDefault(); onStart(e.clientX); };
    const onMM = (e) => onMove(e.clientX);
    const onTS = (e) => onStart(e.touches[0].clientX);
    const onTM = (e) => { e.preventDefault(); onMove(e.touches[0].clientX); };

    wrap.addEventListener('mousedown', onMD);
    window.addEventListener('mousemove', onMM);
    window.addEventListener('mouseup', onEnd);
    wrap.addEventListener('touchstart', onTS, { passive: true });
    wrap.addEventListener('touchmove', onTM, { passive: false });
    wrap.addEventListener('touchend', onEnd);

    return () => {
      cancelAnimationFrame(s.raf);
      wrap.removeEventListener('mousedown', onMD);
      window.removeEventListener('mousemove', onMM);
      window.removeEventListener('mouseup', onEnd);
      wrap.removeEventListener('touchstart', onTS);
      wrap.removeEventListener('touchmove', onTM);
      wrap.removeEventListener('touchend', onEnd);
    };
  }, [direction]);

  return (
    <div ref={wrapRef} className="ea-mq-wrap" style={{ cursor: 'grab' }}>
      <div ref={trackRef} className="ea-mq-track">
        {[...items, ...items].map((p, i) => <ProjectChip key={direction + i} p={p} />)}
      </div>
    </div>
  );
}

function Projects({ t }) {
  const half = Math.ceil(RUP_PROJECTS.length / 2);
  const rowA = RUP_PROJECTS.slice(0, half);
  const rowB = RUP_PROJECTS.slice(half);
  return (
    <section className="ea-proj" id="proj">
      <div className="ea-proj-head">
        <div>
          <div className="ea-kicker">{t.proj.kicker}</div>
          <h2>{t.proj.title1}<br/>{t.proj.title2}</h2>
        </div>
      </div>
      <MarqueeTrack items={rowA} direction="left" />
      <MarqueeTrack items={rowB} direction="right" />
    </section>
  );
}

// ===================== GEOPORTAL =====================
const GEO_PROJECTS = [
  { name: "Relleno Sanitario Loma de los Cocos", entity: "CARIBE VERDE S.A. E.S.P.", lat: 10.42, lng: -75.54, cat: "Geomática", date: "2026", desc: "Levantamiento ortofotogramétrico del relleno sanitario con drones." },
  { name: "Relleno Regional El Banco", entity: "AGUAS DEL MAGDALENA S.A. E.S.P.", lat: 9.0025, lng: -73.9735, cat: "Interventoría", date: "2025", desc: "Interventoría técnica, ambiental, administrativa y financiera para estudios y diseños del relleno sanitario regional." },
  { name: "PGIRS Ariguaní", entity: "Municipio de Ariguaní, Magdalena", lat: 9.85, lng: -74.08, cat: "PGIRS", date: "2020", desc: "Actualización del PGIRS, plan de emergencia y contingencia de acueducto y PUEAA." },
  { name: "Acueductos Rurales María La Baja", entity: "Municipio de María La Baja, Bolívar", lat: 9.9875, lng: -75.3186, cat: "Acueductos", date: "2019", desc: "Rehabilitación de acueductos rurales, lavado y desinfección de tanques y redes." },
  { name: "Relleno Regional Bosconia", entity: "Aguas del Cesar S.A. E.S.P.", lat: 9.9783, lng: -73.8833, cat: "Interventoría", date: "2016", desc: "Interventoría a la construcción del relleno sanitario regional de Bosconia, Cesar." },
  { name: "PGIRS Barranco de Loba", entity: "Municipio de Barranco de Loba, Bolívar", lat: 8.9411, lng: -74.1211, cat: "PGIRS", date: "2016", desc: "Actualización del PGIRS del municipio." },
  { name: "Diagnóstico Acueducto Barranco de Loba", entity: "Municipio de Barranco de Loba, Bolívar", lat: 8.95, lng: -74.13, cat: "Acueductos", date: "2016", desc: "Diagnóstico del acueducto, lavado y desinfección de redes." },
  { name: "PGIRS Becerril", entity: "Municipio de Becerril, Cesar", lat: 9.7025, lng: -73.2736, cat: "PGIRS", date: "2015", desc: "Actualización del PGIRS del municipio de Becerril." },
  { name: "PGIRS Arjona", entity: "Municipio de Arjona, Bolívar", lat: 10.2433, lng: -75.3386, cat: "PGIRS", date: "2015", desc: "Actualización del PGIRS del municipio de Arjona." },
  { name: "EIA Relleno Becerril", entity: "Municipio de Becerril, Cesar", lat: 9.72, lng: -73.26, cat: "EIA", date: "2014", desc: "Diseños y Estudio de Impacto Ambiental del relleno sanitario." },
  { name: "PGIRS Cartagena de Indias", entity: "D.T. y C. Cartagena de Indias", lat: 10.3910, lng: -75.4794, cat: "PGIRS", date: "2014", desc: "Actualización del PGIRS del Distrito Turístico y Cultural de Cartagena." },
  { name: "Relleno Bioger Colombia", entity: "Bioger Colombia S.A. E.S.P.", lat: 10.35, lng: -75.50, cat: "Diseño", date: "2013", desc: "Diseño y estudio de relleno sanitario." },
  { name: "Relleno Regional San Jacinto", entity: "Municipio de San Jacinto, Bolívar", lat: 9.9761, lng: -75.1233, cat: "Interventoría", date: "2012", desc: "Interventoría a la construcción del relleno sanitario regional." },
  { name: "EIA Relleno San Jacinto", entity: "Municipio de San Jacinto, Bolívar", lat: 9.98, lng: -75.12, cat: "EIA", date: "2011", desc: "Diseño del relleno sanitario regional y elaboración del Estudio de Impacto Ambiental." },
  { name: "Monitoreo Ambiental Bolívar", entity: "Departamento de Bolívar", lat: 9.20, lng: -74.70, cat: "Monitoreo", date: "2004–2009", desc: "Seguimiento y control a factores de riesgo en salud y medio ambiente: acueductos, residuos sólidos, alcantarillados y residuos hospitalarios." },
  { name: "Interventoría Aseo Cartagena", entity: "Alcaldía Mayor de Cartagena", lat: 10.40, lng: -75.48, cat: "Interventoría", date: "2006", desc: "Interventoría al servicio integral de aseo del Distrito de Cartagena de Indias." },
  { name: "Control Dengue Bolívar", entity: "Departamento de Bolívar", lat: 9.10, lng: -74.60, cat: "Salud pública", date: "2003", desc: "Educación comunitaria y control del dengue en el Departamento de Bolívar." },
  { name: "PGIRSH Hospital Cartagena", entity: "ESE Hospital Local Cartagena de Indias", lat: 10.41, lng: -75.50, cat: "PGIRSH", date: "2003", desc: "Elaboración del PGIRSH del hospital local." },
  { name: "PGIRSH Hospital San Jacinto", entity: "ESE Hospital Local de San Jacinto, Bolívar", lat: 9.96, lng: -75.11, cat: "PGIRSH", date: "2003", desc: "Elaboración del PGIRSH del hospital local." },
];

const CAT_COLORS = {
  "Geomática":   "#4CAF50",
  "Interventoría":"#2196F3",
  "PGIRS":       "#FF9800",
  "Monitoreo":   "#9C27B0",
  "Acueductos":  "#00BCD4",
  "EIA":         "#F44336",
  "Diseño":      "#FF5722",
  "PGIRSH":      "#8D6E63",
  "Salud pública":"#E91E63",
};

function GeoPortal() {
  const mapRef = uR(null);
  const leafletMap = uR(null);
  const markersRef = uR([]);
  const [filter, setFilter] = uS("Todos");
  const [active, setActive] = uS(null);

  uE(() => {
    if (leafletMap.current || !window.L) return;
    const map = window.L.map(mapRef.current, {
      center: [9.5, -74.5], zoom: 6,
      zoomControl: true, scrollWheelZoom: false,
    });
    window.L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
      attribution: '© <a href="https://www.openstreetmap.org/copyright">OSM</a> © <a href="https://carto.com/">CARTO</a>',
      maxZoom: 18,
    }).addTo(map);

    GEO_PROJECTS.forEach((p) => {
      const color = CAT_COLORS[p.cat] || "#4CAF50";
      const icon = window.L.divIcon({
        className: '',
        html: `<div class="geo-marker" style="background:${color};border-color:${color}40"></div>`,
        iconSize: [14, 14], iconAnchor: [7, 7],
      });
      const marker = window.L.marker([p.lat, p.lng], { icon })
        .addTo(map)
        .on('click', () => setActive(p));
      markersRef.current.push({ marker, cat: p.cat });
    });
    leafletMap.current = map;
  }, []);

  uE(() => {
    markersRef.current.forEach(({ marker, cat }) => {
      const el = marker.getElement();
      if (el) el.style.opacity = (filter === "Todos" || cat === filter) ? "1" : "0.12";
    });
  }, [filter]);

  const count = filter === "Todos" ? GEO_PROJECTS.length : GEO_PROJECTS.filter(p => p.cat === filter).length;

  return (
    <section className="ea-geo">
      <div className="ea-geo-head">
        <div>
          <div className="ea-kicker green-kicker">GEOPORTAL INTERACTIVO</div>
          <h2>Nuestra huella en el territorio</h2>
          <p>Más de 20 años de proyectos ejecutados en Colombia. Explora nuestra cobertura geográfica.</p>
        </div>
        <div className="ea-geo-counter">
          <span className="ea-geo-counter-n">{count}</span>
          <span className="ea-geo-counter-l">proyecto{count !== 1 ? "s" : ""}{filter !== "Todos" ? ` · ${filter}` : ""}</span>
        </div>
      </div>

      <div className="ea-geo-filters">
        {["Todos", ...Object.keys(CAT_COLORS)].map(c => (
          <button
            key={c}
            className={`ea-geo-pill${filter === c ? " active" : ""}`}
            style={filter === c && c !== "Todos" ? { background: CAT_COLORS[c] + "22", borderColor: CAT_COLORS[c], color: "#fff" } : {}}
            onClick={() => setFilter(c)}
          >
            {c !== "Todos" && <span className="ea-geo-dot" style={{ background: CAT_COLORS[c] }}/>}
            {c}
          </button>
        ))}
      </div>

      <div className="ea-geo-body">
        <div ref={mapRef} className="ea-geo-map"/>
        <div className="ea-geo-panel">
          {active ? (
            <>
              <button className="ea-geo-close" onClick={() => setActive(null)}>×</button>
              <span className="ea-geo-panel-cat" style={{ color: CAT_COLORS[active.cat] || "#4CAF50" }}>{active.cat}</span>
              <h3>{active.name}</h3>
              <p>{active.desc}</p>
              <div className="ea-geo-meta">
                <div><span>ENTIDAD</span>{active.entity}</div>
                <div><span>AÑO</span>{active.date}</div>
              </div>
            </>
          ) : (
            <>
              <p className="ea-geo-legend-title">CATEGORÍAS</p>
              {Object.entries(CAT_COLORS).map(([cat, color]) => (
                <button key={cat} className={`ea-geo-leg-row${filter === cat ? " sel" : ""}`} onClick={() => setFilter(filter === cat ? "Todos" : cat)}>
                  <span className="ea-geo-leg-dot" style={{ background: color }}/>
                  <span>{cat}</span>
                  <span className="ea-geo-leg-count">{GEO_PROJECTS.filter(p => p.cat === cat).length}</span>
                </button>
              ))}
              <p className="ea-geo-hint">Selecciona un marcador para ver detalles</p>
            </>
          )}
        </div>
      </div>
    </section>
  );
}

// ===================== CTA strip =====================
function CtaStrip({ t }) {
  return (
    <section className="ea-cta">
      <div className="ea-cta-text">
        <div className="ea-kicker green-kicker">{t.cta.q}</div>
        <h2>{t.cta.t1}<br/>{t.cta.t2}</h2>
        <a href="#footer" className="ea-btn ea-btn-dark">{t.cta.btn} <span className="ea-arrow">→</span></a>
      </div>
    </section>
  );
}

// ===================== FOOTER =====================
function Footer({ t, lang, setLang }) {
  return (
    <footer className="ea-foot" id="footer">
      <div className="ea-foot-grid">
        <div>
          <window.LogoFull width={200} dark/>
          <p className="ea-foot-desc">{t.foot.desc}</p>
          <div className="ea-foot-social">
            <span><svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M19 3H5C3.9 3 3 3.9 3 5v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM8.6 18.3H6V10h2.6v8.3zm-1.3-9.4c-.8 0-1.5-.7-1.5-1.5s.7-1.5 1.5-1.5 1.5.7 1.5 1.5-.7 1.5-1.5 1.5zM18.3 18.3h-2.6v-4.5c0-1.1-.4-1.8-1.4-1.8-.8 0-1.2.5-1.4 1-.1.2-.1.4-.1.7v4.6h-2.6V10h2.6v1.1c.3-.5 1-1.3 2.4-1.3 1.8 0 3.1 1.2 3.1 3.6v4.9z"/></svg></span>
            <span><svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M12 2.2c3.2 0 3.6 0 4.8.1 1.2.1 1.8.2 2.2.4.6.2 1 .5 1.4.9.4.4.7.8.9 1.4.2.4.4 1 .4 2.2.1 1.2.1 1.6.1 4.8s0 3.6-.1 4.8c-.1 1.2-.2 1.8-.4 2.2-.2.6-.5 1-.9 1.4-.4.4-.8.7-1.4.9-.4.2-1 .4-2.2.4-1.2.1-1.6.1-4.8.1s-3.6 0-4.8-.1c-1.2-.1-1.8-.2-2.2-.4-.6-.2-1-.5-1.4-.9-.4-.4-.7-.8-.9-1.4-.2-.4-.4-1-.4-2.2C2.2 15.6 2.2 15.2 2.2 12s0-3.6.1-4.8c.1-1.2.2-1.8.4-2.2.2-.6.5-1 .9-1.4.4-.4.8-.7 1.4-.9.4-.2 1-.4 2.2-.4C8.4 2.2 8.8 2.2 12 2.2zm0 1.8c-3.2 0-3.5 0-4.7.1-1.1 0-1.7.2-2.1.4-.5.2-.9.4-1.3.8-.4.4-.6.8-.8 1.3-.1.4-.3 1-.4 2.1-.1 1.2-.1 1.5-.1 4.7s0 3.5.1 4.7c0 1.1.2 1.7.4 2.1.2.5.4.9.8 1.3.4.4.8.6 1.3.8.4.1 1 .3 2.1.4 1.2.1 1.5.1 4.7.1s3.5 0 4.7-.1c1.1 0 1.7-.2 2.1-.4.5-.2.9-.4 1.3-.8.4-.4.6-.8.8-1.3.1-.4.3-1 .4-2.1.1-1.2.1-1.5.1-4.7s0-3.5-.1-4.7c0-1.1-.2-1.7-.4-2.1-.2-.5-.4-.9-.8-1.3-.4-.4-.8-.6-1.3-.8-.4-.1-1-.3-2.1-.4-1.2-.1-1.5-.1-4.7-.1zm0 3.1c2.7 0 4.9 2.2 4.9 4.9s-2.2 4.9-4.9 4.9-4.9-2.2-4.9-4.9 2.2-4.9 4.9-4.9zm0 8.1c1.8 0 3.2-1.4 3.2-3.2s-1.4-3.2-3.2-3.2-3.2 1.4-3.2 3.2 1.4 3.2 3.2 3.2zm5.1-8.3c-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1 1.1.5 1.1 1.1-.5 1.1-1.1 1.1z"/></svg></span>
          </div>
        </div>
        <div>
          <h5>{t.foot.h1}</h5>
          {t.foot.l1.map((l, i) => <a key={i} href={["#hero","#exp","servicios.html","#proj","blog.html","#footer"][i] || "#"}>{l}</a>)}
        </div>
        <div>
          <h5>{t.foot.h2}</h5>
          {t.foot.l2.map((l, i) => <a key={i} href={["servicio-geomatica.html","servicio-estudios-ambientales.html","servicio-monitoreo.html","servicio-sig.html","servicio-consultoria.html","servicio-ingenieria.html"][i] || "#"}>{l}</a>)}
        </div>
        <div>
          <h5>{t.foot.h3}</h5>
          <div className="ea-foot-c"><span className="ea-foot-ic">📞</span><a href="tel:+573046205305" style={{color:"inherit"}}>{t.foot.c[0]}</a></div>
          <div className="ea-foot-c"><span className="ea-foot-ic">✉</span><a href="mailto:info@enfoqueambiental.com.co" style={{color:"inherit"}}>{t.foot.c[1]}</a></div>
          <div className="ea-foot-c"><span className="ea-foot-ic">📍</span>{t.foot.c[2]}<br/><span className="dim">{t.foot.c[3]}</span></div>
          <div className="ea-foot-c"><span className="ea-foot-ic">💬</span><a href="https://wa.me/573046205305" target="_blank" rel="noopener" style={{color:"inherit"}}>WhatsApp</a></div>
        </div>
      </div>
      <div className="ea-foot-bottom">
        <span>{t.foot.r}</span>
        <span><a href="#">{t.foot.pp}</a> · <a href="#">{t.foot.tc}</a></span>
      </div>
    </footer>
  );
}

// ===================== APP =====================
function EnfoqueApp() {
  const [lang, setLang] = uS("es");
  const t = T[lang];
  return (
    <div className="ea-root">
      <Nav t={t} lang={lang} setLang={setLang}/>
      <Hero t={t}/>
      <Services t={t}/>
      <Experience t={t}/>
      <Projects t={t}/>
      <GeoPortal/>
      <CtaStrip t={t}/>
      <Footer t={t} lang={lang} setLang={setLang}/>
      <a href="https://wa.me/573046205305" target="_blank" rel="noopener" className="wa-float" aria-label="WhatsApp">
        <svg viewBox="0 0 24 24" width="28" height="28" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1-.2.3-.7.9-.9 1.1-.2.2-.3.2-.6.1-.3-.2-1.2-.5-2.4-1.5-.9-.8-1.5-1.8-1.7-2.1-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5-.1-.1-.7-1.6-.9-2.2-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1.1 2.9 1.2 3.1c.2.2 2.1 3.2 5.1 4.5 2.5 1.1 3 .9 3.5.8.5-.1 1.7-.7 1.9-1.4.2-.7.2-1.2.2-1.4-.1-.2-.3-.3-.5-.4zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.4 1.3 4.9L2 22l5.3-1.4c1.4.8 3 1.2 4.7 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2z"/></svg>
      </a>
    </div>
  );
}

window.EnfoqueApp = EnfoqueApp;
