/* ============================================================
   GlowMerald — Account (profile, orders, wishlist, address, loyalty)
   ============================================================ */
const { useState:useStateAcc } = React;

const ACC_NAV = [
  { k:'profile', label:'Profil', icon:'user' },
  { k:'orders', label:'Pesanan Saya', icon:'shop' },
  { k:'wishlist', label:'Wishlist', icon:'heart' },
  { k:'address', label:'Alamat', icon:'home' },
  { k:'loyalty', label:'Loyalty Points', icon:'gem' },
  { k:'settings', label:'Pengaturan', icon:'spark' },
];
const STATUS_STYLE = { 'Diproses':'st-proc', 'Dikirim':'st-ship', 'Selesai':'st-done' };

function AccountPage(){
  const { param, navigate } = useApp();
  const [section,setSection] = useStateAcc(param || 'profile');

  return (
    <div>
      <div className="page-head">
        <div className="container" style={{ display:'flex', alignItems:'center', gap:18 }}>
          <Avatar name={USER.name} size={64} style={{ border:'1px solid var(--gold-soft)' }}/>
          <div>
            <div className="eyebrow" style={{ marginBottom:6 }}>Akun Saya</div>
            <h1 style={{ fontSize:'clamp(1.6rem,5vw,2.4rem)' }}>{USER.name}</h1>
          </div>
        </div>
      </div>

      <div className="container acc-layout">
        <aside className="acc-aside">
          <nav className="acc-nav">
            {ACC_NAV.map(n=>(
              <button key={n.k} className={'acc-link'+(section===n.k?' active':'')} onClick={()=>setSection(n.k)}>
                <Icon name={n.icon} size={18}/> {n.label}
              </button>
            ))}
          </nav>
        </aside>
        <div className="acc-main">
          {section==='profile' && <ProfileSection/>}
          {section==='orders' && <OrdersSection/>}
          {section==='wishlist' && <WishlistSection/>}
          {section==='address' && <AddressSection/>}
          {section==='loyalty' && <LoyaltySection/>}
          {section==='settings' && <SettingsSection/>}
        </div>
      </div>
    </div>
  );
}

function TierBadge({ tier }){
  const cls = tier==='Inner Circle'||tier==='Ambassador' ? 'tier-emerald':'tier-gold';
  return <span className={'tier-badge '+cls}><Icon name="gem" size={13}/> {tier}</span>;
}

function ProfileSection(){
  return (
    <div>
      <h2 className="acc-h">Profil</h2>
      <div className="acc-card">
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:22, flexWrap:'wrap', gap:12 }}>
          <div style={{ display:'flex', alignItems:'center', gap:16 }}>
            <Avatar name={USER.name} size={56}/>
            <div><div style={{ fontFamily:'var(--serif)', fontSize:'1.25rem' }}>{USER.name}</div><TierBadge tier={USER.tier}/></div>
          </div>
          <button className="btn btn-ghost btn-sm">Edit Profil</button>
        </div>
        <div className="hr-gold" style={{ opacity:.3, margin:'4px 0 22px' }}></div>
        <div className="info-grid">
          <div><div className="field-lab">Nama</div><div>{USER.name}</div></div>
          <div><div className="field-lab">Email</div><div>{USER.email}</div></div>
          <div><div className="field-lab">Telepon</div><div>{USER.phone}</div></div>
          <div><div className="field-lab">Tier</div><div>{USER.tier}</div></div>
        </div>
      </div>
    </div>
  );
}

