// Componentes compartidos: nav, footer, datos de empresa
const COMPANY = {
  name: "Enfoque Ambiental S.A.S.",
  phone: "+57 302 472 8989",
  phoneHref: "tel:+573024728989",
  whatsapp: "https://wa.me/573024728989",
  email: "contacto@enfoqueambiental.com.co",
  emailHref: "mailto:contacto@enfoqueambiental.com.co",
  city: "Cartagena de Indias, Bolívar — Colombia",
  address: "Cartagena de Indias, Bolívar",
  domain: "https://enfoqueambiental.com.co",
  privacyUrl: "/politica-privacidad",
  termsUrl: "/terminos-condiciones",
  contactUrl: "/contacto",
};

const SERVICES = [
  { slug: "geomatica", ic: "layers",
    name: "Geomática y Geoinformación",
    short: "Levantamiento, procesamiento y análisis geoespacial con drones, GPS RTK y LiDAR.",
  },
  { slug: "estudios-ambientales", ic: "pin",
    name: "Estudios y Gestión Ambiental",
    short: "Estudios de impacto ambiental, planes de manejo y trámites de licenciamiento.",
  },
  { slug: "monitoreo", ic: "leaf",
    name: "Monitoreo y Seguimiento",
    short: "Monitoreo ambiental, social y predial con trazabilidad y cumplimiento normativo.",
  },
  { slug: "sig", ic: "chart",
    name: "Sistemas de Información SIG",
    short: "Diseño e implementación de soluciones SIG para análisis espacial y gestión de datos.",
  },
  { slug: "consultoria", ic: "doc",
    name: "Consultoría y Gestión Integral",
    short: "Acompañamiento técnico y estratégico en proyectos ambientales y territoriales.",
  },
  { slug: "ingenieria", ic: "helmet",
    name: "Ingeniería y Diseño de Proyectos",
    short: "Diseño y formulación de proyectos ambientales e infraestructura sostenible.",
  },
];

function NavBar({ active = "home" }) {
  const [open, setOpen] = React.useState(false);
  const items = [
    { k: "home", l: "INICIO", h: "/" },
    { k: "services", l: "SERVICIOS", h: "/servicios" },
    { k: "blog", l: "BLOG", h: "/blog" },
    { k: "contact", l: "CONTACTO", h: "/contacto" },
  ];
  const openContact = () => {
    setOpen(false);
    window.openContactModal?.({ source: "nav" });
  };
  return (
    <nav className="ea-nav">
      <div className="ea-nav-inner">
        <a href="/"><img src="logo-full.png" alt="Enfoque Ambiental" style={{width:170, height:"auto", display:"block"}}/></a>
        <div className="ea-nav-mid">
          {items.map(n => (
            <a key={n.k} href={n.h} className={active === n.k ? "active" : ""}>{n.l}</a>
          ))}
        </div>
        <div style={{display:"flex",gap:12,alignItems:"center"}}>
          <button type="button" onClick={openContact} className="ea-btn ea-btn-dark ea-nav-phone" style={{padding:"10px 18px", fontSize:11, display:"flex", alignItems:"center", gap:8}}>
            COTIZAR <span className="ea-arrow">→</span>
          </button>
          <button className="ea-hamburger" onClick={() => setOpen(!open)} aria-label="Menú" aria-expanded={open} aria-controls="ea-nav-mobile">
            <span/><span/><span/>
          </button>
        </div>
      </div>
      {open && (
        <div className="ea-nav-mobile" id="ea-nav-mobile">
          {items.map(n => (
            <a key={n.k} href={n.h} onClick={() => setOpen(false)}>{n.l}</a>
          ))}
          <button type="button" onClick={openContact}>COTIZAR PROYECTO</button>
          <a href={COMPANY.phoneHref} onClick={() => setOpen(false)}>{COMPANY.phone}</a>
        </div>
      )}
    </nav>
  );
}

