/* AMBER & ZAFRAN — Product Detail Page */
function NoteRow({ label, note, lang, color }) {
  return (
    <div className="note-row">
      <div className="note-dot" style={{ background: color }}>{note[0][0]}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--serif)', fontSize: 16 }}>
          {note.map(n => lang === 'ar' ? n[1] : n[0]).join(lang === 'ar' ? ' · ' : ' · ')}
        </div>
      </div>
      <div style={{ fontFamily: 'var(--sans)', fontSize: 9, letterSpacing: '.2em', textTransform: 'uppercase', color: 'var(--gold-deep-on-light)' }}>{label}</div>
    </div>
  );
}

function PDP({ product: p, t, lang, go, addToCart, onOpen, wish, toggleWish }) {
  const [sizeIdx, setSizeIdx] = useState(0);
  const [qty, setQty] = useState(1);
  const [tab, setTab] = useState('story');
  const [galleryIdx, setGalleryIdx] = useState(0);
  const screenRef = useRef(null);
  const wished = wish.includes(p.id);
  const price = p.sizes[sizeIdx][1];

  // `p` itself arrives already loaded (passed in directly from whichever
  // ProductCard was tapped) — only "related products" needs its own
  // Supabase read, same same-category-first logic as the original mock.
  const [related, setRelated] = useState([]);
  useEffect(() => {
    let cancelled = false;
    AZCatalog.fetchAllProducts()
      .then((all) => {
        if (cancelled) return;
        setRelated(
          all.filter(x => x.id !== p.id && x.cat === p.cat)
            .concat(all.filter(x => x.id !== p.id && x.cat !== p.cat))
            .slice(0, 4)
        );
      })
      .catch((e) => console.error('PDP: failed to load related products', e));
    return () => { cancelled = true; };
  }, [p.id, p.cat]);

  // gallery "angles" rendered with different backgrounds
  const galleryBgs = [
    `linear-gradient(160deg,${p.top}22,${p.bot}33)`,
    'linear-gradient(160deg,#efe6da,#e2d4c4)',
    'radial-gradient(80% 80% at 50% 30%,#2a1116,#160a0d)',
  ];

  return (
    <div>
      {/* GALLERY */}
      <section style={{ position: 'relative', height: 540, background: galleryBgs[galleryIdx], display: 'grid', placeItems: 'center', overflow: 'hidden', transition: 'background .6s var(--ease)' }}>
        <div style={{ position: 'absolute', top: 70, left: '50%', transform: 'translateX(-50%)', fontFamily: 'var(--arabic-display)', fontSize: 120, color: galleryIdx === 2 ? 'rgba(255,255,255,.06)' : 'rgba(118,37,56,.06)', whiteSpace: 'nowrap', pointerEvents: 'none' }}>{p.ar}</div>
        <div style={{ transform: 'scale(1.7)' }}><Flacon p={p} /></div>
        <button
          className="wish" onClick={() => toggleWish(p.id)}
          aria-label={wished ? (lang === 'ar' ? 'إزالة من المفضّلة' : 'Remove from wishlist') : (lang === 'ar' ? 'إضافة إلى المفضّلة' : 'Add to wishlist')}
          aria-pressed={wished}
          style={{ position: 'absolute', top: 64, right: 22, width: 44, height: 44, color: wished ? 'var(--burgundy)' : 'var(--ink)' }}
        >{wished ? <Icon.heartFill /> : <Icon.heart />}</button>
        {/* angle thumbs */}
        <div style={{ position: 'absolute', bottom: 22, left: '50%', transform: 'translateX(-50%)', display: 'flex', gap: 10 }}>
          {galleryBgs.map((g, i) => (
            <button key={i} onClick={() => setGalleryIdx(i)} style={{ width: 48, height: 58, background: g, border: galleryIdx === i ? '1.5px solid var(--ink)' : '1px solid var(--line)', position: 'relative', overflow: 'hidden' }}>
              <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)' }}><Flacon p={p} scale={0.32} showLabel={false} /></div>
            </button>
          ))}
        </div>
      </section>

      {/* INFO */}
      <section style={{ padding: '34px 24px 8px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
          <div>
            <div className="kicker solo">{lang === 'ar' ? p.familyAr : p.family}</div>
            <h1 className="sec-title" style={{ fontSize: 40, marginTop: 12 }}>{lang === 'ar' ? p.ar : p.name}</h1>
            <div style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--arabic-display)', fontSize: 22, color: 'var(--burgundy)', marginTop: 6 }}>{lang === 'ar' ? p.name : p.ar}</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 16 }}>
          <Stars r={5} /><span style={{ fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '.1em', color: 'var(--ink-soft)' }}>{t.reviewsTab}</span>
        </div>
        <p className="lede" style={{ marginTop: 20 }}>{lang === 'ar' ? p.blurbAr : p.blurb}</p>

        {/* size */}
        <div style={{ marginTop: 30 }}>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 10, letterSpacing: '.22em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginBottom: 12 }}>{t.size}</div>
          <div style={{ display: 'flex', gap: 10 }}>
            {p.sizes.map((s, i) => (
              <button key={i} onClick={() => setSizeIdx(i)} style={{ flex: 1, padding: '14px 6px', textAlign: 'center', border: sizeIdx === i ? '1.5px solid var(--ink)' : '1px solid var(--line)', background: sizeIdx === i ? 'var(--ink)' : 'transparent', color: sizeIdx === i ? 'var(--white)' : 'var(--ink)', transition: 'all .3s var(--ease)' }}>
                <div style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--serif)', fontSize: 14 }}>{s[0]}</div>
                <div style={{ fontFamily: 'var(--sans)', fontSize: 11, marginTop: 5, opacity: .8 }}>{t.currency} {s[1]}</div>
              </button>
            ))}
          </div>
        </div>

        {/* qty + add */}
        <div style={{ display: 'flex', gap: 12, marginTop: 22, alignItems: 'stretch' }}>
          <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--line)' }}>
            <button onClick={() => setQty(q => Math.max(1, q - 1))} style={{ padding: '0 16px', height: '100%', display: 'grid', placeItems: 'center' }}><Icon.minus /></button>
            <span style={{ fontFamily: 'var(--serif)', fontSize: 18, minWidth: 24, textAlign: 'center' }}>{qty}</span>
            <button onClick={() => setQty(q => q + 1)} style={{ padding: '0 16px', height: '100%', display: 'grid', placeItems: 'center' }}><Icon.plus /></button>
          </div>
          <button className="btn btn-fill" style={{ flex: 1 }} onClick={() => addToCart(p, p.sizes[sizeIdx], qty)}>{t.addCart} · {t.currency} {price * qty}</button>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 16, fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 11, letterSpacing: lang === 'ar' ? 0 : '.1em', color: 'var(--ink-soft)' }}>
          <Icon.star style={{ color: 'var(--gold)' }} /> {t.freeNote}
        </div>
      </section>

      {/* NOTES PYRAMID */}
      <section style={{ background: 'var(--cream)', padding: '54px 24px', marginTop: 30 }}>
        <div className="sec-head" style={{ marginBottom: 8 }}>
          <div className="kicker solo">{t.notesK}</div>
          <h2 className="sec-title h-md">{t.notesT}</h2>
        </div>
        {/* pyramid visual */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, margin: '20px 0 30px' }}>
          {[['top', t.topN, p.top], ['heart', t.heartN, p.bot], ['base', t.baseN, '#3a1118']].map(([k, lbl, col], i) => (
            <div key={k} style={{ width: `${52 + i * 24}%`, height: 38, background: col, display: 'grid', placeItems: 'center' }}>
              <span style={{ fontFamily: 'var(--sans)', fontSize: 9, letterSpacing: '.24em', textTransform: 'uppercase', color: 'rgba(255,255,255,.92)' }}>{lbl}</span>
            </div>
          ))}
        </div>
        <NoteRow label={t.topN} note={p.notes.top} lang={lang} color={p.top} />
        <NoteRow label={t.heartN} note={p.notes.heart} lang={lang} color={p.bot} />
        <NoteRow label={t.baseN} note={p.notes.base} lang={lang} color={'#3a1118'} />
      </section>

      {/* STORY / CRAFT tabs */}
      <section style={{ padding: '48px 24px' }}>
        <div style={{ display: 'flex', gap: 24, borderBottom: '1px solid var(--line)', marginBottom: 24 }}>
          {[['story', t.detailsTab], ['craft', t.craftK], ['ing', t.ingK]].map(([k, lbl]) => (
            <button key={k} onClick={() => setTab(k)} style={{ paddingBottom: 14, fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: tab === k ? 'var(--ink)' : 'var(--ink-soft)', borderBottom: tab === k ? '1.5px solid var(--burgundy)' : '1.5px solid transparent', marginBottom: -1 }}>{lbl}</button>
          ))}
        </div>
        {tab === 'story' && <p className="body" style={{ fontSize: 16 }}>{lang === 'ar' ? p.blurbAr + ' ' + t.storyB : p.blurb + ' Composed in the Amman atelier, this fragrance is the lingering signature the house was built upon — patient, deliberate, and unmistakably its own.'}</p>}
        {tab === 'craft' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
            {[[lang === 'ar' ? 'الحصاد' : 'The Harvest', lang === 'ar' ? 'تُنتقى المكوّنات النادرة يدوياً في موسمها.' : 'Rare materials, hand-selected at the peak of season.'], [lang === 'ar' ? 'التعتيق' : 'The Ageing', lang === 'ar' ? 'تُعتّق التركيبة في براميل البلوط لأشهر.' : 'Aged in oak for months until the accord settles.'], [lang === 'ar' ? 'الختم' : 'The Seal', lang === 'ar' ? 'تُختم كل قارورة بالذهب يدوياً.' : 'Each flacon hand-finished and sealed in gold.']].map(([h, b], i) => (
              <div key={i} style={{ display: 'flex', gap: 18 }}>
                <span style={{ fontFamily: 'var(--serif)', fontSize: 28, color: 'var(--gold-deep-on-light)', lineHeight: 1 }}>{String(i + 1).padStart(2, '0')}</span>
                <div><div style={{ fontFamily: lang === 'ar' ? 'var(--arabic-display)' : 'var(--serif)', fontSize: 19 }}>{h}</div><p className="body" style={{ marginTop: 4 }}>{b}</p></div>
              </div>
            ))}
          </div>
        )}
        {tab === 'ing' && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
            {[...p.notes.top, ...p.notes.heart, ...p.notes.base].map((n, i) => (
              <span key={i} className="chip" style={{ cursor: 'default' }}>{lang === 'ar' ? n[1] : n[0]}</span>
            ))}
          </div>
        )}
      </section>

      {/* RATING — an overall guest rating only; no individual reviews, names, or quotes */}
      <section style={{ background: 'var(--black)', color: 'var(--white)', padding: '50px 24px', textAlign: 'center' }}>
        <div className="kicker solo center" style={{ justifyContent: 'center', color: 'var(--gold)' }}>{t.reviewsK}</div>
        <h2 className="sec-title h-md" style={{ color: 'var(--white)', marginTop: 10 }}>{t.reviewsTab}</h2>
        <div style={{ fontFamily: 'var(--serif)', fontSize: 56, color: 'var(--gold)', marginTop: 24, lineHeight: 1 }}>{t.overallRating}</div>
        <div style={{ marginTop: 14, display: 'flex', justifyContent: 'center' }}><Stars r={5} c="var(--gold)" /></div>
        <div style={{ fontFamily: lang === 'ar' ? 'var(--arabic)' : 'var(--sans)', fontSize: 11, letterSpacing: lang === 'ar' ? 0 : '.2em', textTransform: 'uppercase', color: 'rgba(253,253,253,.55)', marginTop: 16 }}>{t.reviewsCountPlaceholder}</div>
      </section>

      {/* RELATED */}
      <section className="sec">
        <div className="sec-head"><div className="kicker solo">{lang === 'ar' ? 'اكتشف أيضاً' : 'Discover'}</div><h2 className="sec-title h-md">{t.relatedT}</h2></div>
        <div className="hscroll">
          {related.map(rp => <div key={rp.id} style={{ width: 200 }}><ProductCard p={rp} lang={lang} t={t} onOpen={onOpen} wished={wish.includes(rp.id)} onWish={toggleWish} /></div>)}
        </div>
      </section>

      <Footer t={t} lang={lang} go={go} />
    </div>
  );
}

Object.assign(window, { PDP });
