/* ============================================================
   PRODUCT DETAIL PAGE — category-aware spec sheet & behavior
   ============================================================ */
function ProductPage({ params }) {
  const { nav, addToCart, money, currency, wish, toggleWish, setDrawer } = useStore();
  const p = BB.products.find(x => x.id === params.id) || BB.products[0];
  const [img, setImg] = useState(0);
  const [qty, setQty] = useState(1);
  const [opts, setOpts] = useState(() => {
    const o = {}; if (p.opts) Object.keys(p.opts).forEach(k => o[k] = p.opts[k][0]); return o;
  });
  const [tab, setTab] = useState('desc');
  const liked = wish.includes(p.id);

  useEffect(() => {
    setImg(0); setQty(1); setTab('desc');
    const o = {}; if (p.opts) Object.keys(p.opts).forEach(k => o[k] = p.opts[k][0]); setOpts(o);
  }, [params.id]);

  const cat = BB.catOf(p);
  const isVehicle = p.cat === 'vehicles';
  const specs = BB.specSheet(p);
  const related = BB.products.filter(x => x.cat === p.cat && x.id !== p.id).slice(0, 4);
  const thumbs = IMG.gallery(p.id);
  const otherCur = currency === BB.BRAND.currency.primary.code ? BB.BRAND.currency.secondary.code : BB.BRAND.currency.primary.code;

  const specTitle = { hair: 'Product details', food: 'Product details', beauty: 'Product details', electronics: 'Specifications', home: 'Product details', vehicles: 'Vehicle spec sheet' }[p.cat] || 'Details';
  const trustThird = { hair: 'Genuine, verified quality', food: 'Sealed & date-checked', beauty: 'Genuine, sealed stock', electronics: 'Tested before dispatch', home: 'Quality-checked', vehicles: 'Inspection report included' }[p.cat] || 'Quality-checked';

  const buyNow = () => { addToCart(p, isVehicle ? 1 : qty, opts); setTimeout(() => nav('checkout'), 120); };

  return (
    <div style={{ background: 'var(--cream)' }}>
      <div className="container wide pdp-grid" style={{ padding: 'clamp(32px,4vw,52px) var(--gutter) clamp(56px,8vw,90px)' }}>
        {/* gallery */}
        <div className="pdp-gallery">
          <Ph src={thumbs[img]} label={p.name} variant={p.ph} style={{ aspectRatio: isVehicle ? '4/3' : '1/1', borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-sm)' }} />
          {thumbs.length > 1 && (
            <div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
              {thumbs.map((src, i) => (
                <button key={i} onClick={() => setImg(i)} style={{ flex: 1, borderRadius: 'var(--r-sm)', overflow: 'hidden', boxShadow: img === i ? '0 0 0 2.5px var(--gold)' : 'inset 0 0 0 1px var(--line)' }}>
                  <Ph src={src} label="" variant={p.ph} style={{ aspectRatio: '1' }} />
                </button>
              ))}
            </div>
          )}
        </div>

        {/* info */}
        <div className="pdp-info">
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 12, flexWrap: 'wrap' }}>
            <span className="cat-tag" style={{ fontSize: 12 }}>{cat?.name}</span>
            {p.tags.includes('best') && <span className="badge badge-best">Bestseller</span>}
            {p.tags.includes('new') && <span className="badge badge-new">New in</span>}
          </div>
          <h1 style={{ fontSize: 'clamp(32px,4vw,50px)', lineHeight: 1.04 }}>{p.name}</h1>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginTop: 12 }}>
            {isVehicle ? (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--ink-soft)' }}><I.doc width={16} height={16} style={{ color: 'var(--gold-deep)' }} /> Inspected · condition report available on request</span>
            ) : (
              <><Stars value={p.rating} /> <span className="muted" style={{ fontSize: 13, whiteSpace: 'nowrap' }}>{p.rating} · {p.reviews} reviews</span></>
            )}
          </div>

          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, margin: '20px 0 4px', flexWrap: 'wrap' }}>
            <span style={{ fontFamily: 'var(--serif)', fontWeight: 700, fontSize: 'clamp(30px,3.4vw,40px)' }}>{money(p.price)}</span>
            <span className="muted" style={{ fontSize: 14 }}>≈ {BB.fmt(p.price, otherCur)}</span>
          </div>
          <p style={{ fontSize: 16, color: 'var(--ink-soft)', lineHeight: 1.7, marginTop: 12 }}>{p.desc}</p>

          {/* category-aware spec sheet */}
          {specs.length > 0 && (
            <div style={{ marginTop: 26 }}>
              <p className="eyebrow" style={{ marginBottom: 10 }}>{specTitle}</p>
              <dl className="spec-sheet">
                {specs.map(([label, val]) => (
                  <div className="spec-row" key={label}><dt>{label}</dt><dd>{val}</dd></div>
                ))}
              </dl>
            </div>
          )}

          {/* options */}
          {p.opts && Object.entries(p.opts).map(([key, vals]) => (
            <div key={key} style={{ marginTop: 22 }}>
              <p className="eyebrow" style={{ marginBottom: 10 }}>{key}</p>
              <div style={{ display: 'flex', gap: 9, flexWrap: 'wrap' }}>
                {vals.map(v => (
                  <button key={v} onClick={() => setOpts(o => ({ ...o, [key]: v }))} className={`chip ${opts[key] === v ? 'active' : ''}`}>{v}</button>
                ))}
              </div>
            </div>
          ))}

          {/* qty + actions */}
          {isVehicle ? (
            <div style={{ marginTop: 26, background: 'var(--gold-soft)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: '14px 18px', display: 'flex', gap: 11, alignItems: 'flex-start', fontSize: 13.5, lineHeight: 1.55 }}>
              <I.car width={20} height={20} style={{ color: 'var(--gold-deep)', flexShrink: 0, marginTop: 2 }} />
              <span>Sold as listed — one unit. Checkout reserves this vehicle; we then schedule your inspection and handover. Full refund if it fails inspection.</span>
            </div>
          ) : null}
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: isVehicle ? 14 : 28, flexWrap: 'wrap' }}>
            {!isVehicle && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, border: '1.5px solid var(--line)', borderRadius: 100, padding: 5, background: 'var(--ivory)' }}>
                <button className="qbtn" onClick={() => setQty(q => Math.max(1, q - 1))} aria-label="Decrease quantity"><I.minus width={16} height={16} /></button>
                <span style={{ minWidth: 30, textAlign: 'center', fontSize: 16 }}>{qty}</span>
                <button className="qbtn" onClick={() => setQty(q => q + 1)} aria-label="Increase quantity"><I.plus width={16} height={16} /></button>
              </div>
            )}
            <button className="btn btn-primary btn-lg" style={{ flex: '1 1 200px' }} onClick={() => { addToCart(p, isVehicle ? 1 : qty, opts); setDrawer(true); }}>
              Add to cart · {money(p.price * (isVehicle ? 1 : qty))}
            </button>
          </div>
          <button className="btn btn-gold btn-block btn-lg" style={{ marginTop: 10 }} onClick={buyNow}>Buy it now</button>
          <button onClick={() => toggleWish(p.id)} style={{ display: 'flex', alignItems: 'center', gap: 9, margin: '6px auto 0', fontSize: 13.5, color: 'var(--ink-soft)', padding: '13px 12px', minHeight: 44 }}>
            <I.heart width={18} height={18} style={{ fill: liked ? 'var(--blush-deep)' : 'none', color: liked ? 'var(--blush-deep)' : 'var(--ink-soft)' }} /> {liked ? 'Saved for later' : 'Save for later'}
          </button>

          {/* trust mini — category-aware */}
          <div style={{ display: 'flex', gap: 20, marginTop: 26, paddingTop: 24, borderTop: '1px solid var(--line)', flexWrap: 'wrap' }}>
            {[[I.truck, cat?.dispatch || 'Ships in 1–3 days'], [I.shield, 'Secure checkout'], [I.doc, trustThird]].map(([Ic, t], i) => (
              <span key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--ink-soft)' }}>{Ic({ width: 18, height: 18, style: { color: 'var(--gold-deep)' } })} {t}</span>
            ))}
          </div>
        </div>
      </div>

      {/* tabs: description / delivery */}
      <div className="container wide" style={{ padding: '0 var(--gutter) clamp(56px,8vw,90px)' }}>
        <div style={{ display: 'flex', gap: 4, borderBottom: '1px solid var(--line)', marginBottom: 28 }}>
          {[['desc', 'Description'], ['ship', 'Delivery'], ['ret', 'Returns']].map(([k, l]) => (
            <button key={k} className="tab-btn" onClick={() => setTab(k)} style={{ padding: '14px 22px', fontSize: 13.5, letterSpacing: '.06em', fontWeight: 500, position: 'relative', color: tab === k ? 'var(--ink)' : 'var(--ink-faint)' }}>
              {l}
              {tab === k && <span style={{ position: 'absolute', left: 0, right: 0, bottom: -1, height: 2, background: 'var(--gold)' }} />}
            </button>
          ))}
        </div>
        <div style={{ maxWidth: 680, fontSize: 16, lineHeight: 1.75, color: 'var(--ink-soft)' }}>
          {tab === 'desc' && <p>{p.desc} Every listing is checked against what actually ships — what you see on this page is what arrives.</p>}
          {tab === 'ship' && <p>{cat?.dispatch}. Delivery is nationwide, resolved live through Shipbubble with tracking from your account; orders over {BB.fmt(BB.BRAND.shipping.freeThreshold, BB.BRAND.currency.primary.code)} ship free. {isVehicle ? 'Vehicles are handed over in person after your inspection — no courier involved.' : ''} See our <button className="link-u" style={{ color: 'var(--gold-deep)' }} onClick={() => nav('policy', { id: 'shipping' })}>Shipping Policy</button>.</p>}
          {tab === 'ret' && <p>{isVehicle ? 'Vehicles: inspect before handover — full refund if the car fails your inspection. After handover, sales are final.' : p.cat === 'food' ? 'Food items are non-returnable once seals are broken, but anything that arrives damaged or short-dated is replaced or refunded — send a photo within 48 hours.' : p.cat === 'beauty' ? 'For hygiene, beauty items are returnable within 7 days only if unopened and sealed. Damaged arrivals are replaced promptly.' : 'Returnable within 7 days of delivery, unused and in original packaging.'} Full detail in our <button className="link-u" style={{ color: 'var(--gold-deep)' }} onClick={() => nav('policy', { id: 'returns' })}>Returns Policy</button>.</p>}
        </div>
      </div>

      {/* related */}
      {related.length > 0 && (
        <section style={{ background: 'var(--cream-deep)', borderTop: '1px solid var(--line)' }}>
          <div className="container wide" style={{ padding: 'clamp(56px,8vw,100px) var(--gutter)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', flexWrap: 'wrap', gap: 12, marginBottom: 36 }}>
              <h2 style={{ fontSize: 'clamp(30px,4.5vw,50px)' }}>More in {cat?.name}</h2>
              <button className="link-u" style={{ fontSize: 14, fontWeight: 600 }} onClick={() => nav('shop', { cat: p.cat })}>View all →</button>
            </div>
            <div className="prod-grid">
              {related.map((r, i) => <ProductCard key={r.id} p={r} delay={(i % 4) + 1} />)}
            </div>
          </div>
        </section>
      )}
    </div>
  );
}

Object.assign(window, { ProductPage });
