/* ============================================================
   GlowMerald — Product Detail
   ============================================================ */
const { useState:useStateP } = React;

const REVIEWS = [
  { name:'Anindhita P.', rating:5, date:'Mei 2026', concern:'Brightening', ba:true,
    text:'Sudah 6 minggu pakai dan warna kulit tampak lebih merata. Teksturnya ringan, cocok untuk pagi sebelum makeup.' },
  { name:'Rara S.', rating:5, date:'Apr 2026', concern:'Anti-Aging', ba:false,
    text:'Jadi bagian ritual malam saya. Kulit terasa lebih kenyal dan terawat. Packaging-nya juga terasa premium.' },
  { name:'Maharani', rating:4, date:'Apr 2026', concern:'Barrier', ba:false,
    text:'Menenangkan untuk kulit sensitif saya. Tidak ada rasa perih sama sekali.' },
  { name:'Gisela R.', rating:5, date:'Mar 2026', concern:'Hydration', ba:true,
    text:'Hidrasinya terasa sepanjang hari. Sekarang repeat order untuk kedua kalinya.' },
];

function IngredientChip({ name }){
  const [show,setShow] = useStateP(false);
  return (
    <span className="ing-chip" onMouseEnter={()=>setShow(true)} onMouseLeave={()=>setShow(false)} onClick={()=>setShow(s=>!s)}>
      {name}
      {show && INGREDIENTS[name] && (
        <span className="ing-tip">{INGREDIENTS[name]}</span>
      )}
    </span>
  );
}

function RatingBars({ rating, reviews }){
  const dist = [0.72,0.2,0.05,0.02,0.01]; // 5→1 star share
  return (
    <div className="rating-bars">
      {[5,4,3,2,1].map((s,i)=>(
        <div key={s} className="rb-row">
          <span className="rb-label">{s}★</span>
          <span className="rb-track"><span className="rb-fill" style={{ width:(dist[i]*100)+'%' }}></span></span>
          <span className="rb-pct">{Math.round(dist[i]*100)}%</span>
        </div>
      ))}
    </div>
  );
}

