function Stars({value,size,onChange}){
  size=size||16;
  return (
    <div style={{display:'inline-flex',gap:2}}>
      {[1,2,3,4,5].map(n=>(
        <i key={n} data-lucide="star" onClick={onChange?()=>onChange(n):undefined}
          style={{width:size,height:size,cursor:onChange?'pointer':'default',color:n<=value?'var(--gold-deep)':'var(--border-default)',fill:n<=value?'var(--gold-deep)':'none'}}></i>
      ))}
    </div>
  );
}
function RatingBar({star,count,total}){
  const pct=total?Math.round((count/total)*100):0;
  return (
    <div style={{display:'flex',alignItems:'center',gap:8,fontSize:12,color:'var(--text-muted)',marginBottom:4}}>
      <span style={{width:36}}>{star} star</span>
      <div style={{flex:1,height:4,background:'var(--border-soft)',borderRadius:2,overflow:'hidden'}}><div style={{width:pct+'%',height:'100%',background:'var(--gold-deep)'}}></div></div>
      <span style={{width:24,textAlign:'right'}}>{count}</span>
    </div>
  );
}
function MediaPicker({images,setImages,video,setVideo}){
  function onImg(e){
    const files=Array.from(e.target.files||[]).slice(0,5-images.length);
    files.forEach(f=>{
      if(f.size>10*1024*1024){alert(f.name+' exceeds the 10 MB image limit.');return;}
      setImages(prev=>prev.length>=5?prev:[...prev,{name:f.name,type:f.type,size:f.size,url:URL.createObjectURL(f)}]);
    });
    e.target.value='';
  }
  function onVid(e){
    const f=e.target.files&&e.target.files[0]; if(!f)return;
    if(f.size>50*1024*1024){alert('Video exceeds the 50 MB limit.');return;}
    setVideo({name:f.name,type:f.type,size:f.size,url:URL.createObjectURL(f)});
    e.target.value='';
  }
  return (
    <div style={{marginBottom:16}}>
      <div style={{fontSize:12,letterSpacing:'0.05em',textTransform:'uppercase',color:'var(--text-muted)',marginBottom:8}}>Photos &amp; Video (optional)</div>
      <div style={{display:'flex',gap:10,flexWrap:'wrap'}}>
        {images.map((im,i)=>(<div key={i} style={{position:'relative',width:64,height:64,borderRadius:'var(--radius-sm)',overflow:'hidden',border:'1px solid var(--border-soft)'}}>
          <img src={im.url} alt="" style={{width:'100%',height:'100%',objectFit:'cover'}}/>
          <button onClick={()=>setImages(images.filter((_,j)=>j!==i))} style={{position:'absolute',top:2,right:2,background:'rgba(31,31,31,.7)',color:'#fff',border:'none',borderRadius:'50%',width:18,height:18,fontSize:11,cursor:'pointer'}}>×</button>
        </div>))}
        {images.length<5&&(<label style={{width:64,height:64,border:'1px dashed var(--border-default)',borderRadius:'var(--radius-sm)',display:'flex',alignItems:'center',justifyContent:'center',cursor:'pointer',fontSize:22,color:'var(--text-muted)'}}>+<input type="file" accept=".jpg,.jpeg,.png,.webp" multiple onChange={onImg} style={{display:'none'}}/></label>)}
        {!video&&(<label style={{width:64,height:64,border:'1px dashed var(--border-default)',borderRadius:'var(--radius-sm)',display:'flex',alignItems:'center',justifyContent:'center',cursor:'pointer',fontSize:11,color:'var(--text-muted)',textAlign:'center',padding:4}}>+Video<input type="file" accept=".mp4,.mov" onChange={onVid} style={{display:'none'}}/></label>)}
        {video&&(<div style={{position:'relative',width:64,height:64,borderRadius:'var(--radius-sm)',overflow:'hidden',border:'1px solid var(--border-soft)',background:'var(--beige)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:10,color:'var(--text-muted)',textAlign:'center'}}>
          Video<button onClick={()=>setVideo(null)} style={{position:'absolute',top:2,right:2,background:'rgba(31,31,31,.7)',color:'#fff',border:'none',borderRadius:'50%',width:18,height:18,fontSize:11,cursor:'pointer'}}>×</button>
        </div>)}
      </div>
      <p style={{fontSize:11,color:'var(--text-muted)',marginTop:6}}>Up to 5 images (JPG/PNG/WEBP, 10MB each) and 1 video (MP4/MOV, 50MB).</p>
    </div>
  );
}
function WriteReviewModal({eligible,existing,onClose,onSaved}){
  const [rating,setRating]=React.useState(existing?existing.rating:5);
  const [title,setTitle]=React.useState(existing?existing.title:'');
  const [description,setDescription]=React.useState(existing?existing.description:'');
  const [pros,setPros]=React.useState(existing?existing.pros:'');
  const [cons,setCons]=React.useState(existing?existing.cons:'');
  const [recommend,setRecommend]=React.useState(existing?existing.recommend:true);
  const [images,setImages]=React.useState(existing?existing.images||[]:[]);
  const [video,setVideo]=React.useState(existing?existing.video||null:null);
  const [error,setError]=React.useState('');
  function submit(){
    if(!title.trim()||!description.trim()){setError('Please add a title and a short description.');return;}
    const user=BB_AUTH.currentUser();
    if(existing){
      const res=ReviewStore.update(existing.id,{rating,title:title.trim(),description:description.trim(),pros:pros.trim(),cons:cons.trim(),recommend,images,video});
      if(res&&res.error){setError(res.error);return;}
    }else{
      ReviewStore.submit({productId:eligible.productId,productName:eligible.productName,customerId:user.id,customerEmail:user.email,customerName:user.name,orderId:eligible.orderId,orderNumber:eligible.orderNumber,rating,title:title.trim(),description:description.trim(),pros:pros.trim(),cons:cons.trim(),recommend,images,video});
    }
    onSaved&&onSaved();
    onClose();
  }
  return (
    <div style={{position:'fixed',inset:0,background:'rgba(31,31,31,.55)',zIndex:300,display:'flex',alignItems:'center',justifyContent:'center',padding:24}} onClick={onClose}>
      <div style={{background:'var(--ivory)',maxWidth:520,width:'100%',maxHeight:'88vh',overflow:'auto',borderRadius:'var(--radius-lg)',padding:'32px'}} onClick={e=>e.stopPropagation()}>
        <h2 style={{fontFamily:'var(--font-serif)',fontWeight:400,fontSize:22,margin:'0 0 4px'}}>{existing?'Edit Your Review':'Write a Review'}</h2>
        <p style={{fontSize:13,color:'var(--text-muted)',marginBottom:20}}>{eligible?eligible.productName:existing.productName}</p>
        <div style={{marginBottom:16}}>
          <div style={{fontSize:12,letterSpacing:'0.05em',textTransform:'uppercase',color:'var(--text-muted)',marginBottom:6}}>Overall Rating</div>
          <Stars value={rating} size={24} onChange={setRating}/>
        </div>
        <input value={title} onChange={e=>setTitle(e.target.value)} maxLength={80} placeholder="Review title" style={{width:'100%',padding:'10px 12px',border:'1px solid var(--border-default)',borderRadius:'var(--radius-sm)',fontSize:14,marginBottom:12,fontFamily:'inherit'}}/>
        <textarea value={description} onChange={e=>setDescription(e.target.value)} maxLength={1500} placeholder="Share your experience with this piece…" style={{width:'100%',minHeight:100,padding:'10px 12px',border:'1px solid var(--border-default)',borderRadius:'var(--radius-sm)',fontSize:14,marginBottom:12,fontFamily:'inherit'}}></textarea>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginBottom:12}}>
          <input value={pros} onChange={e=>setPros(e.target.value)} placeholder="Pros (optional)" style={{padding:'10px 12px',border:'1px solid var(--border-default)',borderRadius:'var(--radius-sm)',fontSize:14,fontFamily:'inherit'}}/>
          <input value={cons} onChange={e=>setCons(e.target.value)} placeholder="Cons (optional)" style={{padding:'10px 12px',border:'1px solid var(--border-default)',borderRadius:'var(--radius-sm)',fontSize:14,fontFamily:'inherit'}}/>
        </div>
        <div style={{marginBottom:16,fontSize:13}}>
          <span style={{color:'var(--text-secondary)',marginRight:12}}>Would you recommend this?</span>
          <label style={{marginRight:16}}><input type="radio" checked={recommend===true} onChange={()=>setRecommend(true)}/> Yes</label>
          <label><input type="radio" checked={recommend===false} onChange={()=>setRecommend(false)}/> No</label>
        </div>
        <MediaPicker images={images} setImages={setImages} video={video} setVideo={setVideo}/>
        {error&&<p style={{fontSize:12,color:'#9A4A3C',marginBottom:12}}>{error}</p>}
        <div style={{display:'flex',gap:12}}>
          <PrimaryButton onClick={submit}>{existing?'Save Changes':'Submit Review'}</PrimaryButton>
          <button onClick={onClose} style={{border:'1px solid var(--border-default)',background:'none',borderRadius:'var(--radius-md)',padding:'12px 20px',fontSize:13,cursor:'pointer'}}>Cancel</button>
        </div>
      </div>
    </div>
  );
}
function ReviewCard({r,onHelpful,voted}){
  return (
    <div style={{borderBottom:'1px solid var(--border-soft)',padding:'24px 0'}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:8,flexWrap:'wrap',gap:8}}>
        <div>
          <Stars value={r.rating} size={14}/>
          <div style={{fontSize:15,fontWeight:600,color:'var(--text-primary)',marginTop:6}}>{r.title}</div>
        </div>
        {r.featured&&<span style={{fontSize:10,letterSpacing:'0.06em',textTransform:'uppercase',color:'var(--gold-deep)',border:'1px solid var(--gold-deep)',borderRadius:'var(--radius-pill)',padding:'4px 10px'}}>Featured Experience</span>}
      </div>
      <p style={{fontSize:14,color:'var(--text-secondary)',lineHeight:1.7,margin:'0 0 10px'}}>{r.description}</p>
      {(r.pros||r.cons)&&(
        <div style={{display:'flex',gap:24,fontSize:13,color:'var(--text-secondary)',marginBottom:10,flexWrap:'wrap'}}>
          {r.pros&&<span><strong style={{color:'var(--text-primary)'}}>Pros:</strong> {r.pros}</span>}
          {r.cons&&<span><strong style={{color:'var(--text-primary)'}}>Cons:</strong> {r.cons}</span>}
        </div>
      )}
      {(r.images&&r.images.length>0)&&(
        <div style={{display:'flex',gap:8,marginBottom:10,flexWrap:'wrap'}}>
          {r.images.map((im,i)=>(<img key={i} src={im.url} alt="" style={{width:64,height:64,objectFit:'cover',borderRadius:'var(--radius-sm)'}}/>))}
        </div>
      )}
      <div style={{display:'flex',alignItems:'center',gap:14,fontSize:12,color:'var(--text-muted)',flexWrap:'wrap'}}>
        <span>{r.customerName}</span>
        {r.verifiedPurchase&&<span style={{color:'var(--gold-deep)'}}>Verified Purchase</span>}
        <span>{new Date(r.createdDate).toLocaleDateString('en-IN',{year:'numeric',month:'short',day:'numeric'})}</span>
        <span>{r.recommend?'Recommends this product':'Does not recommend'}</span>
        <button onClick={()=>onHelpful(r.id)} disabled={voted} style={{border:'none',background:'none',cursor:voted?'default':'pointer',color:voted?'var(--text-muted)':'var(--gold-deep)',fontSize:12,padding:0}}>Helpful ({r.helpfulCount||0})</button>
      </div>
    </div>
  );
}
function ReviewsSection({product}){
  const [tick,setTick]=React.useState(0);
  const [sort,setSort]=React.useState('newest');
  const [verifiedOnly,setVerifiedOnly]=React.useState(false);
  const [withImages,setWithImages]=React.useState(false);
  const [showWrite,setShowWrite]=React.useState(false);
  const user=typeof BB_AUTH!=='undefined'?BB_AUTH.currentUser():null;
  const stats=ReviewStore.productStats(product.id);
  const list=ReviewStore.forProduct(product.id,{sort,verifiedOnly,withImages});
  const eligible=user?ReviewStore.canReview(user.id,user.email,product.id):null;
  const myVoterKey=user?(user.id||user.email):null;
  function helpful(id){ ReviewStore.voteHelpful(id,user&&user.id,user&&user.email); setTick(t=>t+1); }
  return (
    <div style={{maxWidth:'var(--container-max)',margin:'0 auto',padding:'0 var(--container-pad) var(--space-section)'}}>
      <Eyebrow>Customer Experience</Eyebrow>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end',marginBottom:32,flexWrap:'wrap',gap:16}}>
        <H2>Reviews</H2>
        {eligible&&<button onClick={()=>setShowWrite(true)} style={{border:'1px solid var(--gold-deep)',color:'var(--gold-deep)',background:'none',borderRadius:'var(--radius-md)',padding:'10px 20px',fontSize:13,letterSpacing:'var(--tracking-wide)',textTransform:'uppercase',cursor:'pointer'}}>Write a Review</button>}
      </div>
      {stats.total>0?(
        <div style={{display:'grid',gridTemplateColumns:'220px 1fr',gap:48,marginBottom:32}}>
          <div>
            <div style={{fontSize:44,fontFamily:'var(--font-serif)',lineHeight:1}}>{stats.average}</div>
            <Stars value={Math.round(stats.average)} size={16}/>
            <div style={{fontSize:13,color:'var(--text-muted)',marginTop:6}}>{stats.total} review{stats.total===1?'':'s'}</div>
          </div>
          <div style={{alignSelf:'center'}}>
            {[5,4,3,2,1].map(s=>(<RatingBar key={s} star={s} count={stats.distribution[s]||0} total={stats.total}/>))}
          </div>
        </div>
      ):(<p style={{color:'var(--text-muted)',fontSize:14,marginBottom:32}}>No reviews yet — be the first to share your experience.</p>)}
      {stats.total>0&&(
        <div style={{display:'flex',gap:20,alignItems:'center',flexWrap:'wrap',marginBottom:12,fontSize:13}}>
          <select value={sort} onChange={e=>setSort(e.target.value)} style={{padding:'8px 10px',border:'1px solid var(--border-default)',borderRadius:'var(--radius-sm)',fontSize:13}}>
            <option value="newest">Newest</option><option value="highest">Highest Rating</option><option value="lowest">Lowest Rating</option><option value="helpful">Most Helpful</option>
          </select>
          <label><input type="checkbox" checked={verifiedOnly} onChange={e=>setVerifiedOnly(e.target.checked)}/> Verified Only</label>
          <label><input type="checkbox" checked={withImages} onChange={e=>setWithImages(e.target.checked)}/> With Photos</label>
        </div>
      )}
      <div>
        {list.map(r=>(<ReviewCard key={r.id} r={r} onHelpful={helpful} voted={myVoterKey?(r.helpfulVoters||[]).includes(myVoterKey):false}/>))}
      </div>
      {showWrite&&eligible&&<WriteReviewModal eligible={eligible} onClose={()=>setShowWrite(false)} onSaved={()=>setTick(t=>t+1)}/>}
    </div>
  );
}
Object.assign(window,{Stars,RatingBar,MediaPicker,WriteReviewModal,ReviewCard,ReviewsSection});
