// ---------- HERO ----------
// Sin fotografía. Las fotos que tenemos las tomó el proveedor con teléfono:
// sirven para ficha de producto, pero a tamaño hero se les nota la luz plana y
// el fondo sin limpiar. En vez de esquivar eso con un plano de detalle, este
// hero directamente no depende de ninguna imagen — la profundidad la dan los
// degradados y el bisel es SVG, nítido a cualquier tamaño.
const Hero = ({ onShop, onSell }) => {
  return (
    <section className="gmr-hero">
      <div className="gmr-hero-field" />
      <div className="gmr-hero-bezel" aria-hidden="true">
        <svg viewBox="0 0 700 700" fill="none">
          {/* Anillo estriado: 60 muescas con dasharray sobre un círculo, no 60
              elementos. pathLength fija la circunferencia para que el reparto
              no dependa del radio. */}
          <circle cx="350" cy="350" r="300" stroke="rgba(168,97,55,.30)" strokeWidth="30"
                  strokeDasharray="9.4 22" pathLength="1884" />
          <circle cx="350" cy="350" r="322" stroke="rgba(168,97,55,.22)" strokeWidth="1" />
          <circle cx="350" cy="350" r="279" stroke="rgba(168,97,55,.22)" strokeWidth="1" />
          <circle cx="350" cy="350" r="252" stroke="rgba(244,242,239,.10)" strokeWidth="1" />
          <circle cx="350" cy="350" r="176" stroke="rgba(244,242,239,.07)" strokeWidth="1" />
          {/* Manecillas a las 10:10, la hora con la que se fotografía un reloj. */}
          <g stroke="rgba(244,242,239,.16)" strokeLinecap="round">
            <line x1="350" y1="350" x2="252" y2="272" strokeWidth="5" />
            <line x1="350" y1="350" x2="466" y2="268" strokeWidth="4" />
          </g>
          <circle cx="350" cy="350" r="6" fill="rgba(168,97,55,.4)" />
        </svg>
      </div>
      <div className="gmr-hero-grain" />

      <div className="gmr-hero-wrap">
        <div className="gmr-hero-copy">
          <img className="gmr-hero-mark" src="/assets/05_Brytez_Lockup_Beige.svg" alt="Brytez" />
          <div><span className="eyebrow">Miami · By appointment</span></div>
          <h1>
            The new standard<br />
            in luxury <em>timepieces.</em>
          </h1>
          <p className="gmr-hero-lede">
            Pre-owned and unworn Rolex, Patek Philippe and Audemars Piguet — verified,
            quoted straight and delivered by hand. No bidding wars, no anonymous sellers.
          </p>
          <div className="gmr-hero-cta">
            <button className="gmr-btn gmr-btn-light" onClick={onShop}>
              Shop Collection <IconArrow size={16} />
            </button>
            <button className="gmr-btn gmr-btn-outline" onClick={onSell}>
              Sell Your Watch
            </button>
          </div>
          <div className="gmr-hero-meta">
            <span><i /> Verified authentic</span>
            <span><i /> Direct WhatsApp line</span>
          </div>
        </div>
      </div>

      <style>{`
        /* dvh y no vh: en Safari iOS la barra de direcciones hace saltar el layout. */
        .gmr-hero{position:relative;overflow:hidden;isolation:isolate;
          background:var(--green-deep);min-height:min(84dvh,720px);display:flex;align-items:center}

        /* Profundidad sin fotografía: foco de luz cálida arriba a la derecha y
           pozo oscuro abajo a la izquierda. Un verde plano se lee como plantilla. */
        .gmr-hero-field{position:absolute;inset:0;z-index:-3;background:
          radial-gradient(120% 90% at 78% 8%,rgba(168,97,55,.16) 0%,rgba(168,97,55,0) 46%),
          radial-gradient(90% 70% at 68% 22%,#39465C 0%,rgba(57,70,92,0) 62%),
          radial-gradient(140% 120% at 12% 96%,#131620 0%,rgba(19,22,32,0) 58%),
          linear-gradient(165deg,#2A3347 0%,#131620 58%,#131620 100%)}
        /* Grano fino: rompe la planitud digital del degradado. */
        .gmr-hero-grain{position:absolute;inset:0;z-index:-1;pointer-events:none;opacity:.06;
          background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='140' height='140'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3'/></filter><rect width='140' height='140' filter='url(%23n)'/></svg>")}

        .gmr-hero-bezel{position:absolute;z-index:-2;right:-16%;top:50%;translate:0 -50%;
          width:min(78vh,660px);aspect-ratio:1;pointer-events:none;
          animation:gmrBezel 1400ms cubic-bezier(.23,1,.32,1) both}
        .gmr-hero-bezel svg{width:100%;height:100%;display:block}
        @keyframes gmrBezel{from{opacity:0;transform:rotate(-7deg) scale(.965)}
          to{opacity:1;transform:rotate(0) scale(1)}}

        .gmr-hero-wrap{position:relative;width:100%;max-width:1440px;margin:0 auto;
          padding:clamp(52px,7vw,90px) clamp(18px,4vw,44px)}
        .gmr-hero-copy{max-width:640px}
        .gmr-hero-mark{height:auto;width:clamp(130px,14vw,190px);margin-bottom:26px;
          filter:drop-shadow(0 10px 26px rgba(0,0,0,.28))}
        .gmr-hero .eyebrow{color:var(--gold)}
        .gmr-hero h1{font-family:var(--serif);font-weight:500;color:#fff;
          font-size:clamp(46px,6.4vw,92px);line-height:.96;letter-spacing:-.024em;
          margin:14px 0 22px;text-wrap:balance}
        .gmr-hero h1 em{font-style:italic;color:var(--gold)}
        .gmr-hero-lede{font-size:clamp(15px,1.2vw,17.5px);line-height:1.62;
          color:rgba(244,242,239,.82);max-width:46ch;text-wrap:pretty;margin:0}
        .gmr-hero-cta{display:flex;flex-wrap:wrap;gap:12px;margin-top:34px}
        .gmr-hero-meta{display:flex;flex-wrap:wrap;align-items:center;gap:14px 20px;margin-top:42px;
          font-family:var(--mono);font-size:10px;letter-spacing:.15em;text-transform:uppercase;
          color:rgba(244,242,239,.56)}
        .gmr-hero-meta span{display:inline-flex;align-items:center;gap:8px}
        .gmr-hero-meta i{width:5px;height:5px;border-radius:50%;background:var(--gold);flex:none}

        /* Botones propios del hero: los del sitio son verdes y se perderían
           sobre fondo verde. Clases y no estilos en línea porque :active y el
           gate de hover no existen inline. */
        .gmr-btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;
          padding:14px 28px;font-family:var(--sans);font-size:13px;font-weight:500;
          letter-spacing:.16em;text-transform:uppercase;border-radius:2px;
          transition:transform 160ms cubic-bezier(.23,1,.32,1),background-color 200ms ease,
          color 200ms ease,border-color 200ms ease}
        .gmr-btn:active{transform:scale(.97)}
        .gmr-btn:focus-visible{outline:2px solid var(--gold);outline-offset:3px}
        .gmr-btn-light{background:#F4F2EF;color:var(--green-deep)}
        .gmr-btn-outline{border:1px solid rgba(244,242,239,.45);color:#F4F2EF;background:transparent}
        /* Sin este gate, en táctil el hover se queda pegado tras el toque. */
        @media (hover:hover) and (pointer:fine){
          .gmr-btn-light:hover{background:#fff}
          .gmr-btn-outline:hover{border-color:#F4F2EF;background:rgba(244,242,239,.1)}
        }

        /* Entrada escalonada. Nunca desde scale(0): nada aparece de la nada. */
        @keyframes gmrRise{to{opacity:1;transform:none}}
        .gmr-hero-copy>*{opacity:0;transform:translateY(10px);
          animation:gmrRise 620ms cubic-bezier(.23,1,.32,1) forwards}
        .gmr-hero-copy>*:nth-child(1){animation-delay:60ms}
        .gmr-hero-copy>*:nth-child(2){animation-delay:120ms}
        .gmr-hero-copy>*:nth-child(3){animation-delay:180ms}
        .gmr-hero-copy>*:nth-child(4){animation-delay:240ms}
        .gmr-hero-copy>*:nth-child(5){animation-delay:300ms}
        .gmr-hero-copy>*:nth-child(6){animation-delay:360ms}

        @media (max-width:900px){
          .gmr-hero{min-height:auto}
          .gmr-hero-bezel{right:-42%;top:6%;translate:0 0;width:118vw;opacity:.85}
          .gmr-hero-wrap{padding:clamp(44px,9vw,60px) clamp(18px,5vw,28px) clamp(40px,8vw,52px)}
          .gmr-hero h1{font-size:clamp(42px,12vw,60px)}
          .gmr-hero-cta .gmr-btn{flex:1 1 100%}
          /* El botón flotante de WhatsApp vive abajo a la derecha: sin este
             hueco, la última línea de confianza se lee por debajo de él. */
          .gmr-hero-meta{margin-top:32px;padding-right:76px}
        }

        /* Reducir movimiento no es quitar toda la animación: la opacidad ayuda
           a comprender, el desplazamiento no. */
        @media (prefers-reduced-motion:reduce){
          .gmr-hero-copy>*{animation:none;opacity:1;transform:none}
          .gmr-hero-bezel{animation:none}
          .gmr-btn{transition:background-color 200ms ease,color 200ms ease}
          .gmr-btn:active{transform:none}
        }
      `}</style>
    </section>
  );
};