function ProductPage(){
  const { param, addToCart, navigate, wishlist, toggleWishlist } = useApp();
  const item = findItem(param) || PRODUCTS[0];
  const [vi,setVi] = useStateP(0);
  const [qty,setQty] = useStateP(1);
  const [tab,setTab] = useStateP('desc');
  const [activeImg,setActiveImg] = useStateP(0);
  const [added,setAdded] = useStateP(false);
  const wished = wishlist.includes(item.id);
  const isBundle = item.type==='Bundle';
  const price = (item.variants&&item.variants[vi]) ? item.variants[vi].price : item.price;
  const thumbs = ['main','texture','ingredient','packaging'];
  const cross = item.id==='serum'?findItem('mask'):findItem('serum');

  const doAdd=()=>{ addToCart(item.id, qty, vi); setAdded(true); setTimeout(()=>setAdded(false),1500); };

  const tabs = isBundle
    ? [['desc','Deskripsi'],['howto','Cara Pakai'],['reviews','Ulasan']]
    : [['desc','Deskripsi'],['howto','Cara Pakai'],['ing','Ingredients'],['reviews','Ulasan']];

  return (
    <div>
      <div className="container" style={{ paddingTop:26 }}>
        <div className="crumb">
          <a onClick={()=>navigate('home')}>Home</a><Icon name="chevron" size={13}/>
          <a onClick={()=>navigate('shop')}>Shop</a><Icon name="chevron" size={13}/>
          <span>{item.name}</span>
        </div>
      </div>

      <div className="container pdp-grid">
        {/* Gallery */}
        <div className="pdp-gallery">
          <div className="pdp-main">
            {activeImg===0
              ? <ProductVisual kind={item.visual}/>
              : <Placeholder label={thumbs[activeImg]==='texture'?'texture shot':thumbs[activeImg]==='ingredient'?'ingredient detail':'packaging shot'} style={{ aspectRatio:'1/1' }}/>}
            {item.bestSeller && <span className="badge-best" style={{ top:16, left:16 }}>Best Seller</span>}
          </div>
          <div className="pdp-thumbs">
            {thumbs.map((t,i)=>(
              <button key={i} className={'pdp-thumb'+(activeImg===i?' active':'')} onClick={()=>setActiveImg(i)}>
                {i===0 ? <ProductVisual kind={item.visual} style={{ aspectRatio:'1/1' }}/> : <Placeholder label="" style={{ aspectRatio:'1/1' }}/>}
              </button>
            ))}
          </div>
        </div>

        {/* Buy box */}
        <div className="pdp-info">
          <div className="eyebrow" style={{ marginBottom:10 }}>{item.type}</div>
          <h1 style={{ fontSize:'clamp(1.9rem,5vw,2.7rem)' }}>{item.name}</h1>
          <p className="ital muted" style={{ fontSize:'1.1rem', margin:'10px 0 14px' }}>{item.tagline||item.sub}</p>
          <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:20 }}>
            <Stars value={item.rating}/>
            <span className="muted" style={{ fontSize:'.84rem' }}>{item.rating} · {item.reviews} ulasan{item.sold?` · ${item.sold} terjual`:''}</span>
          </div>

          <div className="pdp-price">
            {formatRp(price*qty)}
            {isBundle && <span className="strike">{formatRp(item.was*qty)}</span>}
          </div>
          {!isBundle && <p className="muted" style={{ fontSize:'.8rem', marginTop:4 }}>{item.size}</p>}

          {/* variant selector */}
          {item.variants && item.variants.length>1 && (
            <div style={{ margin:'22px 0 4px' }}>
              <div className="field-lab">Pilihan</div>
              <div className="variant-row">
                {item.variants.map((v,i)=>(
                  <button key={i} className={'variant'+(vi===i?' active':'')} onClick={()=>setVi(i)}>
                    <span>{v.label}</span><span className="vprice">{formatRp(v.price)}</span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* qty + actions */}
          <div style={{ display:'flex', alignItems:'center', gap:14, margin:'24px 0 14px', flexWrap:'wrap' }}>
            <div className="qty">
              <button onClick={()=>setQty(q=>Math.max(1,q-1))}><Icon name="minus" size={15}/></button>
              <span>{qty}</span>
              <button onClick={()=>setQty(q=>q+1)}><Icon name="plus" size={15}/></button>
            </div>
            <button className="btn btn-gold" style={{ flex:1, minWidth:200 }} onClick={doAdd}>
              {added ? <span className="added"><Icon name="check" size={16}/> Ditambahkan</span> : 'Tambah ke Keranjang'}
            </button>
          </div>
          <button className={'btn btn-ghost btn-block'+(wished?' wished':'')} onClick={()=>toggleWishlist(item.id)}>
            <Icon name="heart" size={16} fill={wished}/> {wished?'Tersimpan di Wishlist':'Tambah ke Wishlist'}
          </button>

          {/* ingredient chips */}
          {item.ingredients && (
            <div style={{ marginTop:26 }}>
              <div className="field-lab" style={{ marginBottom:10 }}>Bahan Aktif Utama</div>
              <div className="ing-wrap">
                {item.ingredients.map(n=><IngredientChip key={n} name={n}/>)}
              </div>
            </div>
          )}

          {/* BPOM */}
          {item.bpom && (
            <div className="bpom">
              <span className="bpom-ic"><Icon name="shield" size={20}/></span>
              <div>
                <div style={{ fontSize:'.7rem', letterSpacing:'.14em', textTransform:'uppercase', color:'var(--emerald)', fontWeight:600 }}>Terdaftar BPOM</div>
                <div style={{ fontFamily:'var(--serif)', fontSize:'1.05rem', color:'var(--ink)' }}>{item.bpom}</div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div className="container" style={{ marginTop:64 }}>
        <div className="tabs">
          {tabs.map(([k,l])=>(
            <button key={k} className={'tab'+(tab===k?' active':'')} onClick={()=>setTab(k)}>{l}</button>
          ))}
        </div>
        <div className="tab-body">
          {tab==='desc' && (
            <div className="prose">
              <p style={{ fontSize:'1.02rem' }}>{item.desc}</p>
              {item.benefits && (
                <div className="benefit-grid">
                  {item.benefits.map((b,i)=>(
                    <div key={i} className="benefit"><Icon name="check" size={15} style={{ color:'var(--gold-deep)' }}/>{b}</div>
                  ))}
                </div>
              )}
            </div>
          )}
          {tab==='howto' && (
            <ol className="howto">
              {item.howto.map((s,i)=>(<li key={i}><span className="howto-num">{i+1}</span><span>{s}</span></li>))}
            </ol>
          )}
          {tab==='ing' && item.ingredients && (
            <div className="ing-list">
              {item.ingredients.map(n=>(
                <div key={n} className="ing-list-row">
                  <span className="ing-dot"></span>
                  <div><strong>{n}</strong><p className="muted" style={{ margin:'2px 0 0', fontSize:'.88rem' }}>{INGREDIENTS[n]}</p></div>
                </div>
              ))}
            </div>
          )}
          {tab==='reviews' && <ReviewsBlock item={item}/>}
        </div>
      </div>

      {/* What to expect */}
      {item.expect && (
        <section className="section" style={{ background:'var(--cream-deep)', marginTop:60 }}>
          <div className="container">
            <SectionHead eyebrow="What to Expect" title="Perjalanan kulitmu" sub="Hasil bertahap dengan pemakaian rutin dan SPF di pagi hari."/>
            <div className="timeline">
              {item.expect.map((e,i)=>(
                <div key={i} className="tl-step">
                  <div className="tl-marker"><span className="tl-dot"></span>{i<item.expect.length-1 && <span className="tl-line"></span>}</div>
                  <div className="tl-content">
                    <div className="tl-range">{e.range}</div>
                    <p className="muted" style={{ margin:0, fontWeight:300 }}>{e.text}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Cross-sell */}
      {cross && (
        <section className="section">
          <div className="container">
            <SectionHead eyebrow="Complete Your Ritual" title="Lengkapi ritualmu" sub="Pasangan sempurna untuk hasil yang menyeluruh."/>
            <div style={{ maxWidth:360, margin:'0 auto' }}><ProductCard item={cross}/></div>
          </div>
        </section>
      )}
    </div>
  );
}

function ReviewsBlock({ item }){
  return (
    <div className="reviews">
      <div className="rev-summary">
        <div className="rev-score">
          <div className="rev-num">{item.rating}</div>
          <Stars value={item.rating} size={16}/>
          <div className="muted" style={{ fontSize:'.8rem', marginTop:6 }}>{item.reviews} ulasan</div>
        </div>
        <RatingBars rating={item.rating} reviews={item.reviews}/>
      </div>
      <div className="rev-list">
        {REVIEWS.map((r,i)=>(
          <div key={i} className="rev-card">
            <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:10 }}>
              <Avatar name={r.name} size={40}/>
              <div style={{ flex:1 }}>
                <div style={{ fontWeight:500, fontSize:'.9rem' }}>{r.name}</div>
                <div style={{ display:'flex', alignItems:'center', gap:8 }}><Stars value={r.rating} size={12}/><span className="muted" style={{ fontSize:'.72rem' }}>{r.date}</span></div>
              </div>
              <span className="chip ghost-gold">{r.concern}</span>
            </div>
            <p style={{ margin:'0 0 12px', fontSize:'.92rem' }}>{r.text}</p>
            {r.ba && (
              <div style={{ display:'flex', gap:8 }}>
                <Placeholder label="Before" style={{ width:84, height:84, borderRadius:4 }}/>
                <Placeholder label="After" style={{ width:84, height:84, borderRadius:4 }}/>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

window.ProductPage = ProductPage;