function FooterFull() {
  return (
    <footer className="ea-foot" id="footer">
      <div className="ea-foot-grid">
        <div>
          <img src="logo-negativo.png" alt="Enfoque Ambiental" style={{width:200, height:"auto", display:"block"}}/>
          <p className="ea-foot-desc">Ingeniería sostenible, integral y de calidad.</p>
          <div className="ea-foot-social">
            <a href={COMPANY.emailHref}><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></a>
            <a href={COMPANY.whatsapp} target="_blank" rel="noopener"><svg viewBox="0 0 24 24" width="16" height="16" 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>
        </div>
        <div>
          <h5>ENLACES</h5>
          <a href="/">Inicio</a>
          <a href="/servicios">Servicios</a>
          <a href="/#proj">Proyectos</a>
          <a href="/blog">Blog</a>
          <a href="/contacto">Contacto</a>
        </div>
        <div>
          <h5>SERVICIOS</h5>
          {SERVICES.map(s => (
            <a key={s.slug} href={`/servicio-${s.slug}`}>{s.name}</a>
          ))}
        </div>
        <div>
          <h5>CONTACTO</h5>
          <div className="ea-foot-c"><span className="ea-foot-ic">📞</span><a href={COMPANY.phoneHref}>{COMPANY.phone}</a></div>
          <div className="ea-foot-c"><span className="ea-foot-ic">✉</span><a href={COMPANY.emailHref}>{COMPANY.email}</a></div>
          <div className="ea-foot-c"><span className="ea-foot-ic">📍</span>{COMPANY.city}</div>
          <div className="ea-foot-c"><span className="ea-foot-ic">💬</span><a href={COMPANY.whatsapp} target="_blank" rel="noopener">WhatsApp</a></div>
        </div>
      </div>
      <div className="ea-foot-bottom">
        <span>© 2026 Enfoque Ambiental S.A.S. Todos los derechos reservados.</span>
        <span><a href={COMPANY.privacyUrl}>Política de privacidad</a> · <a href={COMPANY.termsUrl}>Términos y condiciones</a></span>
      </div>
    </footer>
  );
}

function buildContactMessage(data) {
  return [
    "Nueva solicitud desde el sitio web de Enfoque Ambiental",
    "",
    `Nombre: ${data.name || ""}`,
    `Empresa: ${data.company || "No indicada"}`,
    `Correo: ${data.email || ""}`,
    `Teléfono: ${data.phone || ""}`,
    `Servicio de interés: ${data.service || "No indicado"}`,
    `Origen: ${data.source || "Sitio web"}`,
    "",
    "Mensaje:",
    data.message || "",
  ].join("\n");
}

