// HOME — v2: Lovable-inspired layout
const { useState, useEffect, useRef } = React;

const HOME_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "mood": "lavender",
  "heroComp": "offer",
  "density": 1.0
} /*EDITMODE-END*/;

const MOODS = {
  lavender: {
    label: "Lovable Lavender",
    "--paper": "#ECE6F2", "--paper-2": "#E2D8EC", "--paper-3": "#D4C8E0",
    "--ink": "#1A0F2E", "--ink-2": "#3A2D4E", "--ink-3": "#6E6280", "--ink-4": "#A399B0",
    "--line": "#D6CCE3", "--brand": "#ED0F44", "--brand-coral": "#FF4D7C",
    "--plum": "#2B1A2E"
  },
  caribbean: {
    label: "Caribbean Sun",
    "--paper": "#FBF5EA", "--paper-2": "#F4EAD3", "--paper-3": "#EBDDBE",
    "--ink": "#1F2410", "--ink-2": "#3A3C26", "--ink-3": "#6B6B52", "--ink-4": "#9F9F86",
    "--line": "#E0D2B6", "--brand": "#E8421C", "--brand-coral": "#F8A33B",
    "--plum": "#1F4032"
  },
  midnight: {
    label: "Midnight Plum",
    "--paper": "#180A1E", "--paper-2": "#23102C", "--paper-3": "#2E1638",
    "--ink": "#F5EBFB", "--ink-2": "#D6C6E0", "--ink-3": "#9888A8", "--ink-4": "#6B5E78",
    "--line": "#3A1F46", "--brand": "#FF3D6E", "--brand-coral": "#FF85A8",
    "--plum": "#0E0613"
  }
};

function TopBadge() {
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 14, padding: "8px 16px 8px 8px", borderRadius: 999, background: "#fff", border: "1px solid var(--line)", boxShadow: "0 6px 16px -8px rgba(26,16,36,0.12)" }}>
      <div style={{ display: "flex" }}>
        {[0, 1, 2, 3].map((i) =>
        <div key={i} style={{ width: 26, height: 26, borderRadius: 999, background: ["#FF7A4D", "#ED0F44", "#FF4D7C", "#8B0524"][i], border: "2px solid #fff", marginLeft: i === 0 ? 0 : -8 }} />
        )}
      </div>
      <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink-2)" }}>+1,200 clientes <span style={{ color: "var(--ink-4)", margin: "0 8px" }}>·</span> ⭐ 4.9</div>
    </div>);

}

// ────────────────────────────────────────────────────────────────────────
// HeroStatsBadge — White pill with stacked colored dots (avatar-style) +
// rotating live business stats with count-up animation.
// Replaces the previous static "25 AÑOS" hero badge.
// ────────────────────────────────────────────────────────────────────────
const HERO_STATS = [
  { n: 49000, prefix: "+", label: "clientes visitan nuestras tiendas / mes", rating: 4.9 },
  { n: 10000, prefix: "+", label: "activaciones mensuales" },
];

function HeroStatsBadge() {
  const [idx, setIdx] = useState(0);
  const [count, setCount] = useState(0);
  const reducedMotion = typeof window !== "undefined" &&
    window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  // Rotate every 4.2s
  useEffect(() => {
    if (reducedMotion) return;
    const t = setInterval(() => setIdx((i) => (i + 1) % HERO_STATS.length), 4200);
    return () => clearInterval(t);
  }, [reducedMotion]);

  // Count-up on each rotation
  useEffect(() => {
    const target = HERO_STATS[idx].n;
    if (reducedMotion) { setCount(target); return; }
    const start = performance.now();
    const duration = 1100;
    let rafId;
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);   // ease-out cubic
      setCount(Math.round(target * eased));
      if (t < 1) rafId = requestAnimationFrame(tick);
    };
    rafId = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafId);
  }, [idx, reducedMotion]);

  const cur = HERO_STATS[idx];
  const numText = count.toLocaleString("es-DO");
  const dotColors = ["#FF7A4D", "#ED0F44", "#FF4D7C", "#8B0524"];

  return (
    <div className="hero-stats-badge" role="status" aria-live="polite" aria-atomic="true">
      {/* Stacked colored dots (decorative; same visual as previous TopBadge) */}
      <div className="hero-stats-avatars" aria-hidden="true">
        {dotColors.map((c, i) => (
          <span key={i} className="hero-stats-avatar" style={{
            background: c,
            marginLeft: i === 0 ? 0 : -10,
            animationDelay: `${i * 0.12}s`,
          }} />
        ))}
      </div>

      {/* Rotating stat */}
      <div className="hero-stats-content" key={idx}>
        <span className="hero-stats-number" aria-hidden="true">
          <span className="hero-stats-prefix">{cur.prefix}</span>
          <span className="hero-stats-digits">{numText}</span>
        </span>
        <span className="hero-stats-label">{cur.label}</span>
        {cur.rating != null && (
          <span className="hero-stats-rating" aria-hidden="true">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 2l2.4 7.4H22l-6 4.4 2.3 7.2L12 16.7 5.7 21l2.3-7.2-6-4.4h7.6z"/>
            </svg>
            <span>{cur.rating.toFixed(1)}</span>
          </span>
        )}
        {/* Screen-reader friendly: full sentence */}
        <span className="sr-only">
          {cur.prefix}{cur.n.toLocaleString("es-DO")} {cur.label}
          {cur.rating != null ? `, valoración ${cur.rating.toFixed(1)} estrellas` : ""}
        </span>
      </div>

      {/* Progress dots */}
      <span className="hero-stats-progress" aria-hidden="true">
        {HERO_STATS.map((_, i) => (
          <span key={i} className={`hero-stats-pdot${i === idx ? " is-active" : ""}`} />
        ))}
      </span>

      <style>{`
        .hero-stats-badge {
          display: inline-flex; align-items: center; gap: 14px;
          padding: 8px 22px 8px 8px;
          border-radius: 999px;
          background: #fff;
          border: 1px solid var(--line);
          box-shadow: 0 8px 20px -10px rgba(26,16,36,0.18), 0 1px 1px rgba(26,16,36,0.04);
          margin-bottom: 32px;
          position: relative;
        }
        .hero-stats-avatars {
          display: inline-flex; align-items: center;
          flex-shrink: 0;
        }
        .hero-stats-avatar {
          width: 26px; height: 26px; border-radius: 999px;
          border: 2px solid #fff;
          box-shadow: 0 2px 4px -1px rgba(26,16,36,0.18);
          animation: bal-stats-avatar-pulse 3.2s ease-in-out infinite;
        }
        @keyframes bal-stats-avatar-pulse {
          0%, 100% { transform: scale(1); }
          50%      { transform: scale(1.08); }
        }

        .hero-stats-content {
          display: inline-flex; align-items: baseline; gap: 8px;
          flex-wrap: wrap;
          min-width: 0;
          animation: bal-hero-stats-in 480ms cubic-bezier(0.32,0.72,0,1) both;
        }
        @keyframes bal-hero-stats-in {
          from { opacity: 0; transform: translateY(4px); }
          to   { opacity: 1; transform: translateY(0); }
        }

        .hero-stats-number {
          display: inline-flex; align-items: baseline; gap: 1px;
          font-size: 15px; font-weight: 800; letter-spacing: -0.015em;
          color: var(--ink);
          line-height: 1;
          font-variant-numeric: tabular-nums;
        }
        .hero-stats-prefix { color: var(--brand); font-size: 13px; font-weight: 700; }
        .hero-stats-digits { color: var(--ink); }

        .hero-stats-label {
          font-size: 13px; font-weight: 500; color: var(--ink-2);
          line-height: 1.2;
        }

        .hero-stats-rating {
          display: inline-flex; align-items: center; gap: 3px;
          padding: 2px 8px;
          border-radius: 999px;
          background: linear-gradient(135deg, #FFE39A 0%, #FFC85C 100%);
          color: #6B4D00;
          font-size: 12px; font-weight: 700;
          letter-spacing: 0;
          font-variant-numeric: tabular-nums;
          box-shadow: inset 0 1px 0 rgba(255,255,255,0.5);
        }
        .hero-stats-rating svg {
          filter: drop-shadow(0 0 2px rgba(255,200,92,0.6));
        }

        .hero-stats-progress {
          display: inline-flex; align-items: center; gap: 3px;
          flex-shrink: 0;
          margin-left: 4px;
          padding-left: 10px;
          border-left: 1px solid var(--line);
        }
        .hero-stats-pdot {
          width: 4px; height: 4px; border-radius: 999px;
          background: var(--paper-3);
          transition: width 320ms cubic-bezier(0.32,0.72,0,1), background 200ms;
        }
        .hero-stats-pdot.is-active {
          width: 14px;
          background: var(--brand);
        }

        .sr-only {
          position: absolute; width: 1px; height: 1px;
          padding: 0; margin: -1px; overflow: hidden;
          clip: rect(0,0,0,0); white-space: nowrap; border: 0;
        }

        @media (max-width: 480px) {
          .hero-stats-badge { padding: 6px 16px 6px 6px; gap: 10px; }
          .hero-stats-avatar { width: 22px; height: 22px; margin-left: -8px !important; }
          .hero-stats-avatar:first-child { margin-left: 0 !important; }
          .hero-stats-number { font-size: 14px; }
          .hero-stats-label  { font-size: 12px; }
          .hero-stats-progress { padding-left: 8px; margin-left: 2px; }
        }
        @media (prefers-reduced-motion: reduce) {
          .hero-stats-avatar, .hero-stats-content { animation: none !important; }
          .hero-stats-pdot { transition: none; }
        }
      `}</style>
    </div>
  );
}