// ---------- TIRA DE INVENTARIO ----------
// Aquí sí caben las fotos del proveedor: a ~240px no se les nota la cámara y
// siguen probando que el stock existe. Lee de WATCHES, que app.jsx reemplaza en
// caliente con el catálogo real, así que no hay piezas fijas que se queden
// obsoletas cuando se venda un reloj. Si el catálogo no carga, no se pinta nada.
const InventoryStrip = ({ onOpen, onViewAll }) => {
  const picks = React.useMemo(() => {
    const seen = new Set();
    const out = [];
    for (const w of WATCHES) {
      if (!(w.image || w.hero_image)) continue;
      const key = `${w.brand}|${(w.model || "").toLowerCase().trim()}`;
      if (seen.has(key)) continue;
      seen.add(key);
      out.push(w);
      if (out.length === 4) break;
    }
    return out;
  }, [WATCHES.length, WATCHES[0] && WATCHES[0].id]);

  if (picks.length < 4) return null;

  return (
    <section className="gmr-strip">
      <div className="gmr-strip-in">
        <div className="gmr-strip-head">
          <div className="gmr-strip-t">Available now</div>
          <button onClick={onViewAll}>View all {WATCHES.length} →</button>
        </div>
        <div className="gmr-strip-row">
          {picks.map((w) => (
            <button key={w.id} className="gmr-strip-item" onClick={() => onOpen(w.id)}>
              <img src={w.image || w.hero_image} loading="lazy" decoding="async"
                   alt={`${w.brand} ${w.model}`} />
              {/* Con la referencia, porque el catálogo trae varias piezas del
                  mismo modelo y sin ella se leen como repetidas. */}
              <span>{[w.model, w.reference].filter(Boolean).join(" ")}</span>
            </button>
          ))}
        </div>
      </div>

      <style>{`
        .gmr-strip{background:var(--paper);border-bottom:1px solid var(--rule);
          padding:clamp(22px,2.6vw,30px) 0 clamp(24px,3vw,34px)}
        .gmr-strip-in{max-width:1440px;margin:0 auto;padding:0 clamp(18px,4vw,44px)}
        .gmr-strip-head{display:flex;justify-content:space-between;align-items:baseline;
          gap:16px;margin-bottom:16px}
        .gmr-strip-t{font-family:var(--mono);font-size:10px;letter-spacing:.18em;
          text-transform:uppercase;color:var(--muted)}
        .gmr-strip-head button{font-family:var(--mono);font-size:10px;letter-spacing:.14em;
          text-transform:uppercase;color:var(--gold-deep);
          border-bottom:1px solid rgba(168,138,78,.4);padding:0 0 2px;
          transition:color 200ms ease,border-color 200ms ease}
        .gmr-strip-row{display:grid;grid-template-columns:repeat(4,1fr);gap:clamp(10px,1.4vw,18px)}
        .gmr-strip-item{position:relative;display:block;padding:0;width:100%;
          border-radius:2px;overflow:hidden;background:var(--paper-2);aspect-ratio:1;
          transition:transform 240ms cubic-bezier(.23,1,.32,1)}
        .gmr-strip-item img{width:100%;height:100%;object-fit:cover;object-position:50% 44%}
        .gmr-strip-item span{position:absolute;left:0;right:0;bottom:0;padding:20px 10px 8px;
          background:linear-gradient(180deg,rgba(31,38,48,0),rgba(31,38,48,.90) 66%);
          font-family:var(--mono);font-size:9px;letter-spacing:.11em;text-transform:uppercase;
          color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:left}
        .gmr-strip-item:focus-visible{outline:2px solid var(--gold);outline-offset:2px}
        @media (hover:hover) and (pointer:fine){
.gmr-strip-head button:hover{color:var(--terracotta);border-color:var(--terracotta)}
.gmr-strip-item:hover{transform:translateY(-3px)}
        }
        @media (max-width:900px){
          /* "View all" pegado al borde derecho cae justo debajo del botón
             flotante de WhatsApp, que lo vuelve intocable. Bajo la fila. */
          .gmr-strip-head{flex-direction:column;align-items:flex-start;gap:8px}
          /* Cuatro tarjetas apiladas serían cuatro pantallas. Carrusel. */
          .gmr-strip-row{display:flex;gap:10px;overflow-x:auto;scroll-snap-type:x mandatory;
            margin:0 clamp(-18px,-5vw,-28px);padding:0 clamp(18px,5vw,28px) 2px;scrollbar-width:none}
          .gmr-strip-row::-webkit-scrollbar{display:none}
          .gmr-strip-item{flex:0 0 40%;scroll-snap-align:start}
        }
        @media (prefers-reduced-motion:reduce){
          .gmr-strip-item{transition:none}
          .gmr-strip-item:hover{transform:none}
        }
      `}</style>
    </section>
  );
};

