// Componentes compartidos entre todas las páginas — Imcopartes Web
// Cargar después de React/Babel y antes del JSX específico de cada página.

const { useState, useEffect } = React;

/* ===== Constantes (datos reales) ===== */
const IMCO = {
  empresa: "IMCOPARTES S.A.S.",
  nit: "901.354.174-0",
  direccion: "Diagonal 46 Sur # 50 - 79, Casa 80",
  ciudad: "Bogotá D.C., Colombia",
  telDisplay: "+57 (601) 238 5115",
  telLink: "+576012385115",
  whatsappDisplay: "+57 300 289 8167",
  whatsappRaw: "573002898167",
  emailContacto: "pedidos@imcopartes.com",
  emailMayoristas: "pedidos@imcopartes.com",
  emailDistribuidores: "pedidos@imcopartes.com",
  emailSoporte: "pedidos@imcopartes.com",
  emailHabeas: "pedidos@imcopartes.com",
  anio: 2026,
};

function waLink(message) {
  const base = `https://wa.me/${IMCO.whatsappRaw}`;
  if (!message) return base;
  return `${base}?text=${encodeURIComponent(message)}`;
}

/* ===== Hook: refresca iconos Lucide después de renders ===== */
function useLucide(deps = []) {
  useEffect(() => {
    let cancelled = false;
    const tick = () => {
      if (cancelled) return;
      if (window.lucide?.createIcons) window.lucide.createIcons();
      else setTimeout(tick, 50);
    };
    requestAnimationFrame(tick);
    return () => { cancelled = true; };
    // eslint-disable-next-line
  }, deps);
}

/* ===== Nav compartido ===== */
function Nav({ active }) {
  const [mobileOpen, setMobileOpen] = useState(false);
  const links = [
    { id: "inicio",         label: "Inicio",         href: "Inicio.html" },
    { id: "catalogo",       label: "Catálogo",       href: "Catalogo.html" },
    { id: "nosotros",       label: "Nosotros",       href: "Nosotros.html" },
    { id: "contacto",       label: "Contacto",       href: "Contacto.html" },
  ];
  return (
    <nav className={"nav" + (mobileOpen ? " nav--mobile-open" : "")}>
      <a className="nav__brand" href="Inicio.html" aria-label="Imcopartes — Inicio">
        <img src="assets/logos/imcopartes-azul-negro.png" alt="Imcopartes" />
      </a>
      <div className="nav__links">
        {links.map((l) => (
          <a
            key={l.id}
            href={l.href}
            className={active === l.id ? "active" : ""}
            onClick={() => setMobileOpen(false)}
          >
            {l.label}
          </a>
        ))}
      </div>
      <div className="nav__actions">
        <a
          className="btn btn-primary"
          href={waLink("Hola Imcopartes, quisiera más información sobre sus productos.")}
          target="_blank"
          rel="noopener noreferrer"
        >
          <i data-lucide="message-circle" style={{ width: 16, height: 16 }}></i>
          Cotizar por WhatsApp
        </a>
        <button
          className="nav__mobile-toggle"
          aria-label="Menú"
          onClick={() => setMobileOpen((v) => !v)}
        >
          <i data-lucide={mobileOpen ? "x" : "menu"} style={{ width: 20, height: 20 }}></i>
        </button>
      </div>
    </nav>
  );
}

