const ProductCard = ({ product, onOpen, onAdd, style = "detailed" }) => {
  const { cart, fmt } = useContext(StoreCtx);
  const comingSoon = product.status === "coming-soon";
  const inCart = cart.some((x) => x.id === product.id);
  // Prefer the YouTube showcase thumbnail (16:9, native to the embed) over a
  // generic in-game screenshot — keeps the paid card visually tied to the
  // walkthrough video. Falls back to the tablet screenshot if the product
  // doesn't have a video yet.
  const videoEntry = product.gallery && product.gallery.find((g) => g.type === "video" && g.youtubeId);
  const imgEntry = product.gallery && product.gallery.find((g) => g.src);
  const cardImg = videoEntry
    ? `https://img.youtube.com/vi/${videoEntry.youtubeId}/maxresdefault.jpg`
    : imgEntry
    ? imgEntry.src
    : "assets/screenshots/tablet-display-full.png";
  const onCardImgError = (e) => {
    // maxresdefault.jpg only exists for HD uploads. If it 404s, fall back to
    // mqdefault.jpg which YouTube generates for every video.
    if (videoEntry && !e.currentTarget.dataset.fb) {
      e.currentTarget.dataset.fb = "1";
      e.currentTarget.src = `https://img.youtube.com/vi/${videoEntry.youtubeId}/mqdefault.jpg`;
    }
  };
  return (
    <div className={`p-card ${style === "minimal" ? "minimal" : ""} ${comingSoon ? "is-soon" : ""}`}>
      <div className="p-card-media" onClick={onOpen} style={{ cursor: "pointer" }}>
        {comingSoon && !imgEntry && !videoEntry ? (
          <Placeholder label={product.name} />
        ) : (
          <img src={cardImg} alt={product.name} className="p-card-img" onError={onCardImgError} style={comingSoon ? { filter: "grayscale(0.7) brightness(0.7)" } : null} />
        )}
        {comingSoon ? <span className="p-card-soon-badge">Coming soon</span> : null}
      </div>
      <div className="p-card-body">
        <div className="p-card-head">
          <h3 onClick={onOpen} style={{ cursor: "pointer" }}>{product.name}</h3>
          <span className="price">{comingSoon ? "Soon" : fmt(product.price)}</span>
        </div>
        {product.resourceName ? (
          <div className="p-card-resource">{product.resourceName}</div>
        ) : null}
        <p className="p-card-desc">{product.tagline}</p>
        <div className="p-card-tags">
          <Tag variant="muted">{product.category}</Tag>
          {comingSoon ? (
            <Tag variant="warn">In development</Tag>
          ) : (
            <>
              {product.version ? <Tag variant="muted">v{product.version}</Tag> : null}
              <Tag variant="accent" icon>Escrow</Tag>
            </>
          )}
        </div>
      </div>
      <div className="p-card-foot">
        <span className="mono">QBX · QB · ESX</span>
        <div style={{ display: "flex", gap: 6 }}>
          <button className="btn btn-sm" onClick={onOpen}>{comingSoon ? "Preview" : "View"}</button>
          {comingSoon ? (
            <button className="btn btn-sm" disabled style={{ cursor: "not-allowed" }}>
              <Icon.Lock size={12} /> Soon
            </button>
          ) : (
            <button
              className="btn btn-sm btn-primary"
              onClick={(e) => { if (!inCart) onAdd(e); }}
              disabled={inCart}
            >
              {inCart ? <><Icon.Check size={13} /> In cart</> : <><Icon.Plus size={13} /> Cart</>}
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

const ComingSoonCard = ({ item }) => (
  <div className="p-card coming">
    <div className="mono">_soon</div>
    <h3 className="cs-name" data-text={item.name}>{item.name}</h3>
    <div className="mono">{item.note}</div>
  </div>
);

const HERO_WORDS = ["just work", "create roleplay", "run day one", "save dev time", "scale clean"];

const Rotator = ({ words, interval = 2400 }) => {
  const [idx, setIdx] = React.useState(0);
  const [phase, setPhase] = React.useState("in"); // in | out
  React.useEffect(() => {
    const t1 = setTimeout(() => setPhase("out"), interval - 420);
    const t2 = setTimeout(() => {
      setIdx((i) => (i + 1) % words.length);
      setPhase("in");
    }, interval);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [idx, interval, words.length]);

  // width animates to content — measure longest word for stability
  const longest = React.useMemo(
    () => words.reduce((a, b) => (a.length >= b.length ? a : b), ""),
    [words]
  );

  return (
    <span className="rotator" aria-live="polite">
      <span className="rotator-ghost" aria-hidden="true">{longest}</span>
      <span key={idx} className={`rotator-word ${phase}`}>{words[idx]}</span>
    </span>
  );
};

const HomePage = ({ navigate, heroLayout, cardStyle, onAdd }) => {
  const featured = PRODUCTS.find((p) => p.id === FEATURED_ID);
  const pad2 = (n) => String(n).padStart(2, "0");
  const liveCount = PRODUCTS.filter(isLive).length;
  const plannedCount = PRODUCTS.filter((p) => !isLive(p)).length + COMING_SOON.length;
  return (
    <div className="route-enter">
      <section className={`hero ${heroLayout === "split" ? "split" : ""}`}>
        <div className="container">
          {heroLayout === "split" ? (
            <div className="hero-grid">
              <HeroContent navigate={navigate} featured={featured} onAdd={onAdd} />
              {(() => {
                const vid = featured?.gallery?.find((g) => g.type === "video" && g.youtubeId)?.youtubeId;
                return (
                  <div
                    className="hero-visual"
                    style={vid ? { aspectRatio: "16 / 9" } : undefined}
                  >
                    {vid ? (
                      <iframe
                        src={`https://www.youtube-nocookie.com/embed/${vid}?rel=0&modestbranding=1`}
                        title="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"
                      />
                    ) : (
                      <div className="video-coming hero-video">
                        <div className="vc-inner">
                          <div className="vc-icon">
                            <svg width="32" height="32" 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">Video coming soon</div>
                          <div className="vc-sub">Dropping with the public release.</div>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })()}
            </div>
          ) : (
            <HeroContent navigate={navigate} featured={featured} onAdd={onAdd} centered />
          )}
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div className="section-head">
            <h2>All scripts</h2>
            <span className="meta">{pad2(liveCount)} LIVE · {pad2(plannedCount)} PLANNED</span>
          </div>
          <div className="card-grid">
            {PRODUCTS.map((p) => (
              <ProductCard
                key={p.id}
                product={p}
                style={cardStyle}
                onOpen={() => navigate("product", p.slug)}
                onAdd={(e) => onAdd(p.id, e.currentTarget)}
              />
            ))}
            {COMING_SOON.map((c) => <ComingSoonCard key={c.id} item={c} />)}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container">
          {/* data-nosnippet: keep this promo block out of Google's snippet so it
              can't get picked as the search-result description / text-fragment
              (it was previously surfacing "New scripts land every 6–8 weeks…"). */}
          <div data-nosnippet className="surface" style={{ padding: "28px 32px", display: "grid", gridTemplateColumns: "1fr auto", gap: 24, alignItems: "center" }}>
            <div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-3)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 6 }}>
                &gt; release_cadence
              </div>
              <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: "-0.01em", marginBottom: 4 }}>
                New scripts land every 6–8 weeks.
              </div>
              <div style={{ color: "var(--fg-2)", fontSize: 14 }}>
                Join the Discord for early access codes, previews and support!
              </div>
            </div>
            <a href="https://discord.gg/ey2sMahZ6t" target="_blank" rel="noreferrer noopener" className="btn btn-lg">
              <Icon.Discord size={16} /> Join Discord
            </a>
          </div>
        </div>
      </section>
    </div>
  );
};

const HeroContent = ({ navigate, featured, onAdd, centered }) => (
  <div style={centered ? { textAlign: "left", maxWidth: 820 } : null}>
    <h1 className="hero-title" style={{ marginTop: 0 }}>
      Scripts that <Rotator words={HERO_WORDS} /> on your server.
    </h1>
    <p className="hero-sub">
      Production-grade FiveM resources for QBX, QBCore, and ESX. Performance-audited before release and
      escrow-protected — but if there's something locked you'd like to edit, just ask. Run into issues? Guaranteed
      support response within 12 hours of ticket creation.
    </p>
    <div className="hero-actions">
      <button className="btn btn-primary btn-lg btn-new-badge" onClick={() => navigate("product", featured.slug)}>
        <span className="new-badge">NEW</span>
        View {featured.name} <Icon.Arrow size={15} />
      </button>
      <button className="btn btn-lg" onClick={() => navigate("scripts")}>
        Browse all scripts
      </button>
    </div>
    <div className="hero-meta">
      <div className="item">
        <span className="label">SUPPORT</span>
        <span className="value">Discord · &lt;12h</span>
      </div>
    </div>
  </div>
);

Object.assign(window, { HomePage, ProductCard, ComingSoonCard });
