/* ============================================================
   PRODUCT DETAIL PAGE
   ============================================================ */

/* On-site “Request a quote” form for price-on-enquiry pieces */
function QuoteForm({ p }) {
  const { toast } = useStore();
  const [sent, setSent] = useState(false);
  const [f, setF] = useState({ name: '', email: '', phone: '', qty: '', msg: '' });
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  const ref = React.useMemo(() => BB.BRAND.orderPrefix + '-' + Math.floor(100000 + Math.random() * 900000), []);
  if (sent) return (
    <div style={{ marginTop: 26, background: 'var(--sage-soft)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: 26, textAlign: 'center' }}>
      <div style={{ width: 54, height: 54, borderRadius: 100, background: 'var(--sage)', color: '#fff', display: 'grid', placeItems: 'center', margin: '0 auto 14px' }}><I.check width={26} height={26} /></div>
      <h3 style={{ fontSize: 22, marginBottom: 6 }}>Quote request received</h3>
      <p style={{ fontSize: 14.5, color: 'var(--ink-soft)', lineHeight: 1.6 }}>Thank you — your reference is <strong style={{ color: 'var(--ink)' }}>{ref}</strong>. We'll get back to you with a price for <strong>{p.name}</strong>. Payment details are shared when your order is confirmed.</p>
    </div>
  );
  const submit = (e) => { e.preventDefault(); if (!f.name.trim() || !f.email.includes('@')) return; setSent(true); toast('Quote request sent ✿', 'heart'); };
  return (
    <form onSubmit={submit} style={{ marginTop: 26, background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: 24, display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div>
        <p className="eyebrow" style={{ marginBottom: 4 }}>Made to order</p>
        <h3 style={{ fontSize: 22 }}>Request a quote</h3>
        <p style={{ fontSize: 13.5, color: 'var(--ink-soft)', marginTop: 4 }}>Tell us what you need and we'll send you a price for this piece.</p>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <div className="field"><label>Name</label><input className="input" value={f.name} onChange={e => set('name', e.target.value)} required /></div>
        <div className="field"><label>Email</label><input type="email" className="input" value={f.email} onChange={e => set('email', e.target.value)} required /></div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <div className="field"><label>Phone (optional)</label><input className="input" value={f.phone} onChange={e => set('phone', e.target.value)} placeholder="+234 …" /></div>
        <div className="field"><label>Quantity</label><input className="input" value={f.qty} onChange={e => set('qty', e.target.value)} placeholder="e.g. 2 bundles" /></div>
      </div>
      <div className="field"><label>Details</label><textarea className="input" rows="3" value={f.msg} onChange={e => set('msg', e.target.value)} placeholder="Colours, names / marks, timeline…" /></div>
      <button className="btn btn-gold btn-block btn-lg" type="submit">Request a quote</button>
      <p className="muted" style={{ fontSize: 12.5, textAlign: 'center' }}>Made to order · we reply with a price · no payment now</p>
    </form>
  );
}

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' }}>
            {p.poa ? (
              <span style={{ fontFamily: 'var(--serif)', fontSize: 34, fontStyle: 'italic' }}>Price on enquiry</span>
            ) : (
              <>
                <span style={{ fontFamily: 'var(--serif)', fontSize: 40 }}>{money(p.price)}</span>
                <span className="muted" style={{ fontSize: 14 }}>≈ {BB.fmt(p.price, currency === BB.BRAND.currency.primary.code ? BB.BRAND.currency.secondary.code : BB.BRAND.currency.primary.code)}</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 */}
          {p.poa ? (
            <QuoteForm p={p} />
          ) : (
            <>
              <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, 'Nationwide delivery'], [I.gift, '100% soft cotton'], [I.check, 'No fade nor fray']].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} Every piece is hand-dyed and checked before it's folded for you. Want a custom colour, name or quantity? Use the Request-a-quote form on any made-to-order piece.</p>}
          {tab === 'care' && <p>{p.care} Keep your adire out of prolonged direct sun to preserve the indigo. Care notes travel with every order.</p>}
          {tab === 'ship' && <p>Ready bundles are dispatched by tracked courier once your order is confirmed. Customized and traditional pieces are dyed to order, so we agree timing with you. See our <button className="link-u" style={{ color: 'var(--gold-deep)' }} onClick={() => nav('policy', { id: 'shipping' })}>Delivery 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 });