function ContactModal() {
  const initial = {
    name: "",
    company: "",
    email: "",
    phone: "",
    service: "",
    message: "",
    accepted: false,
    website: "",
    source: "Sitio web",
  };
  const [open, setOpen] = React.useState(false);
  const [form, setForm] = React.useState(initial);
  const [status, setStatus] = React.useState({ type: "idle", text: "" });

  React.useEffect(() => {
    window.openContactModal = (opts = {}) => {
      setForm({
        ...initial,
        service: opts.service || "",
        source: opts.source || "Sitio web",
        message: opts.message || "",
      });
      setStatus({ type: "idle", text: "" });
      setOpen(true);
    };
    return () => { delete window.openContactModal; };
  }, []);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (event) => {
      if (event.key === "Escape") setOpen(false);
    };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const setField = (field, value) => setForm((current) => ({ ...current, [field]: value }));
  const services = SERVICES.map((service) => service.name);
  const validate = () => {
    if (!form.name.trim() || !form.email.trim() || !form.message.trim()) return "Nombre, correo y mensaje son obligatorios.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) return "Escribe un correo válido.";
    if (!form.accepted) return "Debes aceptar la política de privacidad para enviar la solicitud.";
    return "";
  };

  const submit = async (event) => {
    event.preventDefault();
    const error = validate();
    if (error) {
      setStatus({ type: "error", text: error });
      return;
    }
    setStatus({ type: "loading", text: "Enviando solicitud..." });
    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const result = await response.json().catch(() => ({}));
      if (!response.ok || !result.ok) throw new Error(result.error || "No se pudo enviar el formulario.");
      setStatus({ type: "success", text: "Solicitud enviada. Te responderemos pronto." });
      setForm(initial);
    } catch (err) {
      setStatus({ type: "error", text: "No pudimos enviar el correo ahora. Puedes usar WhatsApp o intentarlo de nuevo." });
    }
  };

  const whatsappText = encodeURIComponent(buildContactMessage(form));
  if (!open) return null;

  return (
    <div className="ea-modal" role="dialog" aria-modal="true" aria-labelledby="ea-contact-title">
      <button className="ea-modal-backdrop" type="button" aria-label="Cerrar formulario" onClick={() => setOpen(false)} />
      <div className="ea-modal-panel">
        <button className="ea-modal-close" type="button" aria-label="Cerrar" onClick={() => setOpen(false)}>×</button>
        <div className="ea-kicker green-kicker">CONTACTO</div>
        <h2 id="ea-contact-title">Cuéntanos sobre tu proyecto</h2>
        <p>Recibiremos tu solicitud en {COMPANY.email}. También puedes continuar por WhatsApp si prefieres una respuesta rápida.</p>
        <form className="ea-contact-form" onSubmit={submit}>
          <input className="ea-hp" tabIndex="-1" autoComplete="off" value={form.website} onChange={(e) => setField("website", e.target.value)} aria-hidden="true" />
          <div className="ea-form-grid">
            <label>Nombre*<input required value={form.name} onChange={(e) => setField("name", e.target.value)} placeholder="Tu nombre" maxLength="120" /></label>
            <label>Empresa<input value={form.company} onChange={(e) => setField("company", e.target.value)} placeholder="Empresa o entidad" maxLength="140" /></label>
            <label>Correo*<input required type="email" value={form.email} onChange={(e) => setField("email", e.target.value)} placeholder="correo@empresa.com" maxLength="160" /></label>
            <label>Teléfono<input value={form.phone} onChange={(e) => setField("phone", e.target.value)} placeholder="+57 ..." maxLength="60" /></label>
          </div>
          <label>Servicio de interés
            <select value={form.service} onChange={(e) => setField("service", e.target.value)}>
              <option value="">Seleccionar servicio</option>
              {services.map((service) => <option key={service} value={service}>{service}</option>)}
            </select>
          </label>
          <label>Mensaje*<textarea required value={form.message} onChange={(e) => setField("message", e.target.value)} placeholder="Describe brevemente tu necesidad, ubicación y tiempos estimados." maxLength="2000" /></label>
          <label className="ea-check">
            <input type="checkbox" checked={form.accepted} onChange={(e) => setField("accepted", e.target.checked)} />
            <span>Acepto la <a href={COMPANY.privacyUrl} target="_blank" rel="noopener">política de privacidad</a> y el tratamiento de mis datos para responder esta solicitud.</span>
          </label>
          {status.text && <div className={`ea-form-status ${status.type}`}>{status.text}</div>}
          <div className="ea-form-actions">
            <button className="ea-btn ea-btn-green" type="submit" disabled={status.type === "loading"}>{status.type === "loading" ? "ENVIANDO..." : "ENVIAR SOLICITUD"} <span className="ea-arrow">→</span></button>
            <a className="ea-btn ea-btn-outline-dark" href={`${COMPANY.whatsapp}?text=${whatsappText}`} target="_blank" rel="noopener">WHATSAPP</a>
          </div>
        </form>
      </div>
    </div>
  );
}

function geoDistanceKm(a, b) {
  const R = 6371;
  const dLat = (b[0] - a[0]) * Math.PI / 180;
  const dLng = (b[1] - a[1]) * Math.PI / 180;
  const lat1 = a[0] * Math.PI / 180;
  const lat2 = b[0] * Math.PI / 180;
  const h = Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLng / 2) ** 2;
  return 2 * R * Math.atan2(Math.sqrt(h), Math.sqrt(1 - h));
}

