/* global React, ReactDOM */
const { useState, useEffect, useRef, useCallback } = React;

/* ─────────────────────────────────────────────────────────
   TWEAKS DEFAULTS
   ────────────────────────────────────────────────────── */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#0b3d6e", "#062a4d", "#4a90d9"],
  "heroTone": "Editorial",
  "heroLayout": "Centered",
  "fontStack": "System",
  "showGrain": true,
  "darkSection": "Navy"
} /*EDITMODE-END*/;

const PALETTES = [
["#0b3d6e", "#062a4d", "#4a90d9"], // signature navy
["#1a4d80", "#0a2540", "#7fb3e8"], // mid royal
["#0d2b4d", "#020e1f", "#3d7dc4"] // deep ink
];

const FONT_STACKS = {
  System: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Helvetica Neue", system-ui, sans-serif',
  Manrope: '"Manrope", -apple-system, system-ui, sans-serif',
  Geist: '"Geist", "Geist Sans", -apple-system, system-ui, sans-serif'
};

/* ─────────────────────────────────────────────────────────
   SVG: GLASSES (geometric, not complicated)
   ────────────────────────────────────────────────────── */
function Glasses({ frame = "#0b3d6e", lens = "#cfd9e6", lensOpacity = 0.55, style = "round", w = 720, accent = "#4a90d9" }) {
  // style: 'round' | 'rect' | 'aviator' | 'wayfarer' | 'cat'
  const shapes = {
    round: { rx: 70, ry: 64, gap: 28 },
    rect: { rx: 86, ry: 50, gap: 22, corner: 14 },
    aviator: { rx: 84, ry: 64, gap: 26, drop: 12 },
    wayfarer: { rx: 80, ry: 56, gap: 24, corner: 22 },
    cat: { rx: 80, ry: 56, gap: 26, corner: 10, lift: 14 }
  };
  const s = shapes[style] || shapes.round;
  const cx1 = 220,cx2 = 500,cy = 220;

  return (
    <svg viewBox="0 0 720 340" width={w} style={{ maxWidth: "100%", height: "auto", display: "block" }}>
      <defs>
        <linearGradient id={`lensGrad-${style}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={accent} stopOpacity={lensOpacity * 0.9} />
          <stop offset="55%" stopColor={lens} stopOpacity={lensOpacity * 0.55} />
          <stop offset="100%" stopColor="#ffffff" stopOpacity={lensOpacity * 0.2} />
        </linearGradient>
        <linearGradient id={`frameGrad-${style}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={frame} />
          <stop offset="100%" stopColor={frame} stopOpacity="0.78" />
        </linearGradient>
        <filter id="softShadow" x="-20%" y="-20%" width="140%" height="180%">
          <feGaussianBlur in="SourceAlpha" stdDeviation="6" />
          <feOffset dx="0" dy="14" result="off" />
          <feComponentTransfer><feFuncA type="linear" slope="0.18" /></feComponentTransfer>
          <feMerge><feMergeNode /><feMergeNode in="SourceGraphic" /></feMerge>
        </filter>
      </defs>

      <g filter="url(#softShadow)">
        {/* bridge */}
        {style === "aviator" ?
        <path d={`M ${cx1 + s.rx - 4} ${cy - 8} Q 360 ${cy - 32} ${cx2 - s.rx + 4} ${cy - 8}`} stroke={`url(#frameGrad-${style})`} strokeWidth="7" fill="none" strokeLinecap="round" /> :

        <path d={`M ${cx1 + s.rx - 4} ${cy} L ${cx2 - s.rx + 4} ${cy}`} stroke={`url(#frameGrad-${style})`} strokeWidth="9" fill="none" strokeLinecap="round" />
        }

        {/* temples (arms) */}
        <path d={`M 24 ${cy - 4} Q 80 ${cy - 24} ${cx1 - s.rx + 8} ${cy - 6}`} stroke={`url(#frameGrad-${style})`} strokeWidth="8" fill="none" strokeLinecap="round" />
        <path d={`M ${cx2 + s.rx - 8} ${cy - 6} Q 640 ${cy - 24} 696 ${cy - 4}`} stroke={`url(#frameGrad-${style})`} strokeWidth="8" fill="none" strokeLinecap="round" />

        {/* left lens */}
        {style === "rect" || style === "wayfarer" || style === "cat" ?
        <rect
          x={cx1 - s.rx} y={cy - s.ry - (s.lift || 0)} rx={s.corner} ry={s.corner}
          width={s.rx * 2} height={s.ry * 2}
          fill={`url(#lensGrad-${style})`}
          stroke={`url(#frameGrad-${style})`} strokeWidth="10"
          transform={style === "cat" ? `rotate(-4 ${cx1} ${cy})` : ""} /> :


        <ellipse cx={cx1} cy={cy + (s.drop || 0) / 2} rx={s.rx} ry={s.ry}
        fill={`url(#lensGrad-${style})`}
        stroke={`url(#frameGrad-${style})`} strokeWidth="10" />
        }

        {/* right lens */}
        {style === "rect" || style === "wayfarer" || style === "cat" ?
        <rect
          x={cx2 - s.rx} y={cy - s.ry - (s.lift || 0)} rx={s.corner} ry={s.corner}
          width={s.rx * 2} height={s.ry * 2}
          fill={`url(#lensGrad-${style})`}
          stroke={`url(#frameGrad-${style})`} strokeWidth="10"
          transform={style === "cat" ? `rotate(4 ${cx2} ${cy})` : ""} /> :


        <ellipse cx={cx2} cy={cy + (s.drop || 0) / 2} rx={s.rx} ry={s.ry}
        fill={`url(#lensGrad-${style})`}
        stroke={`url(#frameGrad-${style})`} strokeWidth="10" />
        }

        {/* lens highlights */}
        <ellipse cx={cx1 - s.rx * 0.45} cy={cy - s.ry * 0.55} rx={s.rx * 0.28} ry={s.ry * 0.18} fill="#ffffff" opacity="0.55" />
        <ellipse cx={cx2 - s.rx * 0.45} cy={cy - s.ry * 0.55} rx={s.rx * 0.28} ry={s.ry * 0.18} fill="#ffffff" opacity="0.55" />
      </g>
    </svg>);

}

/* ─────────────────────────────────────────────────────────
   LOGO MARK (uses the supplied image)
   ────────────────────────────────────────────────────── */
function LogoMark({ size = 28 }) {
  return (
    <div style={{ ...{
        width: size, height: size, borderRadius: "50%",
        background: `url('assets/logo.jpg') center/cover no-repeat`,
        flexShrink: 0
      }, width: "80px", height: "80px" }} />);

}

/* ─────────────────────────────────────────────────────────
   NAV
   ────────────────────────────────────────────────────── */
function Nav({ accent }) {
  const [scrolled, setScrolled] = useState(false);
  const [cart, setCart] = useState(0);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="nav-inner">
        <a className="brand" href="#top">
          <span className="brand-text">
            <span className="brand-name brand-name-logo">
              <LogoMark size={30} />ptidis
            </span>
            <span className="brand-sub">Distribuciones Opticas</span>
          </span>
        </a>
        <div className="nav-links">
          <a href="#marca-polar">Polar</a>
          <a href="#marca-west">West</a>
          <a href="#marca-amarcord">Amarcord</a>
          <a href="#contacto">Contacto</a>
        </div>
        <div className="nav-actions">
          <button className="icon-btn" aria-label="Buscar">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" />
            </svg>
          </button>
          <button className="icon-btn cart" aria-label="Carrito" onClick={() => setCart((c) => c + 1)}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M3 6h2l2 12h12l2-9H7" /><circle cx="9" cy="21" r="1.2" /><circle cx="18" cy="21" r="1.2" />
            </svg>
            {cart > 0 && <span className="cart-badge">{cart}</span>}
          </button>
        </div>
      </div>
    </nav>);

}