// ---------- TRUST BAR ----------
const TrustBar = () => {
  const items = [
    { icon: <IconShield size={22} />, label: "Verified Authentic", sub: "Serial & documentation checked on every sale" },
    { icon: <IconTruck size={22} />, label: "Personal Delivery", sub: "Arranged directly with your specialist" },
    { icon: <IconLock size={22} />, label: "Private, Discreet Purchases", sub: "Direct dealer · No public auctions" },
  ];
  return (
    <section style={{ background: "var(--paper)", borderTop: "1px solid var(--rule)", borderBottom: "1px solid var(--rule)" }}>
      <div style={{
        maxWidth: 1440, margin: "0 auto",
        padding: "28px clamp(18px, 4vw, 44px)",
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))",
        gap: 22,
      }}>
        {items.map((it, i) => (
          <div key={i} style={{ display: "flex", gap: 14, alignItems: "flex-start", color: "var(--text)" }}>
            <div style={{ color: "var(--green)", marginTop: 1 }}>{it.icon}</div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, color: "var(--ink)" }}>{it.label}</div>
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>{it.sub}</div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
};

// ---------- FEATURED ----------
const Featured = ({ onOpen, onInquire, onViewAll }) => {
  return (
    <section style={{ padding: "clamp(60px, 8vw, 104px) clamp(18px, 4vw, 44px)" }}>
      <div style={{ maxWidth: 1440, margin: "0 auto" }}>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 18, marginBottom: 44 }}>
          <div>
            <div className="eyebrow" style={{ color: "var(--gold-deep)" }}>New This Week</div>
            <span className="gold-rule" />
            <h2 className="serif" style={{ fontSize: "clamp(30px, 3.4vw, 46px)", lineHeight: 1.1, margin: "6px 0 0", color: "var(--ink)" }}>
              Just listed.
            </h2>
          </div>
          <button
            onClick={onViewAll}
            style={{ fontSize: 13, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink)", borderBottom: "1px solid var(--gold)", paddingBottom: 2, cursor: "pointer" }}
          >
            View full catalogue ({WATCHES.length}) →
          </button>
        </div>

        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))",
          gap: "clamp(20px, 2.2vw, 32px)",
        }}>
          {(() => {
            const seen = new Set();
            const unique = [];
            for (const w of WATCHES) {
              const key = `${w.brand}|${(w.model || "").toLowerCase().trim()}`;
              if (seen.has(key)) continue;
              seen.add(key);
              unique.push(w);
              if (unique.length === 8) break;
            }
            return unique.map((w) => (
              <WatchCard key={w.id} watch={w} onOpen={() => onOpen(w.id)} onInquire={() => onInquire(w)} />
            ));
          })()}
        </div>
      </div>
    </section>
  );
};