function HeroLeft() {
  return (
    <div className="reveal">
      <HeroStatsBadge />
      <h1 className="display" style={{ maxWidth: 720 }}>
        Conectividad para <span style={{ color: "var(--brand)" }}>cada momento</span> de tu vida
      </h1>
      <p className="lead" style={{ marginTop: 28, maxWidth: 480 }}>
        Distribuidor autorizado Claro desde 2001. Marcando la diferencia y conectando miles de dominicanos todos los meses.
      </p>
      <div style={{ display: "flex", gap: 14, marginTop: 36, flexWrap: "wrap" }}>
        <a href={window.balUrl("planes.html")} className="btn btn-brand">Ver planes <window.Icon.Arrow /></a>
        <a href={window.balUrl("equipos.html")} className="btn btn-ghost" style={{ background: "var(--paper)" }}>Comprar equipos</a>
      </div>
      <div style={{ display: "flex", gap: 28, marginTop: 36, flexWrap: "wrap", color: "var(--ink-2)" }}>
        {["20 Tiendas", "4 Provincias", "Canales digitales"].map((l) =>
        <div key={l} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 14 }}>
          <span style={{ color: "var(--brand)" }}><window.Icon.Check /></span>{l}
        </div>
        )}
      </div>
    </div>);
}

function HeroSlideshow() {
  const [slides, setSlides] = useState([]);
  const [idx, setIdx] = useState(0);
  const [paused, setPaused] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [failedImgs, setFailedImgs] = useState(() => new Set());  // índices de slides con imagen rota

  // Solo EQUIPOS — más vendidos (destacados) + con promo (en oferta). Sin planes.
  useEffect(() => {
    fetch(window.balUrl("admin/api/products.php?limit=40"))
      .then(r => (r.ok ? r.json() : { items: [] }))
      .then((prodRes) => {
        const all = (prodRes.items || []).filter(p => p.image && typeof p.image === "string" && p.image.length > 0);
        const onOffer = (p) => (p.price_old && p.price_old > p.price) ||
          (p.badges || []).some(b => /promo|oferta|descuento/i.test(b));
        // Califican: destacados (más vendidos) O en promo
        const qualified = all.filter(p => p.featured || onOffer(p));
        const pool = (qualified.length >= 2 ? qualified : all).slice(0, 6);

        const slides = pool.map(p => ({
          kind: "product",
          title: p.name,
          subtitle: p.spec || p.plan_tag || "",
          price: p.price,
          priceLabel: "Desde",
          image: p.image,
          badge: onOffer(p) ? "Promo" : (p.featured ? "Más vendido" : "Top"),
          href: window.balUrl(`equipo.html?slug=${encodeURIComponent(p.slug)}`),
        }));

        if (slides.length === 0) {
          slides.push({
            kind: "product",
            title: "Equipos Claro",
            subtitle: "iPhone, Samsung, Motorola y más",
            price: 0, priceLabel: "", image: null,
            badge: "Catálogo",
            href: window.balUrl("equipos.html"),
          });
        }
        setSlides(slides);
        setLoaded(true);
      })
      .catch(() => setLoaded(true));
  }, []);

  // Auto-rotate every 5s
  useEffect(() => {
    if (paused || slides.length < 2) return;
    const t = setInterval(() => setIdx(i => (i + 1) % slides.length), 5000);
    return () => clearInterval(t);
  }, [paused, slides.length]);

  const ready = loaded && slides.length > 0;
  const cur = ready ? slides[idx] : null;
  const isPlan = cur ? cur.kind === "plan" : false;

  return (
    <div className="reveal hero-slideshow" style={{ position: "relative" }}
         onMouseEnter={() => setPaused(true)}
         onMouseLeave={() => setPaused(false)}>
      <div style={{
        background: "linear-gradient(160deg, #2a1538 0%, #1a1024 50%, #2a1538 100%)",
        borderRadius: 32,
        padding: "32px 28px 56px",   // extra bottom padding reserves room for the dots
        color: "#fff",
        position: "relative", overflow: "hidden", aspectRatio: "5/5.5",
        display: "flex", flexDirection: "column", justifyContent: "space-between",
        boxShadow: "0 32px 80px -24px rgba(20,17,15,0.55), 0 4px 12px rgba(20,17,15,0.30)",
      }}>
        {/* Brand glow */}
        <div aria-hidden="true" style={{
          position: "absolute", top: -60, right: -60, width: 360, aspectRatio: 1,
          background: "radial-gradient(circle, rgba(237,15,68,0.30), transparent 60%)",
          pointerEvents: "none",
        }} />
        {/* Dot pattern */}
        <div aria-hidden="true" style={{
          position: "absolute", inset: 0,
          backgroundImage: "radial-gradient(rgba(255,255,255,0.05) 1px, transparent 1px)",
          backgroundSize: "20px 20px",
        }} />

        {/* Skeleton overlay — imita el layout real (eyebrow · teléfono · título/precio)
            para que el contenido aparezca en su lugar, sin "blob" central. */}
        <div aria-hidden={ready} style={{
          position: "absolute", inset: 0, zIndex: 3,
          display: "flex", flexDirection: "column", justifyContent: "space-between",
          padding: "32px 28px 56px",
          background: "linear-gradient(160deg, #2a1538 0%, #1a1024 50%, #2a1538 100%)",
          opacity: ready ? 0 : 1,
          pointerEvents: ready ? "none" : "auto",
          transition: "opacity 380ms cubic-bezier(0.32,0.72,0,1)",
        }}>
          {/* eyebrow */}
          <div className="bal-skel" style={{ width: 120, height: 11, borderRadius: 999 }} />
          {/* phone silhouette */}
          <div style={{ flex: 1, display: "grid", placeItems: "center", minHeight: 0 }}>
            <div className="bal-skel" style={{ width: "42%", maxWidth: 130, aspectRatio: "1/2", borderRadius: 22 }} />
          </div>
          {/* title + price */}
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <div className="bal-skel" style={{ width: "70%", height: 18, borderRadius: 8 }} />
            <div className="bal-skel" style={{ width: "40%", height: 22, borderRadius: 8 }} />
          </div>
        </div>

        {/* Header: kind + badge */}
        <div style={{ position: "relative", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div className="mini" style={{ color: "rgba(255,255,255,0.55)", letterSpacing: "0.16em" }}>
            {ready ? (isPlan ? "★ Plan destacado" : "★ Equipo destacado") : " "}
          </div>
          {ready && cur.badge && (
            <span style={{
              padding: "5px 12px", background: "var(--brand)", color: "#fff",
              borderRadius: 999, fontSize: 10.5, fontWeight: 700,
              letterSpacing: "0.08em", textTransform: "uppercase",
              boxShadow: "0 8px 20px -6px rgba(237,15,68,0.55)",
            }}>{cur.badge}</span>
          )}
        </div>

        {/* Slide content with fade animation */}
        <div key={idx} className="hero-slide-anim" style={{
          position: "relative", display: "flex", justifyContent: "center", alignItems: "center",
          flex: 1, padding: "16px 0", minHeight: 0,
        }}>
          {ready && (isPlan ? (
            <PlanSlideHero plan={cur} />
          ) : (cur.image && !failedImgs.has(idx) ? (
            <img src={cur.image} alt={cur.title} referrerPolicy="no-referrer"
              onError={() => setFailedImgs((s) => new Set(s).add(idx))}
              style={{ maxHeight: "100%", maxWidth: "85%", objectFit: "contain", filter: "drop-shadow(0 24px 32px rgba(0,0,0,0.45))" }} />
          ) : (
            <window.PhoneMock width={220} body="#1a1024" screen="linear-gradient(160deg,#FF7A4D 0%,#ED0F44 50%,#8B0524 100%)" />
          )))}
        </div>

        {/* Title + price + arrow */}
        <div style={{ position: "relative", visibility: ready ? "visible" : "hidden" }}>
          <div className="hero-slide-text" key={`txt-${idx}`}>
            <div style={{
              fontSize: "clamp(20px, 2.4vw, 28px)", fontWeight: 700,
              letterSpacing: "-0.018em", lineHeight: 1.15, color: "#fff",
            }}>{ready ? cur.title : "—"}</div>
            {ready && cur.subtitle && (
              <div style={{ fontSize: 13, color: "rgba(255,255,255,0.65)", marginTop: 6 }}>{cur.subtitle}</div>
            )}
          </div>
          <div style={{
            display: "flex", justifyContent: "space-between", alignItems: "flex-end",
            gap: 12, marginTop: 16,
          }}>
            <div style={{ minWidth: 0, flex: "1 1 auto" }}>
              {ready && cur.price > 0 ? (
                <>
                  <div className="caption" style={{ color: "rgba(255,255,255,0.55)" }}>{cur.priceLabel}</div>
                  <div style={{
                    fontSize: "clamp(20px, 6vw, 26px)",   // shrinks on narrow screens
                    fontWeight: 700, letterSpacing: "-0.02em",
                    color: "var(--brand-coral)", fontVariantNumeric: "tabular-nums",
                    lineHeight: 1.1,
                    wordBreak: "keep-all",
                  }}>RD${Math.round(cur.price).toLocaleString()}{isPlan ? <small style={{ fontSize: 14, opacity: 0.7, fontWeight: 500 }}>/mes</small> : ""}</div>
                </>
              ) : (
                <div style={{ fontSize: 14, color: "rgba(255,255,255,0.7)", fontWeight: 500 }}>{ready ? "A consultar" : "—"}</div>
              )}
            </div>
            <a href={ready ? cur.href : "#"} aria-label={ready ? `Ver ${cur.title}` : "Cargando"} style={{
              flexShrink: 0,
              width: 48, height: 48, borderRadius: 999, background: "var(--brand)", color: "#fff",
              display: "grid", placeItems: "center",
              boxShadow: "0 12px 28px -8px rgba(237,15,68,0.55)",
              transition: "transform 200ms cubic-bezier(0.32,0.72,0,1)",
            }}
              onMouseOver={(e) => e.currentTarget.style.transform = "scale(1.08)"}
              onMouseOut={(e) => e.currentTarget.style.transform = ""}
            ><window.Icon.Arrow /></a>
          </div>
        </div>

        {/* Dot indicators — capped to a sensible width so they never overflow on mobile */}
        {ready && slides.length > 1 && (
          <div style={{
            position: "absolute", bottom: 18, left: "50%", transform: "translateX(-50%)",
            display: "flex", gap: 6, zIndex: 2,
            maxWidth: "calc(100% - 56px)",         // leave breathing room on both sides
            flexWrap: "wrap", justifyContent: "center", rowGap: 6,
          }}>
            {slides.map((_, i) => (
              <button key={i} onClick={() => setIdx(i)} aria-label={`Ir al slide ${i + 1}`} style={{
                width: i === idx ? 22 : 7, height: 7, borderRadius: 999,
                background: i === idx ? "var(--brand)" : "rgba(255,255,255,0.30)",
                border: 0, cursor: "pointer", padding: 0,
                flexShrink: 0,
                transition: "width 280ms cubic-bezier(0.32,0.72,0,1), background 200ms",
              }} />
            ))}
          </div>
        )}
      </div>

      <style>{`
        @keyframes balSlideIn {
          from { opacity: 0; transform: translateY(8px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes balShimmer {
          0%   { background-position: 200% 0; }
          100% { background-position: -200% 0; }
        }
        .bal-skel {
          background: linear-gradient(100deg,
            rgba(255,255,255,0.05) 30%,
            rgba(255,255,255,0.13) 50%,
            rgba(255,255,255,0.05) 70%);
          background-size: 200% 100%;
          animation: balShimmer 1.6s ease-in-out infinite;
        }
        .hero-slide-anim, .hero-slide-text {
          animation: balSlideIn 480ms cubic-bezier(0.16,1,0.3,1) both;
        }
        .hero-slide-text { animation-delay: 80ms; }
        @media (prefers-reduced-motion: reduce) {
          .bal-skel { animation: none; }
          .hero-slide-anim, .hero-slide-text { animation: none; }
        }
      `}</style>
    </div>);
}

function PlanSlideHero({ plan }) {
  return (
    <div style={{
      width: "100%", display: "flex", flexDirection: "column",
      alignItems: "center", justifyContent: "center", gap: 16,
      padding: "12px 0",
    }}>
      <div style={{
        width: 84, height: 84, borderRadius: 24,
        background: "linear-gradient(135deg, var(--brand), var(--brand-deep))",
        color: "#fff", display: "grid", placeItems: "center",
        boxShadow: "0 16px 40px -10px rgba(237,15,68,0.55)",
      }}>
        <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7">
          <path d="M2 12a14 14 0 0 1 20 0M5 15.5a9 9 0 0 1 14 0M8 19a4 4 0 0 1 8 0"/>
          <circle cx="12" cy="21.5" r="1.2" fill="currentColor"/>
        </svg>
      </div>
      <div style={{
        fontSize: 56, fontWeight: 700, letterSpacing: "-0.035em",
        background: "linear-gradient(180deg, #ffeaef 0%, var(--brand-coral) 100%)",
        WebkitBackgroundClip: "text", backgroundClip: "text",
        WebkitTextFillColor: "transparent",
        fontVariantNumeric: "tabular-nums", lineHeight: 1,
      }}>
        {plan.subtitle.match(/\d+/)?.[0] || "1 Gbps"}
        <span style={{ fontSize: 16, marginLeft: 6, color: "rgba(255,255,255,0.6)", WebkitTextFillColor: "currentColor" }}>Mbps</span>
      </div>
    </div>
  );
}

// Backward-compat alias if anything else still references it
function HeroOfferCard() { return <HeroSlideshow />; }

function HeroPhoneStack() {
  return (
    <div className="reveal" style={{ display: "flex", justifyContent: "center", position: "relative", minHeight: 520 }}>
      <div style={{ position: "absolute", inset: "5% 10%", background: "radial-gradient(circle, var(--brand) 0%, transparent 60%)", filter: "blur(60px)", opacity: 0.5 }} />
      <window.PhoneMock width={300} body="#1a1024" screen="linear-gradient(160deg,#FF7A4D 0%,#ED0F44 50%,#8B0524 100%)" />
      <div style={{ position: "absolute", top: 28, left: -8, padding: "10px 14px", background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 14, boxShadow: "0 12px 32px -10px rgba(26,16,36,0.18)", display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ width: 8, height: 8, borderRadius: 999, background: "#22c55e" }} />
        <div><div style={{ fontSize: 10, color: "var(--ink-3)" }}>Activo</div><div style={{ fontSize: 12, fontWeight: 600, color: "var(--ink)" }}>Plan activado</div></div>
      </div>
      <div style={{ position: "absolute", bottom: 56, right: -16, padding: "12px 16px", background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 14, boxShadow: "0 12px 32px -10px rgba(26,16,36,0.18)" }}>
        <div style={{ fontSize: 10, color: "var(--ink-3)" }}>Velocidad</div><div style={{ fontSize: 18, fontWeight: 700, color: "var(--brand)" }}>1000 Mbps</div>
      </div>
      <div style={{ position: "absolute", top: "42%", right: 8, padding: "10px 14px", background: "var(--ink)", color: "var(--paper)", borderRadius: 14, boxShadow: "0 12px 32px -10px rgba(26,16,36,0.25)" }}>
        <div style={{ fontSize: 10, opacity: 0.6 }}>Línea +1809</div><div style={{ fontSize: 13, fontWeight: 700 }}>Activa · 24h</div>
      </div>
    </div>);
}

function HeroBento() {
  return (
    <div className="reveal" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gridTemplateRows: "1fr 1fr", gap: 12, aspectRatio: "1/1.05" }}>
      <div style={{ gridRow: "1 / 3", background: "var(--plum)", borderRadius: 24, padding: 22, color: "#fff", display: "flex", flexDirection: "column", justifyContent: "space-between", position: "relative", overflow: "hidden" }}>
        <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em" }}>iPhone 17<br />Pro Max</div>
        <div style={{ display: "flex", justifyContent: "center", flex: 1, alignItems: "center" }}>
          <window.PhoneMock width={130} body="#FF7A4D" screen="linear-gradient(160deg,#FFB58A,#ED0F44)" />
        </div>
        <div style={{ fontSize: 18, fontWeight: 700, color: "var(--brand-coral)" }}>RD$78,495</div>
      </div>
      <div style={{ background: "var(--brand)", borderRadius: 24, padding: 22, color: "#fff", display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
        <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", opacity: 0.85 }}>Velocidad</div>
        <div><div style={{ fontSize: 38, fontWeight: 700, letterSpacing: "-0.025em", lineHeight: 1 }}>1 Gbps</div><div style={{ fontSize: 12, opacity: 0.85, marginTop: 4 }}>Fibra simétrica</div></div>
      </div>
      <div style={{ background: "var(--paper)", border: "1px solid var(--line)", borderRadius: 24, padding: 22, display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
        <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--ink-3)" }}>Tiendas</div>
        <div><div style={{ fontSize: 38, fontWeight: 700, letterSpacing: "-0.025em", lineHeight: 1, color: "var(--brand)" }}>20</div><div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>En 4 provincias</div></div>
      </div>
    </div>);
}

function Hero({ comp }) {
  const right = comp === "stack" ? <HeroPhoneStack /> : comp === "bento" ? <HeroBento /> : <HeroSlideshow />;
  return (
    <section style={{ padding: "calc(112px * var(--bal-density)) 0 calc(100px * var(--bal-density))", position: "relative", overflow: "hidden" }}>
      <div className="container" style={{ position: "relative" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr", gap: 48, alignItems: "center" }} className="grid-2">
          <HeroLeft />
          {right}
        </div>
      </div>
    </section>);
}

function ApoyoCards() {
  const cards = [
  { t: "Solicita servicios", g: "linear-gradient(135deg,#FFB199,#FF6B8A)" },
  { t: "Muévete a Claro", g: "linear-gradient(135deg,#FF8FA3,#C20A36)" },
  { t: "Conoce ofertas", g: "linear-gradient(135deg,#FFD4D4,#ED0F44)" },
  { t: "Compra equipos", g: "linear-gradient(135deg,#FF6B8A,#8B0524)" },
  { t: "Mide tu velocidad", g: "linear-gradient(135deg,#5C1A35,#1a0f1f)" }];

  return (
    <section style={{ paddingTop: 0 }} data-comment-anchor="21ba0d72a0-section-67-5">
      <div className="container">
        <div className="eyebrow reveal" style={{ marginBottom: 16 }}>Acceso rápido</div>
        <h2 className="reveal h2">¿En qué podemos apoyarte hoy?</h2>
        <div className="reveal" style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 16, marginTop: 48 }}>
          {cards.map((c) =>
          <a key={c.t} href="#" className="apoyo-card" style={{
            aspectRatio: "1/1.1", borderRadius: 22, padding: 24, background: c.g, color: "#fff",
            display: "flex", flexDirection: "column", justifyContent: "space-between", position: "relative", overflow: "hidden"
          }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: "rgba(255,255,255,0.22)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <window.Icon.Arrow style={{ width: 14, height: 14, transform: "rotate(-45deg)" }} />
              </div>
              <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: "-0.012em" }}>{c.t}</div>
            </a>
          )}
        </div>
      </div>
      <style>{`
        .apoyo-card { transition: transform 250ms; }
        .apoyo-card:hover { transform: translateY(-4px); }
        @media (max-width: 900px) {
          .apoyo-card + * {}
          section .container > div:last-child { grid-template-columns: repeat(2, 1fr) !important; }
        }
      `}</style>
    </section>);

}

function PlanesSection() {
  const TABS = [
    { label: "Internet Hogar", family: "internet_hogar", tag: "Solo internet", icon: "Wifi" },
    { label: "Móvil",          family: "movil_postpago", tag: "Solo móvil",    icon: "Phone" },
  ];
  // Default to Internet Hogar (most-requested per analytics)
  const [tabIdx, setTabIdx] = useState(0);
  const [byFamily, setByFamily] = useState({}); // cache per family
  const [status, setStatus] = useState({});      // per-family status

  const cur = TABS[tabIdx];

  // Fetch on tab switch (cache so re-tab is instant)
  useEffect(() => {
    if (byFamily[cur.family] !== undefined) return;
    setStatus(s => ({ ...s, [cur.family]: "loading" }));
    fetch(window.balUrl(`admin/api/plans.php?family=${cur.family}&limit=20`))
      .then(r => r.ok ? r.json() : Promise.reject("HTTP " + r.status))
      .then(d => {
        setByFamily(b => ({ ...b, [cur.family]: d.items || [] }));
        setStatus(s => ({ ...s, [cur.family]: (d.items && d.items.length) ? "ok" : "empty" }));
      })
      .catch(() => setStatus(s => ({ ...s, [cur.family]: "error" })));
  }, [tabIdx]);

  // Curated pick per family. Order = display order (left → center → right).
  // Center = "más popular". Coincide con producto/marketing, no con auto-sort.
  // Si alguno no aparece en la API se cae al pickTopThree heurístico.
  const CURATED_PICKS = {
    movil_postpago: [
      { name: "Smart Especial 3" },
      { name: "Smart Libre 1", popular: true },
      { name: "Smart Libre 2" },
    ],
  };

  const pickTopThree = (items) => {
    if (!items || !items.length) return [];

    // 1) Try curated list first
    const curated = CURATED_PICKS[cur.family];
    if (curated) {
      const found = curated
        .map((c) => {
          const match = items.find((p) => p.name?.toLowerCase().trim() === c.name.toLowerCase().trim());
          return match ? { ...match, _showPopular: !!c.popular } : null;
        })
        .filter(Boolean);
      // Use curated only if ALL 3 resolved — else fall back to heuristic
      if (found.length === curated.length) return found;
    }

    // 2) Heuristic: cheapest entry · most-popular center · premium
    const sorted = [...items].sort((a, b) => Number(a.price) - Number(b.price));
    const popular = sorted.find(p => p.is_popular);
    const featured = sorted.filter(p => p.is_featured);

    if (sorted.length <= 3) {
      return sorted.map((p, i, arr) => ({
        ...p, _showPopular: p.is_popular || (!arr.some(x => x.is_popular) && i === 1)
      }));
    }

    const center = popular || (featured.find(f => f.price >= sorted[Math.floor(sorted.length/2)].price)) || sorted[Math.floor(sorted.length/2)];
    const cheapest = sorted.find(p => p.id !== center.id) || sorted[0];
    const premium = [...sorted].reverse().find(p => p.id !== center.id && p.id !== cheapest.id) || sorted[sorted.length - 1];

    return [cheapest, center, premium].map(p => ({
      ...p,
      _showPopular: p.id === center.id,
    }));
  };

  const items = byFamily[cur.family] || [];
  const top3 = pickTopThree(items);
  const tabStatus = status[cur.family] || "idle";

  return (
    <section style={{ background: "var(--paper-2)" }}>
      <div className="container">
        <div className="reveal" style={{ textAlign: "center" }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Planes destacados</div>
          <h2 className="h1">Tenemos el mejor plan para ti</h2>
          <p className="lead" style={{ marginTop: 16, maxWidth: 600, margin: "16px auto 0" }}>
            Elige el combo perfecto para tu hogar, empresa, evento o estilo de vida.
          </p>
          <div style={{
            display: "inline-flex", marginTop: 32, padding: 6,
            background: "#fff", borderRadius: 999, gap: 4,
            border: "1px solid var(--line)", flexWrap: "wrap", justifyContent: "center",
          }}>
            {TABS.map((t, i) => (
              <button key={t.label} onClick={() => setTabIdx(i)} style={{
                padding: "10px 20px", borderRadius: 999, border: "none", cursor: "pointer",
                fontSize: 14, fontWeight: 500, fontFamily: "inherit",
                background: tabIdx === i ? "var(--ink)" : "transparent",
                color: tabIdx === i ? "#fff" : "var(--ink-2)",
                transition: "background 200ms, color 200ms",
              }}>{t.label}</button>
            ))}
          </div>
        </div>

        {/* Loading skeleton */}
        {tabStatus === "loading" && (
          <div className="grid grid-3 reveal" style={{ marginTop: 48, gap: 20 }}>
            {[0,1,2].map(i => (
              <div key={i} style={{
                background: "#fff", borderRadius: 28, padding: 32, minHeight: 460,
                border: "1px solid var(--line)",
              }}>
                <div style={{ width: 48, height: 48, background: "var(--paper-2)", borderRadius: 14 }} />
                <div style={{ height: 12, width: 90, background: "var(--paper-2)", borderRadius: 4, marginTop: 20 }} />
                <div style={{ height: 22, background: "var(--paper-2)", borderRadius: 6, marginTop: 12 }} />
                <div style={{ height: 40, background: "var(--paper-2)", borderRadius: 8, marginTop: 16 }} />
              </div>
            ))}
          </div>
        )}

        {/* Empty / error / success */}
        {(tabStatus === "empty" || tabStatus === "error") && (
          <div className="reveal" style={{
            marginTop: 48, padding: 48, textAlign: "center",
            background: "#fff", borderRadius: 22, border: "1px solid var(--line)",
            maxWidth: 540, marginInline: "auto",
          }}>
            <div style={{ fontSize: 48, marginBottom: 12 }}>{tabStatus === "error" ? "⚠️" : "📋"}</div>
            <h3 className="h3" style={{ margin: 0 }}>
              {tabStatus === "error" ? "Error al cargar" : `Sin planes ${cur.label.toLowerCase()} aún`}
            </h3>
            <p className="body" style={{ marginTop: 12, color: "var(--ink-3)" }}>
              {tabStatus === "error"
                ? "No pudimos contactar el catálogo."
                : "Estamos preparando el catálogo. Pregúntanos por WhatsApp y te asesoramos."}
            </p>
            <button onClick={() => window.openWhatsApp(`Hola, me interesa un plan de ${cur.label}.`)}
              className="btn btn-brand" style={{ marginTop: 24, border: 0, cursor: "pointer", fontFamily: "inherit" }}>
              Hablar por WhatsApp
            </button>
          </div>
        )}

        {tabStatus === "ok" && (
          <div className="grid grid-3 reveal home-plans-grid" style={{
            marginTop: 56, gap: 20, alignItems: "stretch",
          }}>
            {top3.map((p) => {
              const isPop = !!p._showPopular;
              const Icon = window.Icon[cur.icon] || window.Icon.Wifi;
              const features = buildHomeFeatures(p);
              const planTag = p.short_label
                ? `${cur.tag} · ${p.short_label}`
                : cur.tag;

              return (
                <article key={p.id} style={{
                  background: "#fff",
                  borderRadius: 24, padding: 28, position: "relative",
                  border: isPop ? "2px solid var(--brand)" : "1px solid var(--line)",
                  transform: isPop ? "scale(1.04)" : "none",
                  zIndex: isPop ? 2 : 1,
                  display: "flex", flexDirection: "column", gap: 18, minHeight: 460,
                  boxShadow: isPop
                    ? "0 24px 60px -16px rgba(237,15,68,0.25), 0 4px 12px -4px rgba(20,17,15,0.08)"
                    : "0 1px 1px rgba(20,17,15,0.04), 0 2px 8px -2px rgba(20,17,15,0.04)",
                }}>
                  {isPop && (
                    <span style={{
                      position: "absolute", top: -14, left: "50%", transform: "translateX(-50%)",
                      padding: "6px 16px", background: "var(--brand)", color: "#fff",
                      borderRadius: 999, fontSize: 10.5, fontWeight: 700,
                      letterSpacing: "0.1em", textTransform: "uppercase", whiteSpace: "nowrap",
                      boxShadow: "0 8px 20px -6px rgba(237,15,68,0.55)",
                    }}>★ Más popular</span>
                  )}

                  <div style={{
                    width: 48, height: 48, borderRadius: 14,
                    background: isPop ? "var(--brand)" : "var(--paper-2)",
                    color: isPop ? "#fff" : "var(--brand)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}><Icon /></div>

                  <div className="mini" style={{ color: "var(--ink-3)" }}>{planTag.toUpperCase()}</div>
                  <div className="h4" style={{ marginTop: -6 }}>{p.name}</div>

                  <div>
                    <div style={{
                      fontSize: "clamp(32px, 4vw, 44px)", fontWeight: 700,
                      letterSpacing: "-0.025em", lineHeight: 1, color: "var(--brand)",
                      fontVariantNumeric: "tabular-nums",
                    }}>
                      RD${Math.round(p.price).toLocaleString()}
                    </div>
                    {cur.family.startsWith("movil") ? (
                      <>
                        <div className="caption" style={{ marginTop: 6 }}>/mes sin impuestos</div>
                        <div style={{
                          marginTop: 4, fontSize: 11.5, color: "var(--ink-3)",
                          fontVariantNumeric: "tabular-nums",
                        }}>
                          Con ITBIS/CDT (~30%): <strong style={{ color: "var(--ink)" }}>
                            RD${Math.round(p.price * 1.30).toLocaleString()}
                          </strong>/mes
                        </div>
                      </>
                    ) : (
                      <div className="caption" style={{ marginTop: 6 }}>/mes con impuestos</div>
                    )}
                    {p.promo_label && (
                      <div style={{ marginTop: 8, fontSize: 12, fontWeight: 600, color: "var(--brand-deep)" }}>
                        🎁 {p.promo_label}
                      </div>
                    )}
                  </div>

                  <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
                    {features.map((f, i) => (
                      <li key={i} style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 13.5, color: "var(--ink-2)" }}>
                        <span style={{
                          width: 18, height: 18, borderRadius: 999,
                          background: "var(--brand)", color: "#fff",
                          display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
                        }}>
                          <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.4">
                            <path d="M3 8.5l3.2 3.2L13 4.8" strokeLinecap="round" strokeLinejoin="round" />
                          </svg>
                        </span>
                        <span>{f}</span>
                      </li>
                    ))}
                  </ul>

                  <button onClick={() => window.openLeadForm({
                    kind: "plan",
                    id: p.id,
                    name: p.name,
                    slug: p.slug,
                    price: p.price,
                    extra: {
                      "Familia":     cur.label,
                      "Velocidad":   p.speed_down_mbps ? `${p.speed_down_mbps}${p.speed_up_mbps ? '/' + p.speed_up_mbps : ''} Mbps${p.symmetric ? ' simétrico' : ''}` : null,
                      "Datos":       p.data_unlimited ? "Ilimitados 5G" : (p.data_gb ? `${p.data_gb} GB` : null),
                      "Minutos":     p.minutes_unlimited ? "Ilimitados" : (p.minutes ? `${p.minutes} min` : null),
                      "Roaming USA": p.roaming_usa ? "incluido" : null,
                      "Promoción":   p.promo_label || null,
                    },
                    sourceTag: "home-tabs-plan",
                  })} className="btn" style={{
                    marginTop: "auto", width: "100%", justifyContent: "center",
                    background: isPop ? "var(--brand)" : "var(--ink)", color: "#fff",
                    border: 0, cursor: "pointer", fontFamily: "inherit",
                  }}>
                    Solicitar este plan <window.Icon.Arrow />
                  </button>
                </article>
              );
            })}
          </div>
        )}

        {tabStatus === "ok" && items.length > 3 && (
          <div className="reveal" style={{ textAlign: "center", marginTop: 32 }}>
            <a href={window.balUrl("planes.html#" + cur.family)} className="link link-ink" style={{ fontSize: 14, fontWeight: 600 }}>
              Ver los {items.length} planes {cur.label.toLowerCase()} <window.Icon.Arrow />
            </a>
          </div>
        )}
      </div>

      <style>{`
        @media (max-width: 720px) {
          .home-plans-grid > article {
            transform: none !important;
          }
        }
      `}</style>
    </section>);
}

// Build a concise feature list for the home tabs cards (max 4 bullets)
function buildHomeFeatures(p) {
  if (p.features && p.features.length) {
    return p.features.slice(0, 4);
  }
  const out = [];
  if (p.speed_down_mbps && p.speed_up_mbps && p.speed_down_mbps !== p.speed_up_mbps) {
    out.push(`Internet ${p.speed_down_mbps}/${p.speed_up_mbps} Mbps`);
  } else if (p.speed_down_mbps) {
    out.push(`Internet ${p.speed_down_mbps} Mbps${p.symmetric ? ' simétrico' : ''}`);
  }
  if (p.data_unlimited) out.push("Datos ilimitados 5G");
  else if (p.data_gb) out.push(`${p.data_gb} GB de datos`);
  if (p.minutes_unlimited) out.push("Llamadas ilimitadas");
  else if (p.minutes) out.push(`${p.minutes} minutos`);
  if (p.tv_channels) out.push(`TV ${p.tv_channels}+ canales${p.tv_premium ? ' premium' : ''}`);
  if (p.roaming_usa) out.push("Roaming USA");
  if (p.install_free) out.push("Instalación gratis");
  if (p.modem_included) out.push(p.wifi_standard || "Wi-Fi incluido");
  return out.slice(0, 4);
}

function EquiposSwatches() {
  const [items, setItems] = React.useState([]);
  const [status, setStatus] = React.useState("loading");

  React.useEffect(() => {
    fetch(window.balUrl("admin/api/products.php?limit=8"))
      .then((r) => r.ok ? r.json() : Promise.reject("HTTP " + r.status))
      .then((d) => { setItems(d.items || []); setStatus("ok"); })
      .catch(() => setStatus("error"));
  }, []);

  const BRAND_LABELS = { apple: "Apple", samsung: "Samsung", motorola: "Motorola", xiaomi: "Xiaomi", huawei: "Huawei", google: "Google", otros: "Otros" };

  return (
    <section>
      <div className="container">
        <div className="reveal" style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 24, alignItems: "end", marginBottom: 40 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 12 }}>Equipos</div>
            <h2 className="h2">Los equipos más buscados</h2>
          </div>
          <a href={window.balUrl("equipos.html")} className="link" style={{ fontSize: 14, fontWeight: 600 }}>
            Ver catálogo completo <window.Icon.Arrow />
          </a>
        </div>

        {status === "loading" && (
          <div className="grid grid-4 reveal" style={{ gap: 16 }}>
            {[...Array(4)].map((_, i) => (
              <div key={i} className="card" style={{ padding: 20, minHeight: 320 }}>
                <div style={{ aspectRatio: "1/1", background: "var(--paper-2)", borderRadius: 14, marginBottom: 16 }} />
                <div style={{ height: 14, background: "var(--paper-2)", borderRadius: 4, marginBottom: 8 }} />
                <div style={{ height: 12, width: "60%", background: "var(--paper-2)", borderRadius: 4 }} />
              </div>
            ))}
          </div>
        )}

        {status === "ok" && items.length > 0 && (
          <div className="grid grid-4 reveal" style={{ gap: 16 }}>
            {items.map((it) => <FeaturedProductCard key={it.id} it={it} brandLabel={BRAND_LABELS[it.brand] || it.brand} />)}
          </div>
        )}

        {status === "error" && (
          <div className="card" style={{ padding: 32, textAlign: "center" }}>
            <p className="body" style={{ margin: 0 }}>No pudimos cargar el catálogo destacado.</p>
          </div>
        )}

        <div style={{ display: "flex", justifyContent: "center", marginTop: 32 }}>
          <a href={window.balUrl("equipos.html")} className="btn btn-primary">Ver todos los equipos <window.Icon.Arrow /></a>
        </div>
      </div>
    </section>);

}

// ────────────────────────────────────────────────────────────
// FeaturedProductCard — card de equipo destacado con selector
// de ciudad RD. La interacción del select no dispara el link.
// ────────────────────────────────────────────────────────────
const DR_CIUDADES = [
  "Santo Domingo", "Santiago", "La Romana", "San Pedro de Macorís",
  "San Cristóbal", "Puerto Plata", "La Vega", "San Francisco de Macorís",
  "Higüey", "Moca", "Baní", "Bávaro / Punta Cana",
  "Bonao", "Mao", "Azua", "Nagua", "Cotuí",
];

function FeaturedProductCard({ it, brandLabel }) {
  const badge = it.badges && it.badges.length ? it.badges[0] : null;
  const href = window.balUrl(`equipo.html?slug=${encodeURIComponent(it.slug)}`);
  const [city, setCity] = useState("");
  const [imgFailed, setImgFailed] = useState(false);

  // Stop both navigation and propagation when interacting with the select
  const swallow = (e) => { e.stopPropagation(); };
  const swallowDown = (e) => { e.stopPropagation(); /* keep default so select opens */ };

  return (
    <a href={href} className="card" style={{
      padding: 20, display: "flex", flexDirection: "column", gap: 12, color: "var(--ink)",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
        <span className="tag" style={{ background: "var(--paper-2)", color: "var(--ink-2)", fontSize: 10 }}>
          {brandLabel.toUpperCase()}
        </span>
        {badge && (
          <span style={{ padding: "3px 8px", background: "var(--brand)", color: "#fff", borderRadius: 999, fontSize: 10, fontWeight: 600 }}>
            {badge}
          </span>
        )}
      </div>
      <div style={{ aspectRatio: "1/1", background: "var(--paper-2)", borderRadius: 14,
        display: "flex", justifyContent: "center", alignItems: "center", overflow: "hidden", padding: 8 }}>
        {it.image && !imgFailed ? (
          <img src={it.image} alt={it.name} loading="lazy" referrerPolicy="no-referrer"
            onError={() => setImgFailed(true)}
            style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "contain" }} />
        ) : (
          <window.PhoneMock width={90} body="#1a1a1c" screen="linear-gradient(160deg,#2a2a2c,#0a0a0c)" />
        )}
      </div>
      <div>
        <div style={{ fontSize: 15, fontWeight: 600, letterSpacing: "-0.01em", color: "var(--ink)" }}>{it.name}</div>
        {it.spec && <div className="caption" style={{ marginTop: 2 }}>{it.spec}</div>}
        {it.price > 0
          ? <div className="h4" style={{ color: "var(--brand)", marginTop: 10 }}>RD${Math.round(it.price).toLocaleString()}</div>
          : <div style={{ marginTop: 10, fontSize: 13, color: "var(--ink-3)" }}>Precio a consultar</div>}
      </div>

      {/* CTA — "Lo quiero" (la tarjeta completa ya enlaza al detalle del equipo) */}
      <span
        aria-hidden="true"
        style={{
          marginTop: "auto",
          display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
          padding: "11px 18px",
          background: "var(--grad, linear-gradient(135deg,#FF4D7C,#ED0F44,#FE644D))",
          color: "#fff",
          borderRadius: 999,
          fontSize: 14, fontWeight: 700, letterSpacing: "-0.005em",
          boxShadow: "0 8px 20px -8px rgba(237,15,68,0.45)",
        }}
      >
        Lo quiero
        <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M3 8h10M9 4l4 4-4 4" />
        </svg>
      </span>
    </a>
  );
}

// ============================================================
// AWARDS TIMELINE — "Distribuidor del Año" Claro RD
// ============================================================
const AWARDS = [
  { year: "2012", note: "Primer Premio" },
  { year: "2013", note: "Consolidación" },
  { year: "2015", note: "Presencia Nacional" },
  { year: "2017", note: "Referencia" },
  { year: "2019", note: "Cambio Generacional" },
  { year: "2020", note: "Resiliencia" },
  { year: "2021", note: "Optimización Operativa" },
  { year: "2024", note: "Alto desempeño", featured: true },
];

function TrophyIcon({ size = 56, featured = false }) {
  // Custom-drawn trophy. Featured uses solid brand gradient + glow; default uses outlined ink.
  const fillTop = featured ? "url(#bal-trophy-fill-on)" : "url(#bal-trophy-fill-off)";
  const fillMid = featured ? "var(--brand-deep)" : "rgba(20,17,15,0.78)";
  return (
    <svg
      viewBox="0 0 100 120" width={size} height={size * 1.2}
      aria-hidden="true" focusable="false"
      style={{
        display: "block", margin: "0 auto",
        filter: featured ? "drop-shadow(0 14px 28px rgba(237,15,68,0.55))" : "drop-shadow(0 6px 14px rgba(20,17,15,0.18))",
        transition: "transform 320ms cubic-bezier(0.32,0.72,0,1), filter 320ms",
      }}
    >
      <defs>
        <linearGradient id="bal-trophy-fill-on" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"  stopColor="#FF3A6E" />
          <stop offset="55%" stopColor="#ED0F44" />
          <stop offset="100%" stopColor="#B30A33" />
        </linearGradient>
        <linearGradient id="bal-trophy-fill-off" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"  stopColor="#3a2f3b" />
          <stop offset="100%" stopColor="#1a1024" />
        </linearGradient>
      </defs>
      {/* Cup bowl */}
      <path d="M28 18 C28 16 29 14 31 14 H69 C71 14 72 16 72 18 V40 C72 58 62 70 50 70 C38 70 28 58 28 40 Z" fill={fillTop} />
      {/* Top rim highlight */}
      <ellipse cx="50" cy="18" rx="22" ry="3.5" fill="rgba(255,255,255,0.28)" />
      {/* Left handle */}
      <path d="M28 24 C16 24 14 36 16 44 C18 50 25 50 28 48" stroke={fillTop === "url(#bal-trophy-fill-on)" ? "url(#bal-trophy-fill-on)" : "rgba(20,17,15,0.55)"} strokeWidth="3.5" fill="none" strokeLinecap="round" />
      {/* Right handle */}
      <path d="M72 24 C84 24 86 36 84 44 C82 50 75 50 72 48" stroke={fillTop === "url(#bal-trophy-fill-on)" ? "url(#bal-trophy-fill-on)" : "rgba(20,17,15,0.55)"} strokeWidth="3.5" fill="none" strokeLinecap="round" />
      {/* Stem (trapezoid) */}
      <path d="M44 70 H56 L58 88 H42 Z" fill={fillMid} />
      {/* Pedestal */}
      <rect x="34" y="88" width="32" height="9" rx="2" fill={fillMid} />
      {/* Base */}
      <rect x="26" y="97" width="48" height="8" rx="2" fill={featured ? "#1a1024" : "rgba(20,17,15,0.86)"} />
    </svg>
  );
}

function AwardsTimeline() {
  // Duplicate the items to make the marquee seamless
  const doubled = [...AWARDS, ...AWARDS];

  return (
    <div className="bal-awards reveal" style={{
      marginTop: 88, paddingTop: 56,
      borderTop: "1px solid var(--line)",
      position: "relative",
    }}>
      <div style={{ textAlign: "center", marginBottom: 36 }}>
        <div className="eyebrow" style={{
          color: "var(--brand)", marginBottom: 14,
          display: "inline-flex", alignItems: "center", gap: 10,
        }}>
          <span style={{ width: 30, height: 1, background: "var(--brand)", opacity: 0.5 }} />
          Ganador múltiple del reconocimiento de Claro
          <span style={{ width: 30, height: 1, background: "var(--brand)", opacity: 0.5 }} />
        </div>
        <h3 style={{
          fontSize: "clamp(36px, 5.5vw, 64px)",
          fontWeight: 800, letterSpacing: "-0.035em",
          lineHeight: 1.0, margin: 0,
          color: "var(--ink)",
          textTransform: "uppercase",
        }}>
          Distribuidor <span style={{ fontStyle: "italic", fontWeight: 700, color: "var(--brand)" }}>del año</span>
        </h3>
        <p style={{
          fontSize: 16, lineHeight: 1.55, color: "var(--ink-2)",
          marginTop: 14, marginBottom: 0, maxWidth: 560, marginInline: "auto",
        }}>
          Premio anual otorgado por Claro Dominicana a los mejores distribuidores autorizados del país.
        </p>
      </div>

      {/* Marquee with fade-mask edges */}
      <div className="bal-awards-track" aria-label="Línea de tiempo de premiaciones">
        <div className="bal-awards-marquee">
          {doubled.map((a, i) => (
            <div key={`${a.year}-${i}`} className={`bal-award-item ${a.featured ? "is-featured" : ""}`} title={`${a.year} · ${a.note}`}>
              <TrophyIcon size={a.featured ? 76 : 56} featured={a.featured} />
              <div className="bal-award-year" style={{
                marginTop: 14,
                fontSize: a.featured ? 24 : 18,
                fontWeight: 800, letterSpacing: "-0.02em",
                color: a.featured ? "var(--brand)" : "var(--ink)",
                fontVariantNumeric: "tabular-nums",
              }}>
                {a.year}
              </div>
              <div className="bal-award-note" style={{
                marginTop: 2,
                fontSize: 11.5, fontWeight: 500,
                color: "var(--ink-3)",
                letterSpacing: "0.02em",
                opacity: 0.85,
              }}>
                {a.note}
              </div>
            </div>
          ))}
        </div>
      </div>

      <style>{`
        .bal-awards-track {
          position: relative;
          overflow: hidden;
          -webkit-mask-image: linear-gradient(90deg, transparent 0, #000 8%, #000 92%, transparent 100%);
                  mask-image: linear-gradient(90deg, transparent 0, #000 8%, #000 92%, transparent 100%);
          padding: 8px 0 28px;
        }
        .bal-awards-marquee {
          display: flex;
          gap: 64px;
          width: max-content;
          animation: balAwardsScroll 38s linear infinite;
          will-change: transform;
        }
        .bal-awards-track:hover .bal-awards-marquee,
        .bal-awards-track:focus-within .bal-awards-marquee {
          animation-play-state: paused;
        }
        .bal-award-item {
          flex-shrink: 0;
          min-width: 110px;
          text-align: center;
          padding: 8px 12px;
          transition: transform 280ms cubic-bezier(0.32,0.72,0,1);
        }
        .bal-award-item:hover { transform: translateY(-4px) scale(1.04); }
        .bal-award-item.is-featured {
          min-width: 140px;
        }
        @keyframes balAwardsScroll {
          from { transform: translateX(0); }
          to   { transform: translateX(-50%); }
        }
        @media (prefers-reduced-motion: reduce) {
          .bal-awards-marquee { animation: none; }
          .bal-awards-track {
            overflow-x: auto; scrollbar-width: none;
          }
          .bal-awards-track::-webkit-scrollbar { display: none; }
        }
        @media (max-width: 720px) {
          .bal-awards-marquee { gap: 40px; animation-duration: 30s; }
          .bal-award-item { min-width: 90px; padding: 4px 8px; }
        }
      `}</style>
    </div>
  );
}

function StatsRow() {
  return (
    <section style={{ background: "var(--paper-2)" }}>
      <div className="container">
        <h2 className="reveal h2" style={{ textAlign: "center", maxWidth: 800, marginInline: "auto" }}>Más de dos décadas conectando dominicanos</h2>
        <div className="reveal" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 24, marginTop: 56 }}>
          {[["+25", "años", "Conectando dominicanos"], ["20", "tiendas", "En 4 provincias"], ["Top 3", "", "Distribuidor Claro desde 2001"], ["+90", "empleados", "Comprometidos contigo"]].map(([n, l, d]) =>
          <div key={n + l} style={{ textAlign: "center" }}>
              <div className="display" style={{ color: "var(--brand)" }}>{n}</div>
              {l && <div className="h4" style={{ marginTop: 4 }}>{l}</div>}
              <div className="caption" style={{ marginTop: 6 }}>{d}</div>
            </div>
          )}
        </div>

        <AwardsTimeline />
      </div>
    </section>);

}