/* ─────────────────────────────────────────────────────────
   HERO
   ────────────────────────────────────────────────────── */
const HERO_COPY = {
  Editorial: {
    eyebrow: "Distribuidor oficial en Colombia",
    title: "Visión,",
    title2: "perfeccionada.",
    sub: "Polar, West y Amarcord, tres casas italianas con décadas de oficio. Cuatro formas de mirar el mundo.",
    cta1: "Descubrir Polar",
    cta2: "Pruébalas virtualmente"
  },
  Direct: {
    eyebrow: "Asesoría directa por WhatsApp",
    title: "Gafas que",
    title2: "te miran de vuelta.",
    sub: "Polarizadas SUPER POLARIZED®, acetato italiano, materiales biobasados. Configura tu par en menos de dos minutos.",
    cta1: "Configurar las mías",
    cta2: "Ver colección"
  },
  Poetic: {
    eyebrow: "Belluno · Cadore · Made in Italy",
    title: "Italian style,",
    title2: "designed for the world.",
    sub: "Treinta años de Polar. Setenta y cinco años de West. Una sola obsesión: que las olvides en cuanto te las pongas.",
    cta1: "Conocer la historia",
    cta2: "Reservar prueba"
  }
};

/* ── SoundToggle: floating button to unmute the hero video ── */
function SoundToggle() {
  const [muted, setMuted] = useState(true);
  const toggle = () => {
    const v = window.__heroVideo;
    if (!v) return;
    v.muted = !v.muted;
    if (!v.muted) {
      v.volume = 0.8;
      v.play().catch(() => {});
    }
    setMuted(v.muted);
  };
  return (
    <button className={`sound-toggle ${muted ? "muted" : "on"}`} onClick={toggle}
    aria-label={muted ? "Activar sonido" : "Silenciar"}>
      {muted ?
      <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M11 5 6 9H3v6h3l5 4z" />
          <line x1="22" y1="9" x2="16" y2="15" />
          <line x1="16" y1="9" x2="22" y2="15" />
        </svg> :

      <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M11 5 6 9H3v6h3l5 4z" />
          <path d="M15.5 8.5a5 5 0 0 1 0 7" />
          <path d="M18 6a8 8 0 0 1 0 12" />
        </svg>
      }
      <span className="sound-toggle-label">{muted ? "Activar sonido" : "Sonido"}</span>
    </button>);

}