function polygonAreaHa(latlngs) {
  if (!latlngs.length) return 0;
  const origin = latlngs[0];
  const xy = latlngs.map(([lat, lng]) => {
    const x = geoDistanceKm(origin, [origin[0], lng]) * (lng < origin[1] ? -1 : 1);
    const y = geoDistanceKm(origin, [lat, origin[1]]) * (lat < origin[0] ? -1 : 1);
    return [x, y];
  });
  let area = 0;
  for (let i = 0; i < xy.length; i++) {
    const [x1, y1] = xy[i];
    const [x2, y2] = xy[(i + 1) % xy.length];
    area += x1 * y2 - x2 * y1;
  }
  return Math.abs(area) * 50;
}

const TD_SITE = {
  name: "Parque Ambiental Loma de los Cocos",
  center: [10.27294, -75.48092],
  location: "Turbana / Via Mamonal - Gambote Km 23",
  totalHa: 63,
  disposalHa: 41.47,
  usedHa: 28.13,
  availableHa: 13.56,
};

const TD_PERIMETER = {
  id: "P-01",
  name: "Perimetro tecnico del predio",
  layer: "Predio",
  status: "Operacion",
  areaHa: 63,
  polygon: [
    [10.2807, -75.4867], [10.2816, -75.4783], [10.2762, -75.4717],
    [10.2675, -75.4729], [10.2639, -75.4812], [10.2691, -75.4889],
  ],
};

const TD_OPERATION_AREAS = [
  {
    id: "OP-28",
    name: "Area de disposicion utilizada",
    layer: "Operacion historica",
    status: "28.13 ha usadas",
    areaHa: 28.13,
    fill: "#C06B2E",
    stroke: "#FFB020",
    polygon: [[10.2777,-75.4844],[10.2782,-75.4785],[10.2740,-75.4751],[10.2695,-75.4778],[10.2687,-75.4838],[10.2728,-75.4865]],
  },
  {
    id: "M16",
    name: "Modulo 16 disponible",
    layer: "Expansion georreferenciada",
    status: "Diseño / capacidad",
    areaHa: 6.82,
    fill: "#2E8BC0",
    stroke: "#36A3FF",
    polygon: [[10.2760,-75.4770],[10.2787,-75.4738],[10.2752,-75.4719],[10.2724,-75.4748]],
  },
  {
    id: "M17",
    name: "Modulo 17 disponible",
    layer: "Expansion georreferenciada",
    status: "Diseño / capacidad",
    areaHa: 6.74,
    fill: "#3E8E41",
    stroke: "#89E09A",
    polygon: [[10.2728,-75.4761],[10.2751,-75.4729],[10.2715,-75.4712],[10.2688,-75.4742]],
  },
  {
    id: "AM-01",
    name: "Franja de amortiguacion ambiental",
    layer: "Restriccion",
    status: "Conservar",
    areaHa: 9.4,
    fill: "#315C4B",
    stroke: "#4CAF50",
    polygon: [[10.2801,-75.4861],[10.2810,-75.4808],[10.2788,-75.4770],[10.2750,-75.4794],[10.2744,-75.4850]],
  },
];

const TD_DRAINAGE = [
  { id: "LX-01", name: "Canal perimetral norte", kind: "Lixiviados", color: "#36A3FF", path: [[10.2795,-75.4858],[10.2784,-75.4821],[10.2770,-75.4780],[10.2752,-75.4748]] },
  { id: "LX-02", name: "Conduccion a tratamiento", kind: "Lixiviados", color: "#36A3FF", path: [[10.2728,-75.4861],[10.2704,-75.4834],[10.2689,-75.4801],[10.2672,-75.4768]] },
  { id: "DR-03", name: "Drenaje pluvial sur", kind: "Pluvial", color: "#89E09A", path: [[10.2680,-75.4870],[10.2662,-75.4835],[10.2656,-75.4792],[10.2667,-75.4743]] },
];

