/* ============================================================ PRODUCT (PDP) ============================================================ */
function Accordion({ items, defaultOpen=0 }){
  const [open,setOpen] = useState(defaultOpen);
  return (
    <div className="acc">
      {items.map((it,i)=>(
        <div key={i} className={`acc__item ${open===i?'is-open':''}`}>
          <button className="acc__head" onClick={()=>setOpen(open===i?-1:i)}>
            <span>{it.q}</span><span className="acc__sign"><Icon name="chevD" size={18}/></span>
          </button>
          <div className="acc__panel"><div className="acc__inner">{it.a}</div></div>
        </div>
      ))}
    </div>
  );
}

function CertCard({ p }){
  const [flip,setFlip] = useState(false);
  return (
    <button className={`cert ${flip?'is-flip':''}`} onClick={()=>setFlip(f=>!f)} aria-label="View authenticity details">
      <div className="cert__inner">
        <div className="cert__face cert__front">
          <span className="cert__seal"><Icon name="cert" size={26}/></span>
          <b>Authenticity Details</b>
          <span className="cert__hint">Tap to view product notes</span>
        </div>
        <div className="cert__face cert__back">
          <div className="cert__doc">
            <div className="cert__doc-top">
              <Logo size={0.62}/>
              <span className="badge badge-gold">Prepared</span>
            </div>
            <div className="cert__doc-title deva">प्रमाण पत्र</div>
            <div className="cert__doc-title2">Certificate-ready product details</div>
            <div className="cert__rows">
              <div><span>Item</span><b>{p.name}</b></div>
              <div><span>Stone</span><b>{p.origin}</b></div>
              <div><span>Nature</span><b>Natural · Untreated</b></div>
              <div><span>Spec</span><b>{p.size}</b></div>
              <div><span>Reference</span><b>RR-{p.id.slice(0,3).toUpperCase()}-{String(p.id.length).padStart(2,'0')}</b></div>
            </div>
            <div className="cert__sign"><span className="cert__signline">Rudraa Ratna · Noida</span><span className="cert__stamp">ॐ</span></div>
          </div>
        </div>
      </div>
    </button>
  );
}

function ProductNotFound({ id }){
  const { go } = useContext(Nav);
  const label = id ? id.replace(/-/g, ' ') : 'this product';
  return (
    <main className="pdp">
      <Breadcrumb items={[{label:'Home',page:'home'},{label:'Shop',page:'shop'},{label:'Product not found'}]}/>
      <section className="section">
        <div className="wrap">
          <Reveal className="section-head center">
            <span className="eyebrow no-rule">Product Not Found</span>
            <h1 className="h1" style={{ marginTop:10 }}>We could not find {label}.</h1>
            <p>It may be unavailable, renamed, or awaiting updated product details. Message Rudraa Ratna on WhatsApp for current availability and documentation where applicable.</p>
            <div className="row gap4 wrapflex center mt6" style={{ justifyContent:'center' }}>
              <button className="btn btn-maroon btn-lg" onClick={()=>go('shop')}>Browse Shop <Icon name="arrow" size={17}/></button>
              <a className="btn btn-wa btn-lg" href={RR.wa("Hi Rudraa Ratna, I could not find "+label+". Please share current availability and guidance.")} target="_blank" rel="noopener"><WaGlyph/> Ask on WhatsApp</a>
            </div>
          </Reveal>
        </div>
      </section>
      <PageAnswers page="contact"/>
      <TrustDisclaimer/>
    </main>
  );
}

function ProductPage({ params={} }){
  const p = RR.byId(params.id);
  return p ? <ProductDetail p={p}/> : <ProductNotFound id={params.id}/>;
}