function Hero({ tone, layout, accent, onTryOn }) {
  const c = HERO_COPY[tone] || HERO_COPY.Editorial;
  const isSplit = layout === "Split";
  const { ParallaxStage, HUDOverlay, CountUp, MagneticBtn } = window;

  return (
    <section className={`hero ${isSplit ? "split" : "centered"}`} id="top">
      <div className="hero-bg-glow" style={{ background: `radial-gradient(60% 50% at 50% 30%, ${accent}22, transparent 70%)` }} />
      <div className="hero-inner">
        <div className="eyebrow">{c.eyebrow}</div>
        <h1 className="hero-title">
          <span className="reveal">{c.title}</span><br />
          <span className="reveal italic">{c.title2}</span>
        </h1>
        <p className="hero-sub reveal">{c.sub}</p>
        <div className="hero-cta reveal">
          {MagneticBtn ?
          <MagneticBtn className="btn btn-primary" onClick={() => document.getElementById("marca-polar")?.scrollIntoView({ behavior: "smooth" })}>
              {c.cta1} <span aria-hidden>→</span>
            </MagneticBtn> :

          <a className="btn btn-primary" href="#marca-polar">{c.cta1} <span aria-hidden>→</span></a>
          }
        </div>
        <div className="hero-brands reveal">
          <span>Polar</span>
          <span className="hero-brands-dot" />
          <span>West</span>
          <span className="hero-brands-dot" />
          <span>Amarcord</span>
        </div>
        <div className="hero-product reveal-up">
          <div className="hero-stage hero-stage-video">
            <video
              ref={(el) => { if (el) { el.muted = true; el.volume = 0; } }}
              className="hero-video"
              src="assets/hero-polar.mp4"
              autoPlay
              muted
              loop
              playsInline
              preload="auto"
              aria-label="Campaña Polar Sunglasses" />
            
            <div className="hero-video-tint" aria-hidden />
            <div className="hero-video-corner tl" />
            <div className="hero-video-corner tr" />
            <div className="hero-video-corner bl" />
            <div className="hero-video-corner br" />
          </div>
          <div className="hero-meta">
            <div><span className="meta-num">{CountUp ? <CountUp to={4} /> : "4"}</span><span className="meta-lbl">Marcas curadas</span></div>
            <div><span className="meta-num">100%</span><span className="meta-lbl">Originales europeos</span></div>
            <div><span className="meta-num">72 h</span><span className="meta-lbl">Envío a tu ciudad</span></div>
            <div><span className="meta-num">{CountUp ? <CountUp to={12} suffix=" m" /> : "12 m"}</span><span className="meta-lbl">Garantía fábrica</span></div>
          </div>
        </div>
      </div>
      <a className="scroll-cue" href="#historia" aria-label="Continuar">
        <span />
      </a>
    </section>);

}

