function WishlistTab({ user }) {
  const [items,   setItems]   = useStateA([]);
  const [loading, setLoading] = useStateA(true);
  const [adding,  setAdding]  = useStateA(new Set()); // tracks which items are being added

  const load = () => {
    if (!user || typeof FF_API === 'undefined') return;
    setLoading(true);
    FF_API.wishlist.get()
      .then(d => setItems(Array.isArray(d) ? d : []))
      .catch(()=>setItems([]))
      .finally(()=>setLoading(false));
  };

  useEffectA(load, [user]);

  const remove = async (productId) => {
    setItems(prev => prev.filter(p => p.id !== productId));
    await FF_API.wishlist.toggle(productId).catch(()=>{});
  };

  const moveToCart = async (p) => {
    if (adding.has(p.id)) return;
    setAdding(prev => new Set([...prev, p.id]));
    try {
      await FF_API.cart.add(p.id, 1);
      window.FF_TOAST && window.FF_TOAST(p.name + ' moved to bag ✦');
      await remove(p.id);
    } catch {
      window.FF_TOAST && window.FF_TOAST('Could not add to bag');
    } finally {
      setAdding(prev => { const n = new Set(prev); n.delete(p.id); return n; });
    }
  };

  const moveAllToCart = async () => {
    const available = items.filter(p => !(p.stock === 0 || p.stock === '0'));
    if (!available.length) return;
    window.FF_TOAST && window.FF_TOAST('Adding all to bag…');
    for (const p of available) await moveToCart(p);
  };

  if (loading) return (
    <div style={{ padding:60, textAlign:'center', color:'var(--ff-muted)' }}>
      <div style={{ fontSize:32, marginBottom:12, animation:'ffPulse 1.5s ease infinite' }}>♥</div>
      Loading your wishlist…
    </div>
  );

  if (!items.length) return (
    <div style={{ padding:60, textAlign:'center' }}>
      <div style={{ fontSize:48, marginBottom:16 }}>♡</div>
      <div style={{ fontWeight:700, fontSize:18, marginBottom:8 }}>Nothing saved yet</div>
      <div style={{ color:'var(--ff-muted)', marginBottom:24, fontSize:14 }}>
        Tap ♡ on any product to save it here.
      </div>
      <a href="/shop" className="ff-btn ff-btn--primary">Browse products →</a>
    </div>
  );

  const available = items.filter(p => !(p.stock===0||p.stock==='0'));

  return (
    <div>
      {/* Header row */}
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20, flexWrap:'wrap', gap:12 }}>
        <h2 className="ff-display" style={{ fontSize:22 }}>
          Wishlist <span style={{ color:'var(--ff-muted)', fontWeight:400, fontSize:16 }}>({items.length})</span>
        </h2>
        <div style={{ display:'flex', gap:10, alignItems:'center' }}>
          {available.length > 1 && (
            <button className="ff-btn ff-btn--ink ff-btn--sm" onClick={moveAllToCart}>
              🛍 Move all to bag ({available.length})
            </button>
          )}
          <a href="/shop" style={{ fontSize:13, color:'var(--ff-accent)', fontWeight:600 }}>Keep browsing →</a>
        </div>
      </div>

      {/* Cards grid */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(195px, 1fr))', gap:16 }}>
        {items.map(p => {
          const imgs = Array.isArray(p.images) ? p.images : [];
          const img  = imgs[0] || null;
          const outOfStock = p.stock === 0 || p.stock === '0';
          const isAdding = adding.has(p.id);
          const discount = p.compare ? Math.round((1 - p.price/p.compare)*100) : 0;
          return (
            <div key={p.id} className="ff-card"
              style={{ padding:0, overflow:'hidden', display:'flex', flexDirection:'column',
                opacity: outOfStock ? .75 : 1, transition:'opacity .2s' }}>

              {/* Image */}
              <div style={{ position:'relative', cursor:'pointer' }}
                onClick={() => location.href = `/product/${p.id}`}>
                <div style={{ height:180, background: p.swatch||'var(--ff-bg-2)', overflow:'hidden' }}>
                  {img
                    ? <img src={img} alt={p.name} style={{ width:'100%', height:'100%', objectFit:'cover',
                        filter: outOfStock ? 'grayscale(.4)' : 'none', transition:'transform .3s' }}
                        onMouseOver={e=>e.currentTarget.style.transform='scale(1.04)'}
                        onMouseOut={e=>e.currentTarget.style.transform='scale(1)'}/>
                    : <div style={{ width:'100%', height:'100%', display:'grid', placeItems:'center',
                        fontSize:13, color:'var(--ff-muted)', opacity:.4 }}>{p.name?.slice(0,10)}</div>
                  }
                </div>
                {/* Badges */}
                {outOfStock && (
                  <div style={{ position:'absolute', top:10, left:10, background:'rgba(0,0,0,.6)',
                    color:'#fff', fontSize:9, fontWeight:700, padding:'3px 8px', borderRadius:4,
                    letterSpacing:'.08em', textTransform:'uppercase' }}>Out of stock</div>
                )}
                {discount >= 10 && !outOfStock && (
                  <div style={{ position:'absolute', top:10, left:10, background:'var(--ff-accent)',
                    color:'#fff', fontSize:10, fontWeight:700, padding:'3px 8px', borderRadius:4 }}>
                    {discount}% off
                  </div>
                )}
                {/* Remove ✕ */}
                <button onClick={e=>{ e.stopPropagation(); remove(p.id); }}
                  style={{ position:'absolute', top:8, right:8, width:26, height:26, borderRadius:999,
                    background:'rgba(255,255,255,.92)', border:'none', fontSize:12, cursor:'pointer',
                    display:'flex', alignItems:'center', justifyContent:'center',
                    boxShadow:'0 1px 4px rgba(0,0,0,.15)', color:'var(--ff-ink)' }}
                  title="Remove from wishlist">✕</button>
              </div>

              {/* Info */}
              <div style={{ padding:'12px 14px', flex:1, display:'flex', flexDirection:'column', gap:4 }}>
                <div style={{ fontWeight:600, fontSize:14, lineHeight:1.3, cursor:'pointer' }}
                  onClick={() => location.href = `/product/${p.id}`}>{p.name}</div>
                {p.tagline && <div style={{ fontSize:11, color:'var(--ff-muted)', lineHeight:1.4 }}>{p.tagline}</div>}

                {/* Price row */}
                <div style={{ display:'flex', alignItems:'baseline', gap:8, marginTop:4 }}>
                  <span style={{ fontWeight:800, fontSize:16 }}>{fmtINR(p.price)}</span>
                  {p.compare > p.price && (
                    <span style={{ fontSize:12, color:'var(--ff-muted)', textDecoration:'line-through' }}>{fmtINR(p.compare)}</span>
                  )}
                </div>

                {/* Action buttons */}
                <div style={{ display:'grid', gap:6, marginTop:'auto', paddingTop:10 }}>
                  {outOfStock ? (
                    <div style={{ textAlign:'center', fontSize:12, color:'var(--ff-muted)',
                      padding:'8px', background:'var(--ff-bg-2)', borderRadius:8, fontWeight:500 }}>
                      Notify me when back ·{' '}
                      <span style={{ color:'var(--ff-accent)', cursor:'pointer' }}
                        onClick={() => location.href = `/product/${p.id}`}>View</span>
                    </div>
                  ) : (
                    <button className="ff-btn ff-btn--primary ff-btn--sm ff-btn--block"
                      disabled={isAdding}
                      onClick={() => moveToCart(p)}
                      style={{ gap:6 }}>
                      {isAdding ? '⏳ Adding…' : '🛍 Move to bag'}
                    </button>
                  )}
                  <button className="ff-btn ff-btn--sm ff-btn--block"
                    style={{ fontSize:12 }}
                    onClick={() => location.href = `/product/${p.id}`}>
                    View details →
                  </button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}


// ── ReferralTab ───────────────────────────────────────────────────────────────
function ReferralTab({ user }) {
  const [data,    setData]    = useStateA(null);
  const [copied,  setCopied]  = useStateA(false);
  const [loading, setLoading] = useStateA(true);

  useEffectA(() => {
    if (!user) return;
    fetch('/api/newsletter.php?action=referral-code', {
      headers: { 'Authorization': 'Bearer ' + (localStorage.getItem('ff_token') || '') }
    })
      .then(r => r.json())
      .then(d => { if (d.ok) setData(d); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [user]);

  const copy = () => {
    if (!data?.code) return;
    const link = window.location.origin + '/?ref=' + data.code;
    navigator.clipboard.writeText(link).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2500);
    });
  };

  if (loading) return (
    <div style={{ padding:60, textAlign:'center', color:'var(--ff-muted)' }}>Loading…</div>
  );

  return (
    <div>
      <h2 className="ff-display" style={{ fontSize:22, marginBottom:6 }}>Refer & Earn</h2>
      <p style={{ color:'var(--ff-muted)', fontSize:14, marginBottom:24 }}>
        Share your link. When a friend signs up, they get 10% off — and you get ₹100 off your next order.
      </p>

      {/* How it works */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12, marginBottom:28 }}>
        {[
          { icon:'🔗', title:'Share your link', desc:'Send it to friends, post on WhatsApp, Instagram' },
          { icon:'✅', title:'They sign up', desc:'Friend subscribes using your referral link' },
          { icon:'🎁', title:'You both win', desc:'They get 10% off · You get ₹100 off' },
        ].map(s => (
          <div key={s.title} className="ff-card" style={{ padding:'16px 18px', textAlign:'center' }}>
            <div style={{ fontSize:28, marginBottom:8 }}>{s.icon}</div>
            <div style={{ fontWeight:700, fontSize:13, marginBottom:4 }}>{s.title}</div>
            <div style={{ fontSize:11, color:'var(--ff-muted)', lineHeight:1.5 }}>{s.desc}</div>
          </div>
        ))}
      </div>

      {/* Your link */}
      {data?.code && (
        <div className="ff-card" style={{ padding:20 }}>
          <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'.08em', color:'var(--ff-muted)', marginBottom:10 }}>
            Your referral link
          </div>
          <div style={{ display:'flex', gap:8, marginBottom:14 }}>
            <div style={{ flex:1, padding:'11px 14px', background:'var(--ff-bg-2)',
              borderRadius:10, fontFamily:'monospace', fontSize:13,
              border:'1.5px solid var(--ff-line)', color:'var(--ff-ink-2)',
              overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
              {window.location.origin}/?ref={data.code}
            </div>
            <button className="ff-btn ff-btn--primary ff-btn--sm" onClick={copy} style={{ flexShrink:0 }}>
              {copied ? '✓ Copied!' : '📋 Copy'}
            </button>
          </div>

          {/* Share buttons */}
          <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
            {[
              { label:'WhatsApp', color:'#25D366', emoji:'💬',
                url: `https://wa.me/?text=${encodeURIComponent('Hey! Check out Fussy Finds — amazing products. Use my link for 10% off: ' + window.location.origin + '/?ref=' + data.code)}` },
              { label:'Instagram', color:'#E4439C', emoji:'📸',
                url: `https://www.instagram.com/` },
              { label:'Copy code', color:'var(--ff-ink)', emoji:'🔤',
                action: () => { navigator.clipboard.writeText(data.code); setCopied(true); setTimeout(()=>setCopied(false),2500); } },
            ].map(s => (
              <a key={s.label}
                href={s.url} target={s.url ? '_blank' : undefined}
                onClick={s.action ? (e)=>{e.preventDefault();s.action();} : undefined}
                style={{ display:'flex', alignItems:'center', gap:6, padding:'8px 14px',
                  borderRadius:8, background:s.color, color:'#fff', textDecoration:'none',
                  fontSize:12, fontWeight:600, cursor:'pointer' }}>
                {s.emoji} {s.label}
              </a>
            ))}
          </div>

          {/* Stats */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginTop:20,
            paddingTop:20, borderTop:'1px solid var(--ff-line)' }}>
            <div style={{ textAlign:'center' }}>
              <div style={{ fontFamily:'var(--ff-font-display,serif)', fontSize:32, fontWeight:800, color:'var(--ff-accent)' }}>
                {data.uses || 0}
              </div>
              <div style={{ fontSize:12, color:'var(--ff-muted)', marginTop:2 }}>Referrals</div>
            </div>
            <div style={{ textAlign:'center' }}>
              <div style={{ fontFamily:'var(--ff-font-display,serif)', fontSize:32, fontWeight:800, color:'var(--ff-accent)' }}>
                ₹{(data.earnings || 0).toLocaleString('en-IN')}
              </div>
              <div style={{ fontSize:12, color:'var(--ff-muted)', marginTop:2 }}>Earned</div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}


// ── AddressModal — add a new saved address ────────────────────────────────────
function AddressModal({ onClose, onSaved }) {
  const [form, setForm] = React.useState({
    name:'', phone:'', line1:'', line2:'', city:'', state:'', pincode:''
  });
  const [saving, setSaving] = React.useState(false);
  const [error,  setError]  = React.useState('');

  const save = async () => {
    if (!form.name||!form.phone||!form.line1||!form.city||!form.state||!form.pincode) {
      setError('Please fill all required fields'); return;
    }
    if (!/^\d{6}$/.test(form.pincode)) { setError('Enter a valid 6-digit pincode'); return; }
    setSaving(true); setError('');
    try {
      const token = localStorage.getItem('ff_token');
      const r = await fetch('/api/auth.php?action=add-address', {
        method:'POST',
        headers:{ 'Content-Type':'application/json', 'Authorization':'Bearer '+token },
        body: JSON.stringify(form),
      });
      const d = await r.json();
      if (d.id || d.ok) { onSaved({ ...form, id: d.id }); }
      else setError(d.error || 'Could not save address');
    } catch(e) { setError('Network error'); }
    finally { setSaving(false); }
  };

  const F = ({ label, k, placeholder, required, half }) => (
    <div style={{ gridColumn: half ? 'span 1' : 'span 2' }}>
      <label style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'.07em', color:'var(--ff-muted)', display:'block', marginBottom:5 }}>
        {label}{required && ' *'}
      </label>
      <input className="ff-input" value={form[k]} placeholder={placeholder}
        onChange={e=>setForm(f=>({...f,[k]:e.target.value}))}/>
    </div>
  );

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,.45)', zIndex:400,
      display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}
      onClick={e=>e.target===e.currentTarget&&onClose()}>
      <div style={{ background:'var(--ff-card)', borderRadius:18, padding:28,
        width:'min(480px,100%)', boxShadow:'0 24px 64px rgba(0,0,0,.2)' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20 }}>
          <div style={{ fontFamily:'var(--ff-font-display)', fontWeight:800, fontSize:20 }}>Add address</div>
          <button onClick={onClose} style={{ fontSize:20, background:'none', border:'none', cursor:'pointer', color:'var(--ff-muted)' }}>✕</button>
        </div>
        {error && <div style={{ background:'#FFE4E4', color:'#CC0000', borderRadius:8, padding:'10px 14px', fontSize:13, marginBottom:14 }}>{error}</div>}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:16 }}>
          <F label="Full name"    k="name"    placeholder="Neerav Mehrotra" required/>
          <F label="Phone"        k="phone"   placeholder="9876543210" required/>
          <F label="Address line 1" k="line1" placeholder="House/flat, street" required/>
          <F label="Address line 2" k="line2" placeholder="Landmark, area" half/>
          <F label="City"         k="city"    placeholder="Mumbai" required half/>
          <F label="Pincode"      k="pincode" placeholder="400001" required half/>
          <div style={{ gridColumn:'span 2' }}>
            <label style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'.07em', color:'var(--ff-muted)', display:'block', marginBottom:5 }}>State *</label>
            <select className="ff-input" value={form.state} onChange={e=>setForm(f=>({...f,state:e.target.value}))}>
              <option value="">Select state</option>
              {(window.INDIA_STATES||['Andhra Pradesh','Delhi','Gujarat','Karnataka','Kerala','Madhya Pradesh','Maharashtra','Punjab','Rajasthan','Tamil Nadu','Telangana','Uttar Pradesh','West Bengal']).map(s=>(
                <option key={s} value={s}>{s}</option>
              ))}
            </select>
          </div>
        </div>
        <div style={{ display:'flex', gap:10, justifyContent:'flex-end' }}>
          <button className="ff-btn ff-btn--sm" onClick={onClose}>Cancel</button>
          <button className="ff-btn ff-btn--primary ff-btn--sm" onClick={save} disabled={saving}>
            {saving ? 'Saving…' : 'Save address'}
          </button>
        </div>
      </div>
    </div>
  );
}


