// Product detail page

function ProductPage({ productId, go, onBuyNow, onAddToCart }) {
  const product = PRODUCTS.find(p => p.id === productId) || PRODUCTS[0];
  const [variantId, setVariantId] = React.useState(() => {
    const popular = product.variants.find(v => v.badge === 'Popular');
    return (popular || product.variants[0]).id;
  });
  const variant = product.variants.find(v => v.id === variantId);

  React.useEffect(() => {
    const popular = product.variants.find(v => v.badge === 'Popular');
    setVariantId((popular || product.variants[0]).id);
  }, [productId]);

  const [reviewFilter, setReviewFilter] = React.useState('recent');
  const productReviews = REVIEWS.filter(r => r.product === product.id);
  const allReviewsForDisplay = productReviews.length > 0 ? productReviews : REVIEWS.slice(0, 4);

  const sorted = React.useMemo(() => {
    let list = allReviewsForDisplay.slice();
    if (reviewFilter === 'highest') list.sort((a, b) => b.rating - a.rating);
    else if (reviewFilter === 'lowest') list.sort((a, b) => a.rating - b.rating);
    else if (reviewFilter === 'media') list = list.filter(r => r.hasMedia);
    return list;
  }, [reviewFilter, allReviewsForDisplay]);

  const distribution = React.useMemo(() => {
    const manual = product.reviewsByStar || {};
    const manualTotal = (manual[5] || 0) + (manual[4] || 0) + (manual[3] || 0) + (manual[2] || 0) + (manual[1] || 0);
    if (manualTotal > 0) {
      return [5, 4, 3, 2, 1].map(star => {
        const count = manual[star] || 0;
        const pct = Math.round((count / manualTotal) * 100);
        return { star, pct, count };
      });
    }
    // Fallback: compute from actual reviews and extrapolate to product.reviewCount
    return [5, 4, 3, 2, 1].map(star => {
      const count = allReviewsForDisplay.filter(r => r.rating === star).length;
      const pct = Math.round((count / Math.max(1, allReviewsForDisplay.length)) * 100);
      const fake = Math.round((product.reviewCount * pct) / 100);
      return { star, pct, count: fake };
    });
  }, [product, allReviewsForDisplay]);

  return (
    <section className="max-w-[1280px] mx-auto px-5 md:px-8 pt-8 md:pt-12">
      {/* Breadcrumb */}
      <div className="text-xs mono uppercase tracking-widest text-white/40 mb-6 flex items-center gap-2">
        <button onClick={() => go('home')} className="hover:text-white/70">Home</button>
        <span>/</span>
        <button onClick={() => go('catalog')} className="hover:text-white/70">Catalog</button>
        <span>/</span>
        <button onClick={() => go('catalog', { category: product.category })} className="hover:text-white/70">{CATEGORIES.find(c => c.id === product.category)?.name}</button>
        <span>/</span>
        <span className="text-white/70">{product.name}</span>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-[1.1fr_1fr] gap-8 lg:gap-14">
        {/* Left: imagery + description */}
        <div>
          <div className="relative">
            <div className={`${product.imageUrl ? '' : product.tile} rounded-2xl hairline h-[360px] md:h-[460px] overflow-hidden flex items-center justify-center relative`} style={{ background: product.imageUrl ? '#0c0c14' : undefined }}>
              {product.imageUrl ? (
                <img src={product.imageUrl} alt={product.name} className="absolute inset-0 w-full h-full object-cover" />
              ) : (
                <>
                  <div className="absolute inset-0 grid-bg opacity-40" />
                  <div className="glyph text-[200px]" style={{ color: product.glyphColor, textShadow: `0 0 80px ${product.glyphColor}55` }}>
                    {product.glyph}
                  </div>
                </>
              )}
              <div className="absolute top-4 left-4 flex gap-2">
                <Badge tone="ok"><Dot size={6} /> In stock</Badge>
                <Badge tone="mute">auto-fulfilled</Badge>
              </div>
              <div className="absolute bottom-4 right-4 glass rounded-lg px-3 py-2 text-[11px] mono flex items-center gap-2">
                <Dot color="var(--ok)" size={6} /> last sold 42s ago
              </div>
            </div>
          </div>

          <div className="mt-8">
            <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">About this product</div>
            <p className="text-white/75 leading-relaxed text-[15px]">{product.description}</p>
          </div>

          <div className="mt-8 hairline rounded-2xl p-5" style={{ background: 'var(--bg-1)' }}>
            <div className="flex items-center gap-2 mb-3">
              <Icon name="bolt" size={14} />
              <span className="text-xs mono uppercase tracking-widest text-white/60">Delivery method</span>
            </div>
            <div className="text-[15px]">{product.delivery}</div>
            <div className="mt-4 grid grid-cols-3 gap-3 text-sm">
              <div className="hairline rounded-lg p-3">
                <div className="text-[10px] mono uppercase tracking-widest text-white/40">Avg. time</div>
                <div className="font-medium mt-1">2m 47s</div>
              </div>
              <div className="hairline rounded-lg p-3">
                <div className="text-[10px] mono uppercase tracking-widest text-white/40">Warranty</div>
                <div className="font-medium mt-1">Full term</div>
              </div>
              <div className="hairline rounded-lg p-3">
                <div className="text-[10px] mono uppercase tracking-widest text-white/40">Replacement</div>
                <div className="font-medium mt-1">Auto · 6h</div>
              </div>
            </div>
          </div>

          {/* FAQ */}
          <div className="mt-10">
            <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">FAQ</div>
            <div className="space-y-2">
              {[
                { q: 'How does the delivery work?', a: 'After your crypto payment hits the required number of confirmations, our fulfillment bot generates and sends your credentials/invite/upgrade within seconds. No staff involved, 24/7.' },
                { q: 'Is the account shared with others?', a: 'Shared tiers are rotated across 3–5 users with independent profiles. Private tiers are 1:1 — you are the sole user and the password stays yours to change.' },
                { q: 'What happens if it stops working?', a: 'Open a replacement ticket from your dashboard and the bot auto-issues a fresh key/invite, typically in under 6 hours. You are covered for the entire subscription term.' },
                { q: 'Why only crypto?', a: 'Card payments require identity verification and chargeback risk — incompatible with instant-fulfillment pricing. Crypto settles on-chain with no intermediaries, which is how we keep margins tight.' },
                { q: 'Can I get a refund?', a: 'Before delivery, yes — full refund to the same wallet within 10 minutes. After delivery, we only issue replacements, not refunds, per the warranty policy.' },
              ].map((it, i) => (
                <details key={i} className="hairline rounded-xl group" style={{ background: 'var(--bg-1)' }}>
                  <summary className="flex items-center justify-between px-5 py-4 text-sm">
                    <span className="font-medium">{it.q}</span>
                    <Icon name="chev" size={14} className="chev" />
                  </summary>
                  <div className="px-5 pb-5 text-sm text-white/65 text-pretty">{it.a}</div>
                </details>
              ))}
            </div>
          </div>
        </div>

        {/* Right: purchase panel */}
        <div className="lg:sticky lg:top-24 lg:self-start">
          <div className="glass rounded-2xl p-6">
            <div className="flex items-center gap-2 mb-2">
              <Badge tone="accent">{CATEGORIES.find(c => c.id === product.category)?.name}</Badge>
            </div>
            <h1 className="text-3xl font-semibold tracking-tight">{product.name}</h1>
            <div className="text-white/60 mt-1">{product.tagline}</div>
            <div className="flex items-center gap-3 mt-3">
              <Stars rating={product.rating} />
              <span className="text-sm text-white/60">{product.rating} · {product.reviewCount.toLocaleString()} reviews</span>
            </div>

            <div className="mt-6">
              <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">Choose plan</div>
              <div className="grid grid-cols-1 gap-2 max-h-[320px] overflow-auto hide-scroll pr-1">
                {product.variants.map(v => {
                  const isSelected = variantId === v.id;
                  return (
                    <button
                      key={v.id}
                      onClick={() => setVariantId(v.id)}
                      className={`hairline rounded-xl p-3 text-left selectable flex items-center justify-between ${isSelected ? 'selected' : ''}`}
                    >
                      <div className="min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{v.label}</span>
                          {v.badge && <Badge tone={v.badge === 'Best value' ? 'ok' : 'accent'}>{v.badge}</Badge>}
                        </div>
                        <div className="text-xs mono mt-1 flex items-center gap-1.5" style={{ color: v.inStock < 50 ? 'var(--warn)' : 'var(--ok)' }}>
                          <Dot size={5} color={v.inStock < 50 ? 'var(--warn)' : 'var(--ok)'} />
                          {v.inStock} in stock
                        </div>
                      </div>
                      <div className="text-right shrink-0 ml-3">
                        <div className="font-semibold">{formatUSD(v.price)}</div>
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>

            <div className="mt-6 hairline rounded-xl p-4" style={{ background: 'var(--bg)' }}>
              <div className="flex items-center justify-between">
                <span className="text-[11px] mono uppercase tracking-widest text-white/40">Total</span>
                <span className="text-[11px] mono text-white/40">price locked at checkout</span>
              </div>
              <div className="flex items-baseline gap-3 mt-1">
                <span className="text-3xl font-semibold">{formatUSD(variant.price)}</span>
                <span className="mono text-xs text-white/50">≈ {(variant.price / 142.08).toFixed(4)} SOL</span>
              </div>
              <div className="flex flex-wrap items-center gap-1.5 mt-3">
                <span className="chip mono text-[10px]">SOL</span>
              </div>
            </div>

            <div className="mt-5 grid grid-cols-1 gap-2">
              <button onClick={() => onBuyNow(product, variant)} className="btn-primary py-3.5 text-[15px] inline-flex items-center justify-center gap-2">
                <Icon name="bolt" size={14} /> Buy now · {formatUSD(variant.price)}
              </button>
              <AddToCartButton product={product} variant={variant} onAddToCart={onAddToCart} />
            </div>

            <div className="mt-5 text-xs text-white/50 space-y-1.5">
              <div className="flex items-center gap-2"><Icon name="lock" size={12} /> No account required for guest checkout</div>
              <div className="flex items-center gap-2"><Icon name="shield" size={12} /> Full-term warranty · auto replacement</div>
              <div className="flex items-center gap-2"><Icon name="clock" size={12} /> Median delivery 2m 47s after confirmation</div>
            </div>
          </div>
        </div>
      </div>

      {/* Reviews */}
      <div className="mt-16 grid grid-cols-1 lg:grid-cols-[340px_1fr] gap-8">
        <div>
          <div className="text-[11px] mono uppercase tracking-widest text-white/40 mb-3">Customer reviews</div>
          <div className="flex items-end gap-3">
            <div className="text-5xl font-semibold">{product.rating}</div>
            <div className="pb-1">
              <Stars rating={product.rating} size={16} />
              <div className="text-xs text-white/50 mt-1">{product.reviewCount.toLocaleString()} verified reviews</div>
            </div>
          </div>
          <div className="mt-5 space-y-1.5">
            {distribution.map(d => (
              <div key={d.star} className="flex items-center gap-3 text-xs">
                <span className="w-3 mono">{d.star}</span>
                <div className="flex-1 h-2 rounded-full overflow-hidden" style={{ background: 'rgba(255,255,255,0.06)' }}>
                  <div className="h-full rating-bar" style={{ width: `${d.pct}%` }} />
                </div>
                <span className="text-white/50 w-14 text-right mono">{d.count.toLocaleString()}</span>
              </div>
            ))}
          </div>
          <div className="mt-6 hairline rounded-xl p-4" style={{ background: 'var(--bg-1)' }}>
            <div className="text-xs text-white/50 mb-2">Top mentions</div>
            <div className="flex flex-wrap gap-1.5">
              {['fast delivery', 'works perfect', 'good support', 'reorder', 'clean flow', '4K HDR', 'no issues', 'legit seller'].map(t => (
                <span key={t} className="chip">{t}</span>
              ))}
            </div>
          </div>
        </div>
        <div>
          <div className="flex items-center justify-between mb-4">
            <div className="flex flex-wrap gap-2">
              {[
                { id: 'recent', label: 'Most recent' },
                { id: 'highest', label: 'Highest' },
                { id: 'lowest', label: 'Lowest' },
                { id: 'media', label: 'With media' },
              ].map(f => (
                <button
                  key={f.id}
                  onClick={() => setReviewFilter(f.id)}
                  className={`hairline rounded-full px-3 py-1.5 text-xs ${reviewFilter === f.id ? 'selected' : ''}`}
                  style={reviewFilter === f.id ? { borderColor: 'var(--accent)', background: 'rgba(168,123,255,0.06)' } : {}}
                >
                  {f.label}
                </button>
              ))}
            </div>
            <span className="text-xs text-white/40 mono hidden md:inline">{sorted.length} shown</span>
          </div>
          <div className="space-y-3">
            {sorted.length === 0 ? (
              <div className="hairline rounded-xl p-8 text-center text-sm text-white/50">No reviews match this filter yet.</div>
            ) : sorted.map(r => <ReviewCard key={r.id} r={r} />)}
          </div>
        </div>
      </div>
    </section>
  );
}

function ReviewCard({ r }) {
  return (
    <div className="hairline rounded-xl p-4" style={{ background: 'var(--bg-1)' }}>
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-3 min-w-0">
          <div className="w-9 h-9 rounded-full flex items-center justify-center mono text-xs font-semibold shrink-0" style={{ background: 'rgba(168,123,255,0.12)', color: 'var(--accent)' }}>
            {r.user.slice(0, 2).toUpperCase()}
          </div>
          <div className="min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="font-medium text-sm mono">@{r.user}</span>
              {r.verified && <Badge tone="ok"><Icon name="check" size={10} /> verified</Badge>}
            </div>
            <div className="text-xs text-white/50 mt-0.5">{r.variant} · {r.ago}</div>
          </div>
        </div>
        <Stars rating={r.rating} size={12} />
      </div>
      <p className="text-sm text-white/75 mt-3 text-pretty">{r.text}</p>
      {r.hasMedia && (
        <div className="flex gap-2 mt-3">
          {[0, 1].map(i => (
            <div key={i} className="w-20 h-20 rounded-lg hairline relative overflow-hidden" style={{ background: 'linear-gradient(135deg, rgba(168,123,255,0.1), rgba(111,61,255,0.05))' }}>
              <div className="absolute inset-0 flex items-center justify-center text-white/30"><Icon name="eye" size={18} /></div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function AddToCartButton({ product, variant, onAddToCart }) {
  const [added, setAdded] = React.useState(false);
  const click = () => {
    onAddToCart?.(product, variant);
    setAdded(true);
    setTimeout(() => setAdded(false), 1400);
  };
  return (
    <button onClick={click} className="btn-ghost py-3 text-sm inline-flex items-center justify-center gap-2">
      {added ? <><Icon name="check" size={14} /> Added to cart</> : <><Icon name="cart" size={14} /> Add to cart</>}
    </button>
  );
}

Object.assign(window, { ProductPage, AddToCartButton });