const WatchCard = ({ watch, onOpen, onInquire }) => {
  const [hover, setHover] = React.useState(false);
  const [btnHover, setBtnHover] = React.useState(false);
  return (
    <article
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        cursor: "pointer",
        transition: "transform .3s ease",
        transform: hover ? "translateY(-2px)" : "translateY(0)",
      }}
    >
      <div
        onClick={onOpen}
        style={{
          overflow: "hidden",
          position: "relative",
          background: "var(--paper)",
          transition: "box-shadow .3s ease",
          boxShadow: hover ? "0 24px 44px -26px rgba(15,58,43,0.3)" : "0 0 0 rgba(0,0,0,0)",
        }}
      >
        <WatchPlate watch={watch} />
        {watch.tags?.[0] && (
          <div style={{
            position: "absolute", top: 12, left: 12,
            background: hexA("#FFFFFF", 0.9),
            color: "var(--ink)",
            fontSize: 10,
            letterSpacing: "0.16em",
            textTransform: "uppercase",
            padding: "6px 10px",
            fontFamily: "var(--mono)"
          }}>
            {watch.tags[0]}
          </div>
        )}
      </div>
      <div style={{ paddingTop: 18 }}>
        <div style={{ fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)" }}>
          {watch.brand}
        </div>
        <h3 className="serif" style={{ fontSize: 22, margin: "6px 0 6px", color: "var(--ink)", fontWeight: 500, lineHeight: 1.2 }}>
          {watch.model}
        </h3>
        <div style={{ fontSize: 11, color: "var(--muted)", fontFamily: "var(--mono)", letterSpacing: "0.06em" }}>
          {[watch.reference && `Ref. ${watch.reference}`, watch.condition].filter(Boolean).join(" · ")}
        </div>
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--rule)",
        }}>
          <div style={{ fontFamily: "var(--serif)", fontSize: 22, color: "var(--ink)", fontWeight: 500 }}>
            {watch.price_display || "Price on request"}
          </div>
          <button
            onClick={(e) => { e.stopPropagation(); onInquire(); }}
            onMouseEnter={() => setBtnHover(true)}
            onMouseLeave={() => setBtnHover(false)}
            style={{
              fontSize: 11,
              letterSpacing: "0.16em",
              textTransform: "uppercase",
              color: btnHover ? "#fff" : "var(--green)",
              background: btnHover ? "var(--green)" : "transparent",
              border: `1px solid var(--green)`,
              padding: "9px 14px",
              transition: "all .2s ease",
            }}
          >
            Inquire Now
          </button>
        </div>
      </div>
    </article>
  );
};

