// SERVICIOS, TIENDAS, SOBRE, BLOG, CONTACTO, CARRITO en un solo file por simplicidad
// Each page reads window.PAGE to know what to render
const { useState, useEffect, useRef, useMemo } = React;

// STORES + StoresMap component live in shared.jsx (window.STORES, window.StoresMap)
const STORES = window.STORES;


// =========== SERVICIOS ===========
function ServiciosPage() {
  const services = [
  { tag: "Activación", title: "Activa tu línea Claro hoy.", desc: "Llevas tu cédula, sales con tu número activo. Prepago o pospago, en menos de 20 minutos.", color: "var(--paper-2)" },
  { tag: "Portabilidad", title: "Trae tu número, ahorra 50%.", desc: "Cambia a Claro sin perder tu número. Y obtén 50% off durante 6 meses.", color: "var(--brand)", dark: true, featured: true },
  { tag: "Internet Hogar", title: "Instalación gratis en 48 horas.", desc: "Pedimos cita, llegamos a tu casa, instalamos y configuramos. Tú solo conectas.", color: "var(--paper-2)" }];

  return (
    <window.PageScaffold active="servicios">
      <section style={{ padding: "112px 0 40px", position: "relative" }}>
        <window.DotGrid />
        <div className="container" style={{ position: "relative" }}>
          <div className="eyebrow reveal" style={{ marginBottom: 24 }}>Servicios</div>
          <h1 className="display reveal" style={{ margin: 0 }}>
            Todo lo que necesitas.<br /><span className="italic-display" style={{ color: "var(--brand)" }}>En un solo lugar.</span>
          </h1>
          <p className="lead reveal" style={{ maxWidth: 600, marginTop: 32 }}>
            Activación, portabilidad e instalación de internet hogar. Lo que sea, lo hacemos.
          </p>
        </div>
      </section>

      <section style={{ background: "var(--paper)" }}>
        <div className="container">
          <div className="grid grid-3 reveal" style={{ gap: 16 }}>
            {services.map((s, i) => {
              const prefill = `Hola Baldera, me interesa el servicio de ${s.tag.toLowerCase()}.\n\n${s.title}\n\n¿Pueden darme más información?`;
              return (
                <article key={i} style={{
                  background: s.color, color: s.dark ? "var(--paper)" : "var(--ink)",
                  borderRadius: 24, padding: 36, minHeight: 320,
                  display: "flex", flexDirection: "column", justifyContent: "space-between",
                  gridColumn: i === 1 ? "span 2" : "span 1",
                  position: "relative", overflow: "hidden",
                }}>
                  {s.featured && (
                    <div aria-hidden="true" style={{ position: "absolute", inset: 0, backgroundImage: "radial-gradient(rgba(255,255,255,0.18) 1.5px, transparent 1.5px)", backgroundSize: "24px 24px", opacity: 0.5 }} />
                  )}
                  <div style={{ position: "relative" }}>
                    <span className="mini" style={{ color: s.dark ? (s.featured ? "rgba(255,255,255,0.85)" : "var(--brand-coral)") : "var(--brand)" }}>{s.tag}</span>
                    <h3 style={{ fontSize: s.featured ? "clamp(28px, 3.5vw, 48px)" : "clamp(22px, 2.5vw, 32px)", fontWeight: 700, letterSpacing: "-0.02em", lineHeight: 1.1, marginTop: 16, marginBottom: 16 }}>{s.title}</h3>
                    <p style={{ fontSize: 15, lineHeight: 1.55, opacity: 0.8, margin: 0, maxWidth: 480 }}>{s.desc}</p>
                  </div>
                  <button
                    type="button"
                    onClick={() => window.openContactFAB(prefill)}
                    className="link"
                    style={{
                      color: s.dark ? (s.featured ? "#fff" : "var(--brand-coral)") : "var(--brand)",
                      marginTop: 32, position: "relative",
                      background: "transparent", border: 0, cursor: "pointer",
                      fontFamily: "inherit", fontSize: "inherit", padding: 0,
                      display: "inline-flex", alignItems: "center", gap: 6,
                    }}>
                    Solicitar <window.Icon.Arrow />
                  </button>
                </article>
              );
            })}
          </div>
        </div>
      </section>

      <section style={{ background: "var(--paper-2)" }}>
        <div className="container">
          <div className="reveal" style={{ marginBottom: 56 }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Cómo funciona</div>
            <h2 className="h1" style={{ margin: 0 }}>Tres pasos. <span className="italic-display" style={{ color: "var(--brand)" }}>Sin enredos.</span></h2>
          </div>
          <div className="grid grid-3 reveal" style={{ gap: 24 }}>
            {[
            { n: "01", t: "Cuéntanos", d: "Por WhatsApp, tienda o esta web. Te escuchamos y armamos tu propuesta." },
            { n: "02", t: "Confirmamos", d: "Te enviamos cotización clara, sin letra chica. Tú decides cuándo activar." },
            { n: "03", t: "Activamos", d: "En tienda o a domicilio. En 24h tu línea, equipo o internet está listo." }].
            map((s) =>
            <div key={s.n} style={{ background: "#fff", borderRadius: 22, padding: 32, border: "1px solid var(--line)" }}>
                <div style={{ fontSize: 56, fontWeight: 700, letterSpacing: "-0.04em", color: "var(--brand)", lineHeight: 1 }}>{s.n}</div>
                <div style={{ fontSize: 22, fontWeight: 700, marginTop: 24, letterSpacing: "-0.012em" }}>{s.t}</div>
                <div className="body" style={{ marginTop: 12 }}>{s.d}</div>
              </div>
            )}
          </div>
        </div>
      </section>
    </window.PageScaffold>);

}

// =========== TIENDAS ===========
function TiendasPage() {
  const [prov, setProv] = useState("Santiago");
  const allCount = Object.values(STORES).flat().length;
  return (
    <window.PageScaffold active="tiendas">
      <section style={{
        padding: "120px 0 80px", position: "relative", overflow: "hidden",
        background: `
          radial-gradient(ellipse 65% 50% at 5% -5%, rgba(237,15,68,0.26), transparent 55%),
          radial-gradient(ellipse 55% 60% at 100% 105%, rgba(255,122,77,0.22), transparent 55%),
          radial-gradient(ellipse 38% 38% at 78% 28%, rgba(237,15,68,0.10), transparent 60%),
          linear-gradient(180deg, var(--paper) 0%, var(--paper-2) 100%)
        `,
      }}>
        {/* Soft blurred glow — upper right */}
        <div aria-hidden="true" style={{
          position: "absolute", top: "-18%", right: "-8%",
          width: 540, height: 540, borderRadius: "50%",
          background: "radial-gradient(circle, rgba(237,15,68,0.28) 0%, transparent 65%)",
          filter: "blur(56px)",
          animation: "balTiendasGlow 9s ease-in-out infinite",
          pointerEvents: "none",
        }} />
        {/* Soft blurred glow — lower left */}
        <div aria-hidden="true" style={{
          position: "absolute", bottom: "-25%", left: "-5%",
          width: 420, height: 420, borderRadius: "50%",
          background: "radial-gradient(circle, rgba(255,122,77,0.24) 0%, transparent 60%)",
          filter: "blur(48px)",
          animation: "balTiendasGlow 11s ease-in-out infinite reverse",
          pointerEvents: "none",
        }} />

        <window.DotGrid />

        {/* Location pin dots scattered as decoration */}
        <div aria-hidden="true" style={{ position: "absolute", inset: 0, pointerEvents: "none" }}>
          {[
            { x: "8%",  y: "38%", s: 6, d: 0    },
            { x: "88%", y: "22%", s: 8, d: 0.6  },
            { x: "72%", y: "72%", s: 5, d: 1.2  },
            { x: "18%", y: "78%", s: 7, d: 1.8  },
            { x: "55%", y: "10%", s: 5, d: 2.4  },
            { x: "92%", y: "58%", s: 6, d: 3.0  },
            { x: "32%", y: "60%", s: 4, d: 3.6  },
          ].map((p, i) => (
            <span key={i} style={{
              position: "absolute", left: p.x, top: p.y,
              width: p.s, height: p.s, borderRadius: "50%",
              background: "var(--brand)",
              boxShadow: `0 0 0 ${Math.round(p.s * 1.6)}px rgba(237,15,68,0.10), 0 0 ${p.s * 3}px rgba(237,15,68,0.45)`,
              animation: `balTiendasPin 3.4s ease-in-out ${p.d}s infinite`,
              opacity: 0.85,
            }} />
          ))}
        </div>

        {/* Subtle grid lines (CAD/blueprint feel) */}
        <div aria-hidden="true" style={{
          position: "absolute", inset: 0, pointerEvents: "none",
          backgroundImage: `
            linear-gradient(to right, rgba(26,16,36,0.04) 1px, transparent 1px),
            linear-gradient(to bottom, rgba(26,16,36,0.04) 1px, transparent 1px)
          `,
          backgroundSize: "88px 88px",
          maskImage: "radial-gradient(ellipse at 50% 50%, #000 25%, transparent 80%)",
          WebkitMaskImage: "radial-gradient(ellipse at 50% 50%, #000 25%, transparent 80%)",
        }} />

        {/* Bottom horizon accent line */}
        <div aria-hidden="true" style={{
          position: "absolute", left: 0, right: 0, bottom: 0, height: 1,
          background: "linear-gradient(90deg, transparent 0%, rgba(237,15,68,0.3) 30%, rgba(237,15,68,0.5) 50%, rgba(237,15,68,0.3) 70%, transparent 100%)",
        }} />

        <div className="container" style={{ position: "relative" }}>
          <div className="eyebrow reveal" style={{ marginBottom: 24 }}>Tiendas · {allCount} en RD</div>
          <h1 className="display reveal" style={{ margin: 0 }}>
            Estamos cerca.<br /><span className="italic-display" style={{ color: "var(--brand)" }}>Siempre.</span>
          </h1>
          <p className="lead reveal" style={{ maxWidth: 540, marginTop: 28, color: "var(--ink-2)" }}>
            {allCount} tiendas en 4 provincias. Lunes a sábado. Asesores Claro certificados.
          </p>
        </div>

        <style>{`
          @keyframes balTiendasGlow {
            0%, 100% { transform: scale(1) translate(0, 0); opacity: 1; }
            50%      { transform: scale(1.12) translate(-12px, 8px); opacity: 0.88; }
          }
          @keyframes balTiendasPin {
            0%, 100% { transform: scale(1);   opacity: 0.85; }
            50%      { transform: scale(1.4); opacity: 1; }
          }
        `}</style>
      </section>

      <section style={{ background: "var(--paper-2)", paddingTop: 60 }}>
        <div className="container">
          <div className="reveal" style={{ background: "#fff", borderRadius: 24, padding: 12, border: "1px solid var(--line)", overflow: "hidden", boxShadow: "0 12px 32px -20px rgba(20,17,15,0.18)" }}>
            <window.StoresMap stores={STORES} activeProv={prov} onSelectProv={setProv} />
          </div>

          <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 48, flexWrap: "wrap" }}>
            {Object.keys(STORES).map((p) =>
            <button key={p} onClick={() => setProv(p)} style={{
              padding: "12px 22px", borderRadius: 999,
              background: prov === p ? "var(--ink)" : "#fff",
              color: prov === p ? "var(--paper)" : "var(--ink)",
              border: "1px solid " + (prov === p ? "var(--ink)" : "var(--line)"),
              cursor: "pointer", fontSize: 14, fontWeight: 500
            }}>{p} · {STORES[p].length}</button>
            )}
          </div>

          <div style={{ marginTop: 56, display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16 }} className="grid-2">
            {STORES[prov].map((s, i) => {
              const telHref = "tel:+1" + (s.phone || "").replace(/\D/g, "");
              const mapsHref = s.mapsUrl || (s.lat && s.lng ? `https://www.google.com/maps/dir/?api=1&destination=${s.lat},${s.lng}` : "#");
              const photoSrc = s.photo
                ? (s.photo.startsWith("http") ? s.photo : window.balUrl("uploads/stores/" + s.photo))
                : null;
              return (
                <article key={i} className="card" style={{ background: "#fff", padding: 28 }}>
                  <div style={{ display: "flex", gap: 18, alignItems: "flex-start" }}>
                    {/* Compact photo thumb — 96x96 */}
                    <div style={{
                      width: 96, height: 96, flexShrink: 0,
                      borderRadius: 14,
                      background: photoSrc
                        ? `url("${photoSrc}") center/cover no-repeat`
                        : "linear-gradient(135deg, var(--paper-2), var(--paper-3))",
                      border: "1px solid var(--line)",
                      display: "grid", placeItems: "center",
                      color: "var(--brand)",
                    }}>
                      {!photoSrc && <window.Icon.Pin />}
                    </div>

                    {/* Info */}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                        <span style={{ color: "var(--brand)" }}><window.Icon.Pin /></span>
                        <span className="mini" style={{ color: "var(--ink-3)" }}>{prov}</span>
                      </div>
                      <div style={{ fontSize: 17, fontWeight: 700, letterSpacing: "-0.012em", lineHeight: 1.3 }}>{s.name}</div>
                      {s.address && (
                        <div className="caption" style={{ marginTop: 6, color: "var(--ink-2)", lineHeight: 1.5 }}>
                          {s.address}
                        </div>
                      )}
                      <div className="caption" style={{ marginTop: 6 }}>{s.hours}</div>
                      <div className="caption" style={{ marginTop: 2 }}>
                        <a href={telHref} style={{ color: "inherit" }}>{s.phone}</a>
                      </div>
                    </div>
                  </div>
                  <div style={{ display: "flex", gap: 16, marginTop: 18, paddingTop: 16, borderTop: "1px solid var(--line)" }}>
                    <a href={mapsHref} target="_blank" rel="noopener" className="link">
                      Cómo llegar <window.Icon.Arrow />
                    </a>
                    <a href={telHref} className="link link-ink">Llamar</a>
                  </div>
                </article>
              );
            })}
          </div>
        </div>
      </section>
    </window.PageScaffold>);

}