function OrdersSection(){
  const { navigate } = useApp();
  const [open,setOpen] = useStateAcc(null);
  return (
    <div>
      <h2 className="acc-h">Pesanan Saya</h2>
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        {ORDERS.map(o=>(
          <div key={o.id} className="acc-card order-card">
            <div className="order-head" onClick={()=>setOpen(open===o.id?null:o.id)}>
              <div>
                <div style={{ fontFamily:'var(--serif)', fontSize:'1.05rem' }}>{o.id}</div>
                <div className="muted" style={{ fontSize:'.78rem' }}>{o.date} · {o.items.length} item</div>
              </div>
              <div style={{ display:'flex', alignItems:'center', gap:14 }}>
                <span className={'status '+STATUS_STYLE[o.status]}>{o.status}</span>
                <Icon name="chevronDown" size={18} style={{ transform:open===o.id?'rotate(180deg)':'none', transition:'.2s', color:'var(--muted)' }}/>
              </div>
            </div>
            {open===o.id && (
              <div className="order-detail">
                {o.items.map((it,i)=>(
                  <div key={i} className="order-item">
                    <div style={{ width:54, height:54, borderRadius:4, overflow:'hidden' }}><ProductVisual kind={it.visual} style={{ aspectRatio:'auto', height:54 }}/></div>
                    <div style={{ flex:1 }}><div style={{ fontSize:'.9rem' }}>{it.name}</div><div className="muted" style={{ fontSize:'.78rem' }}>x{it.qty}</div></div>
                    <div style={{ fontWeight:500, fontSize:'.9rem' }}>{formatRp(it.price)}</div>
                  </div>
                ))}
                <div className="hr-gold" style={{ opacity:.3, margin:'14px 0' }}></div>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                  <span className="muted" style={{ fontSize:'.84rem' }}>Total</span>
                  <span style={{ fontFamily:'var(--serif)', fontSize:'1.15rem' }}>{formatRp(o.total)}</span>
                </div>
                <div style={{ display:'flex', gap:10, marginTop:14 }}>
                  {o.status==='Dikirim' && <button className="btn btn-ghost btn-sm">Lacak Pesanan</button>}
                  <button className="btn btn-ghost btn-sm" onClick={()=>navigate('shop')}>Beli Lagi</button>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

function WishlistSection(){
  const { wishlist, navigate } = useApp();
  const items = wishlist.map(findItem).filter(Boolean);
  return (
    <div>
      <h2 className="acc-h">Wishlist</h2>
      {items.length===0
        ? <div className="acc-card center" style={{ padding:'40px 20px' }}>
            <Icon name="heart" size={30} style={{ color:'var(--gold)' }}/>
            <p className="muted" style={{ marginTop:10 }}>Wishlist masih kosong.</p>
            <button className="btn btn-gold btn-sm" onClick={()=>navigate('shop')}>Jelajahi Produk</button>
          </div>
        : <div className="grid grid-3">{items.map(p=><ProductCard key={p.id} item={p}/>)}</div>}
    </div>
  );
}

function AddressSection(){
  const [adding,setAdding] = useStateAcc(false);
  return (
    <div>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <h2 className="acc-h" style={{ marginBottom:0 }}>Alamat</h2>
        <button className="btn btn-ghost btn-sm" onClick={()=>setAdding(a=>!a)}><Icon name="plus" size={14}/> Tambah</button>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:14, marginTop:22 }}>
        {ADDRESSES.map(a=>(
          <div key={a.id} className="acc-card addr-card">
            <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:8 }}>
              <span style={{ fontWeight:500 }}>{a.label}</span>
              {a.def && <span className="chip ghost-gold">Utama</span>}
            </div>
            <div style={{ fontSize:'.9rem' }}>{a.name} · {a.phone}</div>
            <p className="muted" style={{ margin:'6px 0 0', fontSize:'.88rem', fontWeight:300 }}>{a.detail}, {a.city}, {a.prov} {a.post}</p>
            <div style={{ display:'flex', gap:14, marginTop:12 }}>
              <a className="link-gold">Edit</a>{!a.def && <a className="link-gold">Jadikan Utama</a>}
            </div>
          </div>
        ))}
        {adding && (
          <div className="acc-card">
            <h3 className="serif" style={{ fontSize:'1.15rem', marginBottom:16 }}>Alamat Baru</h3>
            <div className="form-2">
              <label className="field"><span className="lab">Nama Penerima</span><input type="text" defaultValue={USER.name}/></label>
              <label className="field"><span className="lab">Nomor Telepon</span><input type="tel" placeholder="+62"/></label>
            </div>
            <label className="field"><span className="lab">Alamat Lengkap</span><textarea rows="2"></textarea></label>
            <div className="form-3">
              <label className="field"><span className="lab">Kota</span><input type="text"/></label>
              <label className="field"><span className="lab">Provinsi</span><select>{PROVINCES.map(p=><option key={p}>{p}</option>)}</select></label>
              <label className="field"><span className="lab">Kode Pos</span><input type="text"/></label>
            </div>
            <button className="btn btn-gold btn-sm" onClick={()=>setAdding(false)}>Simpan Alamat</button>
          </div>
        )}
      </div>
    </div>
  );
}

function LoyaltySection(){
  const idx = TIERS.findIndex(t=>t.name===USER.tier);
  const next = TIERS[idx+1];
  const pct = next ? Math.min(100, Math.round((USER.points-TIERS[idx].min)/(next.min-TIERS[idx].min)*100)) : 100;
  const toNext = next ? next.min-USER.points : 0;
  return (
    <div>
      <h2 className="acc-h">Loyalty Points</h2>
      <div className="loyalty-hero">
        <div className="deco-circle" style={{ width:200, height:200, top:-60, right:-40, opacity:.18 }}></div>
        <div className="eyebrow on-dark">Saldo Poin</div>
        <div style={{ display:'flex', alignItems:'baseline', gap:10 }}>
          <span style={{ fontFamily:'var(--serif)', fontSize:'3rem', color:'var(--gold)' }}>{USER.points.toLocaleString('id-ID')}</span>
          <span style={{ color:'var(--on-dark-muted)' }}>poin</span>
        </div>
        <div style={{ marginTop:8 }}><TierBadge tier={USER.tier}/></div>
        {next && (
          <div style={{ marginTop:22 }}>
            <div style={{ display:'flex', justifyContent:'space-between', fontSize:'.78rem', color:'var(--on-dark-muted)', marginBottom:8 }}>
              <span>{USER.tier}</span><span>{next.name}</span>
            </div>
            <div className="loy-track"><div className="loy-fill" style={{ width:pct+'%' }}></div></div>
            <p style={{ color:'var(--on-dark-muted)', fontSize:'.82rem', marginTop:10, marginBottom:0 }}>
              <span style={{ color:'var(--gold)' }}>{toNext.toLocaleString('id-ID')} poin</span> lagi menuju {next.name}.
            </p>
          </div>
        )}
      </div>
      <h3 className="serif" style={{ fontSize:'1.2rem', margin:'30px 0 16px' }}>Tukar Poin</h3>
      <div className="redeem-grid">
        {[['Voucher Rp 50.000','500 poin'],['Free Sachet Mask','350 poin'],['Free Shipping','200 poin'],['Voucher Rp 150.000','1.400 poin']].map(([t,p],i)=>(
          <div key={i} className="acc-card redeem">
            <div><div style={{ fontFamily:'var(--serif)', fontSize:'1.05rem' }}>{t}</div><div className="muted" style={{ fontSize:'.8rem', marginTop:4 }}>{p}</div></div>
            <button className="btn btn-ghost btn-sm">Tukar</button>
          </div>
        ))}
      </div>
    </div>
  );
}

function SettingsSection(){
  const Toggle = ({ label, on })=>{
    const [v,setV]=useStateAcc(on);
    return (
      <div className="set-row">
        <span>{label}</span>
        <button className={'switch'+(v?' on':'')} onClick={()=>setV(!v)}><span className="knob"></span></button>
      </div>
    );
  };
  return (
    <div>
      <h2 className="acc-h">Pengaturan</h2>
      <div className="acc-card">
        <Toggle label="Notifikasi promo & penawaran" on={true}/>
        <Toggle label="Update status pesanan" on={true}/>
        <Toggle label="Newsletter Beauty Insight" on={false}/>
        <Toggle label="Mode bahasa Inggris" on={false}/>
      </div>
      <button className="btn btn-ghost" style={{ marginTop:20 }}>Keluar</button>
    </div>
  );
}

window.AccountPage = AccountPage;
