/* ============================================================
   GlowMerald — Cart, Checkout (3-step), Confirmation + About/Contact
   ============================================================ */
const { useState:useStateC, useEffect:useEffectC } = React;

const PROMO = { code:'GLOW10', pct:0.1, label:'Diskon 10%' };

/* ---------- CART ---------- */
function CartPage(){
  const { cart, updateQty, removeFromCart, priceOf, labelOf, navigate, cartTotal, toast } = useApp();
  const [promo,setPromo] = useStateC('');
  const [applied,setApplied] = useStateC(null);

  const applyPromo=()=>{
    if(promo.trim().toUpperCase()===PROMO.code){ setApplied(PROMO); toast('Promo diterapkan — '+PROMO.label,'spark'); }
    else { setApplied(null); toast('Kode promo tidak valid'); }
  };
  const discount = applied ? Math.round(cartTotal*applied.pct) : 0;

  if(cart.length===0){
    return (
      <div className="container section center" style={{ minHeight:'50vh', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center' }}>
        <span className="cart-empty-ic"><Icon name="cart" size={34}/></span>
        <h2 style={{ marginTop:18 }}>Keranjang masih kosong</h2>
        <p className="muted" style={{ marginBottom:24 }}>Mulai ritualmu dengan koleksi GlowMerald.</p>
        <button className="btn btn-gold" onClick={()=>navigate('shop')}>Mulai Belanja</button>
      </div>
    );
  }

  return (
    <div>
      <div className="page-head"><div className="container"><div className="eyebrow">Keranjang</div><h1 style={{ fontSize:'clamp(1.8rem,5vw,2.6rem)' }}>Keranjang Belanja</h1></div></div>
      <div className="container cart-layout">
        <div className="cart-items">
          {cart.map(line=>{
            const it = findItem(line.id); if(!it) return null;
            const price = priceOf(line.id,line.vi);
            return (
              <div key={line.key} className="cart-row">
                <div className="cart-thumb" onClick={()=>navigate('product',line.id)}><ProductVisual kind={it.visual} style={{ aspectRatio:'auto', height:'100%' }}/></div>
                <div className="cart-info">
                  <div style={{ display:'flex', justifyContent:'space-between', gap:10 }}>
                    <div>
                      <div style={{ fontFamily:'var(--serif)', fontSize:'1.08rem', lineHeight:1.2 }}>{it.name}</div>
                      <div className="muted" style={{ fontSize:'.78rem', marginTop:3 }}>{labelOf(line.id,line.vi)}</div>
                    </div>
                    <button className="cart-del" onClick={()=>removeFromCart(line.key)} aria-label="Hapus"><Icon name="trash" size={17}/></button>
                  </div>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:14 }}>
                    <div className="qty">
                      <button onClick={()=>updateQty(line.key,line.qty-1)}><Icon name="minus" size={14}/></button>
                      <span>{line.qty}</span>
                      <button onClick={()=>updateQty(line.key,line.qty+1)}><Icon name="plus" size={14}/></button>
                    </div>
                    <div style={{ fontWeight:500 }}>{formatRp(price*line.qty)}</div>
                  </div>
                </div>
              </div>
            );
          })}
          <a className="link-gold" onClick={()=>navigate('shop')} style={{ marginTop:8 }}><Icon name="chevron" size={14} style={{ transform:'rotate(180deg)' }}/> Lanjut Belanja</a>
        </div>

        <aside className="cart-summary">
          <h3 className="serif" style={{ fontSize:'1.3rem', marginBottom:18 }}>Ringkasan</h3>
          <div className="sum-row"><span>Subtotal</span><span>{formatRp(cartTotal)}</span></div>
          {applied && <div className="sum-row" style={{ color:'var(--gold-deep)' }}><span>{applied.label}</span><span>−{formatRp(discount)}</span></div>}
          <div className="sum-row muted"><span>Pengiriman</span><span style={{ fontSize:'.84rem' }}>Dihitung saat checkout</span></div>
          <div className="promo-row">
            <input type="text" value={promo} onChange={e=>setPromo(e.target.value)} placeholder="Kode promo (GLOW10)"/>
            <button className="btn btn-ghost btn-sm" onClick={applyPromo}>Pakai</button>
          </div>
          <div className="hr-gold" style={{ opacity:.4, margin:'18px 0' }}></div>
          <div className="sum-row total"><span>Total</span><span>{formatRp(cartTotal-discount)}</span></div>
          <button className="btn btn-gold btn-block" style={{ marginTop:18 }} onClick={()=>navigate('checkout')}>Checkout</button>
          <p className="muted center" style={{ fontSize:'.72rem', marginTop:14, marginBottom:0 }}><Icon name="shield" size={13} style={{ verticalAlign:'-2px' }}/> Transaksi aman · Produk terdaftar BPOM</p>
        </aside>
      </div>
    </div>
  );
}