// =========== SOBRE ===========
// ════════════════════════════════════════════════════════════════════════════
// TIMELINE — cinematic milestone strip with DR map silhouette + dot grid + sparkles
// ════════════════════════════════════════════════════════════════════════════
function TimelineSection({ items }) {
  return (
    <section className="bal-timeline" aria-labelledby="bal-timeline-title">
      {/* Background layers — ordered bottom to top */}
      <div className="bal-timeline__bg-paper" aria-hidden="true" />
      <DRMapSilhouette />
      <div className="bal-timeline__bg-dots"  aria-hidden="true" />
      <Sparkles count={18} />
      <div className="bal-timeline__bg-fade"  aria-hidden="true" />

      <div className="container" style={{ position: "relative", zIndex: 2 }}>
        <div className="reveal" style={{ textAlign: "center", marginBottom: 64 }}>
          <div className="eyebrow" style={{ color: "var(--brand)", marginBottom: 14, justifyContent: "center", display: "inline-flex", alignItems: "center", gap: 12 }}>
            <span style={{ width: 28, height: 1, background: "var(--brand)", opacity: 0.5 }} />
            25 años, 9 hitos
            <span style={{ width: 28, height: 1, background: "var(--brand)", opacity: 0.5 }} />
          </div>
          <h2 id="bal-timeline-title" className="h1" style={{ margin: 0 }}>
            Línea de <span className="italic-display" style={{ color: "var(--brand)" }}>tiempo.</span>
          </h2>
          <p className="lead" style={{ maxWidth: 620, margin: "18px auto 0", color: "var(--ink-2)" }}>
            De la primera tienda en La Sirena de Calle del Sol al proyecto de expansión
            en prepago. Esto es lo que ha pasado.
          </p>
        </div>

        <ol className="bal-timeline__list" role="list">
          <span className="bal-timeline__spine" aria-hidden="true" />
          {items.map((it, i) => (
            <li
              key={`${it.y}-${i}`}
              className={`bal-timeline__item reveal ${i % 2 === 0 ? "is-left" : "is-right"}`}
              style={{ transitionDelay: `${Math.min(i * 40, 280)}ms` }}
            >
              <span className="bal-timeline__node" aria-hidden="true">
                <span className="bal-timeline__node-dot" />
                <span className="bal-timeline__node-pulse" />
              </span>
              <div className="bal-timeline__card">
                <div className="bal-timeline__year">{it.y}</div>
                <div className="bal-timeline__title">{it.t}</div>
                <p className="bal-timeline__desc">{it.d}</p>
              </div>
            </li>
          ))}
        </ol>
      </div>

      <style>{`
        .bal-timeline {
          position: relative;
          overflow: hidden;
          padding: 40px 0 120px;     /* tighter top so the section flows from the stats grid */
          isolation: isolate;
        }
        /* Paper-warm base, fades into surrounding sections */
        .bal-timeline__bg-paper {
          position: absolute; inset: 0; z-index: -3;
          background:
            radial-gradient(ellipse 80% 60% at 50% 20%, rgba(237,15,68,0.10), transparent 65%),
            linear-gradient(180deg, var(--paper) 0%, var(--paper-2) 100%);
        }
        /* Refined dot grid (denser than DotGrid component) — fades at edges */
        .bal-timeline__bg-dots {
          position: absolute; inset: 0; z-index: -2;
          background-image: radial-gradient(rgba(26,16,36,0.12) 1px, transparent 1px);
          background-size: 24px 24px;
          -webkit-mask-image: radial-gradient(ellipse at center, #000 25%, transparent 75%);
                  mask-image: radial-gradient(ellipse at center, #000 25%, transparent 75%);
          opacity: 0.55;
        }
        /* Soft top + bottom fade so the section blends with neighbors */
        .bal-timeline__bg-fade {
          position: absolute; inset: 0; z-index: 1; pointer-events: none;
          background:
            linear-gradient(180deg, var(--paper) 0%, transparent 14%, transparent 86%, var(--paper-2) 100%);
        }

        .bal-timeline__list {
          position: relative;
          list-style: none;
          padding: 0; margin: 0 auto;
          max-width: 920px;
          display: flex; flex-direction: column;
          gap: 24px;
        }
        /* Vertical spine line, gradient fade at top + bottom */
        .bal-timeline__spine {
          position: absolute;
          left: 50%; top: 0; bottom: 0;
          width: 2px; transform: translateX(-50%);
          background: linear-gradient(180deg,
            transparent 0%,
            rgba(237,15,68,0.45) 8%,
            rgba(237,15,68,0.65) 50%,
            rgba(237,15,68,0.45) 92%,
            transparent 100%);
          border-radius: 999px;
          box-shadow: 0 0 16px rgba(237,15,68,0.32);
        }

        .bal-timeline__item {
          position: relative;
          display: grid;
          grid-template-columns: 1fr 56px 1fr;
          align-items: start;          /* top-align so dot aligns with year text */
        }
        .bal-timeline__item.is-left  .bal-timeline__card { grid-column: 1; text-align: right; }
        .bal-timeline__item.is-right .bal-timeline__card { grid-column: 3; text-align: left;  }

        /* The node (pin) on the spine — vertically aligned with the year text */
        .bal-timeline__node {
          grid-column: 2; position: relative;
          width: 18px; height: 18px; justify-self: center;
          /* Offset so the dot center matches the vertical center of the year text
             (card padding-top 26 + year font-size half ~22 = ~48) */
          margin-top: 32px;
        }
        .bal-timeline__node-dot {
          position: absolute; inset: 0; border-radius: 50%;
          background: linear-gradient(135deg, var(--brand) 0%, var(--brand-deep) 100%);
          box-shadow: 0 0 0 4px rgba(255,255,255,0.95), 0 6px 16px -4px rgba(237,15,68,0.6);
          z-index: 2;
        }
        .bal-timeline__node-pulse {
          position: absolute; inset: -10px; border-radius: 50%;
          background: rgba(237,15,68,0.18);
          animation: bal-pulse 2.8s ease-in-out infinite;
        }
        /* Horizontal connector from dot to card edge.
           Each side gets its own pseudo for direction control. */
        .bal-timeline__item.is-left  .bal-timeline__node::before,
        .bal-timeline__item.is-right .bal-timeline__node::before {
          content: "";
          position: absolute;
          top: 50%; height: 2px;
          background: linear-gradient(
            var(--connector-dir, 90deg),
            rgba(237,15,68,0.55) 0%,
            rgba(237,15,68,0.10) 100%
          );
          transform: translateY(-50%);
          border-radius: 999px;
        }
        .bal-timeline__item.is-left  .bal-timeline__node::before {
          right: calc(100% + 4px); width: 20px;
          --connector-dir: 270deg;        /* fade away from card */
        }
        .bal-timeline__item.is-right .bal-timeline__node::before {
          left: calc(100% + 4px); width: 20px;
          --connector-dir: 90deg;
        }
        @keyframes bal-pulse {
          0%, 100% { transform: scale(1);   opacity: 0.55; }
          50%      { transform: scale(1.6); opacity: 0; }
        }

        .bal-timeline__card {
          background: rgba(255,255,255,0.86);
          border: 1px solid rgba(237,15,68,0.12);
          backdrop-filter: blur(10px) saturate(140%);
          -webkit-backdrop-filter: blur(10px) saturate(140%);
          padding: 22px 28px 24px;
          border-radius: 20px;
          box-shadow: 0 8px 30px -16px rgba(20,17,15,0.18);
          transition: transform 280ms cubic-bezier(0.32,0.72,0,1), box-shadow 280ms;
        }
        .bal-timeline__card:hover {
          transform: translateY(-3px);
          box-shadow: 0 14px 36px -18px rgba(20,17,15,0.28), 0 0 0 1px rgba(237,15,68,0.20);
        }
        /* YEAR — dominant visual anchor of each card */
        .bal-timeline__year {
          font-size: clamp(32px, 3.6vw, 44px);
          font-weight: 800;
          letter-spacing: -0.025em;
          color: var(--brand);
          line-height: 1;
          margin: 0 0 10px;
          font-variant-numeric: tabular-nums;
          display: block;
          /* subtle gradient — works on both light and white cards */
          background: linear-gradient(180deg, var(--brand) 0%, var(--brand-deep) 100%);
          -webkit-background-clip: text;
                  background-clip: text;
          -webkit-text-fill-color: transparent;
          /* tiny baseline accent under the year */
        }
        .bal-timeline__title {
          font-size: 17px; font-weight: 700; letter-spacing: -0.012em;
          color: var(--ink); line-height: 1.3;
        }
        .bal-timeline__desc {
          margin: 6px 0 0; font-size: 14px; line-height: 1.55; color: var(--ink-2);
        }

        @media (max-width: 720px) {
          .bal-timeline { padding: 24px 0 80px; }
          .bal-timeline__spine { left: 24px; transform: none; }
          .bal-timeline__list { max-width: none; }
          .bal-timeline__item {
            grid-template-columns: 48px 1fr;
            align-items: start;
          }
          .bal-timeline__node {
            grid-column: 1; justify-self: start;
            margin-top: 30px;     /* aligns with year on mobile */
          }
          .bal-timeline__item.is-left  .bal-timeline__card,
          .bal-timeline__item.is-right .bal-timeline__card {
            grid-column: 2; text-align: left;
          }
          /* On mobile every connector points right (cards always on the right) */
          .bal-timeline__item.is-left  .bal-timeline__node::before,
          .bal-timeline__item.is-right .bal-timeline__node::before {
            left: calc(100% + 4px); right: auto; width: 16px;
            --connector-dir: 90deg;
          }
          .bal-timeline__year { font-size: clamp(28px, 8vw, 36px); }
        }
        @media (prefers-reduced-motion: reduce) {
          .bal-timeline__node-pulse { animation: none; opacity: 0.4; }
          .bal-timeline__card { transition: none; }
        }
      `}</style>
    </section>
  );
}

