/* global React, Placeholder, Eyebrow, Arr, useUI */

// Hero A — Foto editorial full-bleed con frase ancla en overlay
function HeroA({ setPage }) {
  return (
    <section className="hero-a">
      <Placeholder
        ratio="auto"
        tone="dark"
        label="/ASSETS/HERO-EDITORIAL.JPG"
        corner="◯ FOTO EDITORIAL · MECEDORA EN AMBIENTE"
        ring="◯ HERO"
        fill
      />
      <div className="top-rail">
        <span>DAVA'S · ARTE & DISEÑO</span>
        <span>EDICIÓN MMXXVI · COLOMBIA</span>
      </div>
      <div className="core">
        <h1>
          Tu pieza<br />
          se empieza <span className="you">a tejer</span><br />
          <em>cuando tú</em><br />
          la pides.
        </h1>
        <div className="bottom-rail">
          <p className="lead">
            Muebles tejidos a mano en taller propio.
            Cada pedido enciende la producción — listos en ~15 días, sin bodega y sin atajos.
          </p>
          <div className="ctas">
            <button className="btn bone" onClick={() => setPage("home")}>
              Ver catálogo
              <Arr />
            </button>
            <a className="btn line on-dark" href="https://wa.me/573005260637" target="_blank" rel="noopener">
              WhatsApp directo
            </a>
          </div>
        </div>
      </div>
      <div className="scroll-cue">SCROLL · DESCUBRE</div>
    </section>
  );
}

// Hero B — Producto aislado sobre bone con tipo grande
function HeroB({ setPage, openProduct }) {
  return (
    <section className="hero-b">
      <div className="top-rail">
        <span>PIEZA DEL MES · N°. 047</span>
        <span>HECHA A PEDIDO · 15 DÍAS</span>
      </div>
      <div className="stage">
        <div className="left">
          <div>
            <Eyebrow>Modelo destacado</Eyebrow>
            <h1>
              Mecedoras<br />
              <em>tejidas</em><br />
              a mano.
              <span className="small">— en 8 patrones, sobre teca curada</span>
            </h1>
          </div>
          <div>
            <p className="lead">
              Tu pieza se empieza a tejer cuando tú la pides. Una sola mano por respaldo,
              un solo respaldo por semana — el ritmo del oficio, no el de la fábrica.
            </p>
            <div className="meta-grid">
              <div><div className="k">Desde</div><div className="v">$ 580.000</div></div>
              <div><div className="k">Patrones</div><div className="v">8</div></div>
              <div><div className="k">Producción</div><div className="v">~ 15 d</div></div>
            </div>
            <div className="ctas">
              <button className="btn solid" onClick={() => openProduct({ id: "pavo-real-precolombino", name: "Pavo Real", family: "Mecedora", pattern: "Precolombino", price: "580.000", model: "Pavo Real", wood: "Teca", tone: "dark", variants: ["Lineal", "Precolombino", "Diamante", "Pirámide"] })}>
                Ver esta pieza <Arr />
              </button>
              <button className="btn line">Catálogo completo →</button>
            </div>
          </div>
        </div>
        <div className="product-frame">
          <Placeholder ratio="auto" tone="bone" label="/ASSETS/HERO-PRODUCTO-CUTOUT.PNG" corner="◯ CUTOUT · FONDO BONE" ring="PIEZA" fill />
          <div className="product-tag">N°. 047 / PAVO REAL</div>
          <div className="product-cite">
            <em>Pavo Real</em>
            <span>Patrón · Precolombino</span>
          </div>
        </div>
      </div>
    </section>
  );
}