function MapaTiendas() {
  const stores = window.STORES || {};
  const provs = Object.keys(stores);
  const totalStores = provs.reduce((acc, p) => acc + (stores[p]?.length || 0), 0);
  const [activeProv, setActiveProv] = useState(provs[0] || "Santiago");
  const provList = stores[activeProv] || [];

  return (
    <section style={{ background: "var(--paper-2)" }}>
      <div className="container">
        <div className="reveal" style={{ textAlign: "center", marginBottom: 40 }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>Tiendas · {totalStores} en RD</div>
          <h2 className="h1">Encuentra tu tienda Baldera<br />más cercana</h2>
        </div>
        <div className="reveal home-map-grid" style={{ background: "#fff", borderRadius: 28, padding: 18, border: "1px solid var(--line)", display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 18, boxShadow: "0 16px 40px -24px rgba(20,17,15,0.18)" }}>
          {/* Real interactive map (Leaflet/Mapbox) */}
          <window.StoresMap stores={stores} activeProv={activeProv} onSelectProv={setActiveProv} height={420} />

          {/* Province picker + store list */}
          <div style={{ display: "flex", flexDirection: "column", minWidth: 0 }}>
            <div style={{ display: "flex", gap: 6, marginBottom: 14, flexWrap: "wrap" }}>
              {provs.map((pp) => {
                const active = pp === activeProv;
                return (
                  <button
                    key={pp}
                    onClick={() => setActiveProv(pp)}
                    style={{
                      padding: "7px 12px", borderRadius: 999,
                      border: "1px solid " + (active ? "var(--brand)" : "var(--line)"),
                      background: active ? "var(--brand)" : "#fff",
                      color: active ? "#fff" : "var(--ink-2)",
                      fontSize: 12, fontWeight: 600, cursor: "pointer",
                      transition: "all 140ms",
                    }}
                  >
                    {pp} <span style={{ opacity: 0.6, fontWeight: 500 }}>· {stores[pp]?.length || 0}</span>
                  </button>
                );
              })}
            </div>
            <div style={{ flex: 1, overflowY: "auto", maxHeight: 380, paddingRight: 4 }}>
              {provList.slice(0, 6).map((s, i) => {
                const photoSrc = s.photo
                  ? (s.photo.startsWith("http") ? s.photo : window.balUrl("uploads/stores/" + s.photo))
                  : null;
                return (
                  <div key={i} style={{
                    padding: "12px 0", borderBottom: i < provList.length - 1 && i < 5 ? "1px solid var(--line)" : "none",
                    display: "grid", gridTemplateColumns: "64px 1fr", gap: 12, alignItems: "center",
                  }}>
                    {/* Photo thumb */}
                    <div style={{
                      width: 64, height: 64, borderRadius: 10,
                      background: photoSrc
                        ? `url("${photoSrc}") center/cover no-repeat`
                        : "linear-gradient(135deg, var(--paper-2), var(--paper-3))",
                      display: "grid", placeItems: "center",
                      border: "1px solid var(--line)",
                      flexShrink: 0,
                    }}>
                      {!photoSrc && (
                        <span style={{ color: "var(--ink-4)", display: "grid", placeItems: "center" }}>
                          <window.Icon.Pin />
                        </span>
                      )}
                    </div>
                    {/* Info */}
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", lineHeight: 1.3 }}>{s.name}</div>
                      <div className="caption" style={{ fontSize: 11.5, marginTop: 3, color: "var(--ink-3)" }}>{s.hours}</div>
                      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, alignItems: "center" }}>
                        <a href={`tel:+1${(s.phone || "").replace(/\D/g, "")}`} style={{ fontSize: 12, color: "var(--brand)", fontWeight: 600 }}>{s.phone}</a>
                        <a
                          href={s.mapsUrl || (s.lat && s.lng ? `https://www.google.com/maps/dir/?api=1&destination=${s.lat},${s.lng}` : "#")}
                          target="_blank" rel="noopener" className="link" style={{ fontSize: 11.5 }}>
                          Cómo llegar <window.Icon.Arrow />
                        </a>
                      </div>
                    </div>
                  </div>
                );
              })}
              {provList.length > 6 && (
                <div style={{ paddingTop: 12, textAlign: "center" }}>
                  <a href={window.balUrl("tiendas.html")} className="link" style={{ fontSize: 13, fontWeight: 600 }}>
                    Ver todas las {provList.length} tiendas en {activeProv} <window.Icon.Arrow />
                  </a>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 880px) {
          .home-map-grid { grid-template-columns: 1fr !important; }
          .home-map-grid > div:last-child > div:last-child { max-height: 300px !important; }
        }
      `}</style>
    </section>
  );
}

function PortabilidadBanner() {
  return (
    <section>
      <div className="container">
        <div className="reveal" style={{ background: "linear-gradient(135deg,#FF6B8A 0%,#ED0F44 60%,#8B0524 100%)", borderRadius: 32, padding: "60px 56px", color: "#fff", display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 32, alignItems: "center", position: "relative", overflow: "hidden" }} className="grid-2">
          <div style={{ position: "absolute", inset: 0, backgroundImage: "radial-gradient(rgba(255,255,255,0.15) 1.5px, transparent 1.5px)", backgroundSize: "28px 28px" }} />
          <div style={{ position: "relative" }}>
            <span style={{ display: "inline-block", padding: "5px 12px", background: "rgba(255,255,255,0.18)", borderRadius: 999, fontSize: 11, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase" }}>Portabilidad</span>
            <h2 className="h1" style={{ margin: "20px 0 16px", color: "#fff" }}>Trae tu número a Claro y ahorra 50% por 6 meses</h2>
            <p style={{ fontSize: 16, opacity: 0.9, margin: 0 }}>Sin perder tu número. Activación en menos de 24 horas.</p>
            <a href={window.balUrl("servicios.html")} className="btn" style={{ background: "#fff", color: "var(--brand)", marginTop: 28 }}>Iniciar portabilidad <window.Icon.Arrow /></a>
          </div>
          <div style={{ position: "relative", display: "flex", justifyContent: "center" }}>
            <window.PhoneMock width={200} body="#1a1024" screen="linear-gradient(160deg,#fff,#f7f1f7 60%,#FF6B8A)" />
            <div style={{ position: "absolute", top: 20, right: 0, padding: "8px 12px", background: "#fff", color: "var(--ink)", borderRadius: 12, boxShadow: "0 12px 32px -10px rgba(0,0,0,0.2)" }}>
              <div style={{ fontSize: 9, color: "var(--ink-3)" }}>Tu número</div>
              <div style={{ fontSize: 13, fontWeight: 700 }}>+1 (809)</div>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

function HistoriaSection() {
  // Default content (used until /admin/api/site_settings.php loads or as fallback)
  const DEFAULTS = {
    eyebrow:        "Sobre nosotros",
    title:          "Una historia de conexiones desde",
    accent:         "2001",
    lead:           "Lo que comenzó como una pequeña tienda en Santiago hoy es una de las redes de distribución Claro más importantes del país.",
    cta_label:      "Conoce más sobre Baldera",
    cta_href:       "nosotros.html",
    photo_url:      window.balUrl ? window.balUrl("uploads/familia-baldera.png") : "uploads/familia-baldera.png",
    photo_alt:      "Familia Baldera — equipo Baldera Comunicaciones",
    photo_caption:  "Familia Baldera",
    photo_aspect:   "4/5",
    photo_max:      520,
    card1_title:    "Historia",
    card1_desc:     "25+ años conectando a familias y empresas dominicanas.",
    card2_title:    "Misión",
    card2_desc:     "Llevar la mejor tecnología de comunicación a cada rincón de RD.",
    card3_title:    "Visión",
    card3_desc:     "Ser el aliado de conectividad #1 del Caribe y el país.",
  };

  const [c, setC] = useState(() => Object.assign({}, DEFAULTS, (window.SITE && window.SITE.historia) || {}));
  useEffect(() => {
    const sync = () => {
      const h = (window.SITE && window.SITE.historia) || {};
      setC(Object.assign({}, DEFAULTS, h));
    };
    sync();
    window.addEventListener("baldera-site-ready", sync);
    return () => window.removeEventListener("baldera-site-ready", sync);
  }, []);

  const cards = [
    { t: c.card1_title, d: c.card1_desc },
    { t: c.card2_title, d: c.card2_desc },
    { t: c.card3_title, d: c.card3_desc },
  ];
  return (
    <section style={{
      background: "linear-gradient(160deg, #1a1024 0%, #2a1538 50%, #1a1024 100%)",
      color: "#fff", overflow: "hidden", position: "relative",
    }}>
      {/* Brand glow top-right */}
      <div aria-hidden="true" style={{
        position: "absolute", top: -120, right: -120, width: 540, aspectRatio: 1,
        background: "radial-gradient(circle, rgba(237,15,68,0.25), transparent 60%)",
        pointerEvents: "none",
      }} />
      {/* Dot grid */}
      <div aria-hidden="true" style={{
        position: "absolute", inset: 0,
        backgroundImage: "radial-gradient(rgba(255,255,255,0.06) 1.5px, transparent 1.5px)",
        backgroundSize: "26px 26px", pointerEvents: "none",
      }} />

      <div className="container" style={{ position: "relative" }}>
        <div style={{
          display: "grid", gridTemplateColumns: "1fr 1.05fr",
          gap: 72, alignItems: "center",
        }} className="grid-2">

          {/* Photo slot — aspect, size & source editable desde /admin/settings.php */}
          <div className="reveal historia-photo" style={{
            position: "relative",
            aspectRatio: c.photo_aspect || "4/5",
            maxWidth: c.photo_max || 520,
            borderRadius: 28, overflow: "hidden",
            boxShadow: "0 32px 80px -24px rgba(0,0,0,0.55), 0 4px 12px rgba(0,0,0,0.30)",
          }}>
            {c.photo_url ? (
              <img src={c.photo_url} alt={c.photo_alt || "Foto"} loading="lazy"
                style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center", display: "block" }} />
            ) : (
              <image-slot id="historia-foto" placeholder="Foto: equipo o tienda Baldera" shape="rounded"
                style={{ width: "100%", height: "100%", borderRadius: 28 }}>
                <div style={{ width: "100%", height: "100%", background: "linear-gradient(135deg,#FF8FA3 0%,#ED0F44 60%,#8B0524 100%)", position: "relative" }}>
                  <div style={{ position: "absolute", inset: 0, backgroundImage: "radial-gradient(rgba(255,255,255,0.18) 1.4px, transparent 1.4px)", backgroundSize: "26px 26px" }} />
                  <div style={{ position: "absolute", left: 28, bottom: 28, color: "#fff" }}>
                    <div className="mini" style={{ opacity: 0.92 }}>Foto · suelta tu imagen</div>
                    <div style={{ fontSize: 22, fontWeight: 700, marginTop: 6 }}>{c.photo_caption || "Familia Baldera"}</div>
                  </div>
                </div>
              </image-slot>
            )}
          </div>

          {/* Copy block */}
          <div className="reveal">
            <div style={{
              display: "inline-flex", alignItems: "center", gap: 8,
              padding: "6px 14px", borderRadius: 999,
              background: "rgba(255,255,255,0.08)", color: "var(--brand-coral)",
              fontSize: 11, fontWeight: 700, letterSpacing: "0.16em", textTransform: "uppercase",
              border: "1px solid rgba(255,255,255,0.10)", marginBottom: 20,
            }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--brand-coral)" }} />
              {c.eyebrow}
            </div>

            <h2 style={{
              fontSize: "clamp(36px, 5.4vw, 68px)", fontWeight: 700,
              letterSpacing: "-0.03em", lineHeight: 1.05, margin: 0, color: "#fff",
            }}>
              {c.title}{" "}
              <span className="italic-display" style={{
                background: "linear-gradient(180deg, #ffeaef 0%, var(--brand-coral) 100%)",
                WebkitBackgroundClip: "text", backgroundClip: "text",
                WebkitTextFillColor: "transparent",
              }}>{c.accent}</span>
            </h2>

            <p style={{
              fontSize: "clamp(17px, 1.4vw, 19px)",
              color: "rgba(255,255,255,0.82)",
              marginTop: 28, lineHeight: 1.6, maxWidth: 580,
            }}>{c.lead}</p>

            <div style={{
              display: "grid", gridTemplateColumns: "repeat(3, 1fr)",
              gap: 24, marginTop: 44,
            }} className="historia-cards">
              {cards.map((it) => (
                <div key={it.t} style={{
                  padding: 20, borderRadius: 16,
                  background: "rgba(255,255,255,0.04)",
                  border: "1px solid rgba(255,255,255,0.10)",
                }}>
                  <div style={{
                    width: 40, height: 40, borderRadius: 12,
                    background: "linear-gradient(135deg, var(--brand) 0%, var(--brand-deep) 100%)",
                    color: "#fff",
                    display: "grid", placeItems: "center", marginBottom: 14,
                    boxShadow: "0 8px 20px -6px rgba(237,15,68,0.55)",
                  }}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                      <path d="M12 2l2.4 7.4H22l-6 4.4 2.3 7.2L12 16.7 5.7 21l2.3-7.2-6-4.4h7.6z"/>
                    </svg>
                  </div>
                  <div style={{ fontSize: 16, fontWeight: 700, color: "#fff", letterSpacing: "-0.01em" }}>{it.t}</div>
                  <div style={{
                    fontSize: 14, color: "rgba(255,255,255,0.78)",
                    marginTop: 8, lineHeight: 1.55,
                  }}>{it.d}</div>
                </div>
              ))}
            </div>

            <a href={window.balUrl(c.cta_href || "nosotros.html")} className="btn" style={{
              background: "var(--brand)", color: "#fff", marginTop: 36,
              border: 0, boxShadow: "0 12px 28px -8px rgba(237,15,68,0.55)",
            }}>
              {c.cta_label || "Conoce más sobre Baldera"} <window.Icon.Arrow />
            </a>
          </div>
        </div>
      </div>

      <style>{`
        /* Force the inner image-slot rendering to fill correctly with object-fit */
        .historia-photo image-slot,
        .historia-photo image-slot > * {
          width: 100% !important; height: 100% !important;
          display: block !important;
        }
        .historia-photo img {
          width: 100% !important; height: 100% !important;
          object-fit: cover !important; object-position: center !important;
          display: block !important;
        }
        @media (max-width: 720px) {
          .historia-cards { grid-template-columns: 1fr !important; gap: 12px !important; }
        }
      `}</style>
    </section>);

}

function CTAEnd() {
  return (
    <section style={{ paddingBottom: 80 }}>
      <div className="container">
        <div className="reveal" style={{ textAlign: "center" }}>
          <h2 className="display">Listo para conectarte <span style={{ color: "var(--brand)" }}>con lo mejor</span></h2>
          <p className="lead" style={{ marginTop: 20, maxWidth: 600, marginInline: "auto" }}>Encuentra el plan, equipo o servicio ideal para ti. Estamos a un clic de distancia.</p>
          <div style={{ display: "flex", gap: 14, justifyContent: "center", marginTop: 32, flexWrap: "wrap" }}>
            <a href={window.balUrl("planes.html")} className="btn btn-brand">Ver planes</a>
            <a href={window.balUrl("equipos.html")} className="btn btn-primary">Comprar equipos</a>
            <a href={window.balUrl("tiendas.html")} className="btn btn-ghost">Visitar tienda</a>
          </div>
        </div>
      </div>
    </section>);

}

function App() {
  const [t, setTweak] = window.useTweaks(HOME_TWEAK_DEFAULTS);
  const mood = MOODS[t.mood] || MOODS.lavender;
  useEffect(() => {
    const root = document.documentElement;
    Object.entries(mood).forEach(([k, v]) => {if (k.startsWith("--")) root.style.setProperty(k, v);});
    root.style.setProperty("--bal-density", String(t.density));
    document.body.style.background = mood["--paper"];
    document.body.style.color = mood["--ink"];
  }, [t.mood, t.density]);

  return (
    <window.PageScaffold active="">
      <style>{`
        :root { --bal-density: ${t.density}; }
        section { padding-top: calc(120px * var(--bal-density)); padding-bottom: calc(120px * var(--bal-density)); }
        h1, h2 { font-size: calc(1em * (0.85 + 0.15 * var(--bal-density))); }
      `}</style>
      <Hero comp={t.heroComp} />
      <PlanesSection />
      <EquiposSwatches />
      <StatsRow />
      <MapaTiendas />
      <PortabilidadBanner />
      <HistoriaSection />
      <CTAEnd />
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection title="Mood">
          <window.TweakSelect label="Vibe" value={t.mood} onChange={(v) => setTweak("mood", v)} options={[
          { value: "lavender", label: "Lovable Lavender" },
          { value: "caribbean", label: "Caribbean Sun" },
          { value: "midnight", label: "Midnight Plum" }]
          } />
        </window.TweakSection>
        <window.TweakSection title="Hero composition">
          <window.TweakRadio label="Right side" value={t.heroComp} onChange={(v) => setTweak("heroComp", v)} options={[
          { value: "offer", label: "Offer" },
          { value: "stack", label: "Phone" },
          { value: "bento", label: "Bento" }]
          } />
        </window.TweakSection>
        <window.TweakSection title="Density">
          <window.TweakSlider label="Vertical rhythm" min={0.6} max={1.4} step={0.05} value={t.density} onChange={(v) => setTweak("density", v)} />
        </window.TweakSection>
      </window.TweaksPanel>
    </window.PageScaffold>);

}
window.PAGES = Object.assign({}, window.PAGES, { home: App });
if (!window.__BAL_ROOT) window.__BAL_ROOT = ReactDOM.createRoot(document.getElementById("root"));
window.__BAL_ROOT.render(React.createElement((window.PAGES && window.PAGES[window.PAGE]) || App));