// Dominican Republic silhouette as background watermark.
// Path simplified from public-domain country outline data.
function DRMapSilhouette() {
  return (
    <svg
      className="bal-timeline__map"
      viewBox="0 0 800 360"
      aria-hidden="true"
      style={{
        position: "absolute",
        top: "50%", left: "50%",
        transform: "translate(-50%, -50%)",
        width: "min(1200px, 110%)",
        height: "auto",
        zIndex: -1,
        opacity: 0.12,
        pointerEvents: "none",
      }}
    >
      <defs>
        <linearGradient id="dr-grad" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%"   stopColor="#ED0F44" stopOpacity="0.85" />
          <stop offset="100%" stopColor="#1a1024" stopOpacity="0.65" />
        </linearGradient>
        <filter id="dr-blur" x="-10%" y="-10%" width="120%" height="120%">
          <feGaussianBlur stdDeviation="0.6" />
        </filter>
      </defs>
      {/* Simplified Dominican Republic outline (west coast → north → east → south) */}
      <path
        d="
          M 70 220 C 95 195, 130 188, 165 192
          C 200 178, 240 168, 275 178
          C 310 162, 345 162, 380 172
          C 415 156, 455 148, 495 158
          C 540 150, 590 158, 635 172
          C 680 184, 720 200, 745 224
          C 762 246, 758 268, 730 280
          C 695 296, 645 296, 590 290
          C 540 298, 488 300, 440 296
          C 395 304, 345 304, 300 296
          C 255 304, 210 300, 175 286
          C 140 280, 105 268, 80 252
          C 65 240, 60 230, 70 220 Z
        "
        fill="url(#dr-grad)"
        stroke="#1a1024"
        strokeOpacity="0.25"
        strokeWidth="1.2"
        filter="url(#dr-blur)"
      />
      {/* A few accent landmark dots for cities */}
      <g fill="#ED0F44" opacity="0.55">
        <circle cx="220" cy="218" r="4" />  {/* Santiago */}
        <circle cx="540" cy="262" r="4" />  {/* Santo Domingo */}
        <circle cx="280" cy="232" r="3" />  {/* La Vega */}
        <circle cx="245" cy="208" r="3" />  {/* Moca */}
      </g>
    </svg>
  );
}

