function Accordion({title,children,defaultOpen}){
  const [open,setOpen]=React.useState(!!defaultOpen);
  return (
    <div style={{borderBottom:'1px solid var(--border-soft)'}}>
      <button onClick={()=>setOpen(!open)} style={{width:'100%',display:'flex',justifyContent:'space-between',alignItems:'center',padding:'18px 0',background:'none',border:'none',cursor:'pointer',fontSize:14,letterSpacing:'var(--tracking-wide)',textTransform:'uppercase',color:'var(--text-primary)'}}>
        {title}<i data-lucide={open?'minus':'plus'} style={{width:16,height:16}}></i>
      </button>
      {open&&<div style={{paddingBottom:20,fontSize:15,lineHeight:1.8,color:'var(--text-secondary)'}}>{children}</div>}
    </div>
  );
}
function ProductUnavailable(){
  return (
    <div style={{maxWidth:520,margin:'0 auto',padding:'var(--space-8) var(--container-pad)',textAlign:'center'}}>
      <H2 style={{marginBottom:16}}>This creation is no longer available.</H2>
      <a href="Collections.html" style={{textDecoration:'none'}}><PrimaryButton>Continue Shopping</PrimaryButton></a>
    </div>
  );
}
function Product(){
  const params=new URLSearchParams(location.search);
  const p=productBySlug(params.get('id'));
  if(!p)return <ProductUnavailable/>;
  const [active,setActive]=React.useState(0);
  const [size,setSize]=React.useState('Free Size');
  const [qty,setQty]=React.useState(1);
  const [wished,setWished]=React.useState(false);
  const [added,setAdded]=React.useState(false);
  const [zoom,setZoom]=React.useState({x:50,y:50,on:false});
  const [stock,setStock]=React.useState(null);
  const [viewerOpen,setViewerOpen]=React.useState(false);
  const [cartMsg,setCartMsg]=React.useState('');
  React.useEffect(()=>{
    document.title=`${p.name} — Bold Bee`;
    BB_STORE.pushRecent(p.id);
    setWished(BB_STORE.isWished(p.id));
    setStock(stockInfo(p.id));
    const tpl=FitStore.templateFor(p);
    setSize(tpl.hasSizeSelector?(tpl.sizes[2]||tpl.sizes[0]):'Free Size');
    if(window.lucide)window.lucide.createIcons();
  },[p.id]);
  const related=PRODUCTS.filter(x=>x.collection===p.collection&&x.id!==p.id).slice(0,3);
  const recent=BB_STORE.getRecent().filter(id=>id!==p.id).map(productBySlug).filter(Boolean).slice(0,4);
  const idx=PRODUCTS.findIndex(x=>x.id===p.id);
  const prevP=PRODUCTS[(idx-1+PRODUCTS.length)%PRODUCTS.length];
  const nextP=PRODUCTS[(idx+1)%PRODUCTS.length];
  React.useEffect(()=>{
    const schema={
      "@context":"https://schema.org",
      "@graph":[
        {"@type":"Product",name:p.name,description:productSchemaDescription(p),image:photo(p.imgs[0],1200),sku:p.id,offers:{"@type":"Offer",price:p.price,priceCurrency:"INR",availability:"https://schema.org/InStock",url:location.href}},
        {"@type":"BreadcrumbList",itemListElement:[
          {"@type":"ListItem",position:1,name:"Home",item:"index.html"},
          {"@type":"ListItem",position:2,name:"Shop",item:"Collections.html"},
          {"@type":"ListItem",position:3,name:categoryLabel(p),item:`Collections.html?weave=${encodeURIComponent(categoryLabel(p))}`},
          {"@type":"ListItem",position:4,name:p.name}
        ]}
      ]
    };
    let el=document.getElementById('bb-schema');
    if(!el){el=document.createElement('script');el.type='application/ld+json';el.id='bb-schema';document.head.appendChild(el);}
    el.textContent=JSON.stringify(schema);
    function setMeta(name,content,attr){ let m=document.querySelector(`meta[${attr}="${name}"]`); if(!m){m=document.createElement('meta');m.setAttribute(attr,name);document.head.appendChild(m);} m.setAttribute('content',content); }
    const shortDesc=productSchemaDescription(p);
    setMeta('og:title',`${p.name} — Bold Bee`,'property');
    setMeta('og:description',shortDesc,'property');
    setMeta('og:image',photo(p.imgs[0],1200),'property');
    setMeta('og:url',location.href,'property');
    setMeta('twitter:title',`${p.name} — Bold Bee`,'name');
    setMeta('twitter:description',shortDesc,'name');
    setMeta('twitter:image',photo(p.imgs[0],1200),'name');
  },[p.id]);
  const oos=stock&&stock.status==='out-of-stock';
  const low=stock&&(stock.status==='low-stock'||stock.status==='critical');
  const maxQty=stock?Math.max(0,stock.availableStock):undefined;
  function addToCart(){
    if(oos)return;
    const fresh=stockInfo(p.id);
    setStock(fresh);
    if(fresh.availableStock<=0){setCartMsg('This item is currently out of stock.');return;}
    const result=BB_STORE.addToCart(p.id,size,qty);
    if(result.adjusted){
      setQty(Math.max(1,result.availableStock));
      setCartMsg(`Only ${result.availableStock} item${result.availableStock===1?'':'s'} ${result.availableStock===1?'is':'are'} currently available. Your bag has been adjusted accordingly.`);
    }else{
      setCartMsg('');
      setAdded(true);setTimeout(()=>setAdded(false),2200);
    }
  }
  return (
    <div>
      <Breadcrumbs trail={[{label:'Home',href:'index.html'},{label:'Shop',href:'Collections.html'},{label:categoryLabel(p),href:`Collections.html?weave=${encodeURIComponent(categoryLabel(p))}`},{label:p.name}]}/>
      <div style={{maxWidth:'var(--container-max)',margin:'0 auto',padding:'var(--space-7) var(--container-pad)',display:'grid',gridTemplateColumns:'1fr 1fr',gap:56}}>
        <div>
          <div onClick={()=>setViewerOpen(true)} style={{aspectRatio:'4/5',borderRadius:'var(--radius-lg)',overflow:'hidden',marginBottom:16,cursor:'pointer'}}>
            <img src={photo(p.imgs[active],1600)} alt={p.name} style={{width:'100%',height:'100%',objectFit:'cover'}}/>
          </div>
          <div style={{display:'flex',gap:12}}>
            {p.imgs.map((im,i)=>(<button key={i} onClick={()=>setActive(i)} style={{width:76,height:96,borderRadius:'var(--radius-md)',overflow:'hidden',border:active===i?'2px solid var(--gold-deep)':'1px solid var(--border-soft)',padding:0,cursor:'pointer'}}><img src={photo(im,300)} alt="" style={{width:'100%',height:'100%',objectFit:'cover'}}/></button>))}
          </div>
        </div>
        <div>
          <Eyebrow>{categoryLabel(p)}</Eyebrow>
          <h1 style={{fontFamily:'var(--font-serif)',fontWeight:400,fontSize:'clamp(28px,3vw,40px)',margin:'0 0 8px',color:'var(--text-primary)'}}>{p.name}</h1>
          <div style={{fontSize:14,color:'var(--text-muted)',marginBottom:16}}>{p.sub}</div>
          <div style={{fontSize:22,color:'var(--text-primary)',marginBottom:12}}>{money(p.price)}</div>
          {oos&&<div style={{display:'inline-block',fontSize:12,letterSpacing:'0.05em',textTransform:'uppercase',color:'#9A4A3C',background:'#F2E4E1',padding:'6px 12px',borderRadius:'var(--radius-pill)',marginBottom:20}}>Out of Stock</div>}
          {!oos&&low&&<div style={{display:'inline-block',fontSize:12,letterSpacing:'0.05em',textTransform:'uppercase',color:'#9A4A3C',background:'#F2E4E1',padding:'6px 12px',borderRadius:'var(--radius-pill)',marginBottom:20}}>Only {stock.availableStock} Left in Stock</div>}
          <FitSizeAndGuide product={p} size={size} setSize={setSize}/>
          <div style={{display:'flex',gap:16,alignItems:'center',marginBottom:28}}>
            <QtyStepper qty={qty} onChange={setQty} min={1} max={maxQty}/>
            <PrimaryButton onClick={addToCart} disabled={oos} style={{flex:1}}>{oos?'Out of Stock':(added?'Added to Bag':'Add to Bag')}</PrimaryButton>
            <button onClick={()=>{BB_STORE.toggleWishlist(p.id);const nowWished=BB_STORE.isWished(p.id);setWished(nowWished);if(nowWished)triggerCollectionToast('Added to My Collection');}} aria-label="Add to My Collection" style={{width:52,height:52,border:'1px solid var(--border-default)',borderRadius:'var(--radius-md)',background:'none',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center'}}>
              <i data-lucide="heart" style={{width:18,height:18,color:wished?'var(--gold-deep)':'var(--text-primary)'}}></i>
            </button>
          </div>
          {cartMsg&&<p style={{fontSize:13,color:'#9A4A3C',marginTop:-16,marginBottom:20}}>{cartMsg}</p>}
          {typeof ShareSheet!=='undefined'&&<ShareSheet product={p} url={location.href}/>}
          <Accordion title="Description" defaultOpen={true}>{productBlurb(p)}</Accordion>
          {(!p.category||p.category==='sarees')&&<Accordion title="Fabric & Care">100% pure silk. Dry clean only. Store folded in muslin, away from direct light. Iron on reverse at low heat.</Accordion>}
          <Accordion title="Shipping & Returns">Complimentary shipping across India, dispatched in 5–7 days. Returns accepted within 7 days of delivery, unworn and with tags attached.</Accordion>
        </div>
      </div>
      {typeof CreationChronicle!=='undefined'&&<CreationChronicle product={p}/>}
      {typeof ReviewsSection!=='undefined'&&<ReviewsSection product={p}/>}
      {related.length>0&&(
        <div style={{maxWidth:'var(--container-max)',margin:'0 auto',padding:'0 var(--container-pad) var(--space-section)'}}>
          <Eyebrow>You May Also Like</Eyebrow>
          <H2 style={{marginBottom:32}}>From the Same Weave</H2>
          <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:28}}>{related.map(r=>(<ProductTile key={r.id} p={r}/>))}</div>
        </div>
      )}
      {recent.length>0&&(
        <div style={{maxWidth:'var(--container-max)',margin:'0 auto',padding:'0 var(--container-pad) var(--space-section)'}}>
          <Eyebrow>Recently Viewed</Eyebrow>
          <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:24}}>{recent.map(r=>(<ProductTile key={r.id} p={r}/>))}</div>
        </div>
      )}
      <div style={{maxWidth:'var(--container-max)',margin:'0 auto',padding:'0 var(--container-pad) var(--space-section)',display:'flex',justifyContent:'space-between',borderTop:'1px solid var(--border-soft)',paddingTop:32}}>
        <a href={`Product.html?id=${prevP.id}`} rel="prev" style={{textDecoration:'none',fontSize:13,letterSpacing:'var(--tracking-wide)',textTransform:'uppercase',color:'var(--gold-deep)'}}>← {prevP.name}</a>
        <a href={`Product.html?id=${nextP.id}`} rel="next" style={{textDecoration:'none',fontSize:13,letterSpacing:'var(--tracking-wide)',textTransform:'uppercase',color:'var(--gold-deep)'}}>{nextP.name} →</a>
      </div>
      <div style={{position:'fixed',left:0,right:0,bottom:0,background:'var(--white)',borderTop:'1px solid var(--border-soft)',padding:'14px var(--container-pad)',display:'flex',justifyContent:'space-between',alignItems:'center',zIndex:20}}>
        <div><div style={{fontFamily:'var(--font-serif)',fontSize:16}}>{p.name}</div><div style={{fontSize:14,color:'var(--text-muted)'}}>{money(p.price)}</div></div>
        <PrimaryButton onClick={addToCart} disabled={oos}>{oos?'Out of Stock':(added?'Added':'Add to Bag')}</PrimaryButton>
      </div>
      <div style={{height:80}}></div>
      {viewerOpen&&typeof LuxuryImageViewer!=='undefined'&&<LuxuryImageViewer imgs={p.imgs} index={active} onIndexChange={setActive} onClose={()=>setViewerOpen(false)} alt={p.name}/>}
    </div>
  );
}
window.Product=Product;
