const ProductPage = ({ slug, navigate, onAdd }) => {
  const product = PRODUCTS.find((p) => p.slug === slug) || PRODUCTS[0];
  const { cart, currency, fmt } = useContext(StoreCtx);
  const comingSoon = product.status === "coming-soon";
  const inCart = cart.some((x) => x.id === product.id);
  const [activeImg, setActiveImg] = useState(0);
  const [thumbsExpanded, setThumbsExpanded] = useState(false);
  const addBtnRef = useRef(null);
  const THUMB_CAP = 4;
  // Defend against a product (esp. a hand-added coming-soon one) that ships
  // without a gallery — reading product.gallery[...] directly would throw and
  // white-screen the whole route. Fall back to a single "showcase coming soon"
  // video placeholder, which the render block already knows how to draw.
  const gallery = product.gallery && product.gallery.length
    ? product.gallery
    : [{ type: "video", caption: "Showcase coming soon" }];
  const totalThumbs = gallery.length;
  const showCollapse = totalThumbs > THUMB_CAP && !thumbsExpanded;
  const visibleThumbs = showCollapse ? gallery.slice(0, THUMB_CAP - 1) : gallery;
  const hiddenCount = totalThumbs - (THUMB_CAP - 1);
  // Clamp in case activeImg is stale from a previously-viewed product with a
  // longer gallery (ProductPage stays mounted across slug changes).
  const active = gallery[Math.min(activeImg, gallery.length - 1)] || gallery[0];

  return (
    <div className="route-enter">
      <div className="container">
        <div className="pd-layout">
          <div>
            <div className="pd-breadcrumbs">
              <a href="/" onClick={(e) => { e.preventDefault(); navigate("home"); }} style={{ cursor: "pointer" }}>Home</a>
              {" / "}
              <a href="/scripts" onClick={(e) => { e.preventDefault(); navigate("scripts"); }} style={{ cursor: "pointer" }}>Scripts</a>
              {" / "}
              <span>{product.name}</span>
            </div>
            <h1 className="pd-title">
              {product.name}
              {product.resourceName ? <span className="pd-resource">{product.resourceName}</span> : null}
            </h1>
            <p className="pd-sub">{product.tagline}</p>
            <div style={{ display: "flex", gap: 6, marginBottom: 22, flexWrap: "wrap" }}>
              <Tag variant="muted">{product.category}</Tag>
              {comingSoon ? <Tag variant="warn">Coming soon</Tag> : null}
              {product.version ? <Tag variant="muted">v{product.version}</Tag> : null}
              {product.updated ? <Tag variant="muted">updated {product.updated}</Tag> : null}
            </div>

            <div className="pd-gallery">
              <div
                className="pd-main"
                style={
                  active.type === "video" && active.youtubeId
                    ? { aspectRatio: "16 / 9" }
                    : undefined
                }
              >
                {active.type === "video" && active.youtubeId ? (
                  <iframe
                    key={active.youtubeId}
                    src={`https://www.youtube-nocookie.com/embed/${active.youtubeId}?rel=0&modestbranding=1`}
                    title={active.caption || "Script showcase"}
                    style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0, display: "block", background: "#000" }}
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share; fullscreen"
                    referrerPolicy="strict-origin-when-cross-origin"
                    allowFullScreen
                    loading="lazy"
                  />
                ) : active.type === "video" ? (
                  <div className="video-coming">
                    <div className="vc-inner">
                      <div className="vc-icon">
                        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
                      </div>
                      <div className="vc-label">// script_showcase</div>
                      <div className="vc-title">Coming soon</div>
                      <div className="vc-sub">Full walkthrough video dropping shortly. For now, swipe through the gallery.</div>
                    </div>
                  </div>
                ) : (
                  <img src={active.src} alt={active.caption} className="pd-main-img" />
                )}
                {gallery.length > 1 ? (
                  <>
                    <button
                      className="pd-nav pd-nav-prev"
                      onClick={() => setActiveImg((i) => (i - 1 + gallery.length) % gallery.length)}
                      title="Previous"
                      aria-label="Previous image"
                    >
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
                    </button>
                    <button
                      className="pd-nav pd-nav-next"
                      onClick={() => setActiveImg((i) => (i + 1) % gallery.length)}
                      title="Next"
                      aria-label="Next image"
                    >
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
                    </button>
                    <div className="pd-count">{activeImg + 1} / {gallery.length}</div>
                  </>
                ) : null}
                <div className="pd-caption">{active.caption}</div>
              </div>
              <div className="pd-thumbs">
                {visibleThumbs.map((g, i) => (
                  <div
                    key={i}
                    className={`pd-thumb ${i === activeImg ? "active" : ""}`}
                    onClick={() => setActiveImg(i)}
                  >
                    {g.type === "video" ? (
                      <div
                        className="pd-thumb-video"
                        style={{
                          backgroundImage: `linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), url(assets/screenshots/tablet-display-full.png)`,
                          backgroundSize: "cover",
                          backgroundPosition: "center",
                        }}
                      >
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
                        <span>video</span>
                      </div>
                    ) : (
                      <img src={g.src} alt={g.label} />
                    )}
                  </div>
                ))}
                {showCollapse ? (
                  <button
                    className="pd-thumb pd-thumb-more"
                    onClick={() => setThumbsExpanded(true)}
                    title={`Show ${hiddenCount} more`}
                  >
                    <span className="pd-thumb-more-num">+{hiddenCount}</span>
                    <span className="pd-thumb-more-label">more</span>
                  </button>
                ) : null}
                {thumbsExpanded && totalThumbs > THUMB_CAP ? (
                  <button
                    className="pd-thumb pd-thumb-less"
                    onClick={() => setThumbsExpanded(false)}
                    title="Show less"
                  >
                    <span className="pd-thumb-more-num">−</span>
                    <span className="pd-thumb-more-label">less</span>
                  </button>
                ) : null}
              </div>
            </div>

            <div className="pd-section">
              <h3>// overview</h3>
              <p style={{ color: "var(--fg-1)", fontSize: 14.5, lineHeight: 1.7, margin: 0, maxWidth: 720 }}>
                {product.longDesc}
              </p>
            </div>

            {product.features && product.features.length > 0 ? (
            <div className="pd-section">
              <h3>// {comingSoon ? "planned features" : "features"}</h3>
              <div className="feat-grid">
                {product.features.map((f, i) => {
                  const Ico = Icon[f.icon] || Icon.Bolt;
                  return (
                    <div className="feat" key={i}>
                      <div className="ic"><Ico size={14} /></div>
                      <div>
                        <div className="t">{f.title}</div>
                        <div className="d">{f.desc}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
            ) : null}

            {product.compatibility && product.compatibility.length > 0 ? (
              <div className="pd-section">
                <h3>// compatibility</h3>
                <div className="feat-grid">
                  {product.compatibility.map((c, i) => (
                    <div className="feat" key={i}>
                      <div className="ic"><Icon.Check size={14} /></div>
                      <div>
                        <div className="t">
                          {c.name}
                          {c.resourceName ? (
                            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--accent)", marginLeft: 8, fontWeight: 400 }}>
                              {c.resourceName}
                            </span>
                          ) : null}
                        </div>
                        {c.note ? <div className="d">{c.note}</div> : null}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ) : null}

            {product.requirements && product.requirements.length > 0 ? (
            <div className="pd-section">
              <h3>// requirements</h3>
              <table className="req-table">
                <tbody>
                  {product.requirements.map((r, i) => (
                    <tr key={i}><td>{r[0]}</td><td>{r[1]}</td></tr>
                  ))}
                </tbody>
              </table>
            </div>
            ) : null}
          </div>

          <aside className="pd-sidebar">
            <div className="surface pd-buybox">
              {comingSoon ? (
                <>
                  <div className="pd-price-row">
                    <span className="pd-price" style={{ fontSize: 24 }}>Coming soon</span>
                  </div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 18 }}>
                    {product.comingSoonNote ? `// ${product.comingSoonNote}` : "// in development"}
                    {product.price ? <span style={{ display: "block", marginTop: 4, textTransform: "none" }}>planned price ≈ {fmt(product.price)}</span> : null}
                  </div>
                  <div className="pd-actions">
                    <button className="btn btn-lg btn-block" disabled style={{ cursor: "not-allowed" }}>
                      <Icon.Lock size={14} /> Not yet available
                    </button>
                    <a className="btn btn-primary btn-lg btn-block" href="https://discord.gg/ey2sMahZ6t" target="_blank" rel="noreferrer noopener">
                      <Icon.Discord size={15} /> Get notified on Discord
                    </a>
                  </div>
                </>
              ) : (
                <>
                  <div className="pd-price-row">
                    <span className="pd-price">{fmt(product.price)}</span>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-3)" }}>{currency} · one-time</span>
                  </div>
                  {currency !== "USD" ? (
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--fg-3)", marginBottom: 6 }}>
                      ≈ {formatPrice(product.price, "USD")} · charged in USD
                    </div>
                  ) : null}
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 18 }}>
                    escrow-everything you should need is open.
                  </div>

                  <div className="pd-actions">
                    <button
                      ref={addBtnRef}
                      className="btn btn-primary btn-lg btn-block"
                      onClick={(e) => { if (!inCart) onAdd(product.id, e.currentTarget); }}
                      disabled={inCart}
                    >
                      {inCart ? <><Icon.Check size={14} /> In cart</> : <><Icon.Plus size={14} /> Add to cart</>}
                    </button>
                    <button
                      className="btn btn-lg btn-block"
                      onClick={(e) => inCart ? navigate("checkout") : onAdd(product.id, e.currentTarget, true)}
                    >
                      {inCart ? "Go to checkout" : "Buy now"}
                    </button>
                  </div>
                </>
              )}

              {product.highlights && product.highlights.length > 0 ? (
              <div className="pd-included">
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 10 }}>
                  // {comingSoon ? "planned" : "included"}
                </div>
                <ul>
                  {product.highlights.map((h, i) => (
                    <li key={i}><Icon.Check size={14} /> {h}</li>
                  ))}
                </ul>
              </div>
              ) : null}
            </div>

            <div className="surface" style={{ padding: 16 }}>
              <div className="spec-list">
                <div className="sr"><span className="k">{comingSoon ? "status" : "version"}</span><span className="v">{comingSoon ? "coming soon" : product.version}</span></div>
                <div className="sr"><span className="k">{comingSoon ? "release" : "updated"}</span><span className="v">{comingSoon ? "TBA" : product.updated}</span></div>
                <div className="sr"><span className="k">framework</span><span className="v">qbx · qb · esx</span></div>
                <div className="sr"><span className="k">support</span><span className="v">discord &lt;12h</span></div>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ProductPage });