// Animated sparkles scattered across the timeline section
function Sparkles({ count = 16 }) {
  const sparkles = useMemo(() => {
    const arr = [];
    for (let i = 0; i < count; i++) {
      arr.push({
        id: i,
        left: 5 + Math.random() * 90,        // %
        top: 8 + Math.random() * 84,         // %
        size: 4 + Math.random() * 6,
        delay: Math.random() * 4,
        duration: 3 + Math.random() * 3,
      });
    }
    return arr;
  }, [count]);
  return (
    <div aria-hidden="true" style={{ position: "absolute", inset: 0, zIndex: 0, pointerEvents: "none" }}>
      {sparkles.map((s) => (
        <span key={s.id} className="bal-sparkle" style={{
          position: "absolute",
          left: `${s.left}%`, top: `${s.top}%`,
          width: s.size, height: s.size,
          animationDelay: `${s.delay}s`,
          animationDuration: `${s.duration}s`,
        }} />
      ))}
      <style>{`
        .bal-sparkle {
          display: block;
          border-radius: 50%;
          background: radial-gradient(circle, rgba(237,15,68,0.85) 0%, rgba(237,15,68,0.5) 30%, transparent 70%);
          box-shadow: 0 0 8px rgba(237,15,68,0.6);
          animation-name: bal-sparkle;
          animation-iteration-count: infinite;
          animation-timing-function: ease-in-out;
          will-change: transform, opacity;
        }
        @keyframes bal-sparkle {
          0%, 100% { transform: scale(0.6); opacity: 0; }
          50%      { transform: scale(1.4); opacity: 0.9; }
        }
        @media (prefers-reduced-motion: reduce) {
          .bal-sparkle { animation: none; opacity: 0.25; }
        }
      `}</style>
    </div>
  );
}

function SobrePage() {
  // Photo settings editable desde /admin/settings.php → panel "Página Nosotros"
  const SOBRE_DEFAULTS = {
    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_position: "center center",
    photo_aspect: "21/9",
  };
  const [sobre, setSobre] = useState(() => Object.assign({}, SOBRE_DEFAULTS, (window.SITE && window.SITE.sobre) || {}));
  useEffect(() => {
    const sync = () => setSobre(Object.assign({}, SOBRE_DEFAULTS, (window.SITE && window.SITE.sobre) || {}));
    sync();
    window.addEventListener("baldera-site-ready", sync);
    return () => window.removeEventListener("baldera-site-ready", sync);
  }, []);

  const timeline = [
  { y: "2001", t: "Nace Baldera Comunicaciones", d: "Primera tienda en La Sirena de la Calle del Sol, Santiago." },
  { y: "2004", t: "Cuarta tienda + oficina administrativa", d: "Apertura de la cuarta tienda y primera oficina administrativa en Plaza Pujols, Gurabo." },
  { y: "2005", t: "Operación de subdistribuidores", d: "Inicio del programa de subdistribuidores para expandir la cobertura en todo el Cibao." },
  { y: "2012", t: "Distribuidor Autorizado del Año", d: "Primer reconocimiento como Distribuidor Autorizado del Año por Claro RD." },
  { y: "2013", t: "Protocolo de empresa familiar", d: "Implementación del protocolo de empresas familiares para garantizar continuidad y gobernanza." },
  { y: "2013", t: "Llegamos a Santo Domingo", d: "Inicio de operaciones en la capital con presencia comercial directa.", duplicate: true },
  { y: "2019", t: "Quinto premio anual", d: "Obtención del quinto premio como Distribuidor Autorizado del Año." },
  { y: "2021", t: "Nueva oficina administrativa", d: "Mudanza a una nueva oficina central, soportando el crecimiento del equipo." },
  { y: "2024", t: "Expansión en prepago", d: "Lanzamos el proyecto de expansión de comercios en prepago en Santiago." }];

  return (
    <window.PageScaffold active="nosotros">
      <section style={{ padding: "112px 0 40px", position: "relative" }}>
        <window.DotGrid />
        <div className="container" style={{ position: "relative" }}>
          <div className="eyebrow reveal" style={{ marginBottom: 24 }}>Sobre nosotros</div>
          <h1 className="display reveal" style={{ margin: 0, maxWidth: 1100 }}>
            Una historia<br />que comenzó <span className="italic-display" style={{ color: "var(--brand)" }}>en 2001.</span>
          </h1>
          <p className="lead reveal" style={{ maxWidth: 640, marginTop: 32 }}>
            Baldera Comunicaciones nació en Santiago de los Caballeros con una idea simple: que activar un teléfono no debería ser un dolor de cabeza. 25 años después, seguimos creyéndolo.
          </p>
        </div>
      </section>

      <section style={{ background: "var(--paper)", paddingTop: 0 }}>
        <div className="container">
          <div className="reveal" style={{
            aspectRatio: sobre.photo_aspect || "21/9",
            borderRadius: 32, overflow: "hidden", marginBottom: 80,
            background: "var(--paper-2)",
          }}>
            {sobre.photo_url ? (
              <img src={sobre.photo_url} alt={sobre.photo_alt} loading="lazy"
                style={{
                  width: "100%", height: "100%",
                  objectFit: "cover",
                  objectPosition: sobre.photo_position || "center center",
                  display: "block",
                }} />
            ) : (
              <image-slot id="about-hero" placeholder="Foto: equipo Baldera o tienda" shape="rounded" style={{ width: "100%", height: "100%", borderRadius: 32 }}>
                <div style={{ width: "100%", height: "100%", background: "linear-gradient(120deg, var(--brand-warm), var(--brand) 50%, #8B0524)", position: "relative" }} className="tex-grain">
                  <div style={{ position: "absolute", inset: 0, backgroundImage: "radial-gradient(rgba(255,255,255,0.2) 1.5px, transparent 1.5px)", backgroundSize: "30px 30px" }} />
                  <div style={{ position: "absolute", left: 40, bottom: 40, color: "#fff" }}>
                    <div className="mini" style={{ opacity: 0.85 }}>Foto · placeholder</div>
                    <div style={{ fontSize: 28, fontWeight: 700, marginTop: 8 }}>{sobre.photo_caption || "Equipo Baldera, 2025"}</div>
                  </div>
                </div>
              </image-slot>
            )}
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 32 }} className="grid-4">
            {[["+25", "años"], ["17", "tiendas"], ["Top 3", "Claro RD"], ["+90", "empleados"]].map(([n, l]) =>
            <div key={l} className="reveal" style={{ background: "var(--paper-2)", borderRadius: 22, padding: 32, minHeight: 200 }}>
                <div style={{ fontSize: "clamp(48px, 6vw, 88px)", fontWeight: 700, letterSpacing: "-0.035em", color: "var(--brand)", lineHeight: 0.9 }}>{n}</div>
                <div style={{ fontSize: 16, color: "var(--ink-2)", marginTop: 12 }}>{l}</div>
              </div>
            )}
          </div>

        </div>
      </section>

      {/* ═══ TIMELINE — cinematic with DR map silhouette + sparkles ═══ */}
      <TimelineSection items={timeline} />

      <section style={{ background: "var(--ink)", color: "var(--paper)" }}>
        <div className="container">
          <div className="reveal" style={{ maxWidth: 800 }}>
            <div className="mini" style={{ color: "var(--brand-coral)", marginBottom: 20 }}>Misión</div>
            <h2 className="h1" style={{ color: "var(--paper)", margin: 0 }}>
              Que cada dominicano pueda <span className="italic-display" style={{ color: "var(--brand-coral)" }}>conectarse</span> sin esperar y sin enredarse.
            </h2>
          </div>
        </div>
      </section>
    </window.PageScaffold>);

}

