/* global React, Icon */
const { useState } = React;

function AuthModal({ onClose, onSuccess }) {
  const [mode, setMode] = useState('login'); // login | signup
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);

  const handle = async () => {
    if (!email || !password) { setError('Email dan password wajib diisi'); return; }
    if (mode === 'signup' && !name) { setError('Nama lengkap wajib diisi'); return; }
    setLoading(true); setError(null);
    try {
      if (mode === 'login') {
        await window.IndieAuth.signIn(email, password);
        onSuccess?.();
        onClose?.();
      } else {
        await window.IndieAuth.signUp(email, password, name, phone);
        setSuccess('Akun berhasil dibuat! Cek email untuk konfirmasi, lalu login.');
        setMode('login');
      }
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="auth-modal" onClick={e => e.stopPropagation()}>
        <div className="auth-modal-head">
          <div>
            <span className="eyebrow eyebrow-ink">「 INDIE PAPER 」</span>
            <h2 style={{marginTop:6, fontSize:22}}>
              {mode === 'login' ? 'Masuk ke akun' : 'Buat akun baru'}
            </h2>
          </div>
          <button className="btn btn-ghost btn-sm" onClick={onClose}><Icon.X /></button>
        </div>

        <div className="auth-modal-body">
          {mode === 'signup' && (
            <>
              <div className="field">
                <label>Nama lengkap *</label>
                <input type="text" value={name} onChange={e => setName(e.target.value)} placeholder="Nama lengkap" />
              </div>
              <div className="field">
                <label>WhatsApp (opsional)</label>
                <input type="text" value={phone} onChange={e => setPhone(e.target.value)} placeholder="+62 81..." />
              </div>
            </>
          )}
          <div className="field">
            <label>Email *</label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="hello@studio.com" />
          </div>
          <div className="field">
            <label>Password *</label>
            <input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="••••••••"
              onKeyDown={e => e.key === 'Enter' && handle()} />
          </div>

          {error && (
            <div style={{padding:'10px 14px', background:'#FEF2F2', border:'1px solid #FECACA', color:'#DC2626', fontSize:13, marginBottom:12}}>
              {error}
            </div>
          )}
          {success && (
            <div style={{padding:'10px 14px', background:'#F0FDF4', border:'1px solid #BBF7D0', color:'#166534', fontSize:13, marginBottom:12}}>
              {success}
            </div>
          )}

          <button className="btn btn-primary btn-lg btn-block" onClick={handle} disabled={loading}>
            {loading ? 'Memproses...' : mode === 'login' ? 'Masuk' : 'Buat akun'}
          </button>

          <div style={{textAlign:'center', marginTop:16, fontSize:13, color:'var(--ink-meta)'}}>
            {mode === 'login' ? (
              <>Belum punya akun? <a style={{color:'var(--terracotta)', cursor:'pointer'}} onClick={() => { setMode('signup'); setError(null); }}>Daftar gratis</a></>
            ) : (
              <>Sudah punya akun? <a style={{color:'var(--terracotta)', cursor:'pointer'}} onClick={() => { setMode('login'); setError(null); }}>Masuk</a></>
            )}
          </div>

          <div style={{marginTop:16, paddingTop:16, borderTop:'1px solid var(--paper-card-edge)', fontSize:11, color:'var(--ink-meta)', textAlign:'center', lineHeight:1.6}}>
            Akun INDIE Paper = akun INDIE Member (member.indiespace.id).<br/>
            Login di satu tempat, berlaku di keduanya.
          </div>
        </div>
      </div>
    </div>
  );
}

window.AuthModal = AuthModal;