function ProductDetail({ p }){
  const { go } = useContext(Nav);
  const [view,setView] = useState('product');
  const [qty,setQty] = useState(1);
  const related = RR.PRODUCTS.filter(x=>x.id!==p.id && (x.cat===p.cat || x.purposes.some(pp=>p.purposes.includes(pp)))).slice(0,4);

  useEffect(()=>{ setView('product'); setQty(1); },[p.id]);

  const decision = [
    { ic:'spark', t:'What it is', d:p.whatItIs },
    { ic:'hand', t:'Who should use it', d:p.whoFor },
    { ic:'leaf', t:'Traditional benefit', d:p.benefit },
    { ic:'clock', t:'How to use', d:p.howToUse },
  ];

  return (
    <main className="pdp">
      <Breadcrumb items={[{label:'Home',page:'home'},{label:'Shop',page:'shop'},{label:p.catLabel,page:'shop',params:{cat:p.cat}},{label:p.name}]}/>

      <div className="wrap pdp__top">
        {/* gallery */}
        <div className="pdp__gallery">
          <div className="pdp__stage">
            {view==='product' && <div className="pdp__plinth">{p.image ? <img className="prod-img" src={rrImgSrc(p.image)} alt={rrProductAlt(p)} loading="eager" decoding="async" style={{width:'88%',borderRadius:'14px'}}/> : <GemArt stone={p.stone} form={p.form} size={380}/>}</div>}
            {view==='detail' && <div className="pdp__plinth pdp__plinth--zoom">{p.image ? <img className="prod-img" src={rrImgSrc(p.image)} alt={`${p.name} detail - Rudraa Ratna`} loading="lazy" decoding="async" style={{width:'96%',borderRadius:'14px'}}/> : <GemArt stone={p.stone} form={p.form==='bracelet'?'bead':p.form} size={420}/>}</div>}
            {view==='cert' && <div className="pdp__certview"><CertCard p={p}/></div>}
            <div className="pdp__stage-badges">
              {p.badges?.includes('certified') && <span className="badge badge-gold">Certificate-ready</span>}
              {p.off>=20 && <span className="badge badge-sale">{p.off}% off</span>}
            </div>
          </div>
          <div className="pdp__thumbs">
            {[
              { k:'product', label:'Product', node:<ProductVisual p={p} size={66}/> },
              { k:'detail', label:'Detail', node:p.image ? <ProductVisual p={p} size={66}/> : <GemArt stone={p.stone} form={p.form==='bracelet'?'bead':p.form} size={66}/> },
              { k:'cert', label:'Details', node:<span className="pdp__thumb-cert"><Icon name="cert" size={26}/></span> },
            ].map(t=>(
              <button key={t.k} className={`pdp__thumb ${view===t.k?'is-active':''}`} onClick={()=>setView(t.k)}>
                {t.node}<span>{t.label}</span>
              </button>
            ))}
          </div>
        </div>

        {/* info */}
        <div className="pdp__info">
          <div className="pdp__cat">{p.catLabel} · <span className="deva">{p.deva}</span></div>
          <h1 className="h1 pdp__name">{p.name}</h1>
          <div className="pdp__rate"><Icon name="cert" size={17}/><span>Verified reviews will be shown when available</span></div>
          <p className="pdp__tag lead">{p.tagline}</p>

          <div className="pdp__price">
            <span className="pdp__now">{RR.fmt(p.price)}</span>
            <span className="pdp__was">{RR.fmt(p.mrp)}</span>
            <span className="badge badge-leaf">You save {RR.fmt(p.mrp-p.price)}</span>
          </div>
          <div className="pdp__purposes">
            {p.purposes.map(pp=>(
              <button key={pp} className="pdp__ptag" onClick={()=>go('shop',{purpose:pp})}><PurposeGlyph glyph={RR.purpose(pp).glyph} size={16}/> {RR.purpose(pp).label}</button>
            ))}
          </div>

          {p.consultFirst && (
            <div className="pdp__consult-note"><Icon name="hand" size={20}/><div><b>Worn on recommendation.</b> This gemstone is best chosen after a quick consultation — it's free.</div></div>
          )}

          <div className="pdp__meta">
            <div><span>Specification</span><b>{p.size}</b></div>
            <div><span>Authenticity</span><b>{p.origin} · Natural</b></div>
          </div>

          <div className="pdp__buy">
            <div className="pdp__qty">
              <button onClick={()=>setQty(q=>Math.max(1,q-1))} aria-label="Decrease">–</button>
              <span>{qty}</span>
              <button onClick={()=>setQty(q=>q+1)} aria-label="Increase">+</button>
            </div>
            <button className="btn btn-maroon btn-lg pdp__buybtn"><Icon name="cart" size={18}/> {p.consultFirst?'Reserve':'Buy now'} · {RR.fmt(p.price*qty)}</button>
          </div>
          <a className="btn btn-wa btn-lg btn-block" href={p.waLink} target="_blank" rel="noopener"><WaGlyph/> Ask price &amp; guidance on WhatsApp</a>

          <div className="pdp__assure">
            <div><Icon name="cert" size={19}/> <span>Certificate where applicable</span></div>
            <div><Icon name="truck" size={19}/> <span>Pan-India delivery</span></div>
            <div><Icon name="shield" size={19}/> <span>Energised & cleansed</span></div>
          </div>
        </div>
      </div>

      {/* DECISION-LED DETAIL */}
      <section className="section tight">
        <div className="wrap">
          <Reveal className="section-head"><span className="eyebrow">Decide with clarity</span><h2 className="h2">Everything you need to know</h2></Reveal>
          <div className="decision-grid mt8">
            {decision.map((d,i)=>(
              <Reveal key={i} className="decision card" delay={i*0.06}>
                <span className="decision__ic"><Icon name={d.ic} size={22}/></span>
                <h3 className="h3">{d.t}</h3>
                <p>{d.d}</p>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      {/* AUTHENTICITY REVEAL */}
      <section className="section auth-sec">
        <div className="wrap">
          <Reveal className="section-head center"><span className="eyebrow no-rule">Proof, not promises</span><h2 className="h2">How we check authenticity</h2><p>The market includes dyed glass, coated stones and unclear product listings. Here is how Rudraa Ratna checks your {p.name} before guidance or dispatch.</p></Reveal>
          <div className="auth-sec__grid mt10">
            <Reveal className="auth-sec__compare">
              <div className="fr-mini">
                <div className="fr-mini__stage">
                  <div className="fr-side fr-real"><GemArt stone={p.stone} form={p.form} size={220}/><span className="fr-tag fr-tag--real"><Icon name="check" size={13}/> Genuine {p.name.split(' ')[0]}</span></div>
                  <FRClip stone={p.stone} form={p.form}/>
                </div>
                <p className="fr-mini__cap muted">Drag the handle — real stones hold deep, living colour; fakes look flat, glassy and over-bright.</p>
              </div>
            </Reveal>
            <Reveal className="auth-sec__side" delay={0.1}>
              <CertCard p={p}/>
              <ul className="auth-markers">
                <li><span className="am-num">01</span><div><b>Look</b> — {p.authentic}</div></li>
                <li><span className="am-num">02</span><div><b>Certificate</b> — supplied where applicable, with product specification and authentication details.</div></li>
                <li><span className="am-num">03</span><div><b>Still unsure?</b> Send us a photo on WhatsApp and we'll verify it with you.</div></li>
              </ul>
              <a className="btn btn-wa btn-block" href={RR.wa("Hi Rudraa Ratna, can you confirm the authenticity of the "+p.name+"?")} target="_blank" rel="noopener"><WaGlyph/> Verify on WhatsApp</a>
            </Reveal>
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section className="section tight" style={{ background:'var(--ivory-2)', borderBlock:'1px solid var(--line)' }}>
        <div className="wrap pdp__faq">
          <Reveal className="section-head"><span className="eyebrow">Questions</span><h2 className="h2">Before you buy</h2><p className="muted">Couldn't find your answer? <a className="link-underline" href={p.waLink} target="_blank" rel="noopener">Ask us directly</a>.</p></Reveal>
          <div className="mt6"><Accordion items={p.faqs}/></div>
        </div>
      </section>

      <BeforeYouBuySection/>
      <PageAnswers page="product" product={p}/>
      <TrustDisclaimer/>

      {/* RELATED */}
      <section className="section">
        <div className="wrap">
          <Reveal className="section-head"><span className="eyebrow">You may also like</span><h2 className="h2">Pairs beautifully with</h2></Reveal>
          <div className="prod-grid mt8">{related.map((r,i)=><ProductCard key={r.id} p={r} delay={i*0.06}/>)}</div>
        </div>
      </section>

      {/* sticky mobile buy bar */}
      <div className="pdp__sticky">
        <div className="pdp__sticky-price"><b>{RR.fmt(p.price)}</b><span>{RR.fmt(p.mrp)}</span></div>
        <a className="btn btn-wa btn-sm" href={p.waLink} target="_blank" rel="noopener"><WaGlyph size={16}/> WhatsApp</a>
        <button className="btn btn-maroon btn-sm"><Icon name="cart" size={16}/> {p.consultFirst?'Reserve':'Buy'}</button>
      </div>
    </main>
  );
}

/* fake side with its own slider (clip controlled) */
function FRClip({ stone, form }){
  const [pos,setPos] = useState(54);
  return (
    <React.Fragment>
      <div className="fr-side fr-fake" style={{ clipPath:`inset(0 0 0 ${pos}%)` }}>
        <div className="fr-fake-art"><GemArt stone={stone} form={form} size={220}/></div>
        <span className="fr-tag fr-tag--fake">Imitation / coated</span>
      </div>
      <div className="fr-handle" style={{ left:pos+'%' }}><span><Icon name="chevR" size={14}/><Icon name="chevR" size={14} style={{transform:'rotate(180deg)'}}/></span></div>
      <input className="fr-range" type="range" min="6" max="94" value={pos} onChange={e=>setPos(+e.target.value)} aria-label="Compare real vs fake"/>
    </React.Fragment>
  );
}

Object.assign(window, { ProductPage, ProductDetail, ProductNotFound, Accordion, CertCard, FRClip });
