// AuthModal.jsx — customer login / register modal

function AuthModal() {
  const [open, setOpen]       = React.useState(false);
  const [mode, setMode]       = React.useState('login');
  const [user, setUser]       = React.useState(window.BB_STORE.user);
  const [form, setForm]       = React.useState({ name: '', email: '', phone: '', password: '' });
  const [loading, setLoading] = React.useState(false);
  const [err, setErr]         = React.useState('');
  const [showMenu, setShowMenu] = React.useState(false);

  React.useEffect(() => {
    const onOpen = (e) => { setOpen(true); setMode((e.detail && e.detail.mode) || 'login'); setErr(''); };
    const onUser = () => { setUser(window.BB_STORE.user); };
    window.addEventListener('bb-open-auth', onOpen);
    window.addEventListener('bb-user-update', onUser);
    return () => {
      window.removeEventListener('bb-open-auth', onOpen);
      window.removeEventListener('bb-user-update', onUser);
    };
  }, []);

  const set   = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const close = () => { setOpen(false); setErr(''); setForm({ name: '', email: '', phone: '', password: '' }); };

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true); setErr('');
    try {
      const url  = mode === 'login' ? '/api/user/login' : '/api/user/register';
      const body = mode === 'login'
        ? { email: form.email, password: form.password }
        : { name: form.name, email: form.email, phone: form.phone, password: form.password };
      const res  = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Something went wrong');
      window.BB_STORE.setUser(data.user ? { ...data.user, token: data.token } : { email: form.email, token: data.token });
      window.BB_STORE.notify('Welcome' + (data.user && data.user.name ? ', ' + data.user.name + '!' : '!'), 'success');
      close();
    } catch (ex) {
      setErr(ex.message);
    } finally {
      setLoading(false);
    }
  };

  const INPUT = { width: '100%', padding: '12px 14px', background: 'var(--bb-cream)', border: '1px solid var(--line)', borderRadius: 8, fontFamily: 'var(--font-serif)', fontSize: 15, color: 'var(--bb-cocoa)', outline: 'none', boxSizing: 'border-box', transition: 'border-color 200ms' };
  const LBL   = { display: 'block', fontFamily: 'var(--font-display)', fontSize: 9.5, letterSpacing: '0.24em', color: 'var(--bb-gold-deep)', marginBottom: 6 };

  return (
    <>
      {/* Modal */}
      {open && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 8000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>
          <div onClick={close} style={{ position: 'absolute', inset: 0, background: 'rgba(30,10,15,0.65)', backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)' }} />
          <div style={{ position: 'relative', background: 'var(--bb-pearl)', borderRadius: 22, padding: '38px 34px', width: 420, maxWidth: '100%', boxShadow: '0 28px 64px rgba(0,0,0,0.4)', border: '1px solid var(--line-gold)' }}>
            <button onClick={close} style={{ position: 'absolute', top: 16, right: 20, background: 'none', border: 'none', fontSize: 24, color: 'var(--fg-3)', cursor: 'pointer', lineHeight: 1 }}>&#215;</button>

            <div style={{ textAlign: 'center', marginBottom: 26 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.32em', color: 'var(--bb-gold-deep)', marginBottom: 8 }}>&#10022; BLISSFUL BITES</div>
              <h3 style={{ fontFamily: 'var(--font-serif)', fontWeight: 400, fontSize: 26, color: 'var(--bb-burgundy-deep)', margin: 0 }}>
                {mode === 'login' ? 'Welcome back' : 'Create account'}
              </h3>
            </div>

            {/* Tab toggle */}
            <div style={{ display: 'flex', background: 'var(--bb-cream)', borderRadius: 999, padding: 3, marginBottom: 24, border: '1px solid var(--line)', gap: 3 }}>
              {['login', 'signup'].map(m => (
                <button key={m} onClick={() => { setMode(m); setErr(''); }} style={{
                  flex: 1, padding: '9px 0', borderRadius: 999, border: 'none', cursor: 'pointer',
                  fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase',
                  background: mode === m ? 'var(--bb-burgundy)' : 'transparent',
                  color: mode === m ? 'var(--bb-ivory)' : 'var(--fg-2)', transition: 'all 220ms'
                }}>{m === 'login' ? 'Sign In' : 'Sign Up'}</button>
              ))}
            </div>

            <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {mode === 'signup' && (
                <>
                  <div>
                    <span style={LBL}>YOUR NAME</span>
                    <input style={INPUT} type="text" required value={form.name} onChange={set('name')} placeholder="Aanya Mehta" />
                  </div>
                  <div>
                    <span style={LBL}>PHONE (optional)</span>
                    <input style={INPUT} type="tel" value={form.phone} onChange={set('phone')} placeholder="+91 …" />
                  </div>
                </>
              )}
              <div>
                <span style={LBL}>EMAIL</span>
                <input style={INPUT} type="email" required value={form.email} onChange={set('email')} placeholder="you@example.com" />
              </div>
              <div>
                <span style={LBL}>PASSWORD</span>
                <input style={INPUT} type="password" required value={form.password} onChange={set('password')} placeholder="&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;" minLength={6} />
              </div>
              {err && (
                <div style={{ padding: '10px 14px', background: 'rgba(140,46,46,0.08)', border: '1px solid rgba(140,46,46,0.3)', borderRadius: 8, color: '#8C2E2E', fontFamily: 'var(--font-serif)', fontSize: 13 }}>{err}</div>
              )}
              <button type="submit" className="btn btn-primary" style={{ padding: '14px 24px', marginTop: 4 }} disabled={loading}>
                {loading ? '…' : mode === 'login' ? 'Sign In →' : 'Create Account →'}
              </button>
              <p style={{ textAlign: 'center', fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 13, color: 'var(--fg-3)', margin: 0 }}>
                {mode === 'login' ? 'New here? ' : 'Already a member? '}
                <button type="button" onClick={() => { setMode(mode === 'login' ? 'signup' : 'login'); setErr(''); }} style={{ background: 'none', border: 'none', color: 'var(--bb-burgundy)', cursor: 'pointer', fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 13, padding: 0, textDecoration: 'underline' }}>
                  {mode === 'login' ? 'Create an account' : 'Sign in'}
                </button>
              </p>
            </form>
          </div>
        </div>
      )}
    </>
  );
}

window.AuthModal = AuthModal;