// ---------- WHY ----------
const Why = ({ onInquire }) => {
  const items = [
    {
      n: "01",
      icon: <IconGem size={26} />,
      title: "Sourced on demand",
      body:
        "Every piece is sourced through an established dealer network the moment you ask for it — we quote only what we can actually secure, at the price we quote.",
    },
    {
      n: "02",
      icon: <IconEye size={26} />,
      title: "Verification first",
      body:
        "Serial and reference numbers are checked against the supplying dealer's records, and documentation is reviewed piece by piece — with photos or live video before you commit.",
    },
    {
      n: "03",
      icon: <IconPackage size={26} />,
      title: "Personal delivery",
      body:
        "Once your purchase is confirmed on WhatsApp, your specialist arranges delivery with you personally — discreet, in person, and around your schedule.",
    },
  ];
  return (
    <section style={{ padding: "clamp(60px, 8vw, 104px) clamp(18px, 4vw, 44px)" }}>
      <div style={{ maxWidth: 1440, margin: "0 auto" }}>
        <div style={{ textAlign: "center", marginBottom: 64 }}>
          <div className="eyebrow" style={{ color: "var(--gold-deep)" }}>The Brytez Process</div>
          <span className="gold-rule" style={{ margin: "14px auto" }} />
          <h2 className="serif" style={{ fontSize: "clamp(30px, 3.4vw, 46px)", margin: "6px 0 14px", color: "var(--ink)", lineHeight: 1.1 }}>
            Why collectors choose Brytez.
          </h2>
          <p style={{ color: "var(--muted)", maxWidth: 560, margin: "0 auto", fontSize: 15, lineHeight: 1.6, textWrap: "pretty" }}>
            Three commitments we make on every timepiece we handle.
          </p>
        </div>

        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))",
          gap: "clamp(24px, 3vw, 48px)",
        }}>
          {items.map((it) => (
            <div key={it.n} style={{ position: "relative", paddingTop: 12 }}>
              <div style={{
                fontFamily: "var(--serif)",
                fontSize: 64,
                color: hexA("#A86137", 0.3),
                lineHeight: 0.9,
                fontWeight: 300,
                fontStyle: "italic",
              }}>
                {it.n}
              </div>
              <div style={{ color: "var(--green)", margin: "8px 0 18px" }}>{it.icon}</div>
              <h3 className="serif" style={{ fontSize: 26, margin: "0 0 10px", color: "var(--ink)", fontWeight: 500 }}>
                {it.title}
              </h3>
              <p style={{ color: "var(--text)", fontSize: 14, lineHeight: 1.65, margin: 0, maxWidth: 380, textWrap: "pretty" }}>
                {it.body}
              </p>
            </div>
          ))}
        </div>

        <div style={{ textAlign: "center", marginTop: 64 }}>
          <GoldButton onClick={onInquire}>Speak with a specialist</GoldButton>
        </div>
      </div>
    </section>
  );
};

// ---------- LANDING ROOT ----------
const LandingPage = ({ onOpenWatch, onInquire, onViewAll, onShopCategory, onSell, onNav, onOpenArticle }) => {
  return (
    <main>
      <Hero onShop={onViewAll} onSell={() => (onSell ? onSell() : onInquire(null))} />
      <InventoryStrip onOpen={onOpenWatch} onViewAll={onViewAll} />
      <TrustBar />
      <div id="featured">
        <Featured onOpen={onOpenWatch} onInquire={onInquire} onViewAll={onViewAll} />
      </div>
      <Collections onShop={onShopCategory} />
      <Why onInquire={() => onInquire(null)} />
      <Heritage onAbout={() => onNav && onNav("about")} />
      <SellSection onInquire={() => onInquire(null)} />
      <Journal onOpenPost={onOpenArticle} onAllArticles={() => onNav && onNav("journal")} />
      <FAQ onInquire={() => onInquire(null)} />
      <Newsletter onInquire={() => onInquire(null)} />
    </main>
  );
};

Object.assign(window, { LandingPage });
