// pages-misc.jsx — Brands, FAQ, Account, Track Order

function BrandsPage({ onOpen }) {
  const brands = [...new Set(window.PRODUCTS.map(p => p.brand))];

  const openBrand = (brand) => {
    const slug = (brand || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
    if (window.MS_navigate) window.MS_navigate('brand', { slug });
  };

  return (
    <>
      <h1 className="page-title">The <em>lineup</em>.</h1>
      <p className="page-sub">{brands.length} brands. {window.PRODUCTS.length} cartons. One shipping origin: Tyendinaga, ON.</p>

      <div className="brand-strip" style={{marginTop: 32, gridTemplateColumns: `repeat(${Math.min(brands.length, 5)}, 1fr)`}}>
        {brands.map(b => {
          const slug = (b || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
          return (
            <a
              key={b}
              href={`/brands/${slug}`}
              onClick={(e)=>{ if (e.metaKey||e.ctrlKey||e.shiftKey) return; e.preventDefault(); openBrand(b); }}
              className="brand-card"
              style={{padding: '32px 16px', textDecoration:'none', cursor:'pointer'}}
            >
              {b}
              <span className="count">{window.PRODUCTS.filter(p=>p.brand===b).length} sku</span>
            </a>
          );
        })}
      </div>

      {brands.map(b => {
        const items = window.PRODUCTS.filter(p => p.brand === b);
        return (
          <div key={b} style={{marginTop: 56}}>
            <div className="section-head">
              <div>
                <span className="sticker-tag">★ Brand</span>
                <h2>{b}.</h2>
              </div>
              <a
                href={`/brands/${(b || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')}`}
                onClick={(e)=>{ if (e.metaKey||e.ctrlKey||e.shiftKey) return; e.preventDefault(); openBrand(b); }}
                className="link"
                style={{cursor:'pointer'}}
              >
                {items.length} cartons →
              </a>
            </div>
            <div className="grid-4">
              {items.map(p => <ProductCard key={p.sku} p={p} onAdd={(p)=>window.addCart && window.addCart(p)} onOpen={onOpen}/>)}
            </div>
          </div>
        );
      })}
    </>
  );
}

function FAQPage() {
  const [open, setOpen] = React.useState(0);
  return (
    <>
      <h1 className="page-title" style={{textAlign:'center'}}>Frequently <em>asked</em>.</h1>
      <p className="page-sub" style={{textAlign:'center', margin:'0 auto 40px'}}>Shipping, payment, restocks. The basics.</p>

      <div className="faq-list">
        {window.FAQ.map((f, i) => (
          <div key={i} className={"faq-item " + (open === i ? 'open' : '')}>
            <div className="faq-q" onClick={()=>setOpen(open === i ? -1 : i)}>
              <span className="q-text">{f.q}</span>
              <span className="chevron">+</span>
            </div>
            <div className="faq-a">{f.a}</div>
          </div>
        ))}
      </div>

      <div className="promo-strip" style={{marginTop: 80, maxWidth: 820, marginLeft:'auto', marginRight:'auto'}}>
        <div>
          <h3>Still stuck?</h3>
          <p>Email <code>help@madsmokes.ca</code>. We reply within 24h, usually faster.</p>
        </div>
        <button className="btn btn-primary btn-lg">Email us</button>
      </div>
    </>
  );
}

// ---- Auth forms ----

function AuthPanel({ onLogin, onRegister }) {
  const [mode, setMode] = React.useState('login'); // 'login' | 'register' | 'forgot'
  const referralCode = (typeof window !== 'undefined' && window.getStoredReferral && window.getStoredReferral()) || '';
  const [form, setForm] = React.useState({
    email: '', password: '', first_name: '', last_name: '', date_of_birth: '',
    referral_code: referralCode,
  });
  const [error, setError] = React.useState('');
  const [info, setInfo] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true); setError(''); setInfo('');
    try {
      if (mode === 'login') {
        await onLogin(form.email, form.password);
      } else if (mode === 'register') {
        await onRegister(form);
      } else if (mode === 'forgot') {
        const r = await window.api.post('/auth/forgot-password', { email: form.email });
        setInfo(r.message || 'If that email is registered, a reset link is on its way.');
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const headings = {
    login:    { h: <>Sign <em>in</em>.</>,           sub: 'Welcome back.' },
    register: { h: <>Create <em>account</em>.</>,    sub: 'One account. Every order. All yours.' },
    forgot:   { h: <>Reset <em>password</em>.</>,    sub: "Drop your email — we'll send a reset link." },
  };

  return (
    <div style={{maxWidth: 480, margin: '0 auto'}}>
      <h1 className="page-title" style={{marginBottom:4}}>{headings[mode].h}</h1>
      <p className="page-sub" style={{marginBottom: 32}}>{headings[mode].sub}</p>

      <form className="checkout-form" onSubmit={submit} style={{gap: 14}}>
        {error && (
          <div style={{background:'var(--blood)', color:'var(--bone)', padding:'10px 14px',
                       fontSize:12, fontWeight:700, borderRadius:4, gridColumn:'1/-1'}}>
            {error}
          </div>
        )}
        {info && (
          <div style={{background:'var(--acid)', color:'var(--ink)', padding:'10px 14px',
                       fontSize:12, fontWeight:700, borderRadius:4, gridColumn:'1/-1'}}>
            ★ {info}
          </div>
        )}

        {mode === 'register' && (
          <>
            <div>
              <label className="label">First name</label>
              <input className="field" required value={form.first_name} onChange={e=>set('first_name',e.target.value)}/>
            </div>
            <div>
              <label className="label">Last name</label>
              <input className="field" required value={form.last_name} onChange={e=>set('last_name',e.target.value)}/>
            </div>
          </>
        )}

        <div style={{gridColumn:'1/-1'}}>
          <label className="label">Email</label>
          <input className="field" type="email" required value={form.email} onChange={e=>set('email',e.target.value)}/>
        </div>
        {mode !== 'forgot' && (
          <div style={{gridColumn:'1/-1'}}>
            <label className="label">Password</label>
            <input className="field" type="password" required minLength={8} value={form.password} onChange={e=>set('password',e.target.value)}/>
          </div>
        )}

        {mode === 'register' && (
          <div style={{gridColumn:'1/-1'}}>
            <label className="label">Date of birth <span style={{color:'var(--smoke-400)', fontWeight:400}}>(must be 19+)</span></label>
            <input className="field" type="date" required value={form.date_of_birth} onChange={e=>set('date_of_birth',e.target.value)}/>
          </div>
        )}

        {mode === 'register' && (
          <div style={{gridColumn:'1/-1'}}>
            <label className="label">
              Referral code <span style={{color:'var(--smoke-400)', fontWeight:400}}>(optional · $10 off first carton)</span>
            </label>
            <input
              className="field"
              type="text"
              value={form.referral_code || ''}
              onChange={e=>set('referral_code', e.target.value.toUpperCase())}
              placeholder="FRIENDCODE"
              style={{textTransform:'uppercase', letterSpacing: 2, fontFamily:'var(--font-mono)'}}
            />
            {referralCode && form.referral_code === referralCode && (
              <p style={{fontSize:11, color:'var(--acid)', marginTop:4, fontWeight:700}}>
                ★ Referral code pre-filled from your link
              </p>
            )}
          </div>
        )}

        <div style={{gridColumn:'1/-1', display:'flex', gap:12, alignItems:'center', marginTop:4}}>
          <button className="btn btn-primary btn-lg" type="submit" disabled={loading} style={{flex:1, justifyContent:'center'}}>
            {loading ? '...'
              : mode === 'login'    ? 'Sign in'
              : mode === 'register' ? 'Create account'
              :                       'Send reset link'}
          </button>
        </div>

        {mode === 'login' && (
          <p style={{gridColumn:'1/-1', fontSize:12, color:'var(--smoke-400)', textAlign:'center', marginTop:4}}>
            <button type="button" onClick={()=>{setMode('forgot'); setError(''); setInfo('');}}
              style={{background:'none', border:'none', color:'var(--smoke-400)', cursor:'pointer', textDecoration:'underline', fontSize:12}}>
              Forgot your password?
            </button>
          </p>
        )}

        <p style={{gridColumn:'1/-1', fontSize:12, color:'var(--smoke-400)', textAlign:'center', marginTop:4}}>
          {mode === 'login'    && <>No account? <button type="button" onClick={()=>{setMode('register'); setError(''); setInfo('');}} style={{background:'none', border:'none', color:'var(--acid)', cursor:'pointer', fontWeight:700, fontSize:12}}>Create one</button></>}
          {mode === 'register' && <>Already have one? <button type="button" onClick={()=>{setMode('login'); setError(''); setInfo('');}} style={{background:'none', border:'none', color:'var(--acid)', cursor:'pointer', fontWeight:700, fontSize:12}}>Sign in</button></>}
          {mode === 'forgot'   && <>Remember it? <button type="button" onClick={()=>{setMode('login'); setError(''); setInfo('');}} style={{background:'none', border:'none', color:'var(--acid)', cursor:'pointer', fontWeight:700, fontSize:12}}>Sign in</button></>}
        </p>
      </form>
    </div>
  );
}

function ResetPasswordPage({ token, onSuccess }) {
  const [pw, setPw] = React.useState('');
  const [pw2, setPw2] = React.useState('');
  const [error, setError] = React.useState('');
  const [info, setInfo] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    if (!token) { setError('Missing reset token. Use the link from your email.'); return; }
    if (pw.length < 8) { setError('Password must be at least 8 characters.'); return; }
    if (pw !== pw2) { setError("Passwords don't match."); return; }
    setLoading(true); setError(''); setInfo('');
    try {
      await window.api.post('/auth/reset-password', { token, new_password: pw });
      setInfo('Password updated. Redirecting to sign in…');
      setTimeout(() => { onSuccess(); }, 1500);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{maxWidth: 480, margin: '0 auto'}}>
      <h1 className="page-title" style={{marginBottom:4}}>Reset <em>password</em>.</h1>
      <p className="page-sub" style={{marginBottom: 32}}>Pick something you'll actually remember.</p>
      <form onSubmit={submit} className="checkout-form" style={{gap: 14}}>
        {error && (
          <div style={{background:'var(--blood)', color:'var(--bone)', padding:'10px 14px', fontSize:12, fontWeight:700, borderRadius:4, gridColumn:'1/-1'}}>
            {error}
          </div>
        )}
        {info && (
          <div style={{background:'var(--acid)', color:'var(--ink)', padding:'10px 14px', fontSize:12, fontWeight:700, borderRadius:4, gridColumn:'1/-1'}}>
            ★ {info}
          </div>
        )}
        <div style={{gridColumn:'1/-1'}}>
          <label className="label">New password (8+ characters)</label>
          <input className="field" type="password" required minLength={8} value={pw} onChange={e=>setPw(e.target.value)} autoFocus/>
        </div>
        <div style={{gridColumn:'1/-1'}}>
          <label className="label">Confirm new password</label>
          <input className="field" type="password" required minLength={8} value={pw2} onChange={e=>setPw2(e.target.value)}/>
        </div>
        <div style={{gridColumn:'1/-1', marginTop: 4}}>
          <button className="btn btn-primary btn-lg" type="submit" disabled={loading} style={{width:'100%', justifyContent:'center'}}>
            {loading ? '...' : 'Update password'}
          </button>
        </div>
      </form>
    </div>
  );
}


// ---- Address management ----

function AddressForm({ initial, onSubmit, onCancel, submitting }) {
  const [form, setForm] = React.useState({
    full_name:        initial?.full_name        || '',
    line_1:           initial?.line_1           || '',
    line_2:           initial?.line_2           || '',
    city:             initial?.city             || '',
    province:         initial?.province         || 'ON',
    postal_code:      initial?.postal_code      || '',
    phone:            initial?.phone            || '',
    label:            initial?.label            || 'Home',
    is_default:       !!initial?.is_default,
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const submit = (e) => { e.preventDefault(); onSubmit(form); };

  return (
    <form onSubmit={submit} className="checkout-form" style={{gap: 12, maxWidth: 480, marginTop: 12}}>
      <div style={{gridColumn:'1/-1'}}>
        <label className="label">Label (Home, Work…)</label>
        <input className="field" value={form.label} onChange={e=>set('label', e.target.value)}/>
      </div>
      <div style={{gridColumn:'1/-1'}}>
        <label className="label">Full name *</label>
        <input className="field" required value={form.full_name} onChange={e=>set('full_name', e.target.value)}/>
      </div>
      <div style={{gridColumn:'1/-1'}}>
        <label className="label">Street address *</label>
        <input className="field" required value={form.line_1} onChange={e=>set('line_1', e.target.value)}/>
      </div>
      <div style={{gridColumn:'1/-1'}}>
        <label className="label">Apt / suite (optional)</label>
        <input className="field" value={form.line_2} onChange={e=>set('line_2', e.target.value)}/>
      </div>
      <div className="row-3">
        <div>
          <label className="label">City *</label>
          <input className="field" required value={form.city} onChange={e=>set('city', e.target.value)}/>
        </div>
        <div>
          <label className="label">Province *</label>
          <select className="field" value={form.province} onChange={e=>set('province', e.target.value)}>
            {['ON','BC','AB','SK','MB','NB','NS','PEI','NL','YT','NT'].map(p=><option key={p}>{p}</option>)}
          </select>
        </div>
        <div>
          <label className="label">Postal *</label>
          <input className="field" required value={form.postal_code} onChange={e=>set('postal_code', e.target.value.toUpperCase())}/>
        </div>
      </div>
      <div style={{gridColumn:'1/-1'}}>
        <label className="label">Phone (optional)</label>
        <input className="field" value={form.phone} onChange={e=>set('phone', e.target.value)}/>
      </div>
      <div style={{gridColumn:'1/-1', display:'flex', alignItems:'center', gap: 8}}>
        <input
          type="checkbox" id="is_default"
          checked={form.is_default} onChange={e=>set('is_default', e.target.checked)}
        />
        <label htmlFor="is_default" style={{fontSize: 13, cursor: 'pointer'}}>Default shipping address</label>
      </div>
      <div style={{gridColumn:'1/-1', display:'flex', gap: 12, marginTop: 8}}>
        <button type="submit" className="btn btn-primary" disabled={submitting}>
          {submitting ? 'Saving…' : (initial ? 'Update address' : 'Save address')}
        </button>
        <button type="button" className="btn btn-ghost" onClick={onCancel} disabled={submitting}>
          Cancel
        </button>
      </div>
    </form>
  );
}

function AddressesTab({ addresses, setAddresses, addrsLoaded }) {
  const [editing, setEditing] = React.useState(null); // null | 'new' | address object
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');

  const save = async (form) => {
    setSubmitting(true); setError('');
    try {
      if (editing === 'new') {
        const r = await window.api.post('/users/addresses', form);
        setAddresses(arr => [...arr, r.address]);
      } else {
        const r = await window.api.put('/users/addresses/' + editing.id, form);
        setAddresses(arr => arr.map(a => a.id === editing.id ? r.address : a));
      }
      // If marked as default, unmark others locally
      if (form.is_default) {
        setAddresses(arr => arr.map(a => ({
          ...a,
          is_default: editing !== 'new' && a.id === editing.id ? true
            : editing === 'new' && a === arr[arr.length - 1] ? true
            : false,
        })));
      }
      setEditing(null);
    } catch (err) {
      setError(err.message || 'Could not save address.');
    } finally {
      setSubmitting(false);
    }
  };

  const remove = async (id) => {
    if (!confirm('Delete this address?')) return;
    try {
      await window.api.del('/users/addresses/' + id);
      setAddresses(arr => arr.filter(a => a.id !== id));
    } catch (err) {
      alert('Could not delete: ' + err.message);
    }
  };

  return (
    <>
      <h3 style={{fontFamily:'var(--font-display)', fontSize:32, textTransform:'uppercase', margin:'0 0 16px'}}>Addresses</h3>
      {!addrsLoaded && <p style={{color:'var(--fg-3)'}}>Loading...</p>}
      {addrsLoaded && !addresses.length && !editing && (
        <p style={{color:'var(--smoke-400)', fontSize:13}}>No saved addresses yet.</p>
      )}

      {addresses.map(a => (
        <div key={a.id} className="card" style={{maxWidth:480, marginBottom:12}}>
          {a.is_default && <div className="t-eyebrow" style={{marginBottom:6}}>Default ship-to</div>}
          {a.label && a.label !== 'Home' && (
            <div style={{fontSize:11, color:'var(--smoke-400)', textTransform:'uppercase', letterSpacing:'.08em', marginBottom: 4}}>
              {a.label}
            </div>
          )}
          <div style={{fontFamily:'var(--font-mono)', fontSize:14, lineHeight:1.6, color:'var(--bone)'}}>
            {a.full_name}<br/>
            {a.line_1}{a.line_2 ? ', ' + a.line_2 : ''}<br/>
            {a.city}, {a.province} {a.postal_code}
            {a.phone && <><br/>{a.phone}</>}
          </div>
          <div style={{display:'flex', gap: 8, marginTop: 12}}>
            <button type="button" className="btn btn-ghost" style={{padding:'6px 12px', fontSize:11}}
              onClick={()=>setEditing(a)}>Edit</button>
            <button type="button" className="btn btn-ghost" style={{padding:'6px 12px', fontSize:11, color: 'var(--blood)'}}
              onClick={()=>remove(a.id)}>Delete</button>
          </div>
        </div>
      ))}

      {error && (
        <div style={{background:'var(--blood)', color:'var(--bone)', padding:'10px 14px', fontFamily:'var(--font-mono)', fontSize:12, fontWeight:700, borderRadius:4, maxWidth:480, marginBottom:12}}>
          ★ {error}
        </div>
      )}

      {!editing && (
        <button type="button" className="btn btn-primary" style={{marginTop:8}} onClick={()=>setEditing('new')}>
          + Add address
        </button>
      )}
      {editing && (
        <AddressForm
          initial={editing === 'new' ? null : editing}
          onSubmit={save}
          onCancel={()=>{ setEditing(null); setError(''); }}
          submitting={submitting}
        />
      )}
    </>
  );
}

// ---- Restock alerts tab ----

function RestockAlertsTab() {
  const [alerts, setAlerts] = React.useState([]);
  const [loaded, setLoaded] = React.useState(false);

  React.useEffect(() => {
    window.api.get('/restock-alerts')
      .then(d => { setAlerts(d.alerts || []); setLoaded(true); })
      .catch(() => setLoaded(true));
  }, []);

  const remove = async (id) => {
    if (!confirm('Remove this alert?')) return;
    try {
      await window.api.del('/restock-alerts/' + id);
      setAlerts(arr => arr.filter(a => a.id !== id));
    } catch (err) {
      alert('Could not remove: ' + err.message);
    }
  };

  return (
    <>
      <h3 style={{fontFamily:'var(--font-display)', fontSize:32, textTransform:'uppercase', margin:'0 0 16px'}}>Restock alerts</h3>
      {!loaded && <p style={{color:'var(--fg-3)'}}>Loading…</p>}
      {loaded && !alerts.length && (
        <p style={{color:'var(--smoke-400)', fontSize:13}}>
          No restock alerts. Sign up on any out-of-stock product page to get notified when it drops.
        </p>
      )}
      {alerts.map(a => (
        <div key={a.id} className="card" style={{maxWidth:480, marginBottom:12, display:'flex', alignItems:'center', gap: 12, padding: 14}}>
          {a.image_url && (
            <img src={a.image_url} alt={a.product_name}
              style={{width: 60, height: 60, objectFit: 'contain', background:'var(--bone-warm)', border:'2px solid var(--ink)'}}/>
          )}
          <div style={{flex: 1, minWidth: 0}}>
            <div style={{fontFamily:'var(--font-ui)', fontWeight: 700, fontSize: 14, textTransform:'uppercase', color:'var(--bone)'}}>
              {a.product_name}
            </div>
            <div style={{fontFamily:'var(--font-mono)', fontSize: 11, color: a.stock_status === 'out_of_stock' ? 'var(--ember)' : 'var(--acid)', marginTop: 2, textTransform:'uppercase'}}>
              {a.stock_status === 'out_of_stock' ? 'Still out' : 'Back in stock!'}
              {a.notified_at && ' · Notified ' + new Date(a.notified_at).toLocaleDateString()}
            </div>
          </div>
          <button className="btn btn-ghost" style={{padding:'6px 10px', fontSize: 11, color:'var(--blood)'}}
            onClick={()=>remove(a.id)}>Remove</button>
        </div>
      ))}
    </>
  );
}

// ---- Connected AccountPage ----

function AccountPage({ user, onTrack, onLogin, onRegister, onLogout }) {
  const [tab, setTab] = React.useState('orders');
  const [orders, setOrders] = React.useState([]);
  const [addresses, setAddresses] = React.useState([]);
  const [profile, setProfile] = React.useState(null);
  const [profileForm, setProfileForm] = React.useState({});
  const [profileMsg, setProfileMsg] = React.useState('');
  const [ordersLoaded, setOrdersLoaded] = React.useState(false);
  const [addrsLoaded, setAddrsLoaded] = React.useState(false);

  // Load tab data — must come BEFORE any conditional return to keep hook order stable
  React.useEffect(() => {
    if (!user) return;
    if (tab === 'orders' && !ordersLoaded) {
      window.api.get('/orders?limit=10')
        .then(d => { setOrders(d.orders || []); setOrdersLoaded(true); })
        .catch(() => setOrdersLoaded(true));
    }
    if (tab === 'addresses' && !addrsLoaded) {
      window.api.get('/users/addresses')
        .then(d => { setAddresses(d.addresses || []); setAddrsLoaded(true); })
        .catch(() => setAddrsLoaded(true));
    }
    if (tab === 'profile' && !profile) {
      window.api.get('/users/profile')
        .then(d => { setProfile(d.user); setProfileForm({ phone: d.user.phone || '', display_name: d.user.display_name || '' }); })
        .catch(() => {});
    }
  }, [tab, user]);

  // Not logged in — show auth forms
  if (!user) {
    return <AuthPanel onLogin={onLogin} onRegister={onRegister}/>;
  }

  // Admin/staff — show CMS redirect
  const isAdmin = user.role === 'admin' || user.role === 'staff';

  const saveProfile = async () => {
    try {
      await window.api.put('/users/profile', profileForm);
      setProfileMsg('Saved!');
      setTimeout(() => setProfileMsg(''), 2500);
    } catch (err) {
      setProfileMsg('Error: ' + err.message);
    }
  };

  const displayName = user.display_name || user.first_name || user.email.split('@')[0];

  return (
    <>
      <h1 className="page-title">Your <em>account</em>.</h1>
      <p className="page-sub">Hey, {displayName}. Welcome back.</p>

      <EmailVerificationBanner user={user}/>

      {isAdmin && (
        <div style={{background:'var(--acid)', color:'var(--ink)', padding:'14px 20px',
                     border:'2px solid var(--ink)', boxShadow:'4px 4px 0 var(--ink)',
                     display:'flex', alignItems:'center', justifyContent:'space-between',
                     marginBottom: 28, borderRadius:4}}>
          <div>
            <strong style={{fontFamily:'var(--font-ui)', fontWeight:700, fontSize:13, textTransform:'uppercase', letterSpacing:'.1em'}}>
              ★ {user.role === 'admin' ? 'Admin' : 'Staff'} access
            </strong>
            <p style={{fontSize:12, marginTop:3}}>You have CMS access. Manage products, orders, blog & more.</p>
          </div>
          <a href="/admin" target="_blank" rel="noreferrer"
             className="btn btn-primary" style={{whiteSpace:'nowrap', border:'2px solid var(--ink)'}}>
            Open CMS ↗
          </a>
        </div>
      )}

      <div className="account-grid">
        <div className="account-nav">
          <a className={tab==='orders' ? 'active' : ''} onClick={()=>setTab('orders')}>Orders</a>
          <a className={tab==='addresses' ? 'active' : ''} onClick={()=>setTab('addresses')}>Addresses</a>
          <a className={tab==='profile' ? 'active' : ''} onClick={()=>setTab('profile')}>Profile</a>
          <a className={tab==='alerts' ? 'active' : ''} onClick={()=>setTab('alerts')}>Restock alerts</a>
          <a className={tab==='referrals' ? 'active' : ''} onClick={()=>setTab('referrals')}>Refer &amp; earn</a>
          <a onClick={onLogout} style={{marginTop:20, color:'var(--blood)', cursor:'pointer'}}>Sign out</a>
        </div>

        <div>
          {tab === 'orders' && (
            <>
              <h3 style={{fontFamily:'var(--font-display)', fontSize:32, textTransform:'uppercase', margin:'0 0 16px'}}>Orders</h3>
              {!ordersLoaded && <p style={{color:'var(--fg-3)'}}>Loading...</p>}
              {ordersLoaded && !orders.length && (
                <div style={{color:'var(--smoke-400)', padding:'40px 0', textAlign:'center'}}>
                  <p style={{fontFamily:'var(--font-display)', fontSize:24, textTransform:'uppercase', color:'var(--bone)'}}>No orders yet.</p>
                  <p style={{marginTop:8, fontSize:13}}>Your first carton is a click away.</p>
                </div>
              )}
              {orders.map(o => (
                <div className="order-row" key={o.id}>
                  <div>
                    <div className="order-id">#{o.order_number}</div>
                    <div className="order-meta">{new Date(o.created_at).toLocaleDateString('en-CA', {year:'numeric',month:'short',day:'numeric'})} · {o.item_count} items</div>
                  </div>
                  <span className={"status " + o.status.replace(/_/g,'-')}>{o.status.replace(/_/g,' ')}</span>
                  <span style={{fontFamily:'var(--font-mono)', fontWeight:700, color:'var(--acid)'}}>${parseFloat(o.grand_total).toFixed(2)}</span>
                  <a
                    href={'/order/' + o.order_number}
                    onClick={(e)=>{
                      if (e.metaKey || e.ctrlKey || e.shiftKey) return;
                      e.preventDefault();
                      window.MS_navigate && window.MS_navigate('confirm', { orderNumber: o.order_number });
                    }}
                    className="btn btn-ghost"
                    style={{padding:'8px 14px', fontSize:11, textDecoration:'none'}}
                  >
                    View
                  </a>
                </div>
              ))}
            </>
          )}

          {tab === 'addresses' && (
            <AddressesTab
              addresses={addresses}
              setAddresses={setAddresses}
              addrsLoaded={addrsLoaded}
            />
          )}

          {tab === 'profile' && (
            <>
              <h3 style={{fontFamily:'var(--font-display)', fontSize:32, textTransform:'uppercase', margin:'0 0 16px'}}>Profile</h3>
              <div className="checkout-form" style={{maxWidth:480, gap:12}}>
                <div style={{gridColumn:'1/-1'}}>
                  <label className="label">Email</label>
                  <input className="field" value={user.email} disabled style={{opacity:.6}}/>
                </div>
                <div style={{gridColumn:'1/-1'}}>
                  <label className="label">Display name</label>
                  <input className="field" value={profileForm.display_name || ''} onChange={e=>setProfileForm(f=>({...f,display_name:e.target.value}))}/>
                </div>
                <div style={{gridColumn:'1/-1'}}>
                  <label className="label">Phone</label>
                  <input className="field" value={profileForm.phone || ''} onChange={e=>setProfileForm(f=>({...f,phone:e.target.value}))}/>
                </div>
                <div style={{gridColumn:'1/-1', display:'flex', alignItems:'center', gap:12}}>
                  <button className="btn btn-primary" onClick={saveProfile}>Save changes</button>
                  {profileMsg && <span style={{fontSize:12, color: profileMsg.startsWith('Error') ? 'var(--blood)' : 'var(--acid)', fontWeight:700}}>{profileMsg}</span>}
                </div>
              </div>
            </>
          )}

          {tab === 'alerts' && <RestockAlertsTab/>}

          {tab === 'referrals' && <ReferralsTab user={user} profile={profile} setProfile={setProfile} setTab={setTab}/>}
        </div>
      </div>
    </>
  );
}

// ---- Referrals tab ----

function ReferralsTab({ user, profile, setProfile, setTab }) {
  const [copied, setCopied] = React.useState('');

  // Hydrate profile if not yet loaded
  React.useEffect(() => {
    if (!profile) {
      window.api.get('/users/profile')
        .then(d => setProfile(d.user))
        .catch(() => {});
    }
  }, [profile]);

  const code = profile?.referral_code;
  const count = profile?.referral_count || 0;

  const shareUrl = code
    ? `${window.location.origin}/?ref=${encodeURIComponent(code)}`
    : '';
  const shareSubject = encodeURIComponent('Try Mad Smokes — $10 off your first carton');
  const shareBody = encodeURIComponent(
    `Hey — I've been ordering native smokes from Mad Smokes. Use my link for $10 off your first carton: ${shareUrl}`
  );

  const copy = (text, what) => {
    if (!text) return;
    try {
      navigator.clipboard.writeText(text);
      setCopied(what);
      setTimeout(() => setCopied(''), 1800);
    } catch {}
  };

  if (!profile) {
    return <p style={{color:'var(--fg-3)'}}>Loading…</p>;
  }

  if (!code) {
    return (
      <>
        <h3 style={{fontFamily:'var(--font-display)', fontSize:32, textTransform:'uppercase', margin:'0 0 16px'}}>Refer &amp; earn</h3>
        <p style={{color:'var(--fg-2)', maxWidth:520}}>
          Your referral code isn't set up yet. Contact support and we'll get you sorted.
        </p>
      </>
    );
  }

  return (
    <>
      <h3 style={{fontFamily:'var(--font-display)', fontSize:32, textTransform:'uppercase', margin:'0 0 8px'}}>Refer &amp; earn</h3>
      <p style={{color:'var(--fg-2)', maxWidth:560, marginBottom: 28}}>
        Send your code to a mate. They get <strong style={{color:'var(--acid)'}}>$10 off</strong> their first carton.
        You get <strong style={{color:'var(--acid)'}}>$10 credit</strong> on their first paid order.
      </p>

      <div style={{
        background:'var(--ink-soft)', border:'2px solid var(--ink-2)', borderRadius: 4,
        padding: 24, maxWidth: 600, marginBottom: 24
      }}>
        <div className="t-eyebrow" style={{marginBottom: 6}}>Your code</div>
        <div style={{
          fontFamily:'var(--font-mono)', fontWeight: 800, fontSize: 30, letterSpacing: 3,
          color:'var(--acid)', margin: '4px 0 18px', userSelect: 'all'
        }}>
          {code}
        </div>

        <div className="t-eyebrow" style={{marginBottom: 6}}>Share link</div>
        <div style={{display:'flex', gap:8, marginBottom: 8}}>
          <input
            className="field"
            value={shareUrl}
            readOnly
            onClick={(e)=>e.target.select()}
            style={{flex:1, fontFamily:'var(--font-mono)', fontSize:12}}
          />
          <button
            type="button"
            className="btn btn-primary"
            onClick={()=>copy(shareUrl, 'link')}
            style={{whiteSpace:'nowrap'}}
          >
            {copied === 'link' ? '✓ Copied' : 'Copy link'}
          </button>
        </div>

        <div style={{display:'flex', flexWrap:'wrap', gap: 8, marginTop: 14}}>
          <a
            className="btn btn-ghost"
            href={`mailto:?subject=${shareSubject}&body=${shareBody}`}
            style={{textDecoration:'none', fontSize: 12}}
          >
            ✉ Email
          </a>
          <a
            className="btn btn-ghost"
            href={`sms:?body=${shareBody}`}
            style={{textDecoration:'none', fontSize: 12}}
          >
            ☎ Text
          </a>
          <a
            className="btn btn-ghost"
            href={`https://wa.me/?text=${shareBody}`}
            target="_blank"
            rel="noreferrer"
            style={{textDecoration:'none', fontSize: 12}}
          >
            WhatsApp
          </a>
          <button
            type="button"
            className="btn btn-ghost"
            onClick={()=>copy(code, 'code')}
            style={{fontSize: 12}}
          >
            {copied === 'code' ? '✓ Copied' : 'Copy code only'}
          </button>
        </div>
      </div>

      <div style={{
        display:'grid', gridTemplateColumns:'repeat(2, 1fr)', gap: 12, maxWidth: 600, marginBottom: 24
      }}>
        <div style={{background:'var(--ink-soft)', border:'2px solid var(--ink-2)', borderRadius: 4, padding: 18}}>
          <div className="t-eyebrow">Friends signed up</div>
          <div style={{fontFamily:'var(--font-mono)', fontWeight: 700, fontSize: 28, color:'var(--bone)', marginTop: 4}}>
            {count}
          </div>
        </div>
        <div style={{background:'var(--ink-soft)', border:'2px solid var(--ink-2)', borderRadius: 4, padding: 18}}>
          <div className="t-eyebrow">Credit earned</div>
          <div style={{fontFamily:'var(--font-mono)', fontWeight: 700, fontSize: 28, color:'var(--acid)', marginTop: 4}}>
            ${(count * 10).toFixed(2)}
          </div>
        </div>
      </div>

      <div style={{
        background:'var(--ink)', border:'1px dashed var(--ink-2)', borderRadius: 4,
        padding: 18, maxWidth: 600, fontSize: 13, color:'var(--fg-2)', lineHeight: 1.6
      }}>
        <strong style={{color:'var(--bone)', display:'block', marginBottom: 6}}>How it works</strong>
        1. Share your link or code with friends who smoke.<br/>
        2. They get $10 off their first carton when they enter your code at checkout.<br/>
        3. Once their order ships, $10 is credited to your account — apply it to any future order.
      </div>
    </>
  );
}

function TrackOrderPage() {
  const [orderId, setOrderId] = React.useState('');
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');

  const fmtDateTime = (iso) => {
    if (!iso) return '—';
    const d = new Date(iso);
    const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    const hh = d.getHours();
    const mm = String(d.getMinutes()).padStart(2,'0');
    const ampm = hh >= 12 ? 'pm' : 'am';
    const h12 = ((hh + 11) % 12) + 1;
    return `${months[d.getMonth()]} ${d.getDate()} · ${h12}:${mm}${ampm}`;
  };
  const fmtDate = (iso) => {
    if (!iso) return '—';
    const d = new Date(iso);
    return d.toLocaleDateString('en-CA', { year: 'numeric', month: 'short', day: 'numeric' });
  };

  const track = async () => {
    if (!orderId.trim()) return;
    setLoading(true); setError(''); setData(null);
    try {
      const res = await window.api.get('/tracking/' + encodeURIComponent(orderId.trim()));
      setData(res);
    } catch (err) {
      setError(err.message || 'Order not found.');
    } finally {
      setLoading(false);
    }
  };

  // Map order status → which step is "current"
  const stepIndex = (status) => {
    const order = ['pending', 'awaiting_payment', 'payment_confirmed', 'processing', 'shipped', 'out_for_delivery', 'delivered'];
    const idx = order.indexOf(status);
    if (idx < 0) return 0;
    if (idx <= 1) return 0;          // placed
    if (idx === 2) return 1;          // paid
    if (idx === 3 || idx === 4) return 2; // shipped
    if (idx >= 5) return 3;           // out for delivery / delivered
    return 0;
  };

  const order = data?.order;
  const shipment = data?.shipment;
  const events = data?.events || [];
  const current = order ? stepIndex(order.status) : 0;
  const isDelivered = order?.status === 'delivered';

  const steps = order ? [
    { label: 'Placed',           when: fmtDateTime(order.created_at) },
    { label: 'Paid',             when: order.payment_status === 'confirmed' || current >= 1 ? fmtDateTime(order.paid_at || order.created_at) : 'Pending' },
    { label: 'Shipped',          when: order.shipped_at ? fmtDateTime(order.shipped_at) : 'Pending' },
    { label: isDelivered ? 'Delivered' : 'Out for delivery', when: order.delivered_at ? fmtDateTime(order.delivered_at) : (shipment?.estimated_delivery ? fmtDate(shipment.estimated_delivery) + ' · ETA' : 'Pending') },
  ] : [];

  const statusLabel = (s) => (s || '').replace(/_/g, ' ');
  const progressPct = current === 0 ? 0 : current === 1 ? 33 : current === 2 ? 67 : 100;

  return (
    <>
      <h1 className="page-title">Track <em>order</em>.</h1>
      <p className="page-sub">Drop your order number. Updates from Canada Post in real time.</p>

      <div style={{display:'grid', gridTemplateColumns: '1fr auto', gap: 12, maxWidth: 600, margin: '32px 0 40px'}}>
        <input
          className="field"
          value={orderId}
          onChange={e=>setOrderId(e.target.value)}
          placeholder={`MS-${new Date().getFullYear()}-XXXXX`}
          onKeyDown={e=>{ if (e.key === 'Enter') track(); }}
        />
        <button className="btn btn-primary btn-lg" onClick={track} disabled={loading || !orderId.trim()}>
          {loading ? 'Looking…' : 'Track'}
        </button>
        {(data || error) && (
          <button
            type="button"
            className="btn btn-ghost"
            onClick={()=>{ setOrderId(''); setData(null); setError(''); }}
            style={{gridColumn:'1 / -1', justifySelf:'flex-start'}}
          >
            ← Search another order
          </button>
        )}
      </div>

      {error && (
        <div style={{background:'var(--blood)', color:'var(--bone)', padding:'14px 20px',
                     fontFamily:'var(--font-mono)', fontSize:13, fontWeight:700, borderRadius:4,
                     maxWidth: 600, marginBottom: 24}}>
          ★ {error}
        </div>
      )}

      {data && order && (
        <div style={{background:'var(--ink-soft)', border:'2px solid var(--ink-2)', borderRadius: 4, padding: 32}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom: 18}}>
            <div>
              <div className="t-eyebrow">Order</div>
              <div style={{fontFamily:'var(--font-mono)', fontSize: 22, fontWeight: 700, color:'var(--bone)'}}>#{order.order_number}</div>
            </div>
            <span className={"status " + (order.status || '').replace(/_/g, '-')}>{statusLabel(order.status)}</span>
          </div>
          <div className="tracker">
            <div className="tracker-line"><div className="fill" style={{width: progressPct + '%'}}/></div>
            {steps.map((s, i) => (
              <div key={s.label} className={"tracker-step " + (i === current && !isDelivered ? 'current' : i <= current ? 'done' : '')}>
                <div className="dot">{i < current ? '✓' : i+1}</div>
                <div className="label">{s.label}</div>
                <div className="when">{s.when}</div>
              </div>
            ))}
          </div>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap: 18, marginTop: 24}}>
            <div className="spec-grid" style={{margin:0, gridTemplateColumns:'1fr'}}>
              <div className="spec"><dt>Carrier</dt><dd>{shipment?.carrier || 'Canada Post'} {shipment?.service ? '· ' + shipment.service : ''}</dd></div>
              <div className="spec"><dt>Tracking #</dt><dd>{shipment?.tracking_number || '—'}</dd></div>
              <div className="spec"><dt>ETA</dt><dd>{shipment?.estimated_delivery ? fmtDate(shipment.estimated_delivery) : (order.estimated_delivery ? fmtDate(order.estimated_delivery) : '—')}</dd></div>
            </div>
            <div className="spec-grid" style={{margin:0, gridTemplateColumns:'1fr'}}>
              <div className="spec"><dt>Shipped from</dt><dd>{shipment?.origin_facility || 'Tyendinaga, ON'}</dd></div>
              <div className="spec"><dt>Method</dt><dd>{order.shipping_method || 'Canada Post Expedited'}</dd></div>
              <div className="spec"><dt>Status</dt><dd style={{textTransform:'capitalize'}}>{statusLabel(order.status)}</dd></div>
            </div>
          </div>

          {events.length > 0 && (
            <div style={{marginTop: 24, paddingTop: 20, borderTop: '1px solid var(--ink-2)'}}>
              <div className="t-eyebrow" style={{marginBottom: 10}}>Recent scans</div>
              {events.slice(0, 5).map((ev, i) => (
                <div key={i} style={{display:'grid', gridTemplateColumns:'160px 1fr', gap: 12, paddingTop: 8, fontSize: 13, fontFamily:'var(--font-mono)'}}>
                  <span style={{color:'var(--fg-3)'}}>{fmtDateTime(ev.event_at)}</span>
                  <span style={{color:'var(--bone)'}}>{ev.description || ev.status}{ev.location ? ' · ' + ev.location : ''}</span>
                </div>
              ))}
            </div>
          )}

          <p style={{fontSize: 12, color:'var(--fg-3)', marginTop: 16}}>
            ★ Box ships plain — no "Mad Smokes" anywhere. No signature required.
          </p>
        </div>
      )}

      {!data && !error && !loading && (
        <div style={{textAlign:'center', padding: 60, color:'var(--smoke-400)'}}>
          <img src="assets/skull-icon.png" alt="" style={{height: 80, opacity: .3, transform:'rotate(-12deg)'}}/>
          <p style={{marginTop: 16, fontSize: 13}}>Enter your order number above to see live tracking.</p>
        </div>
      )}
    </>
  );
}

// VerifyEmailPage — processes ?token= from the verification email link
function VerifyEmailPage({ token, onSuccess }) {
  const [status, setStatus] = React.useState(token ? 'verifying' : 'no-token');
  const [msg, setMsg] = React.useState('');

  React.useEffect(() => {
    if (!token) return;
    api.post('/auth/verify-email', { token })
      .then(() => {
        setStatus('success');
        setMsg('Email verified! Redirecting to your account...');
        setTimeout(() => onSuccess && onSuccess(), 2000);
      })
      .catch(err => {
        setStatus('error');
        setMsg(err.message || 'Verification failed. The link may have expired.');
      });
  }, [token]);

  return (
    <div style={{textAlign:'center', padding:'80px 20px', maxWidth:480, margin:'0 auto'}}>
      <img src="/assets/skull-icon.png" alt="" style={{height:100, opacity:.5, marginBottom:20}}/>
      <h1 className="page-title" style={{fontSize:28}}>
        {status === 'verifying' ? 'Verifying...' : status === 'success' ? 'Verified.' : status === 'error' ? 'Hmm.' : 'No token.'}
      </h1>
      <p style={{color:'var(--smoke-400)', marginTop:12, lineHeight:1.6}}>
        {status === 'verifying' ? 'Checking your verification link...'
         : status === 'success' ? msg
         : status === 'error' ? msg
         : 'This link looks incomplete. Try clicking the button in your verification email again.'}
      </p>
      {status === 'error' && (
        <button className="btn btn-primary" style={{marginTop:20}}
          onClick={() => { if (window.MS_navigate) window.MS_navigate('account'); }}>
          Go to Account
        </button>
      )}
    </div>
  );
}

// EmailVerificationBanner — shown on account page when email is not verified
function EmailVerificationBanner({ user }) {
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);

  if (!user || user.email_verified) return null;

  const resend = async () => {
    setSending(true);
    try {
      await api.post('/auth/resend-verification');
      setSent(true);
    } catch (err) {
      alert(err.message || 'Failed to send verification email');
    } finally {
      setSending(false);
    }
  };

  return (
    <div style={{
      background:'#1E1E18', border:'2px solid #D4F537', padding:'14px 20px',
      borderRadius:4, marginBottom:24, display:'flex', alignItems:'center',
      justifyContent:'space-between', gap:12, flexWrap:'wrap',
    }}>
      <div style={{fontSize:13, color:'var(--bone)'}}>
        <strong style={{color:'#D4F537'}}>Verify your email</strong> — check your inbox for a verification link to unlock all account features.
      </div>
      {sent ? (
        <span style={{fontSize:12, color:'#D4F537', fontWeight:700}}>✓ Sent!</span>
      ) : (
        <button className="btn btn-sm btn-primary" onClick={resend} disabled={sending}>
          {sending ? 'Sending...' : 'Resend link'}
        </button>
      )}
    </div>
  );
}

window.BrandsPage = BrandsPage;
window.FAQPage = FAQPage;
window.AccountPage = AccountPage;
window.TrackOrderPage = TrackOrderPage;
window.ResetPasswordPage = ResetPasswordPage;
window.VerifyEmailPage = VerifyEmailPage;
window.EmailVerificationBanner = EmailVerificationBanner;
