// pages-account.jsx — AuthModal, AccountPage, AdminDashboard — all live data
const { useState: useStateA, useEffect: useEffectA } = React;

// ─── AUTH MODAL ───────────────────────────────────────────────────────────────
function AuthModal({ open, onClose, onLogin, onRegister, refreshUser }) {
  const [mode,          setMode]         = useStateA('login');
  // signup steps: 'email' → 'otp' → 'details' → done
  // login steps:  'login'
  const [step,          setStep]         = useStateA('login');
  const [email,         setEmail]        = useStateA('');
  const [emailVerified, setEmailVerified]= useStateA(false);
  const [otp,           setOtp]          = useStateA('');
  const [otpHint,       setOtpHint]      = useStateA('');
  const [resendCd,      setResendCd]     = useStateA(0);
  const [name,          setName]         = useStateA('');
  const [phone,         setPhone]        = useStateA('');
  const [password,      setPassword]     = useStateA('');
  const [pwStrength,    setPwStrength]   = useStateA({ upper:false, lower:false, num:false, len:false });
  const [error,         setError]        = useStateA('');
  const [loading,       setLoading]      = useStateA(false);

  useEffectA(() => {
    if (resendCd <= 0) return;
    const t = setTimeout(() => setResendCd(c => c-1), 1000);
    return () => clearTimeout(t);
  }, [resendCd]);

  const switchMode = (m) => {
    setMode(m);
    setStep(m === 'signup' ? 'email' : 'login');
    setError(''); setEmail(''); setPassword(''); setName(''); setPhone('');
    setEmailVerified(false); setOtp('');
  };

  if (!open) return null;

  // ── Step handlers ─────────────────────────────────────────

  const sendOtp = async () => {
    if (!email || !email.includes('@')) { setError('Enter a valid email'); return; }
    setError(''); setLoading(true);
    try {
      const res = await fetch('/api/auth.php?action=send-pre-otp', {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({email})
      });
      const d = await res.json();
      if (!res.ok) { setError(d.error || 'Could not send code'); return; }
      setOtpHint(d.email || email);
      setStep('otp');
      setResendCd(30);
    } finally { setLoading(false); }
  };

  const verifyOtp = async () => {
    if (otp.length < 6) return;
    setError(''); setLoading(true);
    try {
      const res = await fetch('/api/auth.php?action=verify-pre-otp', {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({email, code: otp})
      });
      const d = await res.json();
      if (!res.ok) { setError(d.error || 'Wrong code. Try again.'); return; }
      setEmailVerified(true);
      setStep('details');
      setOtp('');
    } finally { setLoading(false); }
  };

  const checkPw = (pw) => {
    setPassword(pw);
    setPwStrength({
      len:   pw.length >= 8,
      upper: /[A-Z]/.test(pw),
      lower: /[a-z]/.test(pw),
      num:   /[0-9]/.test(pw),
    });
  };

  const createAccount = async () => {
    if (!name.trim())               { setError('Name is required'); return; }
    if (!pwStrength.len || !pwStrength.upper || !pwStrength.lower || !pwStrength.num)
                                     { setError('Password does not meet requirements'); return; }
    setError(''); setLoading(true);
    try {
      const result = await onRegister(email, password, name, phone);
      if (!result.ok) { setError(result.error || 'Registration failed'); return; }
      // Mark email verified immediately — user already proved ownership
      try {
        const token = localStorage.getItem('ff_access_token');
        await fetch('/api/auth.php?action=mark-verified', {
          method:'POST',
          headers:{'Content-Type':'application/json','Authorization':'Bearer '+token}
        });
        if (refreshUser) await refreshUser();
      } catch {}
      onClose();
    } finally { setLoading(false); }
  };

  const loginSubmit = async () => {
    if (!email || !password) { setError('Enter email and password'); return; }
    setError(''); setLoading(true);
    try {
      const result = await onLogin(email, password);
      if (!result.ok) { setError(result.error || 'Wrong email or password'); return; }
      onClose();
    } finally { setLoading(false); }
  };

  const resendCode = async () => {
    if (resendCd > 0) return;
    setLoading(true);
    try {
      const res = await fetch('/api/auth.php?action=send-pre-otp', {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({email})
      });
      if (res.ok) { setResendCd(60); setOtp(''); setError(''); }
    } finally { setLoading(false); }
  };

  const HEADER = {
    login:   { title:'Welcome back, fussy',  sub:'Your bag, orders and wishlists are waiting.' },
    email:   { title:'Join Fussy Finds',     sub:'Enter your email to get started.' },
    otp:     { title:'Check your inbox',     sub:`We sent a 6-digit code to ${otpHint}` },
    details: { title:'Almost done!',         sub:`${email} ✓ — now set your password.` },
  };
  const h = HEADER[step] || HEADER.login;

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,.55)', zIndex:250, display:'grid', placeItems:'center', padding:16, animation:'ffFade .18s' }}>
      <div className="ff-card" style={{ width:'min(440px, 100%)', padding:0, overflow:'hidden', animation:'ffPop .22s' }}>
        <div style={{ background:'var(--ff-accent)', color:'#fff', padding:'22px 24px', position:'relative' }}>
          <button onClick={onClose} style={{ position:'absolute', top:14, right:14, color:'#fff' }}><Icon.Close/></button>
          <div style={{ fontSize:24, marginBottom:4 }}>✦</div>
          <h2 className="ff-display" style={{ fontSize:28 }}>{h.title}</h2>
          <p style={{ fontSize:13, opacity:.9, marginTop:4 }}>{h.sub}</p>
        </div>
        <div style={{ padding:24 }}>

          {/* ── Mode tabs (login/signup) — only on first step ── */}
          {(step === 'login' || step === 'email') && (
            <div style={{ display:'flex', gap:4, padding:3, background:'rgba(0,0,0,.05)', borderRadius:999, marginBottom:18 }}>
              {[{k:'login',l:'Log in'},{k:'signup',l:'Sign up'}].map(t => (
                <button key={t.k} onClick={()=>switchMode(t.k)} style={{
                  flex:1, padding:'8px 12px', borderRadius:999, fontSize:13, fontWeight:600,
                  background: mode===t.k ? '#fff' : 'transparent',
                  boxShadow: mode===t.k ? 'var(--ff-shadow-sm)' : 'none',
                  border: mode===t.k ? 'var(--ff-border)' : '2px solid transparent',
                }}>{t.l}</button>
              ))}
            </div>
          )}

          {/* ── STEP: login ── */}
          {step === 'login' && (
            <div style={{ display:'grid', gap:10 }}>
              <input className="ff-input" type="email" placeholder="Email" value={email} onChange={e=>setEmail(e.target.value)} autoFocus/>
              <input className="ff-input" type="password" placeholder="Password" value={password} onChange={e=>setPassword(e.target.value)}
                onKeyDown={e=>e.key==='Enter'&&loginSubmit()}/>
              {error && <div style={{ fontSize:13, color:'var(--ff-accent)', padding:'8px 12px', background:'rgba(228,67,156,.08)', borderRadius:8 }}>{error}</div>}
              <button className="ff-btn ff-btn--primary ff-btn--block" onClick={loginSubmit} disabled={loading}>
                {loading ? 'Logging in…' : 'Log in'}
              </button>
              <button className="ff-btn ff-btn--block" onClick={onClose}>Continue as guest</button>
              <div style={{ fontSize:11, color:'var(--ff-muted)', textAlign:'center' }}>
                By continuing you agree to our{' '}
                <a href="/terms" target="_blank" style={{ color:'var(--ff-ink-2)', textDecoration:'underline' }}>Terms</a>
                {' '}&amp;{' '}
                <a href="/privacy" target="_blank" style={{ color:'var(--ff-ink-2)', textDecoration:'underline' }}>Privacy Policy</a>.
              </div>
            </div>
          )}

          {/* ── STEP: email (signup step 1) ── */}
          {step === 'email' && (
            <div style={{ display:'grid', gap:12 }}>
              <div style={{ fontSize:13, color:'var(--ff-muted)', marginBottom:4 }}>
                <span style={{ background:'var(--ff-sun)', padding:'2px 8px', borderRadius:4, fontWeight:700, fontSize:12 }}>Step 1 of 3</span>
                {' '} Verify your email address
              </div>
              <input className="ff-input" type="email" placeholder="your@email.com" value={email}
                onChange={e=>setEmail(e.target.value)}
                onKeyDown={e=>e.key==='Enter'&&sendOtp()}
                autoFocus/>
              {error && <div style={{ fontSize:13, color:'var(--ff-accent)', padding:'8px 12px', background:'rgba(228,67,156,.08)', borderRadius:8 }}>{error}</div>}
              <button className="ff-btn ff-btn--primary ff-btn--block" onClick={sendOtp}
                disabled={loading || !email.includes('@') || !email.includes('.')}>
                {loading ? 'Sending code…' : 'Send verification code →'}
              </button>
              <button className="ff-btn ff-btn--block" onClick={onClose}>Continue as guest</button>
            </div>
          )}

          {/* ── STEP: otp (signup step 2) ── */}
          {step === 'otp' && (
            <div style={{ display:'grid', gap:14 }}>
              <div style={{ fontSize:13, color:'var(--ff-muted)' }}>
                <span style={{ background:'var(--ff-sun)', padding:'2px 8px', borderRadius:4, fontWeight:700, fontSize:12 }}>Step 2 of 3</span>
                {' '} Enter the code sent to <strong>{otpHint}</strong>
              </div>
              <input className="ff-input" placeholder="6-digit code" value={otp} maxLength={6}
                onChange={e=>setOtp(e.target.value.replace(/\D/g,'').slice(0,6))}
                onKeyDown={e=>e.key==='Enter'&&verifyOtp()}
                style={{ textAlign:'center', fontSize:32, fontFamily:'monospace', fontWeight:700, letterSpacing:'.25em' }}
                autoFocus/>
              {error && <div style={{ fontSize:13, color:'var(--ff-accent)', padding:'8px 12px', background:'rgba(228,67,156,.08)', borderRadius:8, textAlign:'center' }}>{error}</div>}
              <button className="ff-btn ff-btn--primary ff-btn--block" onClick={verifyOtp}
                disabled={loading || otp.length < 6}>
                {loading ? 'Verifying…' : 'Verify code ✓'}
              </button>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                <button onClick={()=>setStep('email')} style={{ fontSize:12, color:'var(--ff-muted)', background:'none', border:'none', cursor:'pointer' }}>
                  ← Change email
                </button>
                <button onClick={resendCode} disabled={resendCd>0||loading}
                  style={{ fontSize:12, color:resendCd>0?'var(--ff-muted)':'var(--ff-accent)', background:'none', border:'none', cursor:resendCd>0?'default':'pointer', fontWeight:500 }}>
                  {resendCd>0?`Resend in ${resendCd}s`:'Resend code'}
                </button>
              </div>
            </div>
          )}

          {/* ── STEP: details (signup step 3) ── */}
          {step === 'details' && (
            <div style={{ display:'grid', gap:10 }}>
              <div style={{ fontSize:13, color:'var(--ff-muted)', marginBottom:4 }}>
                <span style={{ background:'var(--ff-lime)', padding:'2px 8px', borderRadius:4, fontWeight:700, fontSize:12 }}>Step 3 of 3</span>
                {' '} <span style={{ color:'var(--ff-teal)', fontWeight:600 }}>✓ {email}</span> verified!
              </div>
              <input className="ff-input" placeholder="Your full name *" value={name} onChange={e=>setName(e.target.value)} autoFocus/>
              <input className="ff-input" placeholder="Phone number (optional)" value={phone}
                onChange={e=>setPhone(e.target.value.replace(/\D/g,'').slice(0,10))}/>
              <input className="ff-input" type="password" placeholder="Create password *" value={password}
                onChange={e=>checkPw(e.target.value)}/>
              {/* Password strength */}
              {password.length > 0 && (
                <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:4, fontSize:11 }}>
                  {[
                    ['8+ characters', pwStrength.len],
                    ['Uppercase letter', pwStrength.upper],
                    ['Lowercase letter', pwStrength.lower],
                    ['Number', pwStrength.num],
                  ].map(([label, ok]) => (
                    <div key={label} style={{ display:'flex', alignItems:'center', gap:4, color: ok?'var(--ff-teal)':'var(--ff-muted)' }}>
                      <span>{ok?'✓':'○'}</span> {label}
                    </div>
                  ))}
                </div>
              )}
              {error && <div style={{ fontSize:13, color:'var(--ff-accent)', padding:'8px 12px', background:'rgba(228,67,156,.08)', borderRadius:8 }}>{error}</div>}
              <button className="ff-btn ff-btn--primary ff-btn--block" onClick={createAccount}
                disabled={loading || !name.trim() || !pwStrength.len || !pwStrength.upper || !pwStrength.lower || !pwStrength.num}>
                {loading ? 'Creating account…' : 'Create account ✦'}
              </button>
              <div style={{ fontSize:11, color:'var(--ff-muted)', textAlign:'center' }}>
                By continuing you agree to our{' '}
                <a href="/terms" target="_blank" style={{ color:'var(--ff-ink-2)', textDecoration:'underline' }}>Terms</a>
                {' '}&amp;{' '}
                <a href="/privacy" target="_blank" style={{ color:'var(--ff-ink-2)', textDecoration:'underline' }}>Privacy Policy</a>.
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}


Object.assign(window, { AuthModal });