function AccountPage({ user, onLogout, goto, loadOrders, initialTab, refreshUser }) {
  const [tab,        setTab]       = useStateA(initialTab || 'orders');
  const [openOrder,  setOpenOrder] = useStateA(null);
  const [orders,     setOrders]    = useStateA([]);
  const [addresses,  setAddresses] = useStateA([]);
  const [addrModal,  setAddrModal]  = useStateA(false);
  const [ordLoading, setOrdLoading]= useStateA(false);
  // Profile edit state
  const [profName,   setProfName]  = useStateA('');
  const [profPhone,  setProfPhone] = useStateA('');
  const [profSaved,  setProfSaved] = useStateA(false);
  const [pwCurr,     setPwCurr]    = useStateA('');
  const [pwNew,      setPwNew]     = useStateA('');
  const [pwMsg,      setPwMsg]     = useStateA('');
  // Email OTP verification
  const [otpStep,    setOtpStep]   = useStateA(false);
  const [otpCode,    setOtpCode]   = useStateA('');
  const [otpMsg,     setOtpMsg]    = useStateA('');
  const [otpLoading, setOtpLoading]= useStateA(false);
  const [otpCd,      setOtpCd]     = useStateA(0);
  const [isVerified, setIsVerified]= useStateA(user?.email_verified == 1);

  useEffectA(() => { setIsVerified(user?.email_verified == 1); }, [user]);
  useEffectA(() => {
    if (otpCd <= 0) return;
    const t = setTimeout(() => setOtpCd(c => c-1), 1000);
    return () => clearTimeout(t);
  }, [otpCd]);

  const sendVerifyOtp = async () => {
    setOtpLoading(true); setOtpMsg('');
    const { ok, data } = await FF_API.auth.sendOtp();
    setOtpLoading(false);
    if (ok) { setOtpStep(true); setOtpCd(30); setOtpMsg('Code sent to ' + (data.email || user.email)); }
    else setOtpMsg(data.error || 'Failed to send');
  };

  const submitOtp = async () => {
    if (otpCode.length < 6) return;
    setOtpLoading(true); setOtpMsg('');
    const { ok, data } = await FF_API.auth.verifyOtp(otpCode);
    setOtpLoading(false);
    if (ok) {
      setIsVerified(true); setOtpStep(false); setOtpMsg(''); setOtpCode('');
      // Refresh user object so email_verified persists across reloads
      if (refreshUser) await refreshUser();
    } else {
      setOtpMsg(data.error || 'Wrong code');
    }
  };

  useEffectA(() => {
    if (!user) return;
    setProfName(user.name  || '');
    setProfPhone(user.phone || '');
  }, [user]);

  // Load orders when tab opens
  useEffectA(() => {
    if (typeof FF_API === 'undefined') return;
    if (tab === 'orders' && user) {
      setOrdLoading(true);
      FF_API.orders.list()
        .then(d => setOrders(Array.isArray(d) ? d : []))
        .catch(console.error)
        .finally(() => setOrdLoading(false));
    }
    if (tab === 'addresses' && user) {
      FF_API.orders.getAddresses()
        .then(d => setAddresses(Array.isArray(d) ? d : []))
        .catch(console.error);
    }
  }, [tab, user]);

  if (!user) {
    return (
      <main style={{ maxWidth:600, margin:'60px auto', padding:24, textAlign:'center' }}>
        <h1 className="ff-display" style={{ fontSize:36 }}>Log in to see your account</h1>
        <button className="ff-btn ff-btn--primary" style={{ marginTop:16 }} onClick={()=>goto({page:'home', openLogin:true})}>Log in</button>
      </main>
    );
  }

  const saveProfile = async () => {
    const { ok } = await FF_API.auth.updateProfile({ name: profName, phone: profPhone });
    if (ok) setProfSaved(true);
    setTimeout(() => setProfSaved(false), 2000);
  };

  const changePassword = async () => {
    setPwMsg('');
    const { ok, data } = await FF_API.auth.changePassword(pwCurr, pwNew);
    setPwMsg(ok ? '✓ Password changed' : (data.error || 'Failed'));
    if (ok) { setPwCurr(''); setPwNew(''); }
  };

  return (
    <main style={{ maxWidth:1200, margin:'0 auto', padding:'32px 24px 80px' }}>
      {/* Unverified email warning banner */}
      {!isVerified && (
        <div style={{ marginBottom:20, padding:'12px 18px', background:'#FFF3CC', border:'1.5px solid #F5D878', borderRadius:12, display:'flex', alignItems:'center', justifyContent:'space-between', gap:12, flexWrap:'wrap' }}>
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            <span style={{ fontSize:20 }}>⚠️</span>
            <div>
              <div style={{ fontWeight:700, fontSize:14 }}>Your email is not verified</div>
              <div style={{ fontSize:12, color:'var(--ff-ink-2)', marginTop:1 }}>Verify to secure your account and receive order updates.</div>
            </div>
          </div>
          <button onClick={sendVerifyOtp} disabled={otpLoading} className="ff-btn ff-btn--ink ff-btn--sm">
            {otpLoading ? 'Sending…' : 'Verify now →'}
          </button>
        </div>
      )}

      {/* Inline OTP verification (from banner) */}
      {otpStep && !isVerified && (
        <div style={{ marginBottom:20, padding:'20px 24px', background:'var(--ff-card)', border:'var(--ff-border)', borderRadius:12 }}>
          <div style={{ fontWeight:700, fontSize:15, marginBottom:6 }}>📧 Enter verification code</div>
          <div style={{ fontSize:13, color:'var(--ff-muted)', marginBottom:14 }}>{otpMsg}</div>
          <div style={{ display:'flex', gap:10 }}>
            <input className="ff-input" value={otpCode} maxLength={6}
              onChange={e=>setOtpCode(e.target.value.replace(/\D/g,'').slice(0,6))}
              placeholder="6-digit code"
              style={{ fontFamily:'monospace', fontSize:22, letterSpacing:'.2em', textAlign:'center', fontWeight:700, maxWidth:200 }}
              autoFocus/>
            <button className="ff-btn ff-btn--primary" onClick={submitOtp} disabled={otpCode.length<6||otpLoading}>
              {otpLoading ? '…' : 'Verify ✓'}
            </button>
            <button className="ff-btn ff-btn--ghost ff-btn--sm" onClick={()=>setOtpStep(false)} style={{ color:'var(--ff-muted)' }}>Cancel</button>
          </div>
          <button onClick={sendVerifyOtp} disabled={otpCd>0||otpLoading} style={{ marginTop:10, fontSize:12, color: otpCd>0?'var(--ff-muted)':'var(--ff-accent)', background:'none', border:'none', cursor: otpCd>0?'default':'pointer' }}>
            {otpCd>0 ? `Resend in ${otpCd}s` : 'Resend code'}
          </button>
        </div>
      )}

      <div style={{ display:'flex', alignItems:'center', gap:16, marginBottom:24 }}>
        <div style={{ width:64, height:64, borderRadius:999, background:'var(--ff-lime)', border:'var(--ff-border)', display:'grid', placeItems:'center', fontFamily:"'Space Grotesk',sans-serif", fontSize:28, fontWeight:700 }}>
          {(user.name||'F')[0].toUpperCase()}
        </div>
        <div>
          <h1 className="ff-display" style={{ fontSize:36 }}>Hey {user.name?.split(' ')[0] || 'fussy'} ✦</h1>
          <div style={{ fontSize:14, color:'var(--ff-muted)', display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
            {user.email}
            {isVerified
              ? <span style={{ fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:4, background:'var(--ff-mint)', color:'#0A5A2A' }}>✓ Verified</span>
              : <span onClick={()=>setTab('profile')} style={{ fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:4, background:'#FFE4E4', color:'#8B0000', cursor:'pointer' }}>⚠ Unverified · Click to verify</span>
            }
            · Member since {user.created_at?.slice(0,7) || 'recently'}
          </div>
        </div>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'220px 1fr', gap:28 }} className="ff-shop-grid">
        <aside>
          <nav style={{ display:'grid', gap:4 }}>
            {[
              { k:'orders',    l:'Orders',    i:<Icon.Box/> },
              { k:'wishlist',  l:'Wishlist',  i:'♥' },
              { k:'referral',  l:'Refer & Earn', i:'🎁' },
              { k:'addresses', l:'Addresses', i:<Icon.Truck/> },
              { k:'profile',   l: isVerified ? 'Profile' : <span style={{display:'flex',alignItems:'center',gap:6}}>Profile <span style={{fontSize:9,fontWeight:700,padding:'1px 5px',borderRadius:3,background:'#FFE4E4',color:'#8B0000'}}>!</span></span>, i:<Icon.User/> },
            ].map(t => (
              <button key={t.k} onClick={()=>setTab(t.k)} style={{
                padding:'10px 12px', borderRadius:10, display:'flex', alignItems:'center', gap:10,
                background: tab===t.k ? 'var(--ff-ink)' : 'transparent',
                color: tab===t.k ? '#fff' : 'inherit', fontWeight: tab===t.k ? 600 : 500,
                fontSize:14, textAlign:'left',
              }}>{t.i} {t.l}</button>
            ))}
            <button onClick={onLogout} style={{ padding:'10px 12px', borderRadius:10, fontSize:14, textAlign:'left', color:'var(--ff-muted)', marginTop:12 }}>Log out</button>
          </nav>
        </aside>

        <div>
          {/* ORDERS TAB */}
          {tab === 'orders' && (
            <div>
              <h2 className="ff-display" style={{ fontSize:28, marginBottom:16 }}>Your orders</h2>
              {ordLoading ? (
                <div style={{ padding:40, textAlign:'center', color:'var(--ff-muted)' }}>Loading orders…</div>
              ) : orders.length === 0 ? (
                <div className="ff-card" style={{ padding:40, textAlign:'center' }}>
                  <div style={{ fontSize:40 }}>📦</div>
                  <h3 className="ff-display" style={{ fontSize:22, marginTop:10 }}>No orders yet</h3>
                  <p style={{ color:'var(--ff-muted)', marginTop:6 }}>Your orders will appear here after checkout.</p>
                  <button className="ff-btn ff-btn--primary" style={{ marginTop:14 }} onClick={()=>goto({page:'shop'})}>Start shopping</button>
                </div>
              ) : (
                <div style={{ display:'grid', gap:14 }}>
                  {orders.map(o => (
                    <div key={o.id} className="ff-card" style={{ padding:18 }}>
                      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:10 }}>
                        <div>
                          <div style={{ fontSize:12, color:'var(--ff-muted)' }}>{o.created_at?.slice(0,10)}</div>
                          <div style={{ fontWeight:700, fontFamily:"'Space Grotesk',sans-serif" }}>#{o.id}</div>
                        </div>
                        <OrderStatusChip status={o.status}/>
                        <div style={{ fontWeight:700, fontFamily:"'Space Grotesk',sans-serif" }}>{fmtINR(o.total)}</div>
                        <div style={{ display:'flex', gap:6 }}>
                          <button className="ff-btn ff-btn--sm" onClick={()=>setOpenOrder(openOrder===o.id ? null : o.id)}>
                            {openOrder===o.id ? 'Hide' : 'Track'}
                          </button>
                          <a href={FF_URLS.order(o.id)} className="ff-btn ff-btn--sm ff-btn--primary" style={{ textDecoration:'none' }}>
                            View order
                          </a>
                        </div>
                      </div>

                      {/* Order items thumbnails */}
                      <div style={{ display:'flex', gap:8, marginTop:12 }}>
                        {(o.items||[]).map((it, i) => (
                          <div key={i} style={{ width:52, height:52, borderRadius:8, overflow:'hidden', border:'var(--ff-border)', background:it.swatch||'#FFC7A8', flexShrink:0 }}>
                            {it.image
                              ? <img src={it.image} alt={it.name} style={{ width:'100%', height:'100%', objectFit:'cover' }} onError={e=>e.target.style.display='none'}/>
                              : <ProductArt product={{ id:it.product_id, name:it.name, cat:'home', swatch:it.swatch||'#FFC7A8' }} ratio="1/1" size="sm"/>
                            }
                          </div>
                        ))}
                      </div>

                      {/* Tracking accordion */}
                      {openOrder === o.id && (
                        <OrderTracking orderId={o.id}/>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* ADDRESSES TAB */}
          {tab === 'wishlist' && (
            <WishlistTab user={user} goto={window.FF_CTX?.goto}/>
          )}

          {tab === 'referral' && (
            <ReferralTab user={user}/>
          )}

          {tab === 'addresses' && (
            <div>
              {addrModal && <AddressModal onClose={()=>setAddrModal(false)} onSaved={(a)=>{ setAddresses(p=>[...p,a]); setAddrModal(false); window.FF_TOAST&&window.FF_TOAST('Address saved ✓'); }}/>}
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20 }}>
                <h2 className="ff-display" style={{ fontSize:28 }}>Saved addresses</h2>
                <button className="ff-btn ff-btn--primary ff-btn--sm" onClick={()=>setAddrModal(true)}>+ Add address</button>
              </div>
              {addresses.length === 0 ? (
                <div className="ff-card" style={{ padding:32, textAlign:'center' }}>
                  <div style={{ fontSize:36, marginBottom:10 }}>🏠</div>
                  <p style={{ color:'var(--ff-muted)', marginBottom:16 }}>No saved addresses yet.</p>
                  <button className="ff-btn ff-btn--primary ff-btn--sm" onClick={()=>setAddrModal(true)}>+ Add your first address</button>
                </div>
              ) : (
                <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
                  {addresses.map(a => (
                    <div key={a.id} className="ff-card" style={{ padding:18, background: a.is_default==1 ? 'var(--ff-sun)' : '#fff' }}>
                      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6 }}>
                        <span className="ff-chip">{a.label}</span>
                        {a.is_default==1 && <span style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'.08em' }}>Default</span>}
                      </div>
                      <div style={{ fontWeight:700 }}>{a.name}</div>
                      <div style={{ fontSize:13, marginTop:4 }}>{a.line1}{a.line2 ? ', '+a.line2 : ''}</div>
                      <div style={{ fontSize:13 }}>{a.city}, {a.state} — {a.pincode}</div>
                      <div style={{ fontSize:12, color:'var(--ff-ink-2)', marginTop:6 }}>+91 {a.phone}</div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* PROFILE TAB */}
          {tab === 'profile' && (
            <div style={{ display:'grid', gap:20 }}>
              <div className="ff-card" style={{ padding:24, maxWidth:540 }}>
                <h2 className="ff-display" style={{ fontSize:24, marginBottom:18 }}>Profile details</h2>
                <div style={{ display:'grid', gap:12 }}>
                  <div><label className="ff-label">Name</label><input className="ff-input" value={profName} onChange={e=>setProfName(e.target.value)}/></div>
                  <div><label className="ff-label">Email</label><input className="ff-input" value={user.email} disabled style={{ opacity:.6 }}/></div>
                  <div><label className="ff-label">Phone</label><input className="ff-input" value={profPhone} onChange={e=>setProfPhone(e.target.value.replace(/\D/g,'').slice(0,10))}/></div>
                  <button className="ff-btn ff-btn--primary" style={{ justifySelf:'start', marginTop:6 }} onClick={saveProfile}>
                    {profSaved ? '✓ Saved!' : 'Save changes'}
                  </button>
                </div>
              </div>

              {/* Email verification card */}
              <div className="ff-card" style={{ padding:24, maxWidth:540, background: isVerified ? 'var(--ff-mint)' : '#FFF8F0', border: isVerified ? '1.5px solid #78D5A8' : '1.5px solid #F5D878' }}>
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:12 }}>
                  <div>
                    <div style={{ fontWeight:700, fontSize:15 }}>
                      {isVerified ? '✅ Email verified' : '⚠️ Email not verified'}
                    </div>
                    <div style={{ fontSize:13, color:'var(--ff-ink-2)', marginTop:3 }}>
                      {isVerified
                        ? `${user.email} is verified.`
                        : 'Verify your email to secure your account and receive order updates.'
                      }
                    </div>
                  </div>
                  {!isVerified && (
                    <button className="ff-btn ff-btn--ink ff-btn--sm" onClick={sendVerifyOtp} disabled={otpLoading} style={{ flexShrink:0 }}>
                      {otpLoading ? 'Sending…' : 'Send code'}
                    </button>
                  )}
                </div>
                {otpStep && !isVerified && (
                  <div style={{ marginTop:14, display:'grid', gap:8 }}>
                    <div style={{ fontSize:12, color:'var(--ff-ink-2)' }}>{otpMsg}</div>
                    <div style={{ display:'flex', gap:8 }}>
                      <input className="ff-input" value={otpCode} maxLength={6}
                        onChange={e=>setOtpCode(e.target.value.replace(/\D/g,'').slice(0,6))}
                        placeholder="6-digit code"
                        style={{ fontFamily:'monospace', fontSize:20, letterSpacing:'.2em', textAlign:'center', fontWeight:700 }}/>
                      <button className="ff-btn ff-btn--primary" onClick={submitOtp} disabled={otpCode.length<6||otpLoading}>
                        {otpLoading?'…':'Verify'}
                      </button>
                    </div>
                    <button onClick={sendVerifyOtp} disabled={otpCd>0||otpLoading}
                      style={{ fontSize:12, color: otpCd>0?'var(--ff-muted)':'var(--ff-accent)', background:'none', border:'none', cursor: otpCd>0?'default':'pointer', textAlign:'left' }}>
                      {otpCd>0?`Resend in ${otpCd}s`:'Resend code'}
                    </button>
                  </div>
                )}
              </div>

              <div className="ff-card" style={{ padding:24, maxWidth:540 }}>
                <h2 className="ff-display" style={{ fontSize:20, marginBottom:14 }}>Change password</h2>
                <div style={{ display:'grid', gap:10 }}>
                  <div><label className="ff-label">Current password</label><input className="ff-input" type="password" value={pwCurr} onChange={e=>setPwCurr(e.target.value)}/></div>
                  <div><label className="ff-label">New password</label><input className="ff-input" type="password" value={pwNew} onChange={e=>setPwNew(e.target.value)} placeholder="Min 8 chars, upper+lower+number"/></div>
                  {pwMsg && <div style={{ fontSize:13, color: pwMsg.startsWith('✓') ? 'var(--ff-teal)' : 'var(--ff-accent)' }}>{pwMsg}</div>}
                  <button className="ff-btn" style={{ justifySelf:'start' }} onClick={changePassword}>Update password</button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </main>
  );
}

// Loads order tracking lazily — shows live Shiprocket data if AWB assigned
function OrderTracking({ orderId }) {
  const [order, setOrder] = useStateA(null);

  useEffectA(() => {
    // orders.php?action=get automatically fetches live Shiprocket data
    // when awb_code is present — no manual sync needed
    FF_API.orders.get(orderId)
      .then(o => setOrder(o))
      .catch(console.error);
  }, [orderId]);

  if (!order) return (
    <div style={{ marginTop:14, fontSize:13, color:'var(--ff-muted)', display:'flex', alignItems:'center', gap:8 }}>
      <span>⏳</span> Loading…
    </div>
  );

  // ── Static milestone steps (always shown, top = placed, bottom = delivered)
  const STEPS = [
    { key:'placed',   label:'Order placed',       icon:'📋' },
    { key:'packed',   label:'Packed',              icon:'📦' },
    { key:'shipped',  label:'Shipped',             icon:'🚚' },
    { key:'delivery', label:'Out for delivery',    icon:'🛵' },
    { key:'delivered',label:'Delivered',           icon:'✅' },
  ];

  // Map order status → which step is current
  const statusMap = {
    'Processing':       'placed',
    'Packed':           'packed',
    'Shipped':          'shipped',
    'Out for delivery': 'delivery',
    'Delivered':        'delivered',
  };
  const currentKey = statusMap[order.status] || 'placed';
  const currentIdx = STEPS.findIndex(s => s.key === currentKey);

  // Live Shiprocket activities (auto-fetched by orders.php when AWB present)
  const activities = order.sr_tracking?.shipment_track_activities || [];
  const hasLive    = activities.length > 0;

  return (
    <div style={{ marginTop:18, paddingTop:18, borderTop:'2px dashed rgba(0,0,0,.1)' }}>

      {/* AWB badge */}
      {order.awb_code && (
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center',
          marginBottom:16, flexWrap:'wrap', gap:8 }}>
          <h4 className="ff-display" style={{ fontSize:16, margin:0 }}>
            {hasLive ? 'Live Tracking' : 'Order Updates'}
          </h4>
          <div style={{ fontSize:12, color:'var(--ff-ink-2)', display:'flex', gap:8, alignItems:'center' }}>
            {order.courier_name && <span style={{ fontWeight:600 }}>{order.courier_name}</span>}
            <span style={{ fontFamily:'monospace', background:'var(--ff-bg-2)',
              padding:'2px 8px', borderRadius:4 }}>{order.awb_code}</span>
          </div>
        </div>
      )}

      {/* ── Static milestone tracker (always shown) ── */}
      {!order.awb_code && (
        <h4 className="ff-display" style={{ fontSize:16, marginBottom:16 }}>Order Updates</h4>
      )}

      <div style={{ position:'relative', paddingLeft:28, marginBottom: hasLive ? 20 : 0 }}>
        <div style={{ position:'absolute', left:8, top:4, bottom:4, width:2,
          background:'var(--ff-line)', borderRadius:2 }}/>
        {STEPS.map((step, i) => {
          const done    = i < currentIdx;
          const current = i === currentIdx;
          const future  = i > currentIdx;
          return (
            <div key={step.key} style={{ position:'relative', paddingBottom:16,
              opacity: future ? .45 : 1 }}>
              <div style={{
                position:'absolute', left:-28, top:0,
                width:18, height:18, borderRadius:999,
                display:'flex', alignItems:'center', justifyContent:'center',
                fontSize:10,
                background: current ? 'var(--ff-accent)' : done ? 'var(--ff-ink)' : 'var(--ff-card)',
                border: future ? '2px solid var(--ff-line)' : current ? '2px solid var(--ff-accent)' : '2px solid var(--ff-ink)',
                color: (current||done) ? '#fff' : 'var(--ff-muted)',
              }}>
                {done ? '✓' : current ? '●' : ''}
              </div>
              <div style={{ fontWeight: current ? 700 : done ? 600 : 400, fontSize:13,
                color: current ? 'var(--ff-accent)' : done ? 'var(--ff-ink)' : 'var(--ff-muted)' }}>
                {step.label}
              </div>
              {current && order.status === 'Processing' && (
                <div style={{ fontSize:11, color:'var(--ff-muted)', marginTop:2 }}>
                  {order.created_at ? new Date(order.created_at).toLocaleDateString('en-IN',{day:'numeric',month:'short',hour:'2-digit',minute:'2-digit'}) : 'Just now'}
                </div>
              )}
              {current && order.awb_code && order.status === 'Shipped' && (
                <div style={{ fontSize:11, color:'var(--ff-muted)', marginTop:2 }}>
                  AWB: {order.awb_code}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* ── Live Shiprocket activity feed (shown when AWB assigned) ── */}
      {hasLive && (
        <div style={{ background:'var(--ff-bg-2)', borderRadius:12, padding:'14px 16px' }}>
          <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase',
            letterSpacing:'.08em', color:'var(--ff-muted)', marginBottom:12 }}>
            Courier updates
          </div>
          {order.sr_tracking?.shipment_status && (
            <div style={{ marginBottom:10, fontWeight:700, fontSize:13,
              display:'flex', alignItems:'center', gap:8 }}>
              <span>{order.sr_tracking.shipment_status==='Delivered'?'✅':
                order.sr_tracking.shipment_status==='Out For Delivery'?'🛵':'🚚'}</span>
              {order.sr_tracking.shipment_status}
              {order.sr_tracking.etd && (
                <span style={{ fontWeight:400, fontSize:11, color:'var(--ff-muted)' }}>
                  · ETA {new Date(order.sr_tracking.etd).toLocaleDateString('en-IN',{day:'numeric',month:'short'})}
                </span>
              )}
            </div>
          )}
          <div style={{ position:'relative', paddingLeft:16 }}>
            <div style={{ position:'absolute', left:4, top:4, bottom:4, width:1.5,
              background:'var(--ff-line)' }}/>
            {activities.slice(0,8).map((a,i) => (
              <div key={i} style={{ position:'relative', paddingBottom:12 }}>
                <div style={{ position:'absolute', left:-16, top:3, width:9, height:9,
                  borderRadius:999, background: i===0 ? 'var(--ff-accent)' : 'var(--ff-line)',
                  border: i===0 ? '2px solid var(--ff-accent)' : 'none' }}/>
                <div style={{ fontSize:12, fontWeight: i===0 ? 600 : 400 }}>
                  {a['sr-status'] || a.activity}
                </div>
                <div style={{ fontSize:11, color:'var(--ff-muted)' }}>
                  {a.date}{a.location ? ' · ' + a.location : ''}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Dispatched but no activities yet */}
      {order.awb_code && !hasLive && (
        <div style={{ fontSize:12, color:'var(--ff-muted)', padding:'8px 0' }}>
          🚚 Dispatched via {order.courier_name||'courier'} — tracking updates coming soon.
        </div>
      )}
    </div>
  );
}

function OrderStatusChip({ status }) {
  const map = {
    'Delivered':        { bg:'var(--ff-mint)' },
    'Out for delivery': { bg:'var(--ff-sun)' },
    'Processing':       { bg:'var(--ff-lav)' },
    'Packed':           { bg:'var(--ff-lav)' },
    'Shipped':          { bg:'var(--ff-sky)' },
    'Refunded':         { bg:'#E5E5E5' },
    'Cancelled':        { bg:'#FFDDDD' },
  };
  const m = map[status] || { bg:'#fff' };
  return <span className="ff-chip" style={{ background:m.bg }}>{status}</span>;
}

// ─── ADMIN DASHBOARD ──────────────────────────────────────────────────────────
// ─── ADMIN DASHBOARD — Full control panel ────────────────────────────────────

Object.assign(window, { AccountPage, WishlistTab, OrderTracking, OrderStatusChip });