// =========== BLOG ===========
function BlogPage() {
  const [items, setItems] = useState([]);
  const [status, setStatus] = useState("loading");

  useEffect(() => {
    fetch(window.balUrl("admin/api/posts.php?limit=20"))
      .then(r => r.ok ? r.json() : Promise.reject("HTTP " + r.status))
      .then(d => {
        setItems(d.items || []);
        setStatus(d.items && d.items.length ? "ok" : "empty");
      })
      .catch(() => setStatus("error"));
  }, []);

  const featured = items.find(i => i.is_featured) || items[0];
  const rest = items.filter(i => i !== featured);

  const fmtDate = (s) => {
    if (!s) return "";
    const d = new Date(s.replace(' ', 'T'));
    return d.toLocaleDateString("es-DO", { day: "2-digit", month: "short", year: "numeric" });
  };

  return (
    <window.PageScaffold active="blog">
      <section style={{ padding: "112px 0 40px", position: "relative" }}>
        <window.DotGrid />
        <div className="container" style={{ position: "relative" }}>
          <div className="eyebrow reveal" style={{ marginBottom: 24 }}>Blog</div>
          <h1 className="display reveal" style={{ margin: 0 }}>
            Historias,<br />guías y <span className="italic-display" style={{ color: "var(--brand)" }}>noticias.</span>
          </h1>
          <p className="lead reveal" style={{ marginTop: 32, maxWidth: 600 }}>
            Tecnología, planes Claro, equipos y novedades del sector telecom RD.
          </p>
        </div>
      </section>

      <section style={{ background: "var(--paper)" }}>
        <div className="container">
          {status === "loading" && (
            <div className="grid grid-3" style={{ gap: 16 }}>
              {[...Array(6)].map((_, i) => (
                <div key={i} className="card" style={{ padding: 0, overflow: "hidden" }}>
                  <div style={{ aspectRatio: "16/10", background: "var(--paper-2)" }} />
                  <div style={{ padding: 28 }}>
                    <div style={{ height: 12, width: 80, background: "var(--paper-2)", borderRadius: 4 }} />
                    <div style={{ height: 18, marginTop: 14, background: "var(--paper-2)", borderRadius: 4 }} />
                    <div style={{ height: 14, marginTop: 8, width: "60%", background: "var(--paper-2)", borderRadius: 4 }} />
                  </div>
                </div>
              ))}
            </div>
          )}

          {status === "empty" && (
            <div className="card" style={{ padding: 64, textAlign: "center" }}>
              <div style={{ fontSize: 56, marginBottom: 16 }}>📝</div>
              <h3 className="h3" style={{ margin: 0 }}>Aún no hay artículos publicados</h3>
              <p className="body" style={{ marginTop: 12, color: "var(--ink-3)" }}>
                Vuelve pronto · estamos preparando contenido fresco.
              </p>
            </div>
          )}

          {status === "error" && (
            <div className="card" style={{ padding: 48, textAlign: "center" }}>
              <h3 className="h3" style={{ margin: 0 }}>Error de carga</h3>
              <p className="body" style={{ marginTop: 12 }}>No pudimos cargar los artículos.</p>
            </div>
          )}

          {status === "ok" && featured && (
            <a href={window.balUrl(`post.html?slug=${encodeURIComponent(featured.slug)}`)} className="reveal card" style={{
              display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 0, padding: 0, overflow: "hidden",
              marginBottom: 56, color: "var(--ink)",
            }}>
              <div style={{
                aspectRatio: "16/10", position: "relative",
                background: featured.cover
                  ? `url(${featured.cover}) center/cover`
                  : "linear-gradient(135deg, var(--brand-warm), var(--brand) 60%, #8B0524)",
              }} className={featured.cover ? "" : "tex-grain"}>
                {!featured.cover && (
                  <div style={{ position: "absolute", inset: 0, backgroundImage: "radial-gradient(rgba(255,255,255,0.18) 1.5px, transparent 1.5px)", backgroundSize: "24px 24px" }} />
                )}
                {featured.is_featured && (
                  <div style={{ position: "absolute", left: 24, top: 24, padding: "6px 12px", background: "#fff", borderRadius: 999, fontSize: 11, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase" }}>★ Destacado</div>
                )}
              </div>
              <div style={{ padding: 40, display: "flex", flexDirection: "column", justifyContent: "center" }}>
                {featured.category && <div className="mini" style={{ color: "var(--brand)" }}>{featured.category}</div>}
                <h2 className="h2" style={{ margin: "16px 0 12px", letterSpacing: "-0.025em", lineHeight: 1.15 }}>{featured.title}</h2>
                {featured.excerpt && <p className="body" style={{ margin: 0, color: "var(--ink-2)" }}>{featured.excerpt}</p>}
                <div style={{ display: "flex", gap: 14, marginTop: 24, fontSize: 13, color: "var(--ink-3)", flexWrap: "wrap" }}>
                  {featured.published_at && <span>{fmtDate(featured.published_at)}</span>}
                  {featured.reading_minutes && <><span>·</span><span>{featured.reading_minutes} min de lectura</span></>}
                  {featured.author && <><span>·</span><span>por {featured.author}</span></>}
                </div>
              </div>
            </a>
          )}

          {status === "ok" && rest.length > 0 && (
            <div className="grid grid-3 reveal" style={{ gap: 16 }}>
              {rest.map((p) => (
                <a key={p.id} href={window.balUrl(`post.html?slug=${encodeURIComponent(p.slug)}`)} className="card" style={{
                  padding: 0, overflow: "hidden", color: "var(--ink)",
                  display: "flex", flexDirection: "column",
                }}>
                  <div style={{
                    aspectRatio: "16/10", position: "relative",
                    background: p.cover
                      ? `url(${p.cover}) center/cover`
                      : "linear-gradient(135deg, var(--paper-3), var(--paper-2))",
                  }} className={p.cover ? "" : "tex-grain"} />
                  <div style={{ padding: 24, flex: 1, display: "flex", flexDirection: "column" }}>
                    {p.category && <div className="mini" style={{ color: "var(--brand)" }}>{p.category}</div>}
                    <h3 style={{ fontSize: 19, fontWeight: 700, letterSpacing: "-0.015em", lineHeight: 1.25, margin: "12px 0 10px" }}>{p.title}</h3>
                    {p.excerpt && (
                      <p style={{ fontSize: 14, color: "var(--ink-3)", lineHeight: 1.55, margin: 0, marginBottom: 14 }}>
                        {p.excerpt.length > 110 ? p.excerpt.slice(0, 110) + "…" : p.excerpt}
                      </p>
                    )}
                    <div style={{ marginTop: "auto", display: "flex", gap: 10, fontSize: 12, color: "var(--ink-4)", flexWrap: "wrap" }}>
                      {p.published_at && <span>{fmtDate(p.published_at)}</span>}
                      {p.reading_minutes && <><span>·</span><span>{p.reading_minutes} min</span></>}
                    </div>
                  </div>
                </a>
              ))}
            </div>
          )}
        </div>
      </section>
    </window.PageScaffold>);

}

// =========== CONTACTO ===========
function ContactoPage() {
  const TOPICS = [
    { key: "Planes",       icon: "📶", desc: "Cotizo un plan" },
    { key: "Equipos",      icon: "📱", desc: "Quiero un equipo" },
    { key: "Portabilidad", icon: "🔄", desc: "Traer mi número" },
    { key: "Soporte",      icon: "🛠", desc: "Ayuda técnica" },
    { key: "Reclamación",  icon: "⚠️", desc: "Tengo una queja" },
  ];
  const PREFERS = ["WhatsApp", "Llamada", "Email"];

  const [form, setForm] = useState({
    name: "", email: "", phone: "", topic: "Planes", prefer: "WhatsApp",
    msg: "", consent: true,
  });
  const [status, setStatus] = useState("idle"); // idle | sending | sent | error
  const [error, setError] = useState(null);
  const [site, setSite] = useState(window.SITE || {});

  useEffect(() => {
    const u = () => setSite(window.SITE || {});
    window.addEventListener("baldera-site-ready", u);
    return () => window.removeEventListener("baldera-site-ready", u);
  }, []);

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    if (!form.name.trim()) { setError("Pon tu nombre."); return; }
    if (!form.phone.trim() && !form.email.trim()) { setError("Necesitamos un teléfono o email."); return; }
    if (!form.consent) { setError("Acepta el contacto para continuar."); return; }

    setStatus("sending");
    try {
      const r = await fetch(window.balUrl("admin/api/lead_submit.php"), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: form.name, email: form.email, phone: form.phone,
          message: `[${form.topic}] [Prefiere: ${form.prefer}] ${form.msg}`.trim(),
          source: "contacto",
          page: location.pathname,
        }),
      });
      const d = await r.json();
      if (!r.ok || !d.ok) throw new Error(d.error || "fail");
      setStatus("sent");
    } catch (err) {
      setStatus("error");
      setError(err.message);
    }
  };

  const whatsappShortcut = () => {
    const msg = `Hola Baldera, soy ${form.name || "cliente"}. ${form.topic}: ${form.msg || "Me gustaría más información"}.`;
    window.openWhatsApp(msg);
  };

  return (
    <window.PageScaffold active="contacto">
      <section style={{ padding: "112px 0 40px", position: "relative" }}>
        <window.DotGrid />
        <div className="container" style={{ position: "relative" }}>
          <div className="eyebrow reveal" style={{ marginBottom: 24 }}>Contacto</div>
          <h1 className="display reveal" style={{ margin: 0 }}>
            Cuéntanos.<br /><span className="italic-display" style={{ color: "var(--brand)" }}>Te escuchamos.</span>
          </h1>
          <p className="lead reveal" style={{ marginTop: 28, maxWidth: 600 }}>
            Por WhatsApp en segundos, llamada al instante, o el formulario si prefieres detalles. Lo que sea más cómodo.
          </p>
        </div>
      </section>

      {/* Quick channels strip */}
      <section style={{ background: "var(--paper)", paddingTop: 40 }}>
        <div className="container">
          <div className="grid grid-3 reveal" style={{ gap: 16, marginBottom: 56 }}>
            <ContactCard
              title="WhatsApp" desc="Respuesta en menos de 5 min · Lun-Sáb 8AM-8PM"
              value={site.whatsapp || "(849) 220-9239"} tag="Más rápido" featured
              onClick={() => window.openWhatsApp("Hola Baldera, quiero información.", site.whatsapp)} />
            <ContactCard
              title="Llámanos" desc="Soporte 24/7 · todos los días"
              value={site.phone || "(809) 200-6262"}
              onClick={() => location.href = `tel:${(site.phone || "+18492209239").replace(/[^\d+]/g, "")}`} />
            <ContactCard
              title="Email" desc="Respondemos en menos de 24h"
              value={site.email || "ventas@baldera.com.do"}
              onClick={() => location.href = `mailto:${site.email || "ventas@baldera.com.do"}`} />
          </div>

          {/* Form */}
          <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 64 }} className="grid-2">
            <div className="reveal">
              <h2 className="h3" style={{ margin: "0 0 8px" }}>O escríbenos un mensaje</h2>
              <p className="body" style={{ margin: "0 0 32px", color: "var(--ink-3)" }}>
                Te contactamos por el canal que prefieras.
              </p>

              {status === "sent" ? (
                <div style={{ background: "var(--paper-2)", borderRadius: 22, padding: 48, textAlign: "center" }}>
                  <div style={{ fontSize: 56, marginBottom: 16 }}>✦</div>
                  <h3 className="h3" style={{ margin: 0 }}>Mensaje recibido.</h3>
                  <p className="body" style={{ marginTop: 12, color: "var(--ink-3)" }}>
                    Te contactaremos por <strong>{form.prefer}</strong> en menos de 24 h hábiles.
                  </p>
                  <button onClick={whatsappShortcut} className="btn" style={{
                    background: "#25D366", color: "#fff", marginTop: 28, border: 0, cursor: "pointer", fontFamily: "inherit"
                  }}>
                    Adelanta tu mensaje por WhatsApp
                  </button>
                </div>
              ) : (
                <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 20 }}>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                    <Field label="Nombre *" value={form.name} onChange={(v) => setForm({ ...form, name: v })} required />
                    <Field label="Email" type="email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} />
                  </div>
                  <Field label="Teléfono / WhatsApp" type="tel" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} placeholder="+1 809..." />

                  <div>
                    <label className="mini" style={{ color: "var(--ink-3)", display: "block", marginBottom: 12 }}>
                      ¿Sobre qué nos contactas?
                    </label>
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: 8 }}>
                      {TOPICS.map((t) => (
                        <button type="button" key={t.key} onClick={() => setForm({ ...form, topic: t.key })} style={{
                          padding: "12px 14px", borderRadius: 14,
                          background: form.topic === t.key ? "var(--ink)" : "#fff",
                          color: form.topic === t.key ? "var(--paper)" : "var(--ink)",
                          border: "1px solid " + (form.topic === t.key ? "var(--ink)" : "var(--line)"),
                          cursor: "pointer", fontSize: 13, fontWeight: 500,
                          textAlign: "left", display: "flex", flexDirection: "column", gap: 4,
                          fontFamily: "inherit",
                        }}>
                          <span style={{ fontSize: 18 }}>{t.icon}</span>
                          <span style={{ fontWeight: 600 }}>{t.key}</span>
                          <span style={{ fontSize: 11, opacity: 0.7 }}>{t.desc}</span>
                        </button>
                      ))}
                    </div>
                  </div>

                  <div>
                    <label className="mini" style={{ color: "var(--ink-3)", display: "block", marginBottom: 12 }}>
                      ¿Cómo prefieres que te contactemos?
                    </label>
                    <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                      {PREFERS.map((p) => (
                        <button type="button" key={p} onClick={() => setForm({ ...form, prefer: p })} style={{
                          padding: "8px 16px", borderRadius: 999,
                          background: form.prefer === p ? "var(--brand)" : "#fff",
                          color: form.prefer === p ? "#fff" : "var(--ink)",
                          border: "1px solid " + (form.prefer === p ? "var(--brand)" : "var(--line)"),
                          cursor: "pointer", fontSize: 13, fontWeight: 500, fontFamily: "inherit",
                        }}>{p}</button>
                      ))}
                    </div>
                  </div>

                  <div>
                    <label className="mini" style={{ color: "var(--ink-3)", display: "block", marginBottom: 8 }}>Mensaje</label>
                    <textarea value={form.msg} onChange={(e) => setForm({ ...form, msg: e.target.value })} rows={5}
                      placeholder="Cuéntanos qué necesitas con el mayor detalle posible…"
                      style={{
                        width: "100%", padding: 16, borderRadius: 14, border: "1px solid var(--line)",
                        fontSize: 15, fontFamily: "inherit", resize: "vertical", background: "#fff",
                      }} />
                  </div>

                  <label style={{ display: "flex", gap: 10, fontSize: 13, color: "var(--ink-3)", lineHeight: 1.5 }}>
                    <input type="checkbox" checked={form.consent} onChange={(e) => setForm({ ...form, consent: e.target.checked })}
                      style={{ marginTop: 4 }} />
                    <span>Acepto que Baldera me contacte por el canal indicado para responder a esta solicitud.</span>
                  </label>

                  {error && (
                    <div style={{ background: "#FCE7E9", color: "var(--brand-deep)", padding: 12, borderRadius: 12, fontSize: 13 }}>
                      ⚠️ {error}
                    </div>
                  )}

                  <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
                    <button type="submit" disabled={status === "sending"} className="btn btn-brand"
                      style={{ alignSelf: "flex-start", border: 0, cursor: "pointer", fontFamily: "inherit",
                              opacity: status === "sending" ? 0.6 : 1 }}>
                      {status === "sending" ? "Enviando…" : "Enviar mensaje"} <window.Icon.Arrow />
                    </button>
                    <button type="button" onClick={whatsappShortcut} className="btn"
                      style={{ background: "#25D366", color: "#fff", border: 0, cursor: "pointer", fontFamily: "inherit" }}>
                      Mejor por WhatsApp
                    </button>
                  </div>
                </form>
              )}
            </div>

            <div className="reveal" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <div style={{ background: "var(--paper-2)", borderRadius: 22, padding: 28 }}>
                <div className="mini" style={{ color: "var(--ink-3)", marginBottom: 12 }}>Horario de atención</div>
                <div style={{ fontSize: 15, lineHeight: 1.7 }}>
                  <div><strong>Lunes – Viernes</strong> · 8:00 AM – 8:00 PM</div>
                  <div><strong>Sábado</strong> · 9:00 AM – 6:00 PM</div>
                  <div><strong>Domingo</strong> · 10:00 AM – 4:00 PM</div>
                  <div style={{ marginTop: 12, color: "var(--ink-3)", fontSize: 13 }}>
                    Soporte técnico 24/7 por llamada
                  </div>
                </div>
              </div>

              <a href={window.balUrl("tiendas.html")} style={{
                background: "var(--ink)", color: "var(--paper)", borderRadius: 22, padding: 28,
                display: "block",
              }}>
                <div className="mini" style={{ color: "var(--brand-coral)", marginBottom: 12 }}>17 tiendas en RD</div>
                <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.018em" }}>
                  Visítanos en tienda
                </div>
                <div style={{ fontSize: 14, opacity: 0.78, marginTop: 8 }}>
                  Santiago · Santo Domingo · La Vega · Moca
                </div>
                <div style={{ marginTop: 16, fontSize: 13, color: "var(--brand-coral)" }}>
                  Ver todas las tiendas →
                </div>
              </a>

              <div style={{ background: "#fff", borderRadius: 22, padding: 28, border: "1px solid var(--line)" }}>
                <div className="mini" style={{ color: "var(--ink-3)", marginBottom: 12 }}>Tiempos de respuesta</div>
                <div style={{ fontSize: 14, lineHeight: 1.8 }}>
                  <Tier color="#25D366" label="WhatsApp" eta="< 5 min" />
                  <Tier color="var(--brand)" label="Llamada" eta="Inmediato" />
                  <Tier color="#0070f3" label="Formulario" eta="< 24 h" />
                  <Tier color="var(--ink-3)" label="Email" eta="< 24 h" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </window.PageScaffold>);

}