/* ─────────────────────────────────────────────────────────
   PRODUCT FEATURE (split detail)
   ────────────────────────────────────────────────────── */
function ProductDetail({ accent }) {
  const [colorIdx, setColorIdx] = useState(0);
  const colors = [
  { name: "Marino", hex: "#0b3d6e" },
  { name: "Ónix", hex: "#1a1a1a" },
  { name: "Carey", hex: "#7a4a26" },
  { name: "Cristal", hex: "#b8c7d8" },
  { name: "Cobre", hex: "#b66a3d" }];

  return (
    <section className="product" id="producto">
      <div className="product-inner">
        <div className="product-visual">
          <div className="product-bg" />
          <div className="product-tag">Modelo destacado</div>
          <Glasses style="round" frame={colors[colorIdx].hex} accent={accent} w={620} />
          <div className="product-rotate">
            <button aria-label="Rotar izquierda">‹</button>
            <span>360°</span>
            <button aria-label="Rotar derecha">›</button>
          </div>
        </div>
        <div className="product-info">
          <div className="eyebrow muted">Polar · Belluno, Italia</div>
          <h2 className="display-2">Polar 3033.</h2>
          <p className="lede">
            La aviator polarizada que abrió mercado en 1993. Montura TR90 termoplástico ligero,
            lentes <strong>SUPER POLARIZED®</strong> categoría 3, clip magnético graduable opcional.
            Treinta años y cien mercados después, sigue siendo nuestra más vendida.
          </p>
          <div className="price-row">
            <div className="price">€295</div>
            <div className="price-meta">o desde €24,58/mes · sin intereses</div>
          </div>

          <div className="opt">
            <div className="opt-label">Color de montura · <strong>{colors[colorIdx].name}</strong></div>
            <div className="swatches">
              {colors.map((col, i) =>
              <button key={col.name} className={`swatch ${i === colorIdx ? "on" : ""}`}
              style={{ background: col.hex }} onClick={() => setColorIdx(i)} aria-label={col.name} />
              )}
            </div>
          </div>

          <div className="spec-grid">
            <div><span>Material</span><strong>TR90 termoplástico</strong></div>
            <div><span>Lente</span><strong>SUPER POLARIZED®</strong></div>
            <div><span>Calibre</span><strong>49 · 18 · 145</strong></div>
            <div><span>Origen</span><strong>Belluno, Italia</strong></div>
          </div>

          <div className="product-cta">
            <button className="btn btn-primary">Añadir al carrito</button>
            <button className="btn btn-text">Reservar prueba en casa →</button>
          </div>
        </div>
      </div>
    </section>);

}

/* ─────────────────────────────────────────────────────────
   HERITAGE — three brand origin stories with image slots
   ────────────────────────────────────────────────────── */
const BRANDS = [
{
  id: "polar",
  name: "Polar",
  eyebrow: "Belluno · 1993 · Italia",
  year: "1993",
  tagline: "Italian style, designed for the world.",
  paragraphs: [
  "Nacida en el corazón del distrito óptico italiano, en Belluno, Polar lleva más de tres décadas reescribiendo lo que significa una gafa polarizada. Es hoy la mayor marca italiana independiente de gafas de sol con lentes polarizadas, monturas ópticas y clip-on.",
  "Su tecnología propia SUPER POLARIZED® combina filtros de alta densidad con monturas TR90 — un termoplástico ligero, flexible y casi irrompible — para dar a cada par la misma sensación: que pesan menos de lo que deberían."],

  facts: [
  { k: "Fundada", v: "1993" },
  { k: "Origen", v: "Belluno, Italia" },
  { k: "Distribución", v: "+100 mercados" },
  { k: "Especialidad", v: "Super Polarized® · Clip magnético" }]

},
{
  id: "west",
  name: "West",
  eyebrow: "Cadore · 1950 · IOVES Spa",
  year: "1950",
  tagline: "Hechas en Italia. Hechas con tiempo.",
  paragraphs: [
  "West nace dentro de IOVES Spa, una de las fábricas históricas de Cadore — la región de los Dolomitas donde se fabrican algunas de las mejores gafas del mundo desde principios del siglo XX. Tres generaciones trabajando el acetato y el nylon.",
  "La colección West es la respuesta italiana al diseño contemporáneo: formas simples, líneas modernas, y la firma técnica de la casa — su clip magnético con lente polarizada que convierte unas graduadas en gafas de sol en un gesto."],

  facts: [
  { k: "Fundada", v: "1950" },
  { k: "Origen", v: "Cadore, Dolomitas" },
  { k: "Materiales", v: "Acetato · Nylon ligero" },
  { k: "Firma", v: "Clip magnético polarizado" }]

},
{
  id: "amarcord",
  name: "Amarcord",
  eyebrow: "Cadore · IOVES Spa · Solo mujer",
  year: "1973",
  tagline: "Yo recuerdo. También en italiano.",
  paragraphs: [
  "«Amarcord» significa «yo recuerdo» en el dialecto de Romagna. Es también la película con la que Federico Fellini ganó el Oscar a Mejor Película Extranjera en 1975 — una postal nostálgica de la Italia que ya no existe. La colección toma ese mismo espíritu.",
  "Pensada exclusivamente para mujer, Amarcord reinterpreta formas icónicas con paletas contemporáneas y excentricidades de color. Acetato Mazzucchelli y acero inoxidable, hechos en la misma fábrica de Cadore que produce West. Elegancia con un guiño."],

  facts: [
  { k: "Origen", v: "Cadore, Italia" },
  { k: "Fabricante", v: "IOVES Spa (1950)" },
  { k: "Materiales", v: "Acetato · Acero inoxidable" },
  { k: "Línea", v: "Exclusiva mujer" }]

}];