/* ---------- CHECKOUT ---------- */
const STEPS = ['Pengiriman','Pembayaran','Konfirmasi'];
function CheckoutPage(){
  const { cart, cartTotal, priceOf, labelOf, navigate, clearCart, toast } = useApp();
  const [step,setStep] = useStateC(0);
  const [ship,setShip] = useStateC('jne');
  const [pay,setPay] = useStateC('BCA');
  const [addr,setAddr] = useStateC({ name:USER.name, phone:USER.phone, detail:ADDRESSES[0].detail, city:ADDRESSES[0].city, prov:ADDRESSES[0].prov, post:ADDRESSES[0].post });

  useEffectC(()=>{ if(cart.length===0) navigate('cart'); },[]);

  const shipObj = SHIPPING.find(s=>s.id===ship);
  const shipCost = shipObj?shipObj.price:0;
  const total = cartTotal + shipCost;

  const next=()=>{ if(step<2) setStep(step+1); window.scrollTo({top:0}); };
  const back=()=>{ if(step>0) setStep(step-1); else navigate('cart'); };

  const placeOrder=()=>{
    const order = {
      number:'GM-2406-'+Math.floor(10000+Math.random()*89999),
      date:new Date().toLocaleDateString('id-ID',{day:'numeric',month:'long',year:'numeric'}),
      items: cart.map(l=>{ const it=findItem(l.id); return { name:it.name, label:labelOf(l.id,l.vi), qty:l.qty, price:priceOf(l.id,l.vi), visual:it.visual }; }),
      subtotal:cartTotal, shipCost, total, ship:shipObj, pay, addr, eta:shipObj.eta,
    };
    try{ localStorage.setItem('gm_last_order', JSON.stringify(order)); }catch(e){}
    clearCart(); toast('Pesanan berhasil dibuat','check'); navigate('confirm');
  };

  return (
    <div>
      <div className="page-head"><div className="container"><div className="eyebrow">Checkout</div><h1 style={{ fontSize:'clamp(1.8rem,5vw,2.6rem)' }}>Selesaikan Pesanan</h1></div></div>

      <div className="container">
        <div className="stepper">
          {STEPS.map((s,i)=>(
            <div key={s} className={'step'+(i===step?' active':'')+(i<step?' done':'')}>
              <span className="step-num">{i<step?<Icon name="check" size={15}/>:i+1}</span>
              <span className="step-label">{s}</span>
              {i<STEPS.length-1 && <span className="step-bar"></span>}
            </div>
          ))}
        </div>
      </div>

      <div className="container checkout-layout">
        <div className="checkout-main">
          {step===0 && (
            <div className="acc-card fade-up">
              <h3 className="serif" style={{ fontSize:'1.25rem', marginBottom:18 }}>Alamat Pengiriman</h3>
              <div className="form-2">
                <label className="field"><span className="lab">Nama Lengkap</span><input type="text" value={addr.name} onChange={e=>setAddr({...addr,name:e.target.value})}/></label>
                <label className="field"><span className="lab">Nomor Telepon</span><input type="tel" value={addr.phone} onChange={e=>setAddr({...addr,phone:e.target.value})}/></label>
              </div>
              <label className="field"><span className="lab">Alamat Lengkap</span><textarea rows="2" value={addr.detail} onChange={e=>setAddr({...addr,detail:e.target.value})}></textarea></label>
              <div className="form-3">
                <label className="field"><span className="lab">Kota</span><input type="text" value={addr.city} onChange={e=>setAddr({...addr,city:e.target.value})}/></label>
                <label className="field"><span className="lab">Provinsi</span><select value={addr.prov} onChange={e=>setAddr({...addr,prov:e.target.value})}>{PROVINCES.map(p=><option key={p}>{p}</option>)}</select></label>
                <label className="field"><span className="lab">Kode Pos</span><input type="text" value={addr.post} onChange={e=>setAddr({...addr,post:e.target.value})}/></label>
              </div>
              <h3 className="serif" style={{ fontSize:'1.25rem', margin:'24px 0 16px' }}>Metode Pengiriman</h3>
              <div className="opt-list">
                {SHIPPING.map(s=>(
                  <label key={s.id} className={'opt'+(ship===s.id?' active':'')}>
                    <input type="radio" name="ship" checked={ship===s.id} onChange={()=>setShip(s.id)}/>
                    <span className="opt-radio"></span>
                    <span className="opt-ic"><Icon name="truck" size={20}/></span>
                    <div style={{ flex:1 }}><div style={{ fontWeight:500, fontSize:'.92rem' }}>{s.name}</div><div className="muted" style={{ fontSize:'.78rem' }}>Estimasi {s.eta}</div></div>
                    <span style={{ fontWeight:500 }}>{formatRp(s.price)}</span>
                  </label>
                ))}
              </div>
            </div>
          )}
          {step===1 && (
            <div className="acc-card fade-up">
              <h3 className="serif" style={{ fontSize:'1.25rem', marginBottom:18 }}>Metode Pembayaran</h3>
              {PAYMENTS.map(g=>(
                <div key={g.group} style={{ marginBottom:22 }}>
                  <div className="field-lab" style={{ marginBottom:10 }}>{g.group}</div>
                  <div className="pay-grid">
                    {g.options.map(o=>(
                      <button key={o} className={'pay-opt'+(pay===o?' active':'')} onClick={()=>setPay(o)}>
                        <span className="pay-name">{o}</span>
                        {pay===o && <span className="pay-check"><Icon name="check" size={13}/></span>}
                      </button>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
          {step===2 && (
            <div className="acc-card fade-up">
              <h3 className="serif" style={{ fontSize:'1.25rem', marginBottom:18 }}>Tinjau Pesanan</h3>
              <div className="review-block">
                <div className="field-lab">Dikirim ke</div>
                <p style={{ margin:'4px 0 0' }}>{addr.name} · {addr.phone}<br/><span className="muted">{addr.detail}, {addr.city}, {addr.prov} {addr.post}</span></p>
              </div>
              <div className="review-block"><div className="field-lab">Pengiriman</div><p style={{ margin:'4px 0 0' }}>{shipObj.name} · estimasi {shipObj.eta}</p></div>
              <div className="review-block"><div className="field-lab">Pembayaran</div><p style={{ margin:'4px 0 0' }}>{pay}</p></div>
              <div className="hr-gold" style={{ opacity:.3, margin:'8px 0 16px' }}></div>
              {cart.map(l=>{ const it=findItem(l.id); return (
                <div key={l.key} className="order-item" style={{ paddingBottom:12 }}>
                  <div style={{ width:48, height:48, borderRadius:4, overflow:'hidden' }}><ProductVisual kind={it.visual} style={{ aspectRatio:'auto', height:48 }}/></div>
                  <div style={{ flex:1 }}><div style={{ fontSize:'.88rem' }}>{it.name}</div><div className="muted" style={{ fontSize:'.76rem' }}>{labelOf(l.id,l.vi)} · x{l.qty}</div></div>
                  <div style={{ fontWeight:500, fontSize:'.88rem' }}>{formatRp(priceOf(l.id,l.vi)*l.qty)}</div>
                </div>
              ); })}
            </div>
          )}

          <div style={{ display:'flex', gap:12, marginTop:20 }}>
            <button className="btn btn-ghost" onClick={back}>{step===0?'Kembali ke Keranjang':'Sebelumnya'}</button>
            {step<2
              ? <button className="btn btn-gold" style={{ flex:1 }} onClick={next}>Lanjutkan</button>
              : <button className="btn btn-gold" style={{ flex:1 }} onClick={placeOrder}>Buat Pesanan · {formatRp(total)}</button>}
          </div>
        </div>

        <aside className="cart-summary">
          <h3 className="serif" style={{ fontSize:'1.3rem', marginBottom:18 }}>Ringkasan</h3>
          {cart.map(l=>{ const it=findItem(l.id); return (
            <div key={l.key} className="sum-row" style={{ fontSize:'.86rem' }}><span className="muted">{it.name} ×{l.qty}</span><span>{formatRp(priceOf(l.id,l.vi)*l.qty)}</span></div>
          ); })}
          <div className="hr-gold" style={{ opacity:.3, margin:'14px 0' }}></div>
          <div className="sum-row"><span>Subtotal</span><span>{formatRp(cartTotal)}</span></div>
          <div className="sum-row"><span>Pengiriman</span><span>{formatRp(shipCost)}</span></div>
          <div className="hr-gold" style={{ opacity:.4, margin:'14px 0' }}></div>
          <div className="sum-row total"><span>Total</span><span>{formatRp(total)}</span></div>
        </aside>
      </div>
    </div>
  );
}

/* ---------- CONFIRMATION ---------- */
function ConfirmPage(){
  const { navigate } = useApp();
  let order=null; try{ order = JSON.parse(localStorage.getItem('gm_last_order')); }catch(e){}
  if(!order){
    return (
      <div className="container section center" style={{ minHeight:'50vh' }}>
        <h2>Tidak ada pesanan</h2>
        <button className="btn btn-gold" onClick={()=>navigate('shop')}>Mulai Belanja</button>
      </div>
    );
  }
  return (
    <div className="container section" style={{ maxWidth:680 }}>
      <div className="center fade-up">
        <div className="confirm-check"><Icon name="check" size={40} stroke={2}/></div>
        <div className="eyebrow" style={{ marginTop:24 }}>Terima Kasih</div>
        <h1 style={{ fontSize:'clamp(2rem,6vw,3rem)' }}>Pesanan diterima</h1>
        <p className="muted">Nomor pesanan <strong style={{ color:'var(--ink)' }}>{order.number}</strong></p>
      </div>

      <div className="acc-card" style={{ marginTop:32 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
          <div><div className="field-lab">Estimasi Tiba</div><div style={{ fontFamily:'var(--serif)', fontSize:'1.1rem' }}>{order.ship.name} · {order.eta}</div></div>
          <span className="status st-proc">Diproses</span>
        </div>
        <div className="hr-gold" style={{ opacity:.3, margin:'4px 0 16px' }}></div>
        {order.items.map((it,i)=>(
          <div key={i} className="order-item">
            <div style={{ width:50, height:50, borderRadius:4, overflow:'hidden' }}><ProductVisual kind={it.visual} style={{ aspectRatio:'auto', height:50 }}/></div>
            <div style={{ flex:1 }}><div style={{ fontSize:'.9rem' }}>{it.name}</div><div className="muted" style={{ fontSize:'.76rem' }}>{it.label} · x{it.qty}</div></div>
            <div style={{ fontWeight:500, fontSize:'.88rem' }}>{formatRp(it.price*it.qty)}</div>
          </div>
        ))}
        <div className="hr-gold" style={{ opacity:.3, margin:'14px 0' }}></div>
        <div className="sum-row"><span className="muted">Subtotal</span><span>{formatRp(order.subtotal)}</span></div>
        <div className="sum-row"><span className="muted">Pengiriman</span><span>{formatRp(order.shipCost)}</span></div>
        <div className="sum-row total"><span>Total</span><span>{formatRp(order.total)}</span></div>
        <div className="muted" style={{ fontSize:'.82rem', marginTop:14 }}>Dibayar via {order.pay} · Dikirim ke {order.addr.city}</div>
      </div>

      <div style={{ display:'flex', gap:12, marginTop:24, justifyContent:'center', flexWrap:'wrap' }}>
        <button className="btn btn-ghost" onClick={()=>navigate('account','orders')}>Lacak Pesanan</button>
        <button className="btn btn-gold" onClick={()=>navigate('shop')}>Lanjut Belanja</button>
      </div>
    </div>
  );
}

/* ---------- ABOUT / CONTACT ---------- */
function AboutPage(){
  const { navigate } = useApp();
  return (
    <div>
      <section style={{ background:'var(--dark)', color:'var(--on-dark)', marginTop:'calc(-1 * var(--nav-h))', paddingTop:'calc(var(--nav-h) + 80px)', paddingBottom:80, position:'relative', overflow:'hidden' }}>
        <div className="deco-circle" style={{ width:360, height:360, top:-120, right:-100 }}></div>
        <div className="container" style={{ maxWidth:760, textAlign:'center', position:'relative' }}>
          <div className="eyebrow on-dark">Brand Story</div>
          <h1 style={{ color:'var(--on-dark)' }}>Terinspirasi dari Emerald</h1>
          <p className="ital" style={{ fontSize:'1.3rem', color:'var(--gold)', marginTop:18 }}>Glow from Within, Confidence Revealed.</p>
        </div>
      </section>
      <section className="section"><div className="container" style={{ maxWidth:720 }}>
        <p style={{ fontSize:'1.15rem', lineHeight:1.7 }}>GlowMerald lahir di bawah naungan PT Global Makmur Sempurna sebagai representasi kecantikan modern yang berpadu dengan sentuhan alami. Terinspirasi dari kata <span className="ital">Emerald</span> — batu permata hijau yang melambangkan ketenangan, kemurnian, dan keseimbangan hidup.</p>
        <p className="muted" style={{ fontWeight:300 }}>Filosofi kami sederhana namun kuat: setiap individu berhak bersinar dengan caranya sendiri. Kecantikan sejati bukan tentang kesempurnaan, melainkan tentang kulit yang sehat, terawat, dan memancarkan cahaya alami dari dalam diri.</p>
        <div className="rule" style={{ margin:'40px 0' }}><Icon name="spark" size={16}/></div>
        <div className="grid grid-3" style={{ textAlign:'center' }}>
          {[['Premium Natural','Formula berkualitas dari bahan alami pilihan.'],['Accessible Luxury','Pengalaman mewah yang dapat dinikmati semua kalangan.'],['Confidence First','Mendorong percaya diri dari dalam, bukan sekadar tampilan.']].map(([t,d],i)=>(
            <div key={i}><h3 style={{ fontSize:'1.1rem', marginBottom:8 }}>{t}</h3><p className="muted" style={{ fontSize:'.86rem', fontWeight:300 }}>{d}</p></div>
          ))}
        </div>
        <div className="center" style={{ marginTop:44 }}><button className="btn btn-gold" onClick={()=>navigate('shop')}>Jelajahi Produk</button></div>
      </div></section>
    </div>
  );
}

function ContactPage(){
  return (
    <div>
      <div className="page-head"><div className="container"><div className="eyebrow">Contact</div><h1 style={{ fontSize:'clamp(2rem,6vw,3rem)' }}>Hubungi Kami</h1></div></div>
      <div className="container section contact-layout" style={{ paddingTop:32 }}>
        <div className="acc-card">
          <h3 className="serif" style={{ fontSize:'1.25rem', marginBottom:18 }}>Kirim Pesan</h3>
          <div className="form-2">
            <label className="field"><span className="lab">Nama</span><input type="text"/></label>
            <label className="field"><span className="lab">Email</span><input type="email"/></label>
          </div>
          <label className="field"><span className="lab">Pesan</span><textarea rows="4"></textarea></label>
          <button className="btn btn-gold">Kirim Pesan</button>
        </div>
        <div>
          <h3 className="serif" style={{ fontSize:'1.25rem', marginBottom:18 }}>PT Global Makmur Sempurna</h3>
          <p className="muted" style={{ fontWeight:300 }}>Cengkareng Business City, Lot 12 Boutique 27, Jl. Atang Sanjaya No 21, Benda — Tangerang.</p>
          <div className="contact-list">
            <div><span className="field-lab">Email</span>official@glowmerald.id</div>
            <div><span className="field-lab">Website</span>glowmerald.id</div>
            <div><span className="field-lab">Instagram</span>@glowmeraldofficial</div>
            <div><span className="field-lab">Telepon</span>+62 811 1008 8887</div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CartPage, CheckoutPage, ConfirmPage, AboutPage, ContactPage });
