/* global React, Icon */
/* eslint-disable no-unused-vars */

const { useState: useState2, useEffect: useEffect2 } = React;
const VCFG2 = (typeof window !== "undefined" && window.VCF_CFG) || {};

/* ============================================================
   TIENDAS
   ============================================================ */

const STORES = [
  { name: "Amazon",     tag: "Electrónica · Hogar",       domain: "amazon.com",     color: "FF9900" },
  { name: "Shein",      tag: "Moda · Accesorios",         domain: "shein.com",      color: "000000" },
  { name: "eBay",       tag: "Subastas · Coleccionables", domain: "ebay.com",       color: "E53238" },
  { name: "Walmart",    tag: "Supermercado · Hogar",      domain: "walmart.com",    color: "0071DC" },
  { name: "Temu",       tag: "Ofertas · Todo",            domain: "temu.com",       color: "FB7701" },
  { name: "Nike",       tag: "Deportes",                  domain: "nike.com",       color: "111111" },
  { name: "Target",     tag: "Departamentales",           domain: "target.com",     color: "CC0000" },
  { name: "AliExpress", tag: "Ofertas · Todo",            domain: "aliexpress.com", color: "E62E04" },
  { name: "Best Buy",   tag: "Electrónica",               domain: "bestbuy.com",    color: "0046BE" },
  { name: "Macy's",     tag: "Departamentales",           domain: "macys.com",      color: "E21A23" },
  { name: "Samsung",    tag: "Electrónica",               domain: "samsung.com",    color: "1428A0" },
  { name: "Apple",      tag: "Tecnología",                domain: "apple.com",      color: "111111" },
];

function VCTiendas() {
  return (
    <section style={{ padding: "60px 0 100px", overflow: "hidden", background: "var(--vc-cream)" }}>
      <div className="vc-shell">
        <div style={{ textAlign: "center", maxWidth: 720, margin: "0 auto 48px" }}>
          <span className="vc-eyebrow" style={{ justifyContent: "center" }}>Tu mundo en compras</span>
          <h2 className="vc-section-title">Compra en miles de tiendas en USA.</h2>
          <p className="vc-section-sub" style={{ margin: "18px auto 0" }}>
            Tu dirección Vía Courier funciona en cualquier tienda con envío doméstico en Estados Unidos.
            Estos son algunos de nuestros favoritos.
          </p>
        </div>
      </div>

      <div style={{ position: "relative", marginTop: 24 }}>
        <MarqueeFade />
        <div style={{ display: "flex", gap: 14, animation: "vc-marquee 38s linear infinite", width: "max-content" }}>
          {[...STORES, ...STORES].map((s, i) => <StoreChip key={i} {...s} />)}
        </div>
      </div>

      <div style={{ position: "relative", marginTop: 14 }}>
        <MarqueeFade />
        <div style={{ display: "flex", gap: 14, animation: "vc-marquee 46s linear infinite reverse", width: "max-content" }}>
          {[...STORES.slice().reverse(), ...STORES.slice().reverse()].map((s, i) => <StoreChip key={i} {...s} />)}
        </div>
      </div>
    </section>
  );
}

function MarqueeFade() {
  return (
    <>
      <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 120, background: "linear-gradient(90deg, var(--vc-cream), transparent)", zIndex: 2, pointerEvents: "none" }} />
      <div style={{ position: "absolute", right: 0, top: 0, bottom: 0, width: 120, background: "linear-gradient(-90deg, var(--vc-cream), transparent)", zIndex: 2, pointerEvents: "none" }} />
    </>
  );
}

function StoreChip({ name, tag, color, domain }) {
  const onImgError = (e) => {
    const el = e.currentTarget;
    const step = el.getAttribute("data-step") || "0";
    if (step === "0") {
      el.setAttribute("data-step", "1");
      el.src = `https://www.google.com/s2/favicons?domain=${domain}&sz=64`;
    } else {
      el.style.display = "none";
      const fb = el.nextSibling; if (fb) fb.style.display = "grid";
    }
  };
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14, background: "var(--vc-white)", border: "1px solid var(--vc-line)", borderRadius: "var(--r-pill)", padding: "12px 22px 12px 14px", flexShrink: 0, transition: "transform .25s ease, box-shadow .25s ease" }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "var(--shadow-card)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = "none"; }}
    >
      <div style={{ width: 40, height: 40, borderRadius: "50%", background: `#${color}12`, display: "grid", placeItems: "center", flexShrink: 0, position: "relative", overflow: "hidden" }}>
        <img src={`https://icons.duckduckgo.com/ip3/${domain}.ico`} alt={name} width="26" height="26" loading="lazy" data-step="0" style={{ display: "block", objectFit: "contain", borderRadius: 5 }} onError={onImgError} />
        <span style={{ display: "none", position: "absolute", inset: 0, borderRadius: "50%", background: `#${color}`, color: "#fff", placeItems: "center", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16 }}>{name[0]}</span>
      </div>
      <div style={{ lineHeight: 1.1 }}>
        <div style={{ fontWeight: 700, fontSize: 16 }}>{name}</div>
        <div style={{ fontSize: 11.5, color: "var(--vc-ink-mute)", marginTop: 3, fontWeight: 500 }}>{tag}</div>
      </div>
    </div>
  );
}