function Heritage({ palette }) {
  return (
    <section className="heritage" id="historia">
      <div className="heritage-intro">
        <div className="eyebrow muted">Las marcas</div>
        <h2 className="display-2">Tres casas italianas.<br />Una marca propia.</h2>
        <p className="lede">
          Traímos Polar, West y Amarcord directo de Italia — tres fábricas históricas que dominan su oficio.
        </p>
      </div>

      {BRANDS.map((b, idx) => {
        const hasImage = b.id !== "eko";
        return (
          <article key={b.id} className={`brand-block ${idx % 2 === 1 ? "flip" : ""} ${hasImage ? "" : "no-visual"}`} id={`marca-${b.id}`}>
          {hasImage &&
            <div className="brand-visual">
            <div className="brand-aspect">
              <img src={`assets/brand-photo-${b.id}.webp`} alt={`Foto de la marca ${b.name}`} className="brand-photo-img"/>
            </div>
            <div className="brand-year">{b.year}</div>
          </div>
            }

          <div className="brand-content">
            <div className="eyebrow">{b.eyebrow}</div>
            <h3 className="brand-name">{b.name}.</h3>
            <p className="brand-tagline">{b.tagline}</p>
            {b.paragraphs.map((p, i) =>
              <p key={i} className="brand-para">{p}</p>
              )}

            <div className="brand-facts">
              {b.facts.map((f) =>
                <div key={f.k}>
                  <span className="fact-k">{f.k}</span>
                  <strong className="fact-v">{f.v}</strong>
                </div>
                )}
            </div>
          </div>
        </article>);

      })}
    </section>);

}

/* ─────────────────────────────────────────────────────────
   COLLECTION GRID
   ────────────────────────────────────────────────────── */
function Collection({ accent }) {
  // Six empty slots — user will drop product photos here once available.
  const items = [
  { slot: "polar-01", cat: "Polar" },
  { slot: "polar-02", cat: "Polar" },
  { slot: "west-01", cat: "West" },
  { slot: "west-02", cat: "West" },
  { slot: "amarcord-01", cat: "Amarcord" },
  { slot: "amarcord-02", cat: "Amarcord" },
  { slot: "eko-01", cat: "Eko" },
  { slot: "eko-02", cat: "Eko" }];

  const [filter, setFilter] = useState("Todas");
  const cats = ["Todas", "Polar", "West", "Amarcord", "Eko"];
  const filtered = filter === "Todas" ? items : items.filter((i) => i.cat === filter);

  return (
    <section className="collection" id="modelos">
      <div className="collection-inner">
        <div className="collection-head">
          <div>
            <div className="eyebrow muted">Modelos en tienda</div>
            <h2 className="display-2">Los modelos.<br />Pronto, los tuyos aquí.</h2>
          </div>
          <div className="filter-pills">
            {cats.map((c) =>
            <button key={c} className={`pill ${filter === c ? "on" : ""}`} onClick={() => setFilter(c)}>{c}</button>
            )}
          </div>
        </div>

        <div className="grid">
          {filtered.map((it) =>
          <div key={it.slot} className="card">
              <div className="card-stage">
                <span className="card-tag">{it.cat}</span>
                <div className="card-aspect">
                  <image-slot
                  id={`model-${it.slot}`}
                  shape="rect"
                  radius="14"
                  placeholder={`Sube foto del modelo · ${it.cat}`}
                  style={{ width: "100%", height: "100%", background: "transparent" }}>
                </image-slot>
                </div>
              </div>
              <div className="card-body">
                <div className="card-cat">Línea {it.cat}</div>
                <div className="card-name">Próximamente</div>
                <div className="card-price">{it.cat === "Eko" ? "$200.000" : "$350.000"}</div>
              </div>
            </div>
          )}
        </div>

        <p className="collection-note">
          Estamos preparando la primera campaña de fotos. Mientras tanto, escríbenos para ver el catálogo completo.
        </p>
      </div>
    </section>);

}