function Tier({ color, label, eta }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 0", borderBottom: "1px solid var(--line)" }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
        <span style={{ width: 8, height: 8, borderRadius: 999, background: color }} />
        <span>{label}</span>
      </span>
      <strong style={{ fontSize: 13, color: "var(--ink)" }}>{eta}</strong>
    </div>
  );
}

function Field({ label, value, onChange, type = "text", placeholder = "", required = false }) {
  return (
    <div>
      <label className="mini" style={{ color: "var(--ink-3)", display: "block", marginBottom: 8 }}>{label}</label>
      <input type={type} value={value} onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder} required={required}
        style={{
          width: "100%", padding: "14px 16px", borderRadius: 14, border: "1px solid var(--line)",
          fontSize: 15, fontFamily: "inherit", background: "#fff",
        }} />
    </div>);
}
function ContactCard({ title, desc, value, tag, featured, onClick }) {
  return (
    <button onClick={onClick} style={{
      background: featured ? "var(--brand)" : "#fff", color: featured ? "#fff" : "var(--ink)",
      borderRadius: 22, padding: 28, border: featured ? "none" : "1px solid var(--line)",
      display: "flex", flexDirection: "column", gap: 8, position: "relative",
      cursor: "pointer", fontFamily: "inherit", textAlign: "left", width: "100%",
    }}>
      {tag && <span style={{ position: "absolute", top: 16, right: 16, padding: "4px 10px", background: "#fff", color: "var(--brand)", borderRadius: 999, fontSize: 10, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase" }}>{tag}</span>}
      <div className="mini" style={{ color: featured ? "rgba(255,255,255,0.85)" : "var(--ink-3)" }}>{title}</div>
      <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.018em", marginTop: 8 }}>{value}</div>
      <div style={{ fontSize: 13, opacity: 0.75, marginTop: 4 }}>{desc}</div>
    </button>);
}

// =========== CARRITO ===========
function CarritoPage() {
  const [items, setItems] = useState(() => (window.Cart ? window.Cart.list() : []));
  const [phone, setPhone] = useState("");
  const [note, setNote]   = useState("");
  const [site, setSite]   = useState(window.SITE || {});

  useEffect(() => {
    const sync = () => setItems(window.Cart ? window.Cart.list() : []);
    sync();
    window.addEventListener("baldera-cart-change", sync);
    window.addEventListener("storage", sync);
    const u = () => setSite(window.SITE || {});
    window.addEventListener("baldera-site-ready", u);
    return () => {
      window.removeEventListener("baldera-cart-change", sync);
      window.removeEventListener("storage", sync);
      window.removeEventListener("baldera-site-ready", u);
    };
  }, []);

  const subtotal = items.reduce((s, i) => s + (Number(i.price) || 0) * (i.qty || 0), 0);
  const tax = Math.round(subtotal * 0.18);
  const total = subtotal + tax;

  const updateQty = (key, delta) => {
    const cur = items.find((x) => x.key === key);
    if (!cur) return;
    window.Cart.update(key, (cur.qty || 0) + delta);
  };
  const removeItem = (key) => window.Cart.remove(key);

  const checkout = () => {
    const target = phone.trim() || (site.whatsapp || "");
    if (phone.trim() && !/^[+]?[\d\s\-()]{8,}$/.test(phone.trim())) {
      alert("El número que escribiste no parece válido. Déjalo vacío para usar el de la empresa.");
      return;
    }
    window.Cart.checkout({ phone: target || undefined, note: note.trim() || undefined });
  };

  return (
    <window.PageScaffold active="">
      <section style={{ padding: "112px 0 40px", position: "relative" }}>
        <window.DotGrid />
        <div className="container" style={{ position: "relative" }}>
          <div className="eyebrow reveal" style={{ marginBottom: 24 }}>Tu pedido</div>
          <h1 className="display reveal" style={{ margin: 0 }}>
            {items.length === 0 ? <>Carrito <span className="italic-display" style={{ color: "var(--brand)" }}>vacío.</span></> :
              <>Casi <span className="italic-display" style={{ color: "var(--brand)" }}>listo.</span></>}
          </h1>
          {items.length > 0 && (
            <p className="lead reveal" style={{ marginTop: 24, maxWidth: 540 }}>
              Confirma tu pedido por WhatsApp. Te respondemos en menos de 5 min.
            </p>
          )}
        </div>
      </section>

      <section style={{ background: "var(--paper)", paddingTop: 40 }}>
        <div className="container">
          {items.length === 0 ? (
            <div style={{ background: "var(--paper-2)", borderRadius: 22, padding: 80, textAlign: "center", maxWidth: 600, margin: "0 auto" }}>
              <div style={{ fontSize: 64, marginBottom: 16 }}>🛒</div>
              <h3 className="h3" style={{ margin: 0 }}>Aún no has agregado nada</h3>
              <p className="body" style={{ marginTop: 16, color: "var(--ink-3)" }}>
                Explora nuestro catálogo de equipos y planes Claro.
              </p>
              <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 32, flexWrap: "wrap" }}>
                <a href={window.balUrl("equipos.html")} className="btn btn-brand">Ver equipos</a>
                <a href={window.balUrl("planes.html")} className="btn btn-ghost">Ver planes</a>
              </div>
            </div>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 48 }} className="grid-2">
              <div className="reveal" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                {items.map((it) => (
                  <div key={it.key} style={{
                    background: "#fff", borderRadius: 22, padding: 20,
                    border: "1px solid var(--line)",
                    display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 20, alignItems: "center",
                  }}>
                    <div style={{
                      width: 80, height: 80, background: "var(--paper-2)", borderRadius: 14,
                      display: "flex", justifyContent: "center", alignItems: "center", padding: 6, overflow: "hidden",
                    }}>
                      {it.image ? (
                        <img src={it.image} alt={it.name} referrerPolicy="no-referrer"
                          style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "contain" }} />
                      ) : it.kind === "plan" ? (
                        <div style={{ fontSize: 22, fontWeight: 700, color: "var(--brand)" }}>5G</div>
                      ) : (
                        <window.PhoneMock width={50} body="#1a1a1c" screen="linear-gradient(160deg,#2a2a2c,#0a0a0c)" />
                      )}
                    </div>

                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 16, fontWeight: 700, letterSpacing: "-0.012em" }}>{it.name}</div>
                      {it.variant && <div className="caption" style={{ marginTop: 2 }}>{it.variant}</div>}
                      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 10 }}>
                        <button onClick={() => updateQty(it.key, -1)} aria-label="Disminuir" style={{
                          width: 28, height: 28, borderRadius: 8, border: "1px solid var(--line)",
                          background: "#fff", cursor: "pointer", fontFamily: "inherit",
                        }}>−</button>
                        <span style={{ fontSize: 14, minWidth: 24, textAlign: "center", fontWeight: 600 }}>{it.qty}</span>
                        <button onClick={() => updateQty(it.key, 1)} aria-label="Aumentar" style={{
                          width: 28, height: 28, borderRadius: 8, border: "1px solid var(--line)",
                          background: "#fff", cursor: "pointer", fontFamily: "inherit",
                        }}>+</button>
                        <button onClick={() => removeItem(it.key)} style={{
                          marginLeft: 8, fontSize: 12, color: "var(--ink-3)", background: "none", border: 0,
                          cursor: "pointer", textDecoration: "underline", fontFamily: "inherit",
                        }}>Quitar</button>
                      </div>
                    </div>

                    <div style={{ fontSize: 16, fontWeight: 700, letterSpacing: "-0.015em", color: "var(--brand)", whiteSpace: "nowrap" }}>
                      RD${(it.price * it.qty).toLocaleString()}
                    </div>
                  </div>
                ))}

                <button onClick={() => window.Cart.clear()} style={{
                  alignSelf: "flex-start", marginTop: 8,
                  background: "transparent", border: 0, color: "var(--ink-3)",
                  fontSize: 13, cursor: "pointer", fontFamily: "inherit", textDecoration: "underline",
                }}>Vaciar carrito</button>
              </div>

              <div className="reveal" style={{
                background: "var(--ink)", color: "var(--paper)", borderRadius: 24, padding: 32,
                position: "sticky", top: 100, alignSelf: "start",
              }}>
                <h3 style={{ fontSize: 20, fontWeight: 700, margin: "0 0 24px", color: "var(--paper)" }}>Resumen</h3>

                {[["Subtotal", subtotal], ["ITBIS (18%)", tax]].map(([l, v]) => (
                  <div key={l} style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", fontSize: 14, opacity: 0.85 }}>
                    <span>{l}</span><span>RD${v.toLocaleString()}</span>
                  </div>
                ))}

                <div style={{ height: 1, background: "rgba(251,248,244,0.18)", margin: "12px 0" }} />

                <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 20, fontWeight: 700, letterSpacing: "-0.018em" }}>
                  <span>Total</span>
                  <span style={{ color: "var(--brand-coral)" }}>RD${total.toLocaleString()}</span>
                </div>

                <div style={{ marginTop: 24, paddingTop: 16, borderTop: "1px solid rgba(251,248,244,0.10)" }}>
                  <label className="mini" style={{ color: "rgba(255,255,255,0.6)", display: "block", marginBottom: 8 }}>
                    ¿Enviar a otro WhatsApp?
                  </label>
                  <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)}
                    placeholder={`Por defecto: ${site.whatsapp || "WhatsApp empresa"}`}
                    style={{
                      width: "100%", padding: "10px 14px", borderRadius: 10,
                      background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.14)",
                      color: "#fff", fontFamily: "inherit", fontSize: 13,
                    }} />
                  <label className="mini" style={{ color: "rgba(255,255,255,0.6)", display: "block", marginBottom: 8, marginTop: 14 }}>
                    Nota (opcional)
                  </label>
                  <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={2}
                    placeholder="Dirección de entrega, hora preferida…"
                    style={{
                      width: "100%", padding: "10px 14px", borderRadius: 10,
                      background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.14)",
                      color: "#fff", fontFamily: "inherit", fontSize: 13, resize: "vertical",
                    }} />
                </div>

                <button onClick={checkout} className="btn" style={{
                  background: "#25D366", color: "#fff", width: "100%", justifyContent: "center",
                  marginTop: 20, border: 0, cursor: "pointer", fontFamily: "inherit", fontSize: 15, fontWeight: 600,
                }}>
                  Confirmar por WhatsApp
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style={{ marginLeft: 6 }}>
                    <path d="M20.52 3.48A11.94 11.94 0 0 0 12.04 0C5.46 0 .14 5.32.14 11.91c0 2.1.55 4.15 1.6 5.96L0 24l6.27-1.65a11.9 11.9 0 0 0 5.77 1.47h.01c6.58 0 11.9-5.32 11.9-11.91 0-3.18-1.24-6.17-3.43-8.43z"/>
                  </svg>
                </button>

                <div style={{ marginTop: 16, padding: 14, background: "rgba(255,255,255,0.06)", borderRadius: 12, fontSize: 12.5, color: "rgba(251,248,244,0.78)", lineHeight: 1.5 }}>
                  Al confirmar, abrimos WhatsApp con el detalle del pedido. Coordinas pago y entrega con un asesor real.
                </div>
              </div>
            </div>
          )}
        </div>
      </section>
    </window.PageScaffold>);

}

