function AuthDrawer({ isOpen, onClose }) {
  const [tab,       setTab]       = React.useState('signup'); // 'signup' | 'signin'
  const [submitted, setSubmitted] = React.useState(false);
  const [loading,   setLoading]   = React.useState(false);
  const [form, setForm] = React.useState({
    firstName: '', lastName: '', email: '', phone: '',
    password: '', street: '', city: '', postal: '', country: 'Indonesia',
    newsletter: true,
  });
  const [errors, setErrors] = React.useState({});

  function set(k, v) { setForm(f => ({ ...f, [k]: v })); setErrors(e => ({ ...e, [k]: '' })); }

  function validate() {
    const e = {};
    if (tab === 'signup') {
      if (!form.firstName.trim()) e.firstName = 'Required';
      if (!form.lastName.trim())  e.lastName  = 'Required';
      if (!form.street.trim())    e.street    = 'Required';
      if (!form.city.trim())      e.city      = 'Required';
      if (!form.postal.trim())    e.postal    = 'Required';
    }
    if (!form.email.includes('@'))        e.email    = 'Valid email required';
    if (form.password.length < 8)         e.password = 'Minimum 8 characters';
    return e;
  }

  function handleSubmit(e) {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setLoading(true);
    setTimeout(() => {
      if (tab === 'signup') {
        const result = window.UmbraDB?.saveAccount?.(form);
        if (result === null) {
          setErrors({ email: 'Account already exists' });
          setLoading(false);
          return;
        }
        window.UmbraDB?.setSession?.(result);
      } else {
        const account = window.UmbraDB?.findAccount?.(form.email);
        if (account) window.UmbraDB?.setSession?.(account);
      }
      setLoading(false);
      setSubmitted(true);
    }, 1100);
  }

  function reset() {
    setSubmitted(false); setLoading(false);
    setForm({ firstName: '', lastName: '', email: '', phone: '', password: '', street: '', city: '', postal: '', country: 'Indonesia', newsletter: true });
    setErrors({});
  }

  // Shared input style factory
  function inp(key) {
    return {
      width: '100%', background: 'none',
      border: 'none', borderBottom: `1px solid ${errors[key] ? 'rgba(0,0,0,0.6)' : 'rgba(0,0,0,0.18)'}`,
      padding: '10px 0', outline: 'none',
      fontFamily: "'Montserrat', sans-serif", fontSize: 12,
      color: '#000000', letterSpacing: '0.04em',
      transition: 'border-color 0.2s',
    };
  }
  function lbl(txt, key) {
    return (
      <div style={{ marginBottom: 4 }}>
        <label style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.28em', color: errors[key] ? '#000000' : 'rgba(0,0,0,0.42)', textTransform: 'uppercase' }}>
          {txt}{errors[key] && <span style={{ marginLeft: 8, color: 'rgba(0,0,0,0.7)' }}>— {errors[key]}</span>}
        </label>
      </div>
    );
  }

  const drawerStyle = {
    position: 'fixed', top: 0, right: 0, bottom: 0,
    width: 460, zIndex: 2001,
    background: '#ffffff', color: '#000000',
    display: 'flex', flexDirection: 'column',
    transform: isOpen ? 'translateX(0)' : 'translateX(100%)',
    transition: 'transform 0.42s cubic-bezier(0.16, 1, 0.3, 1)',
    borderLeft: '1px solid rgba(0,0,0,0.12)',
  };

  return (
    <>
      {isOpen && <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 2000, background: 'rgba(0,0,0,0.5)', animation: 'fadeIn 0.25s ease' }} />}
      <div style={drawerStyle}>

        {/* Header */}
        <div style={{ padding: '28px 36px 0', borderBottom: '1px solid rgba(0,0,0,0.1)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
            <div>
              <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 22, fontWeight: 900 }}>
                {tab === 'signup' ? 'Join Umbra' : 'Welcome Back'}
              </div>
              <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.2em', color: 'rgba(0,0,0,0.4)', marginTop: 4 }}>
                {tab === 'signup' ? 'CREATE AN ACCOUNT' : 'SIGN INTO YOUR ACCOUNT'}
              </div>
            </div>
            <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'crosshair', fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.15em', color: 'rgba(0,0,0,0.4)', transition: 'color 0.15s', paddingTop: 4 }}
              onMouseEnter={e => e.currentTarget.style.color = '#000000'}
              onMouseLeave={e => e.currentTarget.style.color = 'rgba(0,0,0,0.4)'}
            >CLOSE ×</button>
          </div>
          {/* Tabs */}
          {!submitted && (
            <div style={{ display: 'flex', gap: 0 }}>
              {[['signup', 'SIGN UP'], ['signin', 'SIGN IN']].map(([id, label]) => (
                <button key={id} onClick={() => { setTab(id); setErrors({}); }} style={{
                  flex: 1, background: 'none', border: 'none', borderBottom: `2px solid ${tab === id ? '#000000' : 'rgba(0,0,0,0.12)'}`,
                  padding: '10px 0', cursor: 'crosshair',
                  fontFamily: "'Montserrat', sans-serif", fontSize: 12,
                  letterSpacing: '0.22em', color: tab === id ? '#000000' : 'rgba(0,0,0,0.38)',
                  transition: 'all 0.2s',
                }}>{label}</button>
              ))}
            </div>
          )}
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '32px 36px' }}>

          {submitted ? (
            // Success state
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: 24, textAlign: 'center' }}>
              <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 52, fontWeight: 900, color: '#000000', lineHeight: 0.9, letterSpacing: '-0.02em' }}>
                {tab === 'signup' ? <>Welcome<br/><em>to Umbra.</em></> : <>You're<br/><em>back.</em></>}
              </div>
              <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, lineHeight: 2, color: 'rgba(0,0,0,0.5)', maxWidth: 300 }}>
                {tab === 'signup'
                  ? `Your account has been created${form.newsletter ? ' and you\'re subscribed to The Dispatch' : ''}. New arrivals and roast updates will reach you first.`
                  : 'You are now signed in. Your order history and delivery details are ready.'}
              </div>
              <button onClick={() => { reset(); onClose(); }} style={{
                marginTop: 8, padding: '14px 32px',
                background: '#000000', color: '#ffffff', border: 'none',
                fontFamily: "'Montserrat', sans-serif", fontSize: 12,
                letterSpacing: '0.22em', cursor: 'crosshair',
              }}>CONTINUE SHOPPING</button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} autoComplete="off">

              {tab === 'signup' && (
                <>
                  {/* Name */}
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 24 }}>
                    <div>
                      {lbl('First Name', 'firstName')}
                      <input value={form.firstName} onChange={e => set('firstName', e.target.value)} style={inp('firstName')}
                        onFocus={e => e.target.style.borderBottomColor = '#000000'}
                        onBlur={e => e.target.style.borderBottomColor = errors.firstName ? 'rgba(0,0,0,0.6)' : 'rgba(0,0,0,0.18)'} />
                    </div>
                    <div>
                      {lbl('Last Name', 'lastName')}
                      <input value={form.lastName} onChange={e => set('lastName', e.target.value)} style={inp('lastName')}
                        onFocus={e => e.target.style.borderBottomColor = '#000000'}
                        onBlur={e => e.target.style.borderBottomColor = errors.lastName ? 'rgba(0,0,0,0.6)' : 'rgba(0,0,0,0.18)'} />
                    </div>
                  </div>
                </>
              )}

              {/* Email */}
              <div style={{ marginBottom: 24 }}>
                {lbl('Email Address', 'email')}
                <input type="email" value={form.email} onChange={e => set('email', e.target.value)} style={inp('email')}
                  onFocus={e => e.target.style.borderBottomColor = '#000000'}
                  onBlur={e => e.target.style.borderBottomColor = errors.email ? 'rgba(0,0,0,0.6)' : 'rgba(0,0,0,0.18)'} />
              </div>

              {tab === 'signup' && (
                <div style={{ marginBottom: 24 }}>
                  {lbl('Phone Number', 'phone')}
                  <input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} style={inp('phone')} placeholder="+62 ···"
                    onFocus={e => e.target.style.borderBottomColor = '#000000'}
                    onBlur={e => e.target.style.borderBottomColor = 'rgba(0,0,0,0.18)'} />
                </div>
              )}

              {/* Password */}
              <div style={{ marginBottom: tab === 'signup' ? 36 : 24 }}>
                {lbl('Password', 'password')}
                <input type="password" value={form.password} onChange={e => set('password', e.target.value)} style={inp('password')}
                  onFocus={e => e.target.style.borderBottomColor = '#000000'}
                  onBlur={e => e.target.style.borderBottomColor = errors.password ? 'rgba(0,0,0,0.6)' : 'rgba(0,0,0,0.18)'} />
              </div>

              {tab === 'signup' && (
                <>
                  {/* Delivery address */}
                  <div style={{ marginBottom: 12 }}>
                    <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, letterSpacing: '0.3em', color: 'rgba(0,0,0,0.38)', marginBottom: 20, borderTop: '1px solid rgba(0,0,0,0.08)', paddingTop: 20 }}>
                      DELIVERY ADDRESS
                    </div>
                    <div style={{ marginBottom: 20 }}>
                      {lbl('Street Address', 'street')}
                      <input value={form.street} onChange={e => set('street', e.target.value)} style={inp('street')}
                        onFocus={e => e.target.style.borderBottomColor = '#000000'}
                        onBlur={e => e.target.style.borderBottomColor = errors.street ? 'rgba(0,0,0,0.6)' : 'rgba(0,0,0,0.18)'} />
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 20 }}>
                      <div>
                        {lbl('City', 'city')}
                        <input value={form.city} onChange={e => set('city', e.target.value)} style={inp('city')}
                          onFocus={e => e.target.style.borderBottomColor = '#000000'}
                          onBlur={e => e.target.style.borderBottomColor = errors.city ? 'rgba(0,0,0,0.6)' : 'rgba(0,0,0,0.18)'} />
                      </div>
                      <div>
                        {lbl('Postal Code', 'postal')}
                        <input value={form.postal} onChange={e => set('postal', e.target.value)} style={inp('postal')}
                          onFocus={e => e.target.style.borderBottomColor = '#000000'}
                          onBlur={e => e.target.style.borderBottomColor = errors.postal ? 'rgba(0,0,0,0.6)' : 'rgba(0,0,0,0.18)'} />
                      </div>
                    </div>
                    <div>
                      {lbl('Country', 'country')}
                      <select value={form.country} onChange={e => set('country', e.target.value)} style={{ ...inp('country'), appearance: 'none', WebkitAppearance: 'none', cursor: 'crosshair' }}>
                        {['Indonesia', 'Singapore', 'Malaysia', 'Australia', 'United States', 'Other'].map(c => <option key={c}>{c}</option>)}
                      </select>
                    </div>
                  </div>

                  {/* Newsletter opt-in */}
                  <div style={{ marginTop: 28, marginBottom: 8, display: 'flex', alignItems: 'flex-start', gap: 14, cursor: 'crosshair' }} onClick={() => set('newsletter', !form.newsletter)}>
                    <div style={{
                      width: 16, height: 16, marginTop: 1, flexShrink: 0,
                      border: '1px solid rgba(0,0,0,0.4)',
                      background: form.newsletter ? '#000000' : 'transparent',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      transition: 'background 0.15s',
                    }}>
                      {form.newsletter && <div style={{ width: 6, height: 6, background: '#ffffff' }} />}
                    </div>
                    <div>
                      <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, color: '#000000', letterSpacing: '0.05em' }}>Subscribe to The Dispatch</div>
                      <div style={{ fontFamily: "'Montserrat', sans-serif", fontSize: 12, color: 'rgba(0,0,0,0.45)', marginTop: 3, lineHeight: 1.7 }}>New arrivals, roast dates, and the occasional manifesto. Never frequent, always worth reading.</div>
                    </div>
                  </div>
                </>
              )}

              {/* Submit */}
              <button type="submit" disabled={loading} style={{
                width: '100%', marginTop: 32, padding: '18px',
                background: loading ? 'rgba(0,0,0,0.6)' : '#000000',
                color: '#ffffff', border: 'none',
                fontFamily: "'Montserrat', sans-serif", fontSize: 12,
                letterSpacing: '0.22em', cursor: loading ? 'wait' : 'crosshair',
                transition: 'background 0.2s',
              }}>
                {loading ? '···' : tab === 'signup' ? 'CREATE ACCOUNT' : 'SIGN IN'}
              </button>

              {tab === 'signin' && (
                <button type="button" onClick={() => setTab('signup')} style={{
                  width: '100%', marginTop: 12, padding: '14px',
                  background: 'transparent', color: 'rgba(0,0,0,0.5)',
                  border: '1px solid rgba(0,0,0,0.15)',
                  fontFamily: "'Montserrat', sans-serif", fontSize: 12,
                  letterSpacing: '0.2em', cursor: 'crosshair', transition: 'all 0.15s',
                }}
                onMouseEnter={e => { e.currentTarget.style.background = 'rgba(0,0,0,0.05)'; e.currentTarget.style.color = '#000000'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'rgba(0,0,0,0.5)'; }}
                >NO ACCOUNT? SIGN UP</button>
              )}
            </form>
          )}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { AuthDrawer });