/* ─────────────────────────────────────────────────────────
   EYE EXAM CTA
   ────────────────────────────────────────────────────── */
/* ────────────────────────────────────────────────────────
   ONLINE CTA · Colombia
   ──────────────────────────────────────────────────── */
function ExamCTA() {
  return (
    <section className="cta" id="contacto">
      <div className="cta-inner">
        <div className="cta-text">
          <div className="eyebrow muted">100% online · 100% Colombia</div>
          <h2 className="display-2">Sin tienda física.<br />Por eso podemos.</h2>
          <p className="lede">
            Trabajamos solo online para que las italianas originales sean accesibles
            en todo el país. Te asesoramos por WhatsApp, te envíamos rápido y aceptamos cambios sin pregunta.
          </p>
          <div className="cta-buttons">
            <a className="btn btn-primary" href="https://wa.me/573187157478" target="_blank" rel="noreferrer">
              <svg className="wa-svg" viewBox="0 0 24 24" width="16" height="16" aria-hidden>
                <path fill="currentColor" d="M12 2a10 10 0 0 0-8.7 14.9L2 22l5.2-1.3A10 10 0 1 0 12 2Zm5.4 14.2c-.2.6-1.2 1.2-1.7 1.3-.5.1-1 .1-1.7-.1l-1.5-.5c-2.6-1-4.3-3.6-4.4-3.7-.1-.1-1-1.3-1-2.6 0-1.2.6-1.8.8-2.1.2-.2.5-.3.7-.3h.5c.2 0 .4 0 .6.5l.8 2c.1.2.1.4 0 .6l-.3.4-.4.4c-.1.2-.3.3-.1.6.2.3.8 1.4 1.8 2.3 1.3 1.1 2.4 1.5 2.7 1.6.3.1.5.1.7-.1l.8-.9c.2-.2.4-.2.7-.1l1.9.9c.3.2.5.2.6.4 0 .2 0 1-.2 1.5Z" />
              </svg>
              Escríbenos por WhatsApp
            </a>
            <button className="btn btn-text">Cómo elegir tu montura →</button>
          </div>
        </div>
        <div className="cta-cities">
          {[
          { k: "Atención por WhatsApp", v: "Lunes a viernes, respuesta rápida" },
          { k: "Asesoría personalizada", v: "Te ayudamos a elegir tu montura" },
          { k: "Cambios sin costo", v: "30 días para devolver o cambiar" },
          { k: "Garantía oficial", v: "12 meses por defecto de fábrica" }].
          map((s) =>
          <div className="city-row" key={s.k}>
              <span className="city-name">{s.k}</span>
              <span className="city-dot" />
              <span className="city-spots">{s.v}</span>
            </div>
          )}
        </div>
      </div>
    </section>);

}

/* ─────────────────────────────────────────────────────────
   FOOTER
   ────────────────────────────────────────────────────── */
