/* ============================================================
   ADORN — Lookbook: signature shoppable gallery
   Grid (2-col mobile / 3–4-col desktop) → full-screen look
   viewer with tappable hotspot pins → mini product cards
   linking to the PDP.
   ============================================================ */

function MiniProductCard({ product, x, y, onView }) {
  /* flip the card to stay inside the image bounds (tighter on phones) */
  const narrow = typeof window !== "undefined" && window.innerWidth < 720;
  const right = x > (narrow ? 45 : 55), below = y > 62;
  return (
    <div className={"lbv-mini" + (right ? " flip-x" : "") + (below ? " flip-y" : "")}
      style={{ left: x + "%", top: y + "%" }} onClick={(e) => e.stopPropagation()}>
      <div className="lbv-mini-media"><Ph label={product.label} ratio="square" /></div>
      <div className="lbv-mini-body">
        <span className="lbv-mini-cat">{product.sub || product.cat}</span>
        <span className="lbv-mini-name serif">{product.name}</span>
        <Price ngn={product.price} className="lbv-mini-price" />
        <button className="lbv-mini-cta" onClick={onView}>View piece <Icon name="arrow" size={13} /></button>
      </div>
    </div>
  );
}

function LookViewer({ look, onClose, onPrev, onNext, index, total, onNav }) {
  const [active, setActive] = useState(null); // hotspot index
  const products = look.hotspots.map((h) => ({ ...h, product: RB.byId(h.id) })).filter((h) => h.product);

  useEffect(() => { setActive(null); }, [look.id]);
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") onPrev();
      if (e.key === "ArrowRight") onNext();
    };
    window.addEventListener("keydown", onKey);
    document.body.classList.add("no-scroll");
    return () => { window.removeEventListener("keydown", onKey); document.body.classList.remove("no-scroll"); };
  }, [onClose, onPrev, onNext]);

  const goPDP = (id) => { onClose(); onNav("product", { id }); };

  return (
    <div className="lbv" role="dialog" aria-label={"Look: " + look.title} onClick={onClose}>
      <div className="lbv-top" onClick={(e) => e.stopPropagation()}>
        <div className="lbv-title">
          <span className="mono">{look.season}</span>
          <span className="serif">{look.title}</span>
        </div>
        <span className="lbv-counter mono">{String(index + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}</span>
        <button className="lbv-close ic-btn" onClick={onClose} aria-label="Close"><Icon name="close" size={22} /></button>
      </div>

      <div className="lbv-stage" onClick={(e) => e.stopPropagation()}>
        <button className="lbv-arrow prev" onClick={onPrev} aria-label="Previous look"><Icon name="chevron" size={22} style={{ transform: "rotate(180deg)" }} /></button>
        <figure className="lbv-figure" onClick={() => setActive(null)}>
          <Ph label={look.label} ratio="tall" className="lbv-img" />
          {products.map((h, i) => (
            <button key={i} className={"lbv-pin" + (active === i ? " on" : "")}
              style={{ left: h.x + "%", top: h.y + "%" }}
              onClick={(e) => { e.stopPropagation(); setActive(active === i ? null : i); }}
              aria-label={h.product.name}>
              <span className="lbv-pin-dot" />
            </button>
          ))}
          {active !== null && products[active] && (
            <MiniProductCard product={products[active].product}
              x={products[active].x} y={products[active].y}
              onView={() => goPDP(products[active].product.id)} />
          )}
        </figure>
        <button className="lbv-arrow next" onClick={onNext} aria-label="Next look"><Icon name="chevron" size={22} /></button>
      </div>

      <div className="lbv-shelf" onClick={(e) => e.stopPropagation()}>
        <span className="lbv-shelf-label mono">In this look</span>
        <div className="lbv-shelf-items">
          {products.map((h, i) => (
            <button key={i} className={"lbv-shelf-item" + (active === i ? " on" : "")} onClick={() => setActive(active === i ? null : i)}>
              <Ph label={h.product.label} ratio="square" style={{ width: 44, height: 44 }} />
              <div className="lbv-shelf-txt">
                <span>{h.product.name}</span>
                <Price ngn={h.product.price} alt={false} style={{ fontSize: 11.5, color: "var(--ink-soft)" }} />
              </div>
            </button>
          ))}
        </div>
        <p className="lbv-hint">Tap a pin on the image — or a piece here — then follow it to its page.</p>
      </div>
    </div>
  );
}

function LookbookPage({ route, onNav }) {
  const looks = RB.LOOKBOOK;
  const openParam = route.params && route.params.open;
  const [openIdx, setOpenIdx] = useState(() => {
    const i = looks.findIndex((l) => l.id === openParam);
    return i >= 0 ? i : null;
  });
  useEffect(() => {
    const i = looks.findIndex((l) => l.id === (route.params && route.params.open));
    setOpenIdx(i >= 0 ? i : null);
  }, [route]);

  return (
    <div className="fade-page">
      <section className="lb-page-hero">
        <div className="wrap center">
          <h1 className="serif" style={{ fontSize: "clamp(48px,8vw,118px)", fontWeight: 500, lineHeight: 0.98, margin: 0 }}>The Lookbook</h1>
        </div>
      </section>

      <section style={{ paddingBottom: 90 }}>
        <div className="wrap-wide">
          <div className="lbk-grid">
            {looks.map((l, i) => (
              <Reveal key={l.id} delay={(i % 4) + 1} className="lbk-cell">
                <button className="lbk-card zoomable" onClick={() => setOpenIdx(i)} aria-label={"Open look: " + l.title}>
                  <Ph label={l.label} ratio="portrait">
                    {l.hotspots.map((h, k) => (
                      <span key={k} className="lbt-pin" style={{ left: h.x + "%", top: h.y + "%" }} />
                    ))}
                    <span className="lbk-expand"><Icon name="plus" size={15} /> {l.hotspots.length} pieces</span>
                  </Ph>
                  <div className="lbk-cap">
                    <span className="mono">{l.season}</span>
                    <span className="serif">{l.title}</span>
                  </div>
                </button>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      {openIdx !== null && looks[openIdx] && (
        <LookViewer
          look={looks[openIdx]}
          index={openIdx} total={looks.length}
          onClose={() => setOpenIdx(null)}
          onPrev={() => setOpenIdx((openIdx - 1 + looks.length) % looks.length)}
          onNext={() => setOpenIdx((openIdx + 1) % looks.length)}
          onNav={onNav}
        />
      )}
    </div>
  );
}

Object.assign(window, { LookbookPage, LookViewer });