/* ============================================================
   CÓMO FUNCIONA
   ============================================================ */

function VCComoFunciona() {
  const steps = [
    { n: "01", title: "Regístrate gratis", desc: "Crea tu cuenta en menos de 2 minutos y recibe tu número de casillero VIA-#####.", meta: "Sin tarjeta de crédito" },
    { n: "02", title: "Compra en USA", desc: "Usa tu dirección en Miami al momento del checkout en cualquier tienda online.", meta: "Amazon, Shein, eBay…", accent: "blue" },
    { n: "03", title: "Recibe en RD", desc: "Tu paquete llega a Miami, se envía a tu sucursal y te avisamos cuando esté listo.", meta: "Entrega en 24-48 horas" },
  ];

  return (
    <section id="como" style={{ padding: "120px 0", background: "var(--vc-cream-2)", position: "relative", overflow: "hidden" }}>
      <div className="vc-shell">
        <div style={{ maxWidth: 760, marginBottom: 64 }}>
          <span className="vc-eyebrow">La ruta</span>
          <h2 className="vc-section-title">
            Tres paradas, <br />
            <em style={{ fontStyle: "normal", color: "var(--vc-blue)" }}>una sola vía.</em>
          </h2>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 24, position: "relative" }} className="vc-steps-grid">
          <div aria-hidden style={{ position: "absolute", top: 36, left: "16%", right: "16%", height: 2, borderTop: "2px dashed var(--vc-line-strong)", zIndex: 0 }} className="vc-steps-line" />
          {steps.map((s, i) => (
            <StepCard key={i} {...s} active={i === 0} />
          ))}
        </div>

        <div style={{ marginTop: 48, padding: "20px 24px", background: "var(--vc-white)", border: "1px solid var(--vc-line)", borderRadius: "var(--r-lg)", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24, flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
            <div style={{ width: 40, height: 40, borderRadius: 12, background: "var(--vc-amber-tint)", color: "var(--vc-ink)", display: "grid", placeItems: "center" }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="12" r="9" /><path d="M9 12h6M12 9v6" />
              </svg>
            </div>
            <div>
              <div style={{ fontWeight: 700 }}>¿Necesitas ayuda con tu primera compra?</div>
              <div style={{ fontSize: 14, color: "var(--vc-ink-mute)", marginTop: 2 }}>Te guiamos paso a paso por WhatsApp.</div>
            </div>
          </div>
          <a href={VCFG2.whatsapp || "#whatsapp"} className="vc-btn">
            Hablar por WhatsApp <Icon.Arrow />
          </a>
        </div>
      </div>
    </section>
  );
}

function StepCard({ n, title, desc, meta, active, accent }) {
  const isBlue = accent === "blue";
  return (
    <article style={{ position: "relative", zIndex: 1, background: "var(--vc-white)", borderRadius: "var(--r-lg)", padding: 28, border: "1px solid var(--vc-line)", transition: "transform .25s ease, box-shadow .25s ease" }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-4px)"; e.currentTarget.style.boxShadow = "var(--shadow-pop)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = "none"; }}
    >
      <div style={{ width: 72, height: 72, borderRadius: "50%", background: active ? "var(--vc-yellow)" : (isBlue ? "var(--vc-blue)" : "var(--vc-cream)"), border: (active || isBlue) ? "none" : "1px solid var(--vc-line-strong)", display: "grid", placeItems: "center", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 24, color: isBlue ? "#fff" : "var(--vc-ink)", marginBottom: 24 }}>{n}</div>
      <h3 style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 26, letterSpacing: "-0.02em" }}>{title}</h3>
      <p style={{ margin: "12px 0 20px", fontSize: 15.5, lineHeight: 1.55, color: "var(--vc-ink-soft)" }}>{desc}</p>
      <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "6px 12px", borderRadius: "var(--r-pill)", background: "var(--vc-amber-tint)", fontSize: 12.5, fontWeight: 600, color: "var(--vc-ink)" }}>
        <span style={{ width: 5, height: 5, borderRadius: "50%", background: "var(--vc-yellow-deep)" }} />
        {meta}
      </div>
    </article>
  );
}

/* ============================================================
   SUCURSALES — datos reales vía REST (con fallback)
   ============================================================ */