// Page dispatch.
//
// NOTE: We accept `sobre` as a legacy alias for `nosotros` so a stale browser
// cache (old HTML with window.PAGE = "sobre") still renders the right page
// after the /sobre → /nosotros rename. Without this alias a cached HTML would
// fall through to NotFoundPage and confuse the user.
function NotFoundPage() {
  // Track attempted URL so support can debug if reported
  useEffect(() => {
    if (typeof window === "undefined") return;
    document.title = "Página no encontrada — Baldera Comunicaciones";
    // Telemetry: log the 404 if a tracker is available
    if (window.balTrack) {
      try { window.balTrack("404", { path: location.pathname + location.search }); } catch (e) {}
    }
  }, []);

  const suggestions = [
    { label: "Ver planes",      href: "planes.html",   tag: "Internet, móvil y triple play" },
    { label: "Ver equipos",     href: "equipos.html",  tag: "iPhone, Samsung y más" },
    { label: "Sobre nosotros",  href: "nosotros.html", tag: "25 años conectando RD" },
    { label: "Contacto",        href: "contacto.html", tag: "Habla con un asesor" },
  ];

  return (
    <window.PageScaffold active="">
      <section style={{
        padding: "120px 0 80px",
        position: "relative",
        overflow: "hidden",
        background: `
          radial-gradient(ellipse 70% 50% at 50% 0%, rgba(237,15,68,0.10), transparent 60%),
          var(--paper)
        `,
      }}>
        <window.DotGrid />
        <div className="container" style={{ position: "relative", textAlign: "center" }}>
          {/* Massive 404 — the visual anchor */}
          <div className="reveal" aria-hidden="true" style={{
            fontSize: "clamp(140px, 22vw, 280px)",
            fontWeight: 800,
            letterSpacing: "-0.06em",
            lineHeight: 0.9,
            background: "linear-gradient(180deg, var(--brand) 0%, var(--brand-deep) 60%, var(--ink) 100%)",
            WebkitBackgroundClip: "text",
            backgroundClip: "text",
            WebkitTextFillColor: "transparent",
            fontVariantNumeric: "tabular-nums",
            margin: "0 auto",
            userSelect: "none",
          }}>
            404
          </div>

          <div className="reveal eyebrow" style={{ marginTop: 8, color: "var(--brand)", justifyContent: "center", display: "inline-flex" }}>
            Página no encontrada
          </div>

          <h1 className="h1 reveal" style={{ margin: "16px auto 0", maxWidth: 720 }}>
            Buscaste algo que <span className="italic-display" style={{ color: "var(--brand)" }}>no existe.</span>
          </h1>

          <p className="lead reveal" style={{ marginTop: 20, maxWidth: 560, marginInline: "auto", color: "var(--ink-2)" }}>
            Es posible que la URL haya cambiado o que el enlace esté roto. Mira por dónde seguir:
          </p>

          <div className="reveal" style={{
            marginTop: 36,
            display: "flex", gap: 12, flexWrap: "wrap", justifyContent: "center",
          }}>
            <a href={window.balUrl("index.html")} className="btn btn-brand" style={{ padding: "12px 28px" }}>
              Volver al inicio <window.Icon.Arrow />
            </a>
            <a href={window.balUrl("contacto.html")} className="btn btn-ghost" style={{
              padding: "12px 28px",
              background: "#fff", border: "1px solid var(--line)",
            }}>
              Reportar el problema
            </a>
          </div>
        </div>
      </section>

      {/* Quick links — keep the user on site */}
      <section style={{ background: "var(--paper-2)", paddingTop: 56, paddingBottom: 100 }}>
        <div className="container">
          <div className="reveal" style={{ textAlign: "center", marginBottom: 32 }}>
            <div className="mini" style={{ color: "var(--ink-3)", letterSpacing: "0.14em", textTransform: "uppercase" }}>
              O explora
            </div>
          </div>
          <div className="reveal" style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))",
            gap: 16,
            maxWidth: 920, marginInline: "auto",
          }}>
            {suggestions.map((s) => (
              <a key={s.href} href={window.balUrl(s.href)} style={{
                display: "flex", flexDirection: "column", gap: 6,
                padding: "22px 24px",
                background: "#fff",
                border: "1px solid var(--line)",
                borderRadius: 18,
                color: "var(--ink)",
                transition: "transform 200ms cubic-bezier(0.32,0.72,0,1), box-shadow 200ms, border-color 160ms",
              }}
                onMouseOver={(e) => {
                  e.currentTarget.style.transform = "translateY(-3px)";
                  e.currentTarget.style.boxShadow = "0 14px 32px -14px rgba(20,17,15,0.18)";
                  e.currentTarget.style.borderColor = "rgba(237,15,68,0.22)";
                }}
                onMouseOut={(e) => {
                  e.currentTarget.style.transform = "";
                  e.currentTarget.style.boxShadow = "";
                  e.currentTarget.style.borderColor = "var(--line)";
                }}
              >
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <span style={{ fontSize: 16, fontWeight: 700, letterSpacing: "-0.012em" }}>{s.label}</span>
                  <window.Icon.Arrow style={{ color: "var(--brand)" }} />
                </div>
                <span style={{ fontSize: 13, color: "var(--ink-3)" }}>{s.tag}</span>
              </a>
            ))}
          </div>
        </div>
      </section>
    </window.PageScaffold>
  );
}

window.PAGES = Object.assign({}, window.PAGES, {
  servicios: ServiciosPage,
  tiendas:   TiendasPage,
  nosotros:  SobrePage,
  sobre:     SobrePage,        // legacy alias for cached pages pre-rename
  blog:      BlogPage,
  contacto:  ContactoPage,
  carrito:   CarritoPage,
  notfound:  NotFoundPage,
});

if (!window.__BAL_ROOT) window.__BAL_ROOT = ReactDOM.createRoot(document.getElementById("root"));
window.__BAL_ROOT.render(React.createElement(
  (window.PAGES && window.PAGES[window.PAGE]) || NotFoundPage
));