/* ===== WhatsApp FAB ===== */
function WhatsAppFAB({ message }) {
  const msg = message || "Hola Imcopartes, me interesa cotizar productos.";
  return (
    <a
      className="wa-fab"
      href={waLink(msg)}
      target="_blank"
      rel="noopener noreferrer"
      aria-label="Escribir por WhatsApp a Imcopartes"
    >
      {/* Icono WhatsApp oficial (path original) — Lucide no trae uno fiel */}
      <svg viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
        <path d="M17.6 6.32A7.85 7.85 0 0 0 12.05 4a7.94 7.94 0 0 0-6.88 11.9L4 20l4.2-1.1a7.93 7.93 0 0 0 3.84.98h.01a7.94 7.94 0 0 0 7.94-7.94 7.9 7.9 0 0 0-2.39-5.62Zm-5.55 12.21h-.01a6.6 6.6 0 0 1-3.36-.92l-.24-.14-2.49.65.66-2.43-.16-.25a6.6 6.6 0 0 1 10.27-8.16 6.55 6.55 0 0 1 1.93 4.66 6.6 6.6 0 0 1-6.6 6.59Zm3.61-4.94c-.2-.1-1.17-.58-1.35-.64-.18-.07-.31-.1-.45.1s-.51.64-.62.77c-.12.13-.23.15-.42.05a5.4 5.4 0 0 1-1.6-.99 6.04 6.04 0 0 1-1.1-1.37c-.12-.2 0-.31.09-.41.09-.09.2-.23.3-.35.1-.12.13-.2.2-.33.07-.13.04-.25-.02-.35-.05-.1-.45-1.09-.62-1.49-.16-.39-.33-.34-.45-.34h-.39c-.13 0-.35.05-.53.25s-.7.68-.7 1.66.71 1.92.81 2.06c.1.13 1.4 2.13 3.39 2.98.47.21.84.33 1.13.42.48.15.91.13 1.25.08.38-.06 1.17-.48 1.34-.95.16-.46.16-.86.12-.94-.05-.08-.18-.13-.38-.23Z"/>
      </svg>
      <span className="wa-fab__label">Cotizar por WhatsApp</span>
    </a>
  );
}

/* ===== Marcas representadas ===== */
const BRANDS = [
  {
    id: "novparts",
    name: "Novparts",
    tagline: "Repuestos generales · multi-línea",
    desc: "Catálogo amplio para vehículos populares: suspensión, frenos, motor y eléctrico.",
    color: "#145D9E",
    bg: "rgb(255 255 255 / 0.04)",
    border: "rgb(255 255 255 / 0.08)",
  },
  {
    id: "mrshift",
    name: "MrShift",
    tagline: "Transmisión · palancas y kits",
    desc: "Línea especializada en transmisión, palancas de cambio y componentes de caja.",
    color: "#E67E22",
    bg: "rgb(255 255 255 / 0.04)",
    border: "rgb(255 255 255 / 0.08)",
  },
  {
    id: "mrswitch",
    name: "MrSwitch",
    tagline: "Switches · control eléctrico",
    desc: "Switches, sensores y componentes de control eléctrico para múltiples plataformas.",
    color: "#DDF664",
    bg: "rgb(255 255 255 / 0.04)",
    border: "rgb(255 255 255 / 0.08)",
  },
  {
    id: "prolift",
    name: "ProLift",
    tagline: "Fuerza que sostiene",
    desc: "Amortiguadores neumáticos para capó, baúl y compuerta trasera. Soporte, elevación y rendimiento.",
    color: "#ED4720",
    bg: "#1C1C1B",
    border: "rgb(237 71 32 / 0.18)",
    logo: "assets/brand/prolift/icon.png",
    font: "'Barlow Condensed', Impact, system-ui, sans-serif",
  },
  {
    id: "matdefender",
    name: "MatDefender",
    tagline: "Protección para cada camino",
    desc: "Tapetes termoformados automotrices con cobertura total. Defienden el interior del vehículo frente al uso diario, la humedad, el polvo y la suciedad.",
    color: "#1F4744",
    bg: "rgb(255 255 255 / 0.04)",
    border: "rgb(255 255 255 / 0.08)",
  },
  {
    id: "prismaglass",
    name: "PrismaGlass",
    tagline: "Vidrios templados para tableros y radios",
    desc: "Vidrios templados protectores para pantallas de radio y cluster digital. Próximamente.",
    color: "#7C3AED",
    bg: "rgb(255 255 255 / 0.04)",
    border: "rgb(255 255 255 / 0.08)",
  },
];

/* ===== Cookie banner ===== */
function CookieBanner() {
  const [ack, setAck] = useState(() => {
    try { return localStorage.getItem("imco_cookie_ack") === "1"; } catch (e) { return false; }
  });
  if (ack) return null;
  function accept() {
    try { localStorage.setItem("imco_cookie_ack", "1"); } catch (e) {}
    setAck(true);
  }
  return (
    <div className="cookie-banner" role="dialog" aria-label="Aviso de cookies">
      <div className="cookie-banner__inner">
        <i data-lucide="cookie" style={{ width: 22, height: 22, color: "var(--imco-blue)", flexShrink: 0 }}></i>
        <div className="cookie-banner__text">
          <strong>Este sitio usa cookies.</strong>{" "}
          <span>
            Utilizamos cookies propias y de terceros para mejorar tu experiencia y analizar el tráfico.
            Al continuar navegando aceptas nuestra <a href="#">Política de cookies</a> y la{" "}
            <a href="#">Política de tratamiento de datos (Ley 1581 de 2012)</a>.
          </span>
        </div>
        <div className="cookie-banner__actions">
          <button className="btn btn-secondary btn-sm" onClick={accept}>Configurar</button>
          <button className="btn btn-primary btn-sm" onClick={accept}>Aceptar y continuar</button>
        </div>
      </div>
    </div>
  );
}