const BRANCHES_FALLBACK = [
  { id: "b1", name: "Oficina Principal — Don Bosco", region: "Santo Domingo", addr: "Av. 27 de Febrero 282, Don Bosco", hours: "Lun–Vie 9:00am – 6:00pm", phone: "(809) 707-3995", lat: 18.4801, lng: -69.9018, main: true },
];

function VCSucursales() {
  const [branches, setBranches] = useState2(BRANCHES_FALLBACK);
  const [query, setQuery] = useState2("");
  const [selected, setSelected] = useState2(null);
  const mapRef = React.useRef(null);
  const mapEl = React.useRef(null);
  const markers = React.useRef({});
  const listRef = React.useRef(null);

  // Cargar sucursales reales del REST del sitio.
  React.useEffect(() => {
    if (!VCFG2.sucursalesApi) return;
    fetch(VCFG2.sucursalesApi)
      .then((r) => r.json())
      .then((res) => {
        if (res && res.success && Array.isArray(res.data) && res.data.length) {
          const mapped = res.data.map((s) => ({
            id: "s" + s.id,
            name: s.nombre,
            region: "",
            addr: s.direccion || "",
            hours: s.horario || "",
            phone: s.telefono || "",
            wa: s.whatsapp || null,
            idoficina: s.idoficina,
            lat: s.lat, lng: s.lng,
            main: !!s.principal,
          }));
          setBranches(mapped);
          setSelected(mapped[0] ? mapped[0].id : null);
        }
      })
      .catch(() => {});
  }, []);

  const filtered = branches.filter((b) => {
    const q = query.trim().toLowerCase();
    if (!q) return true;
    return (b.name + " " + b.addr + " " + b.region).toLowerCase().includes(q);
  });

  React.useEffect(() => {
    if (!window.L || mapRef.current || !mapEl.current) return;
    const L = window.L;
    const map = L.map(mapEl.current, { center: [18.9, -70.4], zoom: 8, scrollWheelZoom: false, zoomControl: true });
    L.tileLayer("https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png", { attribution: "© OpenStreetMap · © CARTO", maxZoom: 19 }).addTo(map);
    mapRef.current = map;
    setTimeout(() => map.invalidateSize(), 200);
    return () => { map.remove(); mapRef.current = null; };
  }, []);

  // (Re)dibujar marcadores cuando cambian las sucursales.
  React.useEffect(() => {
    const L = window.L;
    if (!L || !mapRef.current) return;
    Object.values(markers.current).forEach((m) => mapRef.current.removeLayer(m));
    markers.current = {};
    const makeIcon = (active) => L.divIcon({
      className: "", iconSize: [34, 44], iconAnchor: [17, 42], popupAnchor: [0, -40],
      html: `<div style="width:34px;height:44px"><svg width="34" height="44" viewBox="0 0 34 44" fill="none"><path d="M17 43C17 43 32 27 32 15A15 15 0 1 0 2 15C2 27 17 43 17 43Z" fill="${active ? "#CEB273" : "#1379CC"}" stroke="#071E3D" stroke-width="2.5"/><circle cx="17" cy="15" r="5.5" fill="#071E3D"/></svg></div>`,
    });
    branches.forEach((b) => {
      const m = L.marker([b.lat, b.lng], { icon: makeIcon(b.id === selected) }).addTo(mapRef.current);
      m.bindPopup(popupHTML(b), { closeButton: true, className: "vc-leaflet-popup" });
      m.on("click", () => setSelected(b.id));
      markers.current[b.id] = m;
    });
  }, [branches]);

  React.useEffect(() => {
    const L = window.L;
    if (!L || !mapRef.current || !selected) return;
    const b = branches.find((x) => x.id === selected);
    Object.entries(markers.current).forEach(([id, m]) => {
      const active = id === selected;
      m.setIcon(L.divIcon({
        className: "", iconSize: active ? [40, 52] : [34, 44], iconAnchor: active ? [20, 50] : [17, 42], popupAnchor: [0, active ? -46 : -40],
        html: `<div style="width:34px;height:44px"><svg width="34" height="44" viewBox="0 0 34 44" fill="none"><path d="M17 43C17 43 32 27 32 15A15 15 0 1 0 2 15C2 27 17 43 17 43Z" fill="${active ? "#CEB273" : "#1379CC"}" stroke="#071E3D" stroke-width="2.5"/><circle cx="17" cy="15" r="5.5" fill="#071E3D"/></svg></div>`,
      }));
    });
    if (b) {
      mapRef.current.flyTo([b.lat, b.lng], 11, { duration: 0.7 });
      markers.current[b.id] && markers.current[b.id].openPopup();
      const node = listRef.current && listRef.current.querySelector(`[data-branch="${b.id}"]`);
      if (node && listRef.current) {
        listRef.current.scrollTo({ top: node.offsetTop - listRef.current.offsetTop - 8, behavior: "smooth" });
      }
    }
  }, [selected]);

  const nearest = () => {
    if (!navigator.geolocation) { setSelected(branches[0] && branches[0].id); return; }
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        const { latitude, longitude } = pos.coords;
        let best = branches[0], bd = Infinity;
        branches.forEach((b) => {
          const d = (b.lat - latitude) ** 2 + (b.lng - longitude) ** 2;
          if (d < bd) { bd = d; best = b; }
        });
        best && setSelected(best.id);
      },
      () => setSelected(branches[0] && branches[0].id),
      { timeout: 6000 }
    );
  };

  return (
    <section id="sucursales" style={{ padding: "120px 0", background: "var(--vc-cream-2)" }}>
      <div className="vc-shell">
        <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 32, alignItems: "end", marginBottom: 40 }} className="vc-section-head">
          <div>
            <span className="vc-eyebrow">Nuestra red</span>
            <h2 className="vc-section-title">Encuentra tu vía <br /> más cercana.</h2>
          </div>
          <div style={{ textAlign: "right" }}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 44, color: "var(--vc-blue)", lineHeight: 1, letterSpacing: "-0.03em" }}>{branches.length}</div>
            <div style={{ fontSize: 13, color: "var(--vc-ink-mute)", fontWeight: 600 }}>paradas en todo el país</div>
          </div>
        </div>

        <div className="vc-suc-layout" style={{ display: "grid", gridTemplateColumns: "380px 1fr", gap: 0, background: "var(--vc-white)", borderRadius: "var(--r-lg)", overflow: "hidden", border: "1px solid var(--vc-line)", boxShadow: "var(--shadow-card)", height: 560 }}>
          <div style={{ display: "flex", flexDirection: "column", borderRight: "1px solid var(--vc-line)", minHeight: 0 }}>
            <div style={{ padding: 18, borderBottom: "1px solid var(--vc-line)" }}>
              <div style={{ position: "relative" }}>
                <span style={{ position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)", color: "var(--vc-ink-mute)" }}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" strokeLinecap="round" /></svg>
                </span>
                <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Buscar sucursal, ciudad o zona…"
                  style={{ width: "100%", padding: "13px 14px 13px 40px", border: "1.5px solid var(--vc-line-strong)", borderRadius: 12, fontSize: 14, fontFamily: "var(--font-sans)", outline: "none", background: "var(--vc-cream)", color: "var(--vc-ink)" }}
                  onFocus={(e) => e.target.style.borderColor = "var(--vc-blue)"}
                  onBlur={(e) => e.target.style.borderColor = "var(--vc-line-strong)"}
                />
              </div>
              <button onClick={nearest} className="vc-btn" style={{ width: "100%", justifyContent: "center", marginTop: 12 }}>
                <Icon.Pin size={16} /> Ver la sucursal más cercana
              </button>
            </div>

            <div style={{ padding: "10px 18px", background: "var(--vc-navy)", color: "#fff", fontSize: 12.5, fontWeight: 700, letterSpacing: ".04em", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <span>{filtered.length} sucursal{filtered.length === 1 ? "" : "es"} encontrada{filtered.length === 1 ? "" : "s"}</span>
              <span style={{ color: "var(--vc-yellow)" }}>Vía Courier</span>
            </div>

            <div ref={listRef} style={{ overflowY: "auto", flex: 1, minHeight: 0 }}>
              {filtered.length === 0 && (
                <div style={{ padding: 24, textAlign: "center", color: "var(--vc-ink-mute)", fontSize: 14 }}>Sin resultados para “{query}”.</div>
              )}
              {filtered.map((b) => (
                <BranchRow key={b.id} b={b} active={b.id === selected} onSelect={() => setSelected(b.id)} />
              ))}
            </div>
          </div>

          <div style={{ position: "relative", minHeight: 0 }}>
            <div ref={mapEl} style={{ position: "absolute", inset: 0 }} />
          </div>
        </div>
      </div>
    </section>
  );
}

function regLink(b) {
  const cfg = window.VCF_CFG || {};
  if (!cfg.registerBase || b.idoficina == null) return null;
  return cfg.registerBase.replace("{idoficina}", encodeURIComponent(b.idoficina));
}

function popupHTML(b) {
  const reg = regLink(b);
  const maps = `https://www.google.com/maps/dir/?api=1&destination=${b.lat},${b.lng}`;
  const wa = b.wa ? ("https://wa.me/" + b.wa) : null;
  return `<div style="font-family:'Plus Jakarta Sans',sans-serif;min-width:212px">
    <div style="font-family:'Bricolage Grotesque',sans-serif;font-weight:800;font-size:15px;color:#0A1A2E">${b.name}</div>
    ${b.addr ? `<div style="font-size:12px;color:#35506E;margin-top:4px">${b.addr}</div>` : ""}
    ${b.phone ? `<div style="font-size:12px;color:#1379CC;margin-top:6px;font-weight:600">${b.phone}</div>` : ""}
    ${reg ? `<a href="${reg}" target="_blank" rel="noopener" style="display:block;text-align:center;margin-top:10px;padding:10px 12px;border-radius:9px;background:var(--vc-yellow);color:#0A1A2E;font-weight:700;font-size:13px;text-decoration:none">Regístrate en esta sucursal</a>` : ""}
    <div style="display:flex;gap:6px;margin-top:6px">
      <a href="${maps}" target="_blank" rel="noopener" style="flex:1;text-align:center;padding:8px;border-radius:9px;border:1.5px solid #C4D6EC;color:#0A1A2E;font-weight:600;font-size:12px;text-decoration:none">Cómo llegar</a>
      ${wa ? `<a href="${wa}" target="_blank" rel="noopener" style="flex:1;text-align:center;padding:8px;border-radius:9px;background:#22B473;color:#fff;font-weight:700;font-size:12px;text-decoration:none">WhatsApp</a>` : ""}
    </div>
  </div>`;
}

function BranchRow({ b, active, onSelect }) {
  const wa = b.wa ? ("https://wa.me/" + b.wa) : (b.phone ? ("https://wa.me/1809" + b.phone.replace(/\D/g, "").slice(-7)) : null);
  const reg = regLink(b);
  return (
    <div data-branch={b.id} onClick={onSelect}
      style={{ padding: "16px 18px", borderBottom: "1px solid var(--vc-line)", cursor: "pointer", position: "relative", background: active ? "var(--vc-blue-soft)" : "transparent", transition: "background .15s ease" }}
      onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = "var(--vc-cream)"; }}
      onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = "transparent"; }}
    >
      {active && <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 4, background: "var(--vc-yellow)" }} />}
      <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
        <h3 style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16.5, letterSpacing: "-0.01em", color: "var(--vc-ink)" }}>{b.name}</h3>
        {b.main && <span className="vc-route-shield" style={{ fontSize: 10, padding: "1px 7px" }}>PRINCIPAL</span>}
      </div>
      {b.addr && (
        <div style={{ fontSize: 13, color: "var(--vc-ink-soft)", marginTop: 6, lineHeight: 1.45, display: "flex", gap: 7 }}>
          <span style={{ color: "var(--vc-blue)", flexShrink: 0, marginTop: 1 }}><Icon.Pin size={14} /></span>
          {b.addr}
        </div>
      )}
      {b.hours && <div style={{ fontSize: 12.5, color: "var(--vc-ink-mute)", marginTop: 6 }}>{b.hours}</div>}
      {reg && (
        <a href={reg} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()}
          style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7, marginTop: 12, padding: "10px 12px", borderRadius: 10, background: "var(--vc-yellow)", color: "var(--vc-ink)", fontSize: 13, fontWeight: 700 }}>
          <Icon.Arrow size={14} /> Regístrate en esta sucursal
        </a>
      )}
      <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
        <a href={`https://www.google.com/maps/dir/?api=1&destination=${b.lat},${b.lng}`} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()}
          style={{ flex: 1, textAlign: "center", padding: "9px 10px", borderRadius: 10, border: "1.5px solid var(--vc-line-strong)", fontSize: 13, fontWeight: 600, color: "var(--vc-ink)", background: "var(--vc-white)" }}>Cómo llegar</a>
        {wa && (
          <a href={wa} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()}
            style={{ flex: 1, textAlign: "center", padding: "9px 10px", borderRadius: 10, background: "var(--vc-green)", color: "#fff", fontSize: 13, fontWeight: 700 }}>WhatsApp</a>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   APP
   ============================================================ */

function VCApp() {
  return (
    <section style={{ padding: "120px 0", position: "relative", overflow: "hidden", background: "radial-gradient(120% 120% at 15% 10%, var(--vc-blue-deep) 0%, var(--vc-navy) 55%, #04122a 100%)", color: "#fff" }}>
      <svg aria-hidden style={{ position: "absolute", left: 0, top: 0, width: "100%", height: "100%", opacity: .5, pointerEvents: "none" }}>
        <defs>
          <pattern id="appdots" x="0" y="0" width="32" height="32" patternUnits="userSpaceOnUse">
            <circle cx="2" cy="2" r="1.4" fill="rgba(255,255,255,.1)" />
          </pattern>
        </defs>
        <rect width="100%" height="100%" fill="url(#appdots)" />
      </svg>
      <div aria-hidden style={{ position: "absolute", right: "-4%", bottom: "-8%", width: 460, height: 460, borderRadius: "50%", background: "radial-gradient(circle, rgba(206,178,115,.18), transparent 62%)", pointerEvents: "none" }} />

      <div className="vc-shell" style={{ position: "relative" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 0.9fr", gap: 64, alignItems: "center" }} className="vc-app-grid">
          <div>
            <span className="vc-eyebrow" style={{ color: "var(--vc-yellow)" }}>App disponible</span>
            <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "clamp(40px, 5vw, 76px)", lineHeight: 0.98, letterSpacing: "-0.035em", margin: "16px 0 0", textWrap: "balance", color: "#fff" }}>
              Tu vía, <br />
              <span style={{ color: "var(--vc-yellow)" }}>en el bolsillo.</span>
            </h2>
            <p style={{ fontSize: 18, lineHeight: 1.55, color: "rgba(255,255,255,.78)", maxWidth: "40ch", marginTop: 24 }}>
              Rastrea envíos, recibe notificaciones cuando tu paquete llegue a Miami
              y gestiona pagos — todo desde Vía Courier Pack.
            </p>
            <ul style={{ listStyle: "none", padding: 0, margin: "32px 0 0", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              {["Rastrea envíos en vivo", "Notificaciones al instante", "Pre-alerta de paquetes", "100% gratis"].map((t, i) => (
                <li key={i} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 14.5, fontWeight: 500, color: "rgba(255,255,255,.9)" }}>
                  <span style={{ width: 22, height: 22, borderRadius: "50%", background: "var(--vc-yellow)", color: "var(--vc-navy)", display: "grid", placeItems: "center" }}>
                    <Icon.Check size={12} />
                  </span>
                  {t}
                </li>
              ))}
            </ul>
            <div style={{ display: "flex", gap: 12, marginTop: 36, flexWrap: "wrap" }}>
              <StoreBadge store="apple" />
              <StoreBadge store="google" />
            </div>
          </div>

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

function StoreBadge({ store }) {
  const isApple = store === "apple";
  const href = isApple
    ? "https://apps.apple.com/do/app/via-courier/id1631621463"
    : "https://play.google.com/store/apps/details?id=com.viacourierpack.appmovil&hl=es_DO";
  return (
    <a href={href} target="_blank" rel="noopener" style={{ display: "flex", alignItems: "center", gap: 12, background: "var(--vc-white)", color: "var(--vc-navy)", padding: "12px 22px", borderRadius: 14, transition: "transform .15s ease, box-shadow .2s ease" }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "var(--shadow-pop)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = "none"; }}
    >
      {isApple ? (
        <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor">
          <path d="M17.05 12.04c-.02-2.86 2.34-4.24 2.45-4.31-1.34-1.96-3.42-2.22-4.16-2.25-1.77-.18-3.46 1.04-4.36 1.04-.92 0-2.3-1.02-3.79-.99-1.95.03-3.75 1.13-4.75 2.87-2.03 3.52-.52 8.71 1.46 11.55.96 1.39 2.11 2.94 3.6 2.88 1.45-.06 2-.93 3.75-.93 1.74 0 2.24.93 3.77.9 1.55-.03 2.54-1.4 3.49-2.8 1.1-1.6 1.55-3.16 1.58-3.24-.04-.02-3.03-1.16-3.06-4.6Z M14.4 4.3c.78-.95 1.32-2.27 1.17-3.59-1.13.05-2.5.75-3.3 1.69-.72.83-1.36 2.18-1.18 3.48 1.25.1 2.54-.64 3.31-1.58Z" />
        </svg>
      ) : (
        <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor">
          <path d="M3.6 1.6c-.4.4-.6 1-.6 1.7v17.4c0 .7.2 1.3.6 1.7l10-10-10-10.8Zm11.2 11.5 2.6 2.6-12.6 7.3 10-9.9Zm5-3.5-3.3-1.9-2.8 2.8 2.8 2.8 3.3-1.9c1.2-.7 1.2-2.1 0-2.8Zm-5-3.4-10-5.8 12.6 7.3-2.6 2.5-1.6-1.6-.4-.4 2-2Z" />
        </svg>
      )}
      <div style={{ lineHeight: 1.1 }}>
        <div style={{ fontSize: 10, opacity: .6 }}>{isApple ? "Descarga en el" : "Disponible en"}</div>
        <div style={{ fontSize: 17, fontWeight: 700 }}>{isApple ? "App Store" : "Google Play"}</div>
      </div>
    </a>
  );
}

function PhoneMock() {
  return (
    <div style={{ display: "grid", placeItems: "center", position: "relative" }}>
      <div style={{ position: "absolute", left: "-8%", top: "12%", zIndex: 0, background: "var(--vc-white)", borderRadius: 14, padding: "12px 14px", boxShadow: "var(--shadow-pop)", width: 230, transform: "rotate(-5deg)", display: "flex", gap: 10, alignItems: "flex-start" }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: "var(--vc-yellow)", display: "grid", placeItems: "center", flexShrink: 0 }}>📦</div>
        <div>
          <div style={{ fontSize: 11, color: "var(--vc-ink-mute)", fontWeight: 600 }}>VÍA COURIER · Ahora</div>
          <div style={{ fontSize: 13, fontWeight: 600, marginTop: 2, lineHeight: 1.3 }}>Tu paquete VIA-00427 llegó a Miami</div>
        </div>
      </div>

      <div style={{ width: 280, height: 580, background: "var(--vc-ink)", borderRadius: 42, padding: 8, position: "relative", boxShadow: "0 40px 80px -20px rgba(15,24,32,.5)", zIndex: 1 }}>
        <div style={{ width: "100%", height: "100%", background: "var(--vc-cream)", borderRadius: 36, overflow: "hidden", position: "relative", padding: "44px 18px 18px" }}>
          <div style={{ position: "absolute", top: 12, left: "50%", transform: "translateX(-50%)", width: 96, height: 26, background: "var(--vc-ink)", borderRadius: 16 }} />
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, fontWeight: 600, color: "var(--vc-ink-mute)", marginBottom: 18 }}>
            <span>9:41</span>
            <span>●●●● 5G ▮</span>
          </div>
          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 12, color: "var(--vc-ink-mute)", fontWeight: 600 }}>Hola, Carla 👋</div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22, letterSpacing: "-0.02em", marginTop: 2 }}>Tus paquetes</div>
          </div>
          <div style={{ background: "var(--vc-ink)", color: "var(--vc-cream)", borderRadius: 18, padding: 16, marginBottom: 12 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--vc-yellow)", fontWeight: 600, letterSpacing: ".1em" }}>
              <span>VIA-00427</span>
              <span>EN TRÁNSITO</span>
            </div>
            <div style={{ fontWeight: 700, marginTop: 6, fontSize: 15 }}>Amazon · 3 ítems</div>
            <div style={{ display: "flex", gap: 4, marginTop: 14, alignItems: "center" }}>
              {["USA", "MIA", "SDQ", "RD"].map((s, i) => (
                <React.Fragment key={s}>
                  <span style={{ width: 10, height: 10, borderRadius: "50%", background: i <= 1 ? "var(--vc-yellow)" : "rgba(251,246,236,.2)" }} />
                  {i < 3 && <div style={{ flex: 1, height: 2, background: i < 1 ? "var(--vc-yellow)" : "rgba(251,246,236,.2)" }} />}
                </React.Fragment>
              ))}
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 9.5, marginTop: 6, color: "rgba(251,246,236,.55)", fontWeight: 600, letterSpacing: ".06em" }}>
              <span>USA</span><span>MIA</span><span>SDQ</span><span>RD</span>
            </div>
          </div>
          {[{ id: "VIA-00425", desc: "Shein · 1 ítem", status: "Listo para retiro" }, { id: "VIA-00422", desc: "eBay · 2 ítems", status: "Entregado" }].map((p) => (
            <div key={p.id} style={{ background: "var(--vc-white)", borderRadius: 14, padding: 12, marginBottom: 8 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--vc-ink-mute)", fontWeight: 600 }}>
                <span>{p.id}</span>
                <span style={{ color: "var(--vc-green)" }}>{p.status}</span>
              </div>
              <div style={{ fontWeight: 600, marginTop: 4, fontSize: 13 }}>{p.desc}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   FOOTER
   ============================================================ */

function VCFooter() {
  return (
    <footer style={{ background: "var(--vc-ink)", color: "var(--vc-cream)", paddingTop: 96, paddingBottom: 32 }}>
      <div className="vc-shell">
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 64, paddingBottom: 64, borderBottom: "1px solid rgba(251,246,236,.12)" }} className="vc-footer-top">
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(56px, 8vw, 120px)", letterSpacing: "-0.035em", lineHeight: 0.95 }}>
              ¿Empezamos <br /> a comprar?
            </div>
            <p style={{ fontSize: 17, lineHeight: 1.5, color: "rgba(251,246,236,.65)", maxWidth: "42ch", marginTop: 24 }}>
              Tu compañero de compras en línea, siempre en tu bolsillo. Explora,
              rastrea y gestiona tus envíos con un toque.
            </p>
          </div>

          <div style={{ background: "rgba(251,246,236,.05)", border: "1px solid rgba(251,246,236,.12)", borderRadius: "var(--r-lg)", padding: 28 }}>
            <div style={{ fontSize: 12, color: "var(--vc-yellow)", fontWeight: 600, letterSpacing: ".18em", textTransform: "uppercase" }}>Crea tu casillero</div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 32, letterSpacing: "-0.02em", marginTop: 6, lineHeight: 1.1 }}>Toma 2 minutos. <br /> Es gratis.</div>
            <div style={{ display: "flex", gap: 10, marginTop: 24, flexWrap: "wrap" }}>
              <a href={VCFG2.registerUrl || "#register"} className="vc-btn vc-btn--yellow">Registrarme <Icon.Arrow /></a>
              <a href={VCFG2.accountUrl || "#login"} className="vc-btn" style={{ background: "rgba(251,246,236,.1)", color: "var(--vc-cream)" }}>Ya tengo cuenta</a>
            </div>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr", gap: 32, padding: "56px 0" }} className="vc-footer-cols">
          <div>
            <div style={{ marginBottom: 20 }}>
              {(VCFG2.logoWhite || VCFG2.logo)
                ? <img src={VCFG2.logoWhite || VCFG2.logo} alt="Vía Courier" style={{ height: 96, width: "auto", display: "block", filter: VCFG2.logoWhite ? "none" : "brightness(0) invert(1)" }} />
                : <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22, letterSpacing: "-0.02em" }}>Vía Courier</span>}
            </div>
            <div style={{ fontSize: 13, color: "rgba(251,246,236,.6)", lineHeight: 1.55 }}>
              <strong style={{ color: "var(--vc-cream)" }}>Miami, FL</strong><br />
              7715 NW 46th Street, Doral, FL 33195<br />
              <a href="tel:+13058481017" style={{ color: "var(--vc-yellow)" }}>+1-305-848-1017</a>
              <br /><br />
              <strong style={{ color: "var(--vc-cream)" }}>Santo Domingo</strong><br />
              Av. 27 de Febrero 282, Don Bosco<br />
              <a href="tel:+18097073995" style={{ color: "var(--vc-yellow)" }}>(809) 707-3995</a>
              <br />
              Lun – Vie: 9:00am – 6:00pm
            </div>
            <div style={{ display: "flex", gap: 8, marginTop: 24 }}>
              <a href={VCFG2.instagram || "https://www.instagram.com/viacourieroficial/"} target="_blank" rel="noopener" style={{ width: 38, height: 38, borderRadius: "50%", background: "rgba(251,246,236,.08)", color: "var(--vc-cream)", display: "grid", placeItems: "center" }}><Icon.Instagram /></a>
            </div>
          </div>

          {[
            { title: "Enlaces rápidos", links: [["Nosotros", VCFG2.nosotrosUrl || "#"], ["Sucursales", VCFG2.sucursalesUrl || "#"], ["Rastrea tu paquete", VCFG2.rastreoUrl || "#"], ["Consulta RUA", VCFG2.rua || "#"]] },
            { title: "Mi cuenta", links: [["Regístrate", VCFG2.registerUrl || "#"], ["Iniciar sesión", VCFG2.accountUrl || "#"]] },
            { title: "Trabaja con nosotros", links: [["Adquiere franquicia", VCFG2.franquiciasUrl || "#"], ["Contacto", VCFG2.whatsapp || "#"]] },
          ].map((col) => (
            <div key={col.title}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".18em", color: "var(--vc-yellow)", textTransform: "uppercase", marginBottom: 18 }}>{col.title}</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12 }}>
                {col.links.map((l) => {
                  const [label, href] = l;
                  const ext = /^https?:\/\//.test(href) && href.indexOf("viacourier.com.do") === -1;
                  return (
                    <li key={label}>
                      <a href={href} target={ext ? "_blank" : undefined} rel={ext ? "noopener" : undefined}
                        style={{ fontSize: 14, color: "rgba(251,246,236,.75)", transition: "color .15s ease" }}
                        onMouseEnter={(e) => e.currentTarget.style.color = "var(--vc-yellow)"}
                        onMouseLeave={(e) => e.currentTarget.style.color = "rgba(251,246,236,.75)"}
                      >{label}</a>
                    </li>
                  );
                })}
              </ul>
            </div>
          ))}
        </div>

        <div style={{ paddingTop: 32, borderTop: "1px solid rgba(251,246,236,.12)", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap", fontSize: 12.5, color: "rgba(251,246,236,.5)" }}>
          <span>© 2026 Vía Courier. Todos los derechos reservados.</span>
          <span>Diseñado con ♥ por <a href="https://pixelescreativos.com.do/" style={{ color: "var(--vc-yellow)" }}>Pixeles Creativos</a></span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { VCTiendas, VCComoFunciona, VCSucursales, VCApp, VCFooter });
