/* ============================================================
   PRODUCT DETAIL PAGE
   ============================================================ */
function ProductPage({ params }) {
  const { nav, addToCart, money, currency, wish, toggleWish, setDrawer, placeOrder, toast } = 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][Math.min(1, p.opts[k].length - 1)]); 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][Math.min(1, p.opts[k].length - 1)]); setOpts(o);
  }, [params.id]);

  const cat = BB.categories.find(c => c.id === p.cat);
  const related = BB.products.filter(x => x.cat === p.cat && x.id !== p.id).slice(0, 4);
  const thumbs = IMG.gallery(p.id);
  const thumbVariants = IMG.gallery(p.id).length > 0 ? IMG.gallery(p.id) : [null,null,null,null];

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

  return (
    <div style={{ background: 'var(--cream)' }}>
      <div className="container wide" style={{ padding: 'clamp(20px,3vw,32px) var(--gutter) 0' }}>
        <p className="eyebrow" style={{ color: 'var(--ink-faint)' }}>
          <button onClick={() => nav('home')} className="link-u">Home</button> /{' '}
          <button onClick={() => nav('shop', { cat: p.cat })} className="link-u">{cat?.name}</button> /{' '}
          <span style={{ color: 'var(--ink-soft)' }}>{p.name}</span>
        </p>
      </div>

      <div className="container wide pdp-grid" style={{ padding: 'clamp(24px,3vw,40px) var(--gutter) clamp(56px,8vw,90px)' }}>
        {/* gallery */}
        <div className="pdp-gallery">
          <Ph src={thumbs[img]} label={`${p.name} — view ${img + 1}`} variant={thumbVariants[img]} style={{ aspectRatio: '4/5', borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-sm)' }} />
          <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={thumbVariants[i]} style={{ aspectRatio: '1' }} />
              </button>
            ))}
          </div>
        </div>

        {/* info */}
        <div className="pdp-info">
          <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
            {p.tags.includes('new') && <span className="badge badge-new">New in</span>}
          </div>
          <h1 style={{ fontSize: 'clamp(34px,4.5vw,54px)', lineHeight: 1.02 }}>{p.name}</h1>

          <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, margin: '22px 0 8px' }}>
            <span style={{ fontFamily: 'var(--serif)', fontSize: 40 }}>{money(p.price)}</span>
            <span className="muted" style={{ fontSize: 14 }}>≈ {BB.fmt(p.price, currency === 'NGN' ? 'USD' : 'NGN')}</span>
          </div>
          <p style={{ fontSize: 16.5, color: 'var(--ink-soft)', lineHeight: 1.7, marginTop: 14 }}>{p.desc}</p>

          {/* options */}
          {p.opts && Object.entries(p.opts).map(([key, vals]) => (
            <div key={key} style={{ marginTop: 24 }}>
              <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 */}
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginTop: 30, flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, border: '1.5px solid var(--line)', borderRadius: 100, padding: 5, background: 'var(--ivory)' }}>
              <button onClick={() => setQty(q => Math.max(1, q - 1))} style={{ width: 40, height: 40, display: 'grid', placeItems: 'center', borderRadius: 100 }}><I.minus width={16} height={16} /></button>
              <span style={{ minWidth: 30, textAlign: 'center', fontSize: 16 }}>{qty}</span>
              <button onClick={() => setQty(q => q + 1)} style={{ width: 40, height: 40, display: 'grid', placeItems: 'center', borderRadius: 100 }}><I.plus width={16} height={16} /></button>
            </div>
            <button className="btn btn-primary btn-lg" style={{ flex: '1 1 180px' }} onClick={() => { addToCart(p, qty, opts); setDrawer(true); }}>Add to cart · {money(p.price * 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: '18px auto 0', fontSize: 13.5, color: 'var(--ink-soft)' }}>
            <I.heart width={18} height={18} style={{ fill: liked ? 'var(--blush-deep)' : 'none', color: liked ? 'var(--blush-deep)' : 'var(--ink-soft)' }} /> {liked ? 'Saved to wishlist' : 'Add to wishlist'}
          </button>

          {/* trust mini */}
          <div style={{ display: 'flex', gap: 20, marginTop: 26, paddingTop: 24, borderTop: '1px solid var(--line)', flexWrap: 'wrap' }}>
            {[[I.truck, 'Processing takes 5–14 days'], [I.shield, 'Secure ₦ / $ checkout'], [I.gift, 'Gift wrap included']].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 / care */}
      <div className="container wide" style={{ paddingBottom: 'clamp(56px,8vw,90px)' }}>
        <div style={{ display: 'flex', gap: 4, borderBottom: '1px solid var(--line)', marginBottom: 28 }}>
          {[['desc', 'Details'], ['care', 'Craft & Care'], ['ship', 'Shipping']].map(([k, l]) => (
            <button key={k} 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} Each piece is hand-finished in our Lagos atelier and quality-checked before it's wrapped for you. Need a custom colour or quantity? Tell us in your order notes at checkout.</p>}
          {tab === 'care' && <p>{p.care} For bespoke or fragile items, retain the original packaging until your event. Detailed care notes are tucked inside every order.</p>}
          {tab === 'ship' && <p>Lagos orders dispatch within 3–5 working days; complimentary delivery over ₦150,000. International shipping to the UK, US, Canada and beyond is calculated at checkout with full tracking. See our <button className="link-u" style={{ color: 'var(--gold-deep)' }} onClick={() => nav('policy', { id: 'shipping' })}>Shipping Policy</button>.</p>}
        </div>
      </div>

      {/* related */}
      {related.length > 0 && (
        <section style={{ background: 'var(--cream-deep)' }}>
          <div className="container wide" style={{ padding: 'clamp(56px,8vw,100px) var(--gutter)' }}>
            <h2 style={{ fontSize: 'clamp(30px,4.5vw,50px)', marginBottom: 36 }}>You may also <em style={{ fontStyle: 'italic' }}>love</em></h2>
            <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 });
