// pdp.jsx — Product detail page

function PDPScreen({ productId, onBack, onAddCart, onOpenCart }) {
  const p = FF_PRODUCTS.find(x => x.id === productId) || FF_PRODUCTS[0];
  const [galleryIdx, setGalleryIdx] = React.useState(0);
  const [variant, setVariant] = React.useState(p.variants[0]);
  const [qty, setQty] = React.useState(1);
  const [openSection, setOpenSection] = React.useState('description');
  const [scrolledPast, setScrolledPast] = React.useState(false);
  const buyBoxRef = React.useRef(null);

  React.useEffect(() => {
    const onScroll = () => {
      if (!buyBoxRef.current) return;
      const r = buyBoxRef.current.getBoundingClientRect();
      setScrolledPast(r.bottom < 80);
    };
    const root = document.querySelector('#pdp-scroll');
    root?.addEventListener('scroll', onScroll);
    return () => root?.removeEventListener('scroll', onScroll);
  }, []);

  const galleryRef = React.useRef(null);
  const onGalleryScroll = (e) => {
    const w = e.target.clientWidth;
    setGalleryIdx(Math.round(e.target.scrollLeft / w));
  };

  return (
    <div id="pdp-scroll" style={{ height: '100%', overflowY: 'auto', overflowX: 'hidden' }}>
      {/* Custom top bar overlay */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 20,
        paddingTop: 'var(--safe-top)',
        background: 'linear-gradient(180deg, rgba(10,10,10,0.7) 0%, transparent 100%)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 12px', height: 56 }}>
          <button onClick={onBack} className="tap"
            style={{ width: 40, height: 40, borderRadius: 20, background: 'rgba(20,20,20,0.7)',
              backdropFilter: 'blur(10px)', border: '1px solid var(--ff-border)',
              color: 'var(--ff-text)', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <IconChevronLeft size={20}/>
          </button>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="tap" style={iconBtnFloat}><IconHeart size={18}/></button>
            <button className="tap" style={iconBtnFloat}><IconShare size={18}/></button>
          </div>
        </div>
      </div>

      {/* Image gallery */}
      <div style={{ marginTop: -56 }}>
        <div ref={galleryRef} onScroll={onGalleryScroll} className="no-scrollbar snap-x"
          style={{ display: 'flex', overflowX: 'auto', aspectRatio: '1/1' }}>
          {[0, 1, 2, 3].map(i => (
            <div key={i} className="snap-start" style={{ flex: '0 0 100%', width: '100%', aspectRatio: '1/1', position: 'relative' }}>
              <ProductVisual id={p.id}/>
              {/* Subtle overlay variation per slide */}
              {i > 0 && (
                <div style={{
                  position: 'absolute', inset: 0,
                  background: i === 1 ? 'radial-gradient(ellipse at 70% 70%, rgba(200,65,13,0.06) 0%, transparent 60%)'
                            : i === 2 ? 'linear-gradient(160deg, transparent 0%, rgba(255,200,150,0.04) 50%, transparent 100%)'
                            : 'radial-gradient(ellipse at 30% 80%, rgba(255,255,255,0.03) 0%, transparent 60%)',
                  pointerEvents: 'none',
                }}/>
              )}
              <div style={{
                position: 'absolute', bottom: 16, right: 16,
                fontFamily: 'var(--ff-mono)', fontSize: 10, color: 'var(--ff-text-3)',
                letterSpacing: '0.16em',
                background: 'rgba(0,0,0,0.5)', padding: '4px 8px', borderRadius: 2,
              }}>VIEW {i + 1} / 4</div>
            </div>
          ))}
        </div>
        {/* dots */}
        <div style={{ display: 'flex', gap: 6, justifyContent: 'center', padding: '14px 0 8px' }}>
          {[0,1,2,3].map(i => (
            <span key={i} style={{
              width: i === galleryIdx ? 18 : 6, height: 6, borderRadius: 3,
              background: i === galleryIdx ? 'var(--ff-orange)' : 'var(--ff-border-strong)',
              transition: 'all 200ms',
            }}/>
          ))}
        </div>
      </div>

      <div ref={buyBoxRef} style={{ padding: '16px 16px 0' }}>
        {/* SKU + tag */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <span className="mono" style={{ fontSize: 11, color: 'var(--ff-text-3)', letterSpacing: '0.12em' }}>{p.sku}</span>
          {p.tag && (
            <span className="mono" style={{
              fontSize: 9, letterSpacing: '0.14em',
              color: p.tag === 'Limited' ? 'var(--ff-warning)' : 'var(--ff-orange)',
              border: `1px solid ${p.tag === 'Limited' ? 'var(--ff-warning)' : 'var(--ff-orange)'}`,
              padding: '2px 6px', borderRadius: 2, textTransform: 'uppercase',
            }}>{p.tag}</span>
          )}
        </div>
        {/* Title */}
        <h1 className="display" style={{ fontSize: 28, margin: 0, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.15 }}>
          {p.name}
        </h1>
        {/* Rating */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12 }}>
          <Stars rating={p.rating} size={14}/>
          <span className="mono" style={{ fontSize: 12, color: 'var(--ff-text-2)' }}>
            {p.rating} · {p.reviews} reviews
          </span>
        </div>
        {/* Price */}
        <div style={{ marginTop: 18, display: 'flex', alignItems: 'baseline', gap: 12 }}>
          <span className="mono" style={{ fontSize: 28, fontWeight: 600, color: 'var(--ff-text)' }}>
            {fmtPrice(p.price)}
          </span>
          <span style={{ fontSize: 12, color: 'var(--ff-text-3)' }}>USD · free US shipping over $150</span>
        </div>

        {/* Short description */}
        <p style={{ marginTop: 14, marginBottom: 0, fontSize: 15.5, lineHeight: 1.55, color: 'var(--ff-text-2)', textWrap: 'pretty' }}>
          {p.short}
        </p>

        {/* In stock */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 18,
          padding: '10px 14px', background: p.inStock ? 'rgba(74,222,128,0.06)' : 'rgba(245,158,11,0.06)',
          border: `1px solid ${p.inStock ? 'rgba(74,222,128,0.25)' : 'rgba(245,158,11,0.25)'}`,
          borderRadius: 4 }}>
          <span style={{ width: 8, height: 8, borderRadius: 4,
            background: p.inStock ? 'var(--ff-success)' : 'var(--ff-warning)',
            boxShadow: `0 0 8px ${p.inStock ? 'var(--ff-success)' : 'var(--ff-warning)'}` }}/>
          <span style={{ fontSize: 13, color: 'var(--ff-text)' }}>
            {p.inStock ? 'In stock · Ships in 24 hrs' : 'Backordered · Ships in 2 weeks'}
          </span>
        </div>

        {/* Variants */}
        {p.variants.length > 1 && (
          <div style={{ marginTop: 24 }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>FINISH · {variant.toUpperCase()}</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {p.variants.map(v => (
                <button key={v} onClick={() => setVariant(v)} className="tap"
                  style={{
                    padding: '12px 16px', minHeight: 48, borderRadius: 4,
                    border: '1px solid', borderColor: variant === v ? 'var(--ff-orange)' : 'var(--ff-border)',
                    background: variant === v ? 'var(--ff-orange-dim)' : 'var(--ff-surface)',
                    color: variant === v ? 'var(--ff-orange)' : 'var(--ff-text)',
                    fontSize: 14, fontWeight: 500, cursor: 'pointer',
                  }}>{v}</button>
              ))}
            </div>
          </div>
        )}

        {/* Quantity + Add to Cart */}
        <div style={{ marginTop: 24, display: 'flex', gap: 10 }}>
          <div style={{
            display: 'flex', alignItems: 'center',
            border: '1px solid var(--ff-border)', borderRadius: 4,
            background: 'var(--ff-surface)', height: 56,
          }}>
            <button onClick={() => setQty(q => Math.max(1, q - 1))} className="tap"
              style={qtyBtn}><IconMinus size={16}/></button>
            <div className="mono" style={{ width: 40, textAlign: 'center', fontWeight: 600 }}>{qty}</div>
            <button onClick={() => setQty(q => q + 1)} className="tap"
              style={qtyBtn}><IconPlus size={16}/></button>
          </div>
          <button onClick={() => onAddCart(p, qty, variant)} className="btn btn-primary tap"
            style={{ flex: 1, height: 56, fontSize: 15 }}>
            <IconCart size={16}/> Add to cart
          </button>
        </div>

        {/* Trust strip */}
        <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {[
            { I: IconTruck, l: 'Ships in 24 hrs' },
            { I: IconShield, l: 'Lifetime warranty' },
            { I: IconReturn, l: '30-day returns' },
            { I: IconWrench, l: p.install },
          ].map((t, i) => (
            <div key={i} style={{
              padding: '12px', display: 'flex', alignItems: 'center', gap: 10,
              border: '1px solid var(--ff-border)', borderRadius: 4, background: 'var(--ff-surface)',
            }}>
              <t.I size={16} color="var(--ff-orange)"/>
              <span style={{ fontSize: 12, color: 'var(--ff-text-2)', lineHeight: 1.3 }}>{t.l}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Specs in mono */}
      <section style={{ padding: '32px 16px 0' }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>SPECIFICATIONS</div>
        <div style={{ background: 'var(--ff-surface)', border: '1px solid var(--ff-border)', borderRadius: 4 }}>
          {p.specs.map((s, i) => (
            <div key={s.k} style={{
              display: 'flex', justifyContent: 'space-between', padding: '14px 16px',
              borderTop: i === 0 ? 'none' : '1px solid var(--ff-border)',
            }}>
              <span style={{ fontSize: 13, color: 'var(--ff-text-2)' }}>{s.k}</span>
              <span className="mono" style={{ fontSize: 13, color: 'var(--ff-text)', fontWeight: 500 }}>{s.v}</span>
            </div>
          ))}
        </div>
      </section>

      {/* Accordions */}
      <section style={{ padding: '32px 16px 0' }}>
        {[
          { k: 'description', t: 'Description', body: <p style={{ margin: 0, color: 'var(--ff-text-2)', fontSize: 14.5, lineHeight: 1.65, textWrap: 'pretty' }}>{p.description}</p> },
          { k: 'install', t: 'Installation', body: (
            <div>
              <p style={{ margin: '0 0 12px', color: 'var(--ff-text-2)', fontSize: 14.5, lineHeight: 1.65 }}>
                {p.install}. Step-by-step video and PDF guide available on our Field Notes page.
              </p>
              <button className="btn btn-secondary tap" style={{ width: '100%' }}>
                <IconPlay size={14}/> Watch installation video
              </button>
            </div>
          )},
          { k: 'reviews', t: `Reviews (${p.reviews})`, body: (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {FF_REVIEWS.slice(0, 2).map((r, i) => (
                <div key={i} style={{ paddingBottom: 16, borderBottom: i === 0 ? '1px solid var(--ff-border)' : 'none' }}>
                  <Stars rating={r.rating}/>
                  <p style={{ margin: '8px 0', fontSize: 14, color: 'var(--ff-text)' }}>“{r.body}”</p>
                  <div style={{ fontSize: 12, color: 'var(--ff-text-3)' }}>{r.name} · {r.role}</div>
                </div>
              ))}
              <button className="btn btn-secondary tap">Read all reviews</button>
            </div>
          )},
          { k: 'faq', t: 'Compatibility & FAQ', body: (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {[
                ['Will this fit my mil-spec lower?', 'Yes — designed for any mil-spec AR-15 lower receiver.'],
                ['Can I install this myself?', 'Yes. Drop-in design, no gunsmith required.'],
                ['Is this legal in my state?', 'Check our compliance page for the current restricted-state list.'],
              ].map(([q, a]) => (
                <div key={q}>
                  <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 4 }}>{q}</div>
                  <div style={{ fontSize: 13, color: 'var(--ff-text-2)', lineHeight: 1.55 }}>{a}</div>
                </div>
              ))}
            </div>
          )},
        ].map(sec => (
          <div key={sec.k} style={{ borderTop: '1px solid var(--ff-border)' }}>
            <button onClick={() => setOpenSection(openSection === sec.k ? null : sec.k)}
              style={{
                width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '20px 0', minHeight: 64,
                background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left',
                color: 'var(--ff-text)',
              }}>
              <span style={{ fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600 }}>{sec.t}</span>
              <IconChevronDown size={18} style={{ color: 'var(--ff-text-2)',
                transform: openSection === sec.k ? 'rotate(180deg)' : 'none', transition: 'transform 200ms' }}/>
            </button>
            {openSection === sec.k && (
              <div style={{ paddingBottom: 24 }}>{sec.body}</div>
            )}
          </div>
        ))}
        <div style={{ borderTop: '1px solid var(--ff-border)' }}/>
      </section>

      {/* Related */}
      <section style={{ padding: '40px 0 0' }}>
        <div style={{ padding: '0 16px', marginBottom: 16 }}>
          <div className="eyebrow" style={{ marginBottom: 6 }}>OFTEN PAIRED WITH</div>
          <h2 className="display" style={{ fontSize: 22, margin: 0, fontWeight: 600 }}>Complete the build</h2>
        </div>
        <div className="no-scrollbar snap-x" style={{ display: 'flex', gap: 12, overflowX: 'auto', padding: '0 16px' }}>
          {FF_PRODUCTS.filter(x => x.id !== p.id).slice(0, 4).map(rp => (
            <div key={rp.id} className="snap-start" style={{ flex: '0 0 70%' }}>
              <ProductCard p={rp} onOpen={() => {}} compact/>
            </div>
          ))}
        </div>
      </section>

      <div style={{ height: 'calc(160px + var(--safe-bottom))' }}/>

      {/* Sticky add-to-cart bar */}
      {scrolledPast && (
        <div style={{
          position: 'fixed', left: 0, right: 0, bottom: 'calc(64px + var(--safe-bottom))',
          padding: '12px 16px',
          background: 'rgba(10,10,10,0.92)', backdropFilter: 'blur(20px)',
          borderTop: '1px solid var(--ff-border)',
          display: 'flex', gap: 10, alignItems: 'center', zIndex: 25,
          animation: 'ff-slide-up 240ms var(--ff-ease-out)',
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12, color: 'var(--ff-text-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {p.name}
            </div>
            <div className="mono" style={{ fontSize: 16, fontWeight: 600, color: 'var(--ff-text)' }}>
              {fmtPrice(p.price * qty)}
            </div>
          </div>
          <button onClick={() => onAddCart(p, qty, variant)} className="btn btn-primary tap"
            style={{ flex: 'none', minWidth: 160 }}>
            Add to cart
          </button>
        </div>
      )}
    </div>
  );
}

const iconBtnFloat = {
  width: 40, height: 40, borderRadius: 20, background: 'rgba(20,20,20,0.7)',
  backdropFilter: 'blur(10px)', border: '1px solid var(--ff-border)',
  color: 'var(--ff-text)', cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
};
const qtyBtn = {
  width: 48, height: '100%', background: 'none', border: 'none',
  color: 'var(--ff-text)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
};

Object.assign(window, { PDPScreen });