// Hero C — Mosaico de productos con tipografía dominante
function HeroC({ setPage, openProduct }) {
  const tiles = [
    { cls: "t1", tone: "dark",  name: "Pavo Real",  family: "Mecedora",  label: "/ASSETS/HERO-MOS-01.JPG", id: "pavo-real-hero" },
    { cls: "t2", tone: "bone",  name: "Colibrí",    family: "Silla",     label: "/ASSETS/HERO-MOS-02.JPG", id: "colibri-hero" },
    { cls: "t3", tone: "terra", name: "Sirena",     family: "Mecedora",  label: "/ASSETS/HERO-MOS-03.JPG", id: "sirena-hero" },
    { cls: "t4", tone: "verde", name: "Acapulco",   family: "Silla",     label: "/ASSETS/HERO-MOS-04.JPG", id: "acapulco-hero" },
    { cls: "t5", tone: "paper", name: "Diamante",   family: "Sofá",      label: "/ASSETS/HERO-MOS-05.JPG", id: "diamante-hero" },
  ];
  return (
    <section className="hero-c">
      <div className="top-rail">
        <span>DAVA'S · 212+ PIEZAS EN CATÁLOGO</span>
        <span>VOL. MMXXVI / 04</span>
      </div>
      <div className="head">
        <h1>
          Hechas a<br />
          mano, <em>una</em><br />
          por una.
        </h1>
        <div className="right">
          <Eyebrow>Lo que estamos tejiendo ahora</Eyebrow>
          <p>
            Tu pieza se empieza a tejer cuando tú la pides. Mecedoras, sillas, comedores y sofás
            sobre teca y pino — todo el catálogo a un toque de WhatsApp.
          </p>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            <button className="btn solid" onClick={() => setPage("home")}>Ver catálogo <Arr /></button>
            <button className="btn line">Modelos icónicos</button>
          </div>
        </div>
      </div>
      <div className="grid">
        {tiles.map((t) => (
          <div className={`tile ${t.cls}`} key={t.cls} onClick={() => openProduct({ id: t.id, name: t.name, family: t.family, pattern: "Precolombino", price: "—", tone: t.tone })}>
            <Placeholder ratio="auto" tone={t.tone} label={t.label} corner={t.family} fill />
            <div className="info">
              <h4>{t.name}</h4>
              <span>{t.family} →</span>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// Hero D — Polaroids rotativas con mensaje aspiracional + copy de venta por pieza
// Cada pieza trae: titular grande, palabra destacada, subcopy de apoyo, y la nota manuscrita.
const HERO_POLAROIDS = [
  {
    img: "/assets/hero/comedor_holanda.jpg",
    nombre: "Comedor Holanda",
    mensaje: "“Para una tardecita de chisme con mis amigas ♡”",
    titular: "La mesa donde",
    titularEm: "todo se cuenta.",
    subcopy: "Comedores tejidos a mano para las sobremesas que no se quieren acabar.",
    bg: "#B5532A",
    mensajeColor: "#8a3d1a",
    titularEmColor: "#8a3d1a",
    pinFrom: "#f6d795", pinMid: "#C8901A", pinTo: "#9c6d12",
  },
  {
    img: "/assets/hero/conjunto_balcon.jpg",
    nombre: "Conjunto Balcón",
    mensaje: "“Dos de estas, una mesita, y tenemos cita en el balcón.”",
    titular: "Tu balcón también",
    titularEm: "merece una cita.",
    subcopy: "Conjuntos tejidos a mano que convierten un rincón en tu lugar favorito.",
    bg: "#7E1232",
    mensajeColor: "#7E1232",
    titularEmColor: "#B0184A",
    pinFrom: "#f29bb8", pinMid: "#d8417a", pinTo: "#8f1d4a",
  },
  {
    img: "/assets/hero/colibri_cafe.jpg",
    nombre: "Mecedora Colibrí",
    mensaje: "“La mecedora que se merece mi viejo.”",
    titular: "Un regalo que",
    titularEm: "se mece toda la vida.",
    subcopy: "Mecedoras tejidas a mano sobre madera curada. Hechas para durar generaciones.",
    bg: "#5A4026",
    mensajeColor: "#5a4026",
    titularEmColor: "#a86f3a",
    pinFrom: "#f6d795", pinMid: "#C8901A", pinTo: "#9c6d12",
  },
  {
    img: "/assets/hero/colibri_verde.jpg",
    nombre: "Mecedora Colibrí",
    mensaje: "“Para nuestro spa. Soñemos juntos.”",
    titular: "Tu espacio para",
    titularEm: "respirar.",
    subcopy: "Piezas tejidas a mano que traen calma a cualquier rincón de tu casa.",
    bg: "#2F5347",
    mensajeColor: "#2f5347",
    titularEmColor: "#4a8c72",
    pinFrom: "#e8a96b", pinMid: "#c17a3a", pinTo: "#8a531f",
  },
  {
    img: "/assets/hero/silla_nido.jpg",
    nombre: "Silla Nido",
    mensaje: "“Tú y yo aquí juntos, piénsalo.”",
    titular: "Una pieza que",
    titularEm: "lo dice todo.",
    subcopy: "Diseños exclusivos tejidos a mano que no encontrarás en ninguna otra tienda.",
    bg: "#7E1232",
    mensajeColor: "#7E1232",
    titularEmColor: "#B0184A",
    pinFrom: "#f29bb8", pinMid: "#d8417a", pinTo: "#8f1d4a",
  },
];


function HeroPortadaPolaroid({ setPage }) {
  const [idx, setIdx] = React.useState(0);
  const [fading, setFading] = React.useState(false);
  const [isMobile, setIsMobile] = React.useState(typeof window !== "undefined" && window.innerWidth < 760);
  const p = HERO_POLAROIDS[idx];

  React.useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth < 760);
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  React.useEffect(() => {
    const t = setInterval(() => {
      setFading(true);
      setTimeout(() => {
        setIdx((i) => (i + 1) % HERO_POLAROIDS.length);
        setFading(false);
      }, 420);
    }, 4600);
    return () => clearInterval(t);
  }, []);

  const goTo = (i) => {
    if (i === idx) return;
    setFading(true);
    setTimeout(() => { setIdx(i); setFading(false); }, 420);
  };

  // ===== LAYOUT MOBILE — apilado en una columna =====
  if (isMobile) {
    return (
      <section style={{
        position: "relative", width: "100%", overflow: "hidden",
        minHeight: "100svh", boxSizing: "border-box",
        fontFamily: "'Inter', sans-serif", paddingBottom: 40,
        background: `linear-gradient(180deg, #F7F2EA 0%, #F7F2EA 22%, ${p.bg} 78%)`,
        transition: "background 0.6s ease",
      }}>
        <style>{`
          @keyframes davas-rock-m { 0% { transform: rotate(-1.5deg); } 100% { transform: rotate(1.5deg); } }
          .davas-hand { font-family: 'Caveat', 'Segoe Script', 'Bradley Hand', cursive; }
        `}</style>

        {/* Polaroid arriba, centrada */}
        <div style={{ position: "relative", zIndex: 2, display: "flex", justifyContent: "center", padding: "48px 24px 8px" }}>
          <div style={{ width: "min(290px, 76vw)", background: "#fff", padding: "13px 13px 0", boxShadow: "0 22px 44px rgba(40,12,22,.28)", transform: "rotate(-2deg)", opacity: fading ? 0 : 1, transition: "opacity 0.4s ease" }}>
            <div style={{ aspectRatio: "1/1", background: "#fafafa", display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden" }}>
              <img src={p.img} alt={p.nombre} style={{ width: "100%", height: "100%", objectFit: "cover", animation: "davas-rock-m 3.8s ease-in-out infinite alternate" }} />
            </div>
            <div style={{ minHeight: 92, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 4, textAlign: "center", padding: "12px 10px 16px" }}>
              <span className="davas-hand" style={{ fontWeight: 700, fontSize: 27, lineHeight: 1, color: "#2a2722" }}>{p.nombre}</span>
              <span className="davas-hand" style={{ fontWeight: 600, fontSize: 18, lineHeight: 1.18, color: p.mensajeColor }}>{p.mensaje}</span>
            </div>
            <div style={{ position: "absolute", top: -11, left: "50%", transform: "translateX(-50%)", width: 24, height: 24, borderRadius: "50%", background: `radial-gradient(circle at 34% 30%, ${p.pinFrom}, ${p.pinMid} 58%, ${p.pinTo})`, boxShadow: "0 4px 9px rgba(40,28,10,.45)" }} />
          </div>
        </div>

        {/* Texto abajo, sobre la zona de color */}
        <div style={{ position: "relative", zIndex: 2, padding: "16px 26px 0", color: "#fff", textAlign: "center" }}>

          <h1 style={{
            fontFamily: "var(--f-display, 'Fraunces', serif)", fontWeight: 400, lineHeight: 1.05,
            letterSpacing: "-0.5px", fontSize: "clamp(26px, 7vw, 36px)", margin: 0,
            opacity: fading ? 0 : 1, transition: "opacity 0.42s ease",
          }}>
            {p.titular} <span style={{ fontStyle: "italic", fontWeight: 300, color: "rgba(255,255,255,.95)" }}>{p.titularEm}</span>
          </h1>
          <p style={{ fontSize: 13.5, lineHeight: 1.5, color: "rgba(255,255,255,.82)", margin: "14px auto 0", maxWidth: 300, opacity: fading ? 0 : 1, transition: "opacity 0.42s ease" }}>
            {p.subcopy}
          </p>
          <div style={{ marginTop: 22, display: "flex", justifyContent: "center" }}>
            <a style={{ width: "100%", maxWidth: 260, textAlign: "center", background: "#fff", color: "#1b1813", fontSize: 14, fontWeight: 600, letterSpacing: ".3px", padding: "14px 0", borderRadius: 40, cursor: "pointer" }} onClick={() => setPage("catalog")}>
              Ver el catálogo →
            </a>
          </div>
          {/* dots */}
          <div style={{ display: "flex", justifyContent: "center", gap: 7, marginTop: 22 }}>
            {HERO_POLAROIDS.map((_, i) => (
              <button key={i} onClick={() => goTo(i)} aria-label={`Pieza ${i + 1}`} style={{ width: i === idx ? 16 : 6, height: 6, borderRadius: 3, border: "none", cursor: "pointer", background: i === idx ? "#fff" : "rgba(255,255,255,.42)", transition: "width .3s, background .3s", padding: 0 }} />
            ))}
          </div>
        </div>
      </section>
    );
  }

  // ===== LAYOUT DESKTOP =====
  return (
    <section
      style={{
        position: "relative",
        width: "100%",
        height: "min(900px, 100vh)",
        minHeight: 620,
        background: "#F7F2EA",
        overflow: "hidden",
        isolation: "isolate",
        fontFamily: "'Inter', sans-serif",
      }}
    >
      <style>{`
        @keyframes davas-rock { 0% { transform: rotate(-2deg); } 100% { transform: rotate(2deg); } }
        @keyframes davas-weave-hero { from { background-position: 0 0, 0 0; } to { background-position: 160px 0, -160px 0; } }
        @keyframes davas-spin-hero { from { transform: rotate(0); } to { transform: rotate(360deg); } }
        @keyframes davas-marquee-hero { from { transform: translateX(0); } to { transform: translateX(-50%); } }
        .davas-cta-a { transition: background .25s; }
        .davas-cta-a:hover { background: #1b1813; }
      `}</style>

      {/* Campo de color derecho + trama tejida */}
      <div style={{
        position: "absolute", top: 0, right: 0, width: "43%", height: "100%",
        background: p.bg, transition: "background 0.6s ease", zIndex: 1,
      }} />
      <div className="weave" style={{
        position: "absolute", top: 0, right: 0, width: "43%", height: "100%", zIndex: 1,
        backgroundImage:
          "repeating-linear-gradient(76deg, rgba(255,214,228,.12) 0 2px, transparent 2px 14px)," +
          "repeating-linear-gradient(-76deg, rgba(255,214,228,.08) 0 2px, transparent 2px 14px)",
        animation: "davas-weave-hero 18s linear infinite",
      }} />
      {/* Franja vertical "Hecho en Colombia" */}
      <div style={{
        position: "absolute", top: "16%", right: "3%", writingMode: "vertical-rl",
        fontSize: 11, letterSpacing: 4, textTransform: "uppercase",
        color: "rgba(247,242,234,.6)", zIndex: 2,
      }}>
        Est. Artesanal — Hecho en Colombia
      </div>

      {/* Anillo girando con texto circular */}
      <svg viewBox="0 0 300 300" style={{
        position: "absolute", right: "30%", top: "13%", width: 120, height: 120, zIndex: 2,
        animation: "davas-spin-hero 40s linear infinite",
      }}>
        <defs><path id="davas-circ" d="M150,150 m-120,0 a120,120 0 1,1 240,0 a120,120 0 1,1 -240,0" /></defs>
        <text style={{ fontFamily: "'Inter'", fontSize: 13, letterSpacing: 6, fill: "rgba(247,242,234,.55)", textTransform: "uppercase" }}>
          <textPath href="#davas-circ">PIEZA ÚNICA · TEJIDO A MANO · </textPath>
        </text>
        <circle cx="150" cy="150" r="5" fill="#C8901A" />
      </svg>

      {/* Polaroid rotativa */}
      <div
        style={{
          position: "absolute", top: "20%", left: "50%", width: "min(512px, 38vw)",
          background: "#fff", padding: "20px 20px 0", boxShadow: "0 32px 66px rgba(40,12,22,.38)",
          transform: "translateX(-12%) rotate(-2.5deg)", zIndex: 3,
          opacity: fading ? 0 : 1,
          transition: "opacity 0.4s ease",
        }}
      >
        <div style={{ height: "min(332px, 26vw)", background: "#fafafa", display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden" }}>
          <img src={p.img} alt={p.nombre} className="rock" style={{ width: "100%", height: "100%", objectFit: "cover", transformOrigin: "50% 90%", animation: "davas-rock 3.8s ease-in-out infinite alternate" }} />
        </div>
        <div style={{ minHeight: 150, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 9, textAlign: "center", padding: "16px 14px 22px" }}>
          <span style={{ fontFamily: "'Caveat', 'Segoe Script', cursive", fontWeight: 700, fontSize: 38, lineHeight: 1, color: "#2a2722", whiteSpace: "nowrap" }}>{p.nombre}</span>
          <span style={{ fontFamily: "'Caveat', 'Segoe Script', cursive", fontWeight: 600, fontSize: 24, lineHeight: 1.2, color: p.mensajeColor, maxWidth: 420 }}>{p.mensaje}</span>
        </div>
        <div style={{
          position: "absolute", top: -15, left: "50%", transform: "translateX(-50%)",
          width: 30, height: 30, borderRadius: "50%",
          background: `radial-gradient(circle at 34% 30%, ${p.pinFrom}, ${p.pinMid} 58%, ${p.pinTo})`,
          boxShadow: "0 5px 11px rgba(40,28,10,.45)",
        }} />
      </div>

      {/* Bloque editorial — titular + subcopy + CTAs, todo junto y rotativo */}
      <div style={{ position: "absolute", left: "5%", top: "50%", transform: "translateY(-50%)", width: "min(560px, 44vw)", zIndex: 4 }}>

        <h1
          style={{
            fontFamily: "var(--f-serif, 'Fraunces', serif)", fontWeight: 400, color: "#1b1813",
            lineHeight: 0.98, letterSpacing: "-1.5px", fontSize: "clamp(34px, 4.6vw, 64px)", margin: 0,
            opacity: fading ? 0 : 1, transform: fading ? "translateY(8px)" : "translateY(0)",
            transition: "opacity 0.42s ease, transform 0.42s ease",
          }}
        >
          {p.titular}<br/>
          <span style={{ fontStyle: "italic", fontWeight: 300, color: p.titularEmColor }}>{p.titularEm}</span>
        </h1>
        <p style={{
          fontFamily: "'Inter'", fontSize: 16, lineHeight: 1.6, color: "#6b6356", maxWidth: 380, margin: "18px 0 0 0",
          opacity: fading ? 0 : 1, transition: "opacity 0.42s ease",
        }}>
          {p.subcopy}
        </p>
        <div style={{ display: "flex", alignItems: "center", gap: 18, marginTop: 30, flexWrap: "wrap" }}>
          <a className="davas-cta-a" style={{ display: "inline-flex", alignItems: "center", gap: 10, background: "#1b1813", color: "#F7F2EA", fontSize: 14, fontWeight: 500, letterSpacing: ".3px", padding: "16px 30px", borderRadius: 40, cursor: "pointer" }} onClick={() => setPage("catalog")}>
            Ver el catálogo
            <span style={{ fontSize: 16 }}>→</span>
          </a>
          <a style={{ display: "inline-flex", alignItems: "center", gap: 8, color: "#1b1813", fontSize: 14, fontWeight: 500, cursor: "pointer" }} href="https://wa.me/573005260637" target="_blank" rel="noopener">
            <span style={{ width: 30, height: 30, borderRadius: "50%", border: "1.5px solid #1b1813", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 13 }}>♥</span>
            Hablar con el taller
          </a>
        </div>
      </div>

      {/* Marquee inferior */}
      <div style={{ position: "absolute", bottom: 0, left: 0, width: "57%", height: 52, borderTop: "1px solid #e2d8c4", overflow: "hidden", display: "flex", alignItems: "center", zIndex: 4, background: "#F7F2EA" }}>
        <div style={{ display: "flex", whiteSpace: "nowrap", width: "max-content", animation: "davas-marquee-hero 28s linear infinite" }}>
          {[0, 1].map((k) => (
            <span key={k} style={{ fontFamily: "'Fraunces'", fontStyle: "italic", fontSize: 17, color: "#1b1813" }}>
              Diseño a medida&nbsp;&nbsp;·&nbsp;&nbsp;
              <span style={{ color: "#C8901A", fontStyle: "normal", letterSpacing: 1 }}>Tejido a mano en Colombia</span>
              &nbsp;&nbsp;·&nbsp;&nbsp;Pieza única&nbsp;&nbsp;·&nbsp;&nbsp;
              <span style={{ color: "#B0184A" }}>Patrón Precolombino</span>
              &nbsp;&nbsp;·&nbsp;&nbsp;
            </span>
          ))}
        </div>
      </div>

      {/* Dots de navegación entre piezas */}
      <div style={{ position: "absolute", bottom: 18, right: "3%", display: "flex", gap: 8, zIndex: 5 }}>
        {HERO_POLAROIDS.map((_, i) => (
          <button
            key={i}
            onClick={() => goTo(i)}
            aria-label={`Ver pieza ${i + 1}`}
            style={{
              width: i === idx ? 18 : 6, height: 6, borderRadius: 3, border: "none", cursor: "pointer",
              background: i === idx ? "#F7F2EA" : "rgba(247,242,234,.4)",
              transition: "width 0.3s ease, background 0.3s ease", padding: 0,
            }}
          />
        ))}
      </div>
    </section>
  );
}



// ===== HeroD — Editorial 2026, ahora el HERO real del home =====
// B · Editorial 2026 — stories full-screen, loop, formato 9:16
// layout "split" → copy arriba (con aire) + info abajo · "bottom" → todo abajo
// Este array es el RESPALDO — si el admin (admin.php → Hero) ya configuró
// las 5 escenas, se usa window.HERO_EDITORIAL en su lugar (inyectado por
// index.php desde hero-editorial.json, ya resuelto contra el catálogo real).
const EDITORIAL_DEFAULT = [
  {
    nombre: "Colibrí",  cat: "mecedoras", slug: "colibri-precolombino",
    img:    "/story_colibri.jpg",  pos: "50% 82%", layout: "split",
    lugar:  "En la terraza, al sol de la mañana",
    copy:   "El primer café del día\nsabe mejor aquí.",
    precio: "desde $400.000",
  },
  {
    nombre: "Nido",     cat: "mecedoras", slug: "mecedora-nido",
    img:    "/story_luna.jpg",     pos: "50% 70%", layout: "split",
    lugar:  "En la sala que todos recuerdan",
    copy:   "Lo primero que escogiste\npensando solo en ti.",
    precio: "desde $650.000",
  },
  {
    nombre: "Sirena",   cat: "mecedoras", slug: "sirena-lineal-con-refuerzo-2",
    img:    "/story_sirena.jpg",   pos: "50% 76%", layout: "split",
    lugar:  "Entre las plantas, donde el tiempo se detiene",
    copy:   "Afuera, la selva.\nAdentro, tú y la calma.",
    precio: "desde $380.000",
  },
  {
    nombre: "Pavo Real Plus", cat: "combos", slug: "pavo-real-plus-4",
    img:    "/story_conjunto.jpg", pos: "50% 70%", layout: "split",
    lugar:  "En el patio, al caer la tarde",
    copy:   "La tarde se alarga\ncuando hay dónde estar.",
    precio: "$1.050.000",
  },
  {
    nombre: "París",    cat: "sillas-bar", slug: "paris-precolombino-especial",
    img:    "/story_barparis.jpg", pos: "50% 42%", layout: "bottom",
    lugar:  "Para tu bar, tu café, tu restaurante",
    copy:   "El asiento que tus\nclientes recordarán.",
    precio: "desde $400.000 · mayorista",
  },
];
const EDITORIAL = (window.HERO_EDITORIAL && window.HERO_EDITORIAL.length) ? window.HERO_EDITORIAL : EDITORIAL_DEFAULT;

function HeroD({ setPage }) {
  const isMob = typeof window !== "undefined" && window.innerWidth < 760;
  const cat   = window.CATALOGO || [];
  const DUR   = 6800;

  const SLIDES = EDITORIAL.map(e => {
    // Buscar por slug primero (más preciso), luego nombre+cat, luego solo nombre
    const prod = (e.slug ? cat.find(p => p.slug === e.slug && p.foto) : null)
              || cat.find(p => p.nombre === e.nombre && p.categoria === e.cat && p.foto)
              || cat.find(p => p.nombre === e.nombre && p.foto)
              || cat.find(p => p.categoria === e.cat && p.foto);
    // precio: del EDITORIAL (ya corregido), no del catálogo para evitar confusiones
    // url: construida directo de cat+slug (confirmada por Alex, funciona sí o sí,
    // sin depender de window.__davasRoute que ha venido fallando)
    return { ...e, id: prod?.id, label: e.nombre, url: `/${e.cat}/${e.slug}` };
  });

  const N = SLIDES.length;
  const TOTAL = N + 1; // +1 página de bienvenida/cierre
  const [active, setActive] = React.useState(0);
  const [phase, setPhase]   = React.useState("in");
  const [paused, setPaused] = React.useState(false);
  const timer = React.useRef(null);
  const touchX = React.useRef(null);

  const isWelcome = active === N;

  const go = (to) => {
    setPhase("out");
    setTimeout(() => { setActive((to + TOTAL) % TOTAL); setPhase("in"); }, 400);
  };

  React.useEffect(() => {
    if (paused) return;
    // bienvenida dura un poco más antes de reiniciar el loop
    const d = isWelcome ? DUR + 1400 : DUR;
    timer.current = setTimeout(() => go(active + 1), d);
    return () => clearTimeout(timer.current);
  }, [active, paused]);

  const jump = (i) => { clearTimeout(timer.current); if (i !== active) go(i); };
  const next = () => { clearTimeout(timer.current); go(active + 1); };
  const prev = () => { clearTimeout(timer.current); go(active - 1); };

  const onTouchStart = (e) => { touchX.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchX.current == null) return;
    const dx = e.changedTouches[0].clientX - touchX.current;
    if (Math.abs(dx) > 45) (dx < 0 ? next : prev)();
    touchX.current = null;
  };

  const slide = SLIDES[active] || SLIDES[0];
  const goCatalog = () => window.__davasRoute?.openCatalog();
  const animClass = phase === "in" ? "ed-in" : "ed-out";
  const isBottom = !isWelcome && slide.layout === "bottom";

  // Este hero ES la zona oscura del home: mientras el scroll siga dentro de
  // su alto real, el header debe ir en blanco. Al salir (Oficio, ya en
  // crema), el header pasa solo a texto oscuro — sin esto dependería de un
  // valor por defecto aproximado.
  const sectionRef = React.useRef(null);
  React.useEffect(() => {
    const el = sectionRef.current;
    if (!el) return;
    const update = () => document.documentElement.style.setProperty("--dark-zone-h", el.offsetHeight + "px");
    update();
    const ro = new ResizeObserver(update);
    ro.observe(el);
    window.addEventListener("resize", update);
    return () => { ro.disconnect(); window.removeEventListener("resize", update); };
  }, []);

  return (
    <section
      ref={sectionRef}
      onTouchStart={onTouchStart}
      onTouchEnd={onTouchEnd}
      onMouseEnter={() => !isMob && setPaused(true)}
      onMouseLeave={() => !isMob && setPaused(false)}
      style={{ position:"relative", height: isMob ? "100svh" : "100vh", minHeight: isMob ? 560 : 620, maxHeight: isMob ? 880 : 1000, overflow:"hidden", background:"#0e0a08", display:"block" }}>
      <style>{`
        @keyframes ed-kb   { from{transform:scale(1.0)} to{transform:scale(1.07)} }
        @keyframes ed-up   { from{opacity:0;transform:translateY(22px)} to{opacity:1;transform:translateY(0)} }
        @keyframes ed-fade { from{opacity:0} to{opacity:1} }
        @keyframes ed-bar  { from{width:0%} to{width:100%} }

        .ed-photo { position:absolute; inset:0; z-index:0; }
        .ed-photo img { width:100%; height:100%; object-fit:cover; display:block; animation: ed-kb ${DUR}ms linear both; }
        .ed-photo.ed-in  { animation: ed-fade .6s ease both; }
        .ed-photo.ed-out { opacity:0; transition: opacity .4s ease; }
        .ed-photo.ed-out img { animation: none; }

        .ed-veil { position:absolute; inset:0; z-index:1; pointer-events:none; }
        .ed-veil.split  { background: linear-gradient(180deg, rgba(8,5,4,.78) 0%, rgba(8,5,4,.40) 24%, rgba(8,5,4,.04) 42%, rgba(8,5,4,0) 54%, rgba(8,5,4,.12) 66%, rgba(8,5,4,.5) 82%, rgba(8,5,4,.86) 100%); }
        .ed-veil.bottom { background: linear-gradient(180deg, rgba(8,5,4,.5) 0%, rgba(8,5,4,.08) 16%, rgba(8,5,4,0) 36%, rgba(8,5,4,0) 46%, rgba(8,5,4,.5) 70%, rgba(8,5,4,.92) 100%); }
        .ed-veil.welcome{ background: radial-gradient(120% 90% at 50% 35%, rgba(42,29,22,.4) 0%, rgba(8,5,4,.6) 70%); }

        .ed-in .ed-a1 { animation: ed-up .6s cubic-bezier(.2,.7,.2,1) .12s both; }
        .ed-in .ed-a2 { animation: ed-up .6s cubic-bezier(.2,.7,.2,1) .24s both; }
        .ed-in .ed-a3 { animation: ed-up .6s cubic-bezier(.2,.7,.2,1) .36s both; }
        .ed-in .ed-a4 { animation: ed-up .6s cubic-bezier(.2,.7,.2,1) .48s both; }
        .ed-out .ed-a1,.ed-out .ed-a2,.ed-out .ed-a3,.ed-out .ed-a4 { opacity:0; transition:opacity .28s; }

        .ed-arrow { position:absolute; top:50%; transform:translateY(-50%); z-index:10; opacity:0; transition:opacity .35s, background .25s, border-color .25s; }
        section:hover .ed-arrow { opacity:.65; }
        .ed-arrow:hover { opacity:1 !important; }
        .ed-arrow {
          width:44px; height:44px; border-radius:50%; border:1.5px solid rgba(247,242,234,.38);
          background:rgba(8,5,4,.35); backdrop-filter:blur(8px); -webkit-backdrop-filter:blur(8px);
          color:#F7F2EA; font-size:22px; cursor:pointer; display:flex; align-items:center; justify-content:center;
          transition:background .25s, border-color .25s; user-select:none; -webkit-user-select:none; }
        .ed-arrow:hover { background:rgba(8,5,4,.6); border-color:rgba(247,242,234,.7); }
        @media(max-width:759px){
          .ed-arrow { width:40px; height:40px; font-size:18px; opacity:.9; top:55%; }
          .ed-arrow.left  { left:12px; }
          .ed-arrow.right { right:12px; }
        }
      `}</style>

      {/* Foto / fondo */}
      <div className={`ed-photo ${animClass}`} key={active}>
        {isWelcome
          ? <div style={{ width:"100%", height:"100%", background:"radial-gradient(120% 90% at 50% 30%, #2a1d16 0%, #0e0a08 78%)" }} />
          : <img src={isMob ? (slide.imgMobile || slide.img) : slide.img} alt={slide.label} style={{ objectPosition: isMob ? slide.pos : (slide.posDesktop || slide.pos) }} />
        }
      </div>
      <div className={`ed-veil ${isWelcome ? "welcome" : slide.layout}`} />
      {/* Flechas */}
      {/* Tap zones (mobile: invisible, desktop: subtle arrow on hover) */}
      <div style={{ position:"absolute", top:0, left:0, bottom:0, width:"28%", zIndex:6, cursor:"pointer" }}
        onClick={prev}
        onTouchEnd={(e)=>{ e.stopPropagation(); e.preventDefault(); prev(); }} />
      <div style={{ position:"absolute", top:0, right:0, bottom:0, width:"28%", zIndex:6, cursor:"pointer" }}
        onClick={next}
        onTouchEnd={(e)=>{ e.stopPropagation(); e.preventDefault(); next(); }} />
      {!isMob && <>
        <div className="ed-arrow left" style={{ left:20 }} onClick={prev}>‹</div>
        <div className="ed-arrow right" style={{ right:20 }} onClick={next}>›</div>
      </>}

      {isWelcome ? (
        /* Página de cierre / bienvenida */
        <div className={animClass} style={{ position:"absolute", inset:0, zIndex:10, display:"flex", flexDirection:"column", justifyContent:"center", padding: isMob ? "0 28px" : "0 56px" , pointerEvents:"none" }}>
          <div style={{ maxWidth:760 }}>
            <div className="ed-a1" style={{ fontSize:10, letterSpacing:"0.3em", textTransform:"uppercase", color:"#E2B25C", marginBottom:18 }}>Bienvenido a DAVA'S</div>
            <h2 className="ed-a2" style={{ fontFamily:"var(--f-display,'Fraunces',serif)", fontWeight:400, fontSize: isMob?"clamp(32px,9vw,44px)":"clamp(42px,4.6vw,72px)", lineHeight:1.04, letterSpacing:"-1px", color:"#F7F2EA", margin:"0 0 20px" }}>
              Todo esto se teje a mano.<br/><span style={{ fontStyle:"italic", color:"#E2B25C" }}>Y ahora, para ti.</span>
            </h2>
            <p className="ed-a3" style={{ fontSize: isMob?15:17, lineHeight:1.6, color:"rgba(247,242,234,.72)", maxWidth:440, margin:"0 0 30px" }}>
              Más de 300 piezas nacidas en nuestro taller de Bogotá. Encuentra la que va a vivir contigo.
            </p>
            <button className="ed-a4" onClick={goCatalog}
              style={{ display:"inline-flex", alignItems:"center", gap:10, background:"#C8901A", color:"#1b1813", fontSize: isMob?15:16, fontWeight:700, padding: isMob?"15px 30px":"18px 38px", borderRadius:2, border:"none", cursor:"pointer", transition:"background .25s", pointerEvents:"auto" }}
              onMouseEnter={e=>e.currentTarget.style.background="#b07c15"}
              onMouseLeave={e=>e.currentTarget.style.background="#C8901A"}>
              Entrar al catálogo →
            </button>
          </div>
        </div>
      ) : isBottom ? (
        /* Layout "bottom" — todo el texto agrupado abajo (París) */
        <div className={animClass} style={{ position:"absolute", left:0, right:0, bottom:0, zIndex:10, padding: isMob ? "0 24px 40px" : "0 56px 62px" , pointerEvents:"none" }}>
          <div style={{ maxWidth:680 }}>
            <div className="ed-a1" style={{ display:"flex", alignItems:"center", gap:10, marginBottom:14 }}>
              <span style={{ width:24, height:1, background:"#E2B25C", flexShrink:0 }} />
              <span style={{ fontSize: isMob?11:12, letterSpacing:"0.16em", textTransform:"uppercase", color:"rgba(247,242,234,.92)", fontWeight:500, textShadow:"0 1px 14px rgba(0,0,0,.7)" }}>{slide.lugar}</span>
            </div>
            <h2 className="ed-a2" style={{ fontFamily:"var(--f-display,'Fraunces',serif)", fontWeight:400, fontSize: isMob?"clamp(22px,6vw,27px)":"clamp(42px,4.4vw,60px)", lineHeight:1.1, letterSpacing:"-1.1px", color:"#F7F2EA", whiteSpace:"pre-line", margin:"0 0 20px", textShadow:"0 2px 40px rgba(0,0,0,.65)" }}>{slide.copy}</h2>
            <div className="ed-a3" style={{ display:"flex", alignItems:"baseline", gap:12, flexWrap:"wrap", marginBottom:20 }}>
              <span style={{ fontSize: isMob?13:14, letterSpacing:"0.22em", textTransform:"uppercase", color:"#fff", fontWeight:600, textShadow:"0 1px 14px rgba(0,0,0,.7)" }}>{slide.label}</span>
              <span style={{ width:4, height:4, borderRadius:"50%", background:"#E2B25C" }} />
              <span style={{ fontSize: isMob?14:16, color:"#E2B25C", fontWeight:500, textShadow:"0 1px 14px rgba(0,0,0,.7)" }}>{slide.precio}</span>
            </div>
            <a href={slide.url} className="ed-a4"
              style={{ display:"inline-flex", alignItems:"center", gap:10, background:"rgba(247,242,234,.96)", color:"#1b1813", fontSize: isMob?14:15, fontWeight:700, padding: isMob?"14px 26px":"16px 32px", borderRadius:2, border:"none", cursor:"pointer", boxShadow:"0 8px 32px rgba(0,0,0,.35)", transition:"background .25s, transform .2s", textDecoration:"none", pointerEvents:"auto" }}
              onMouseEnter={e=>{e.currentTarget.style.background="#fff"; e.currentTarget.style.transform="translateX(4px)";}}
              onMouseLeave={e=>{e.currentTarget.style.background="rgba(247,242,234,.96)"; e.currentTarget.style.transform="translateX(0)";}}>
              Ver esta pieza →
            </a>
          </div>
        </div>
      ) : (
        /* Layout "split" — copy arriba con AIRE, info+cta abajo */
        <>
          {/* ARRIBA: copy con respiro (no pegado al borde) */}
          <div className={animClass} style={{ position:"absolute", top: isMob ? "calc(var(--hdr-h, 84px) + 34px)" : "calc(var(--hdr-h, 100px) + 44px)", left:0, right:0, zIndex:10, padding: isMob ? "0 24px" : "0 72px" , pointerEvents:"none" }}>
            <div style={{ maxWidth:720 }}>
              <div className="ed-a1" style={{ display:"flex", alignItems:"center", gap:10, marginBottom:18 }}>
                <span style={{ width:24, height:1, background:"#E2B25C", flexShrink:0 }} />
                <span style={{ fontSize: isMob?11:12, letterSpacing:"0.16em", textTransform:"uppercase", color:"rgba(247,242,234,.92)", fontWeight:500, textShadow:"0 1px 14px rgba(0,0,0,.7)" }}>{slide.lugar}</span>
              </div>
              <h2 className="ed-a2" style={{ fontFamily:"var(--f-display,'Fraunces',serif)", fontWeight:400, fontSize: isMob?"clamp(28px,7.5vw,40px)":"clamp(42px,4.4vw,62px)", lineHeight:1.04, letterSpacing:"-1.2px", color:"#F7F2EA", whiteSpace:"pre-line", margin:0, textShadow:"0 2px 40px rgba(0,0,0,.65)" }}>{slide.copy}</h2>
            </div>
          </div>
          {/* ABAJO: nombre + precio + CTA */}
          <div className={animClass} style={{ position:"absolute", bottom:0, left:0, right:0, zIndex:10, padding: isMob ? "0 24px 40px" : "0 56px 62px" , pointerEvents:"none" }}>
            <div className="ed-a3" style={{ display:"flex", alignItems:"baseline", gap:12, flexWrap:"wrap", marginBottom:18 }}>
              <span style={{ fontSize: isMob?13:14, letterSpacing:"0.22em", textTransform:"uppercase", color:"#fff", fontWeight:600, textShadow:"0 1px 14px rgba(0,0,0,.7)" }}>{slide.label}</span>
              <span style={{ width:4, height:4, borderRadius:"50%", background:"#E2B25C" }} />
              <span style={{ fontSize: isMob?14:16, color:"#E2B25C", fontWeight:500, textShadow:"0 1px 14px rgba(0,0,0,.7)" }}>{slide.precio}</span>
            </div>
            <a href={slide.url} className="ed-a4"
              style={{ display:"inline-flex", alignItems:"center", gap:10, background:"rgba(247,242,234,.96)", color:"#1b1813", fontSize: isMob?14:15, fontWeight:700, padding: isMob?"14px 26px":"16px 32px", borderRadius:2, border:"none", cursor:"pointer", boxShadow:"0 8px 32px rgba(0,0,0,.35)", transition:"background .25s, transform .2s", textDecoration:"none", pointerEvents:"auto" }}
              onMouseEnter={e=>{e.currentTarget.style.background="#fff"; e.currentTarget.style.transform="translateX(4px)";}}
              onMouseLeave={e=>{e.currentTarget.style.background="rgba(247,242,234,.96)"; e.currentTarget.style.transform="translateX(0)";}}>
              Ver esta pieza →
            </a>
          </div>
        </>
      )}
    </section>
  );
}


function Hero({ variant, setPage, openProduct }) {
  if (variant === "B") return <HeroB setPage={setPage} openProduct={openProduct} />;
  if (variant === "C") return <HeroC setPage={setPage} openProduct={openProduct} />;
  if (variant === "D") return <HeroD setPage={setPage} />;
  return <HeroA setPage={setPage} />;
}

window.Hero = Hero;
window.HeroPortadaPolaroid = HeroPortadaPolaroid;