const TD_CONTROL_POINTS = [
  { id: "PZ-01", name: "Piezometro aguas arriba", layer: "Agua subterranea", lat: 10.2792, lng: -75.4776, value: "Nivel 3.2 m", color: "#36A3FF" },
  { id: "PZ-02", name: "Piezometro aguas abajo", layer: "Agua subterranea", lat: 10.2667, lng: -75.4836, value: "Nivel 4.1 m", color: "#36A3FF" },
  { id: "AR-01", name: "Estacion aire/ruido", layer: "Calidad ambiental", lat: 10.2765, lng: -75.4866, value: "PM10 / dBA", color: "#FFB020" },
  { id: "AR-02", name: "Estacion meteo", layer: "Calidad ambiental", lat: 10.2707, lng: -75.4738, value: "Viento / lluvia", color: "#B98CFF" },
  { id: "GCP-01", name: "Control RTK norte", layer: "Fotogrametria", lat: 10.2801, lng: -75.4860, value: "GCP", color: "#FFFFFF" },
  { id: "GCP-02", name: "Control RTK este", layer: "Fotogrametria", lat: 10.2757, lng: -75.4724, value: "GCP", color: "#FFFFFF" },
  { id: "GCP-03", name: "Control RTK sur", layer: "Fotogrametria", lat: 10.2649, lng: -75.4808, value: "GCP", color: "#FFFFFF" },
];

const TD_GAS_WELLS = [
  [10.2762,-75.4826], [10.2747,-75.4811], [10.2731,-75.4832],
  [10.2720,-75.4797], [10.2708,-75.4820], [10.2752,-75.4779],
  [10.2711,-75.4768], [10.2696,-75.4795],
].map((point, i) => ({
  id: `BG-${String(i + 1).padStart(2, "0")}`,
  name: "Pozo de biogas",
  layer: "Biogas",
  lat: point[0],
  lng: point[1],
  value: "Extraccion pasiva",
  color: "#4CAF50",
}));

const TD_FLIGHT_LINES = [
  [[10.2810,-75.4860],[10.2660,-75.4745]],
  [[10.2800,-75.4874],[10.2650,-75.4759]],
  [[10.2790,-75.4888],[10.2640,-75.4773]],
  [[10.2780,-75.4902],[10.2630,-75.4787]],
  [[10.2820,-75.4846],[10.2670,-75.4731]],
].map((path, i) => ({
  id: `VL-${String(i + 1).padStart(2, "0")}`,
  name: "Linea de vuelo RTK",
  path,
}));

const TD_CONTOURS = [
  [[10.2805,-75.4864],[10.2772,-75.4840],[10.2740,-75.4818],[10.2705,-75.4794],[10.2662,-75.4760]],
  [[10.2792,-75.4882],[10.2760,-75.4858],[10.2727,-75.4835],[10.2689,-75.4811],[10.2649,-75.4779]],
  [[10.2785,-75.4756],[10.2748,-75.4772],[10.2712,-75.4796],[10.2676,-75.4822],[10.2645,-75.4848]],
];

function operationScore(feature) {
  if (!feature) return 0;
  if (feature.id === "OP-28") return 72;
  if (feature.id === "M16" || feature.id === "M17") return 88;
  if (feature.id === "AM-01") return 64;
  return 76;
}