function Footer() {
  const cols = [
  { title: "Marcas", links: ["Polar", "West", "Amarcord", "Comparar marcas"] },
  { title: "Servicio", links: ["WhatsApp", "Asesoría virtual", "Envíos", "Devoluciones", "Cambios"] },
  { title: "Compañía", links: ["Sobre Optidis", "Nuestras marcas", "Sostenibilidad", "Blog", "Trabaja con nosotros"] },
  { title: "Ayuda", links: ["Contacto", "FAQ", "Política de cambios", "Términos", "Privacidad"] }];

  return (
    <footer className="ft">
      <div className="ft-inner">
        <div className="ft-top">
          <a className="brand brand-lg" href="#top">
            <LogoMark size={48} />
            <span className="brand-text">
              <span className="brand-name">Optidis</span>
              <span className="brand-sub">Distribuciones Opticas</span>
            </span>
          </a>
          <div className="ft-news">
            <div>Únete a la lista. Novedades, envíos y eventos en Colombia.</div>
            <form onSubmit={(e) => e.preventDefault()}>
              <input type="email" placeholder="tu@email.com" />
              <button>Suscribirme →</button>
            </form>
          </div>
        </div>
        <div className="ft-cols">
          {cols.map((c) =>
          <div key={c.title}>
              <h4>{c.title}</h4>
              <ul>{c.links.map((l) => <li key={l}><a href="#0">{l}</a></li>)}</ul>
            </div>
          )}
        </div>
        <div className="ft-bottom">
          <span>© 2026 Optidis Colombia · Bogotá, Colombia</span>
          <span className="ft-mini">Distribuidor oficial de Polar, West y Amarcord en Colombia.</span>
        </div>
      </div>
    </footer>);

}

/* ─────────────────────────────────────────────────────────
   APP
   ────────────────────────────────────────────────────── */
function App() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const palette = t.palette || TWEAK_DEFAULTS.palette;
  const accent = palette[2];
  const [tryOn, setTryOn] = useState(false);

  // CSS variable injection
  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty("--navy", palette[0]);
    r.style.setProperty("--navy-deep", palette[1]);
    r.style.setProperty("--accent", palette[2]);
    r.style.setProperty("--font", FONT_STACKS[t.fontStack] || FONT_STACKS.System);
    r.style.setProperty("--grain", t.showGrain ? "1" : "0");
  }, [t.palette, t.fontStack, t.showGrain]);

  // Reveal-on-scroll
  useEffect(() => {
    const els = () => document.querySelectorAll(".reveal, .reveal-up, .tech-card, .card");
    // Fallback: immediately reveal anything already in viewport (covers iframe / SSR / IO race)
    const revealVisible = () => {
      els().forEach((el) => {
        const r = el.getBoundingClientRect();
        if (r.top < window.innerHeight * 0.92) el.classList.add("in");
      });
    };
    requestAnimationFrame(revealVisible);
    const t1 = setTimeout(revealVisible, 100);
    const t2 = setTimeout(revealVisible, 500);

    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {if (e.isIntersecting) e.target.classList.add("in");});
    }, { threshold: 0.08 });
    els().forEach((el) => io.observe(el));
    return () => {io.disconnect();clearTimeout(t1);clearTimeout(t2);};
  }, [t.heroTone, t.heroLayout]);

  const { TweaksPanel, TweakSection, TweakColor, TweakRadio, TweakToggle, TweakSelect } = window;

  return (
    <>
      <Nav accent={accent} />
      <Hero tone={t.heroTone} layout={t.heroLayout} accent={accent} onTryOn={() => setTryOn(true)} />
      {window.TryOnModal && <window.TryOnModal open={tryOn} onClose={() => setTryOn(false)} accent={accent} />}
      <Heritage palette={palette} />
      <ExamCTA />
      <Footer />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Paleta" />
        <TweakColor label="Azules" value={t.palette} options={PALETTES}
        onChange={(v) => setTweak("palette", v)} />
        <TweakSection label="Hero" />
        <TweakRadio label="Tono" value={t.heroTone}
        options={["Editorial", "Direct", "Poetic"]}
        onChange={(v) => setTweak("heroTone", v)} />
        <TweakRadio label="Layout" value={t.heroLayout}
        options={["Centered", "Split"]}
        onChange={(v) => setTweak("heroLayout", v)} />
        <TweakSection label="Tipografía" />
        <TweakSelect label="Stack" value={t.fontStack}
        options={["System", "Manrope", "Geist"]}
        onChange={(v) => setTweak("fontStack", v)} />
        <TweakSection label="Textura" />
        <TweakToggle label="Grano sutil" value={t.showGrain}
        onChange={(v) => setTweak("showGrain", v)} />
      </TweaksPanel>
    </>);

}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);