/* ===== Footer compartido ===== */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer__inner">
        <div className="footer__brand">
          <img src="assets/logos/imcopartes-blanco.svg" alt="Imcopartes" style={{ filter: "brightness(0) invert(1)", height: 36 }} />
          <p>Importamos, distribuimos, respaldamos.</p>
          <div style={{ display: "flex", gap: 10, marginTop: 18, alignItems: "center" }}>
            <a
              href="https://instagram.com/imcopartes"
              target="_blank" rel="noopener noreferrer"
              aria-label="Síguenos en Instagram @imcopartes"
              style={{
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                width: 36, height: 36, borderRadius: 8,
                background: "rgb(255 255 255 / 0.06)",
                border: "1px solid rgb(255 255 255 / 0.08)",
                color: "var(--neutral-200)", textDecoration: "none",
                transition: "background 0.18s ease, color 0.18s ease",
              }}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect>
                <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path>
                <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line>
              </svg>
            </a>
            <a
              href="https://facebook.com/imcopartes"
              target="_blank" rel="noopener noreferrer"
              aria-label="Síguenos en Facebook @imcopartes"
              style={{
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                width: 36, height: 36, borderRadius: 8,
                background: "rgb(255 255 255 / 0.06)",
                border: "1px solid rgb(255 255 255 / 0.08)",
                color: "var(--neutral-200)", textDecoration: "none",
                transition: "background 0.18s ease, color 0.18s ease",
              }}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"></path>
              </svg>
            </a>
          </div>
        </div>
        <div>
          <h4>Catálogo</h4>
          <ul>
            <li><a href="Catalogo.html">Ver catálogo</a></li>
            <li><a href={waLink("Hola, soy distribuidor y quiero acceso al catálogo completo.")} target="_blank" rel="noopener">Acceso distribuidores</a></li>
            <li><a href="assets/catalogo/Lista-de-Productos-Imcopartes-2026.pdf" download="Lista-de-Productos-Imcopartes-2026.pdf" target="_blank" rel="noopener">Lista de productos (PDF)</a></li>
          </ul>
        </div>
        <div>
          <h4>Empresa</h4>
          <ul>
            <li><a href="Nosotros.html">Nosotros</a></li>
            <li><a href="Contacto.html">Contacto</a></li>
          </ul>
        </div>
        <div>
          <h4>Contacto</h4>
          <ul>
            <li><a href={`tel:${IMCO.telLink}`}>{IMCO.telDisplay}</a></li>
            <li><a href={waLink()} target="_blank" rel="noopener">WhatsApp {IMCO.whatsappDisplay}</a></li>
            <li><a href={`mailto:${IMCO.emailContacto}`}>{IMCO.emailContacto}</a></li>
          </ul>
        </div>
      </div>

      <div className="footer__legal">
        <div className="footer__legal-info">
          <strong>{IMCO.empresa}</strong> · {IMCO.ciudad}<br />
          {IMCO.direccion}
        </div>
        <div className="footer__legal-links">
          <a href="#">Términos y condiciones</a>
          <a href="#">Política de tratamiento de datos</a>
          <a href="#">Política de cookies</a>
        </div>
      </div>

      <div className="footer__bottom">
        <span>© {IMCO.anio} {IMCO.empresa} Todos los derechos reservados.</span>
        <span>Vigilado por la Superintendencia de Industria y Comercio (SIC)</span>
      </div>
    </footer>
  );
}

/* ===== Export to window so other pages can use ===== */
Object.assign(window, {
  IMCO, BRANDS, waLink, useLucide,
  Nav, Footer, WhatsAppFAB, CookieBanner,
});