function TerritorialDashboard({ compact = false }) {
  const mapEl = React.useRef(null);
  const mapRef = React.useRef(null);
  const baseRef = React.useRef(null);
  const overlayRef = React.useRef(null);
  const [base, setBase] = React.useState("satellite");
  const [selected, setSelected] = React.useState(TD_OPERATION_AREAS[1]);
  const [activeTool, setActiveTool] = React.useState("Identificar");
  const [layers, setLayers] = React.useState({
    perimeter: true,
    operation: true,
    modules: true,
    drainage: true,
    gas: true,
    monitoring: true,
    survey: true,
    contours: false,
  });

  const baseMaps = {
    satellite: {
      label: "Satelite",
      url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
      attribution: "Tiles Esri",
    },
    topo: {
      label: "Topografico",
      url: "https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png",
      attribution: "OpenTopoMap",
    },
    light: {
      label: "Carto",
      url: "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png",
      attribution: "OSM CARTO",
    },
    dark: {
      label: "Nocturno",
      url: "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png",
      attribution: "OSM CARTO",
    },
  };

  const toggleLayer = (key) => setLayers((current) => ({ ...current, [key]: !current[key] }));
  const flightKm = TD_FLIGHT_LINES.reduce((sum, route) => {
    return sum + geoDistanceKm(route.path[0], route.path[1]);
  }, 0).toFixed(1);
  const metrics = [
    ["Predio", `${TD_SITE.totalHa} ha`, "#36A3FF"],
    ["Disp. final", `${TD_SITE.disposalHa} ha`, "#4CAF50"],
    ["Usado", `${TD_SITE.usedHa} ha`, "#FFB020"],
    ["Disponible", `${TD_SITE.availableHa} ha`, "#B98CFF"],
  ];
  const layerRows = [
    ["perimeter", "Perimetro tecnico", "Predio 63 ha", "#FFFFFF"],
    ["operation", "Area utilizada", "28.13 ha operadas", "#FFB020"],
    ["modules", "Modulos 16 y 17", "13.56 ha disponibles", "#36A3FF"],
    ["drainage", "Drenajes y lixiviados", "Canales / conduccion", "#36A3FF"],
    ["gas", "Pozos de biogas", "8 puntos", "#4CAF50"],
    ["monitoring", "Control ambiental", "Piezometros / aire", "#B98CFF"],
    ["survey", "Vuelo y GCP RTK", `${flightKm} km`, "#FFFFFF"],
    ["contours", "Curvas de nivel", "Modelo de terreno", "#C8D1DC"],
  ];
  const tools = ["Identificar", "Medir", "Buffer", "Filtro", "Exportar"];
  const selectedArea = selected?.areaHa ? `${selected.areaHa} ha` : selected?.value || "Registro operativo";
  const selectedScore = selected?.areaHa ? operationScore(selected) : 91;

  React.useEffect(() => {
    if (!window.L || !mapEl.current || mapRef.current) return;
    const map = window.L.map(mapEl.current, {
      zoomControl: false,
      scrollWheelZoom: false,
      attributionControl: !compact,
    }).setView(TD_SITE.center, compact ? 16 : 16);
    window.L.control.zoom({ position: "bottomright" }).addTo(map);
    overlayRef.current = window.L.layerGroup().addTo(map);
    mapRef.current = map;
    setTimeout(() => map.invalidateSize(), 120);
    return () => {
      map.remove();
      mapRef.current = null;
    };
  }, []);

  React.useEffect(() => {
    const map = mapRef.current;
    if (!map || !window.L) return;
    if (baseRef.current) map.removeLayer(baseRef.current);
    const cfg = baseMaps[base];
    baseRef.current = window.L.tileLayer(cfg.url, {
      maxZoom: 19,
      attribution: cfg.attribution,
    }).addTo(map);
  }, [base]);

  React.useEffect(() => {
    const map = mapRef.current;
    const group = overlayRef.current;
    if (!map || !group || !window.L) return;
    group.clearLayers();

    if (layers.perimeter) {
      const perimeter = window.L.polygon(TD_PERIMETER.polygon, {
        color: "#FFFFFF",
        weight: 2,
        dashArray: "8 6",
        fillColor: "#FFFFFF",
        fillOpacity: 0.03,
      }).addTo(group);
      perimeter.bindTooltip(`<strong>${TD_PERIMETER.name}</strong><br/>${TD_SITE.totalHa} ha - ${TD_SITE.location}`, { sticky: true });
      perimeter.on("click", () => setSelected(TD_PERIMETER));
    }

    TD_OPERATION_AREAS.forEach((area) => {
      const visible = area.id === "OP-28" ? layers.operation : area.id === "AM-01" ? layers.perimeter : layers.modules;
      if (!visible) return;
      const layer = window.L.polygon(area.polygon, {
        color: area.stroke,
        weight: selected?.id === area.id ? 3 : 1.8,
        fillColor: area.fill,
        fillOpacity: selected?.id === area.id ? 0.55 : 0.36,
      }).addTo(group);
      layer.bindTooltip(`<strong>${area.id} - ${area.name}</strong><br/>${area.status}<br/>Area: ${area.areaHa} ha`, { sticky: true });
      layer.on("click", () => setSelected(area));
    });

    if (layers.drainage) {
      TD_DRAINAGE.forEach((drain) => {
        window.L.polyline(drain.path, {
          color: drain.color,
          weight: 4,
          opacity: 0.9,
        }).bindTooltip(`<strong>${drain.id}</strong> ${drain.name}<br/>${drain.kind}`, { sticky: true }).addTo(group);
      });
    }

    if (layers.contours) {
      TD_CONTOURS.forEach((line, i) => {
        window.L.polyline(line, {
          color: "#E4E8EF",
          weight: 1,
          opacity: 0.55,
          dashArray: "2 5",
        }).bindTooltip(`Curva de nivel CN-${i + 1}`, { sticky: true }).addTo(group);
      });
    }

    if (layers.survey) {
      TD_FLIGHT_LINES.forEach((line) => {
        window.L.polyline(line.path, {
          color: "#FFFFFF",
          weight: 1.5,
          opacity: 0.68,
          dashArray: "6 8",
        }).bindTooltip(line.name, { sticky: true }).addTo(group);
      });
    }

    if (layers.gas) {
      TD_GAS_WELLS.forEach((well) => {
        window.L.circleMarker([well.lat, well.lng], {
          radius: 5,
          color: "#0B1D2E",
          weight: 1.5,
          fillColor: well.color,
          fillOpacity: 0.95,
        }).bindTooltip(`<strong>${well.id}</strong> ${well.name}<br/>${well.value}`, { sticky: true }).addTo(group);
      });
    }

    const controls = TD_CONTROL_POINTS.filter((point) => (
      (layers.monitoring && point.layer !== "Fotogrametria") ||
      (layers.survey && point.layer === "Fotogrametria")
    ));
    controls.forEach((point) => {
      const marker = window.L.circleMarker([point.lat, point.lng], {
        radius: point.layer === "Fotogrametria" ? 5 : 7,
        color: point.layer === "Fotogrametria" ? "#0B1D2E" : "#FFFFFF",
        weight: 1.6,
        fillColor: point.color,
        fillOpacity: 0.95,
      }).bindTooltip(`<strong>${point.id}</strong> ${point.name}<br/>${point.value}`, { sticky: true }).addTo(group);
      marker.on("click", () => setSelected(point));
      if (point.layer !== "Fotogrametria") {
        window.L.circle([point.lat, point.lng], {
          radius: point.layer === "Agua subterranea" ? 120 : 90,
          color: point.color,
          weight: 1,
          fillColor: point.color,
          fillOpacity: 0.08,
        }).addTo(group);
      }
    });

    map.fitBounds(window.L.polygon(TD_PERIMETER.polygon).getBounds(), { padding: compact ? [16, 16] : [24, 24] });
    setTimeout(() => map.invalidateSize(), 80);
  }, [layers, selected, compact]);

  return (
    <div className={`ea-territory-dashboard ea-gis-portal${compact ? " compact" : ""}`} aria-label="Geoportal SIG operativo tipo ArcGIS">
      <div className="ea-gis-titlebar">
        <div>
          <span>ENFOQUE GIS ENTERPRISE</span>
          <strong>{TD_SITE.name}</strong>
        </div>
        <div className="ea-gis-title-actions">
          <span>WebMap ID EA-LC-2026</span>
          <button type="button">Compartir</button>
        </div>
      </div>
      <div className="ea-gis-body">
        <aside className="ea-gis-left">
          <div className="ea-gis-search">Buscar capa, modulo o punto...</div>
          <div className="ea-gis-panel-title">Contenido</div>
          <div className="ea-gis-layer-list">
            {layerRows.map(([key, label, detail, color]) => (
              <label key={key} className="ea-gis-layer-row">
                <input type="checkbox" checked={layers[key]} onChange={() => toggleLayer(key)} />
                <span className="ea-gis-swatch" style={{ background: color }}/>
                <span><strong>{label}</strong><small>{detail}</small></span>
              </label>
            ))}
          </div>
          <div className="ea-gis-panel-title">Mapa base</div>
          <div className="ea-gis-basemaps">
            {Object.entries(baseMaps).map(([key, cfg]) => (
              <button key={key} type="button" className={base === key ? "active" : ""} onClick={() => setBase(key)}>{cfg.label}</button>
            ))}
          </div>
        </aside>

        <main className="ea-gis-map-shell">
          <div className="ea-gis-toolstrip">
            {tools.map((tool) => (
              <button key={tool} type="button" className={activeTool === tool ? "active" : ""} onClick={() => setActiveTool(tool)}>{tool}</button>
            ))}
          </div>
          <div className="ea-gis-map" ref={mapEl}>
            {!window.L && <div className="ea-td-map-fallback">Cargando motor cartografico...</div>}
          </div>
          <div className="ea-gis-map-status">
            <span>EPSG:4326 / MAGNA-SIRGAS compatible</span>
            <span>{TD_SITE.center[0].toFixed(5)}, {TD_SITE.center[1].toFixed(5)}</span>
          </div>
          {!compact && (
            <div className="ea-gis-attribute-table">
              <div className="ea-gis-table-head">
                <strong>Tabla de atributos</strong>
                <span>Capas operativas del proyecto</span>
              </div>
              <div className="ea-gis-table-grid">
                {[TD_PERIMETER, ...TD_OPERATION_AREAS].map((row) => (
                  <button type="button" key={row.id} className={selected?.id === row.id ? "active" : ""} onClick={() => setSelected(row)}>
                    <span>{row.id}</span><strong>{row.name}</strong><em>{row.areaHa} ha</em>
                  </button>
                ))}
              </div>
            </div>
          )}
        </main>

        <aside className="ea-gis-right">
          <div className="ea-td-metrics">
            {metrics.map(([label, value, color]) => (
              <div className="ea-td-metric" key={label}>
                <span style={{ background: color }}/>
                <small>{label}</small>
                <strong>{value}</strong>
              </div>
            ))}
          </div>
          <div className="ea-gis-inspector">
            <span>Inspector</span>
            <strong>{selected?.name || TD_SITE.name}</strong>
            <p>{selected?.layer || TD_SITE.location}</p>
            <dl>
              <div><dt>Estado</dt><dd>{selected?.status || "Operacion tecnica"}</dd></div>
              <div><dt>Area / valor</dt><dd>{selectedArea}</dd></div>
              <div><dt>Herramienta</dt><dd>{activeTool}</dd></div>
            </dl>
            <div className="ea-gis-score">
              <span>Consistencia SIG</span>
              <strong>{selectedScore}</strong>
            </div>
          </div>
          <div className="ea-gis-analysis">
            <div><small>Capacidad disponible</small><strong>{TD_SITE.availableHa} ha</strong><span>Modulos 16 y 17</span></div>
            <div><small>Control ambiental</small><strong>{TD_CONTROL_POINTS.length} puntos</strong><span>Piezometros, aire, meteo y GCP</span></div>
            <div><small>Fotogrametria</small><strong>{flightKm} km</strong><span>Lineas RTK simuladas</span></div>
          </div>
        </aside>
      </div>
    </div>
  );
}

// Service icons (replicated from landing)
function SvcIcon({ kind, size = 56, 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;
}

window.NavBar = NavBar;
window.FooterFull = FooterFull;
window.ContactModal = ContactModal;
window.TerritorialDashboard = TerritorialDashboard;
window.SvcIcon = SvcIcon;
window.COMPANY = COMPANY;
window.SERVICES = SERVICES;
