// auth-modal.jsx — Login / Sign-up modal (premium dark)

const { useState } = React;

// ─── Thai error message mapper ────────────────────────────────────
function getAuthErrorMessage(error) {
  const code = error?.code || '';
  const map = {
    'auth/invalid-email':            'รูปแบบอีเมลไม่ถูกต้อง กรุณาตรวจสอบอีกครั้ง',
    'auth/user-not-found':           'ไม่พบบัญชีนี้ในระบบ กรุณาตรวจสอบอีเมลหรือสมัครสมาชิกก่อน',
    'auth/wrong-password':           'รหัสผ่านไม่ถูกต้อง กรุณาลองใหม่อีกครั้ง',
    'auth/invalid-credential':       'อีเมลหรือรหัสผ่านไม่ถูกต้อง กรุณาตรวจสอบแล้วลองใหม่',
    'auth/email-already-in-use':     'อีเมลนี้ถูกใช้งานแล้ว กรุณาเข้าสู่ระบบหรือใช้อีเมลอื่น',
    'auth/weak-password':            'รหัสผ่านสั้นหรือเดาง่ายเกินไป กรุณาใช้รหัสผ่านอย่างน้อย 6 ตัวอักษร',
    'auth/too-many-requests':        'มีการพยายามเข้าสู่ระบบหลายครั้งเกินไป กรุณารอสักครู่แล้วลองใหม่',
    'auth/network-request-failed':   'เชื่อมต่ออินเทอร์เน็ตไม่ได้ กรุณาตรวจสอบสัญญาณแล้วลองใหม่',
    'auth/popup-closed-by-user':     'หน้าต่างเข้าสู่ระบบถูกปิดก่อนดำเนินการเสร็จ',
    'auth/popup-blocked':            'เบราว์เซอร์บล็อกหน้าต่างเข้าสู่ระบบ กรุณาอนุญาต Pop-up แล้วลองใหม่',
    'auth/cancelled-popup-request':  'มีการเปิดหน้าต่างซ้อนกัน กรุณาลองใหม่อีกครั้ง',
    'auth/operation-not-allowed':    'วิธีเข้าสู่ระบบนี้ยังไม่ได้เปิดใช้งาน กรุณาติดต่อผู้ดูแลระบบ',
    'auth/user-disabled':            'บัญชีนี้ถูกระงับการใช้งาน กรุณาติดต่อผู้ดูแลระบบ',
    'auth/requires-recent-login':    'เซสชันหมดอายุ กรุณาเข้าสู่ระบบใหม่อีกครั้ง',
    'auth/account-exists-with-different-credential':
                                     'อีเมลนี้ผูกกับวิธีเข้าสู่ระบบอื่นอยู่แล้ว กรุณาใช้วิธีเดิมที่ลงทะเบียนไว้',
  };
  if (map[code]) return map[code];
  // Mock layer — map known English messages to Thai
  const msg = error?.message || '';
  if (msg.includes('already in use'))         return 'อีเมลนี้ถูกใช้งานแล้ว กรุณาเข้าสู่ระบบหรือใช้อีเมลอื่น';
  if (msg.includes('Invalid email'))          return 'รูปแบบอีเมลไม่ถูกต้อง กรุณาตรวจสอบอีกครั้ง';
  if (msg.includes('Invalid email or password') || msg.includes('invalid credential'))
                                              return 'อีเมลหรือรหัสผ่านไม่ถูกต้อง กรุณาตรวจสอบแล้วลองใหม่';
  if (msg.includes('at least 6'))             return 'รหัสผ่านต้องมีอย่างน้อย 6 ตัวอักษร';
  // Never expose raw Firebase error strings to the user
  if (msg.startsWith('Firebase:'))            return 'ไม่สามารถเข้าสู่ระบบได้ในขณะนี้ กรุณาลองใหม่อีกครั้ง';
  return 'ไม่สามารถเข้าสู่ระบบได้ในขณะนี้ กรุณาลองใหม่อีกครั้ง';
}

// ─── Client-side validation ───────────────────────────────────────
function validateForm(email, password, mode) {
  if (!email.trim()) return 'กรุณากรอกอีเมล';
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) return 'รูปแบบอีเมลไม่ถูกต้อง';
  if (!password) return 'กรุณากรอกรหัสผ่าน';
  if (mode === 'signup' && password.length < 6) return 'รหัสผ่านต้องมีอย่างน้อย 6 ตัวอักษร';
  return null;
}

// ─── Main modal ───────────────────────────────────────────────────
function AuthModal({ open, onClose, accent }) {
  const [mode, setMode] = useState('signin');  // signin | signup
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');

  if (!open) return null;

  const clearErr = () => { if (err) setErr(''); };

  const handleEmailChange = (v) => { setEmail(v); clearErr(); };
  const handlePasswordChange = (v) => { setPassword(v); clearErr(); };

  const switchMode = (next) => { setMode(next); setErr(''); };

  const submit = async () => {
    const validErr = validateForm(email, password, mode);
    if (validErr) { setErr(validErr); return; }
    setBusy(true); setErr('');
    try {
      if (mode === 'signin') await window.VHFirebase.signInEmail(email.trim(), password);
      else await window.VHFirebase.signUpEmail(email.trim(), password);
      onClose();
    } catch (e) {
      setErr(getAuthErrorMessage(e));
    } finally { setBusy(false); }
  };

  const google = async () => {
    setBusy(true); setErr('');
    try {
      await window.VHFirebase.signInGoogle();
      onClose();
    } catch (e) {
      // popup-closed is not really an error worth showing
      if (e?.code !== 'auth/popup-closed-by-user' && e?.code !== 'auth/cancelled-popup-request') {
        setErr(getAuthErrorMessage(e));
      }
    } finally { setBusy(false); }
  };

  const handleKey = (e) => { if (e.key === 'Enter' && !busy) submit(); };

  return (
    <ModalShell onClose={onClose}>
      <div style={{ padding: '28px 22px 22px' }}>
        <div style={{
          fontSize: 11, letterSpacing: 1.4, textTransform: 'uppercase',
          color: window.VH_DIM2, fontWeight: 700, marginBottom: 6,
        }}>JAV HUB</div>
        <div style={{
          fontSize: 22, fontWeight: 700, color: window.VH_TEXT, letterSpacing: -0.4,
        }}>
          {mode === 'signin' ? 'ยินดีต้อนรับกลับ' : 'สมัครสมาชิก'}
        </div>
        <div style={{ fontSize: 13, color: window.VH_DIM, marginTop: 4, lineHeight: 1.45 }}>
          ไลบรารีของคุณเป็นส่วนตัวและผูกกับบัญชีของคุณเท่านั้น
        </div>

        <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <Field
            label="อีเมล" type="email" value={email}
            onChange={handleEmailChange} placeholder="you@example.com"
            onKeyDown={handleKey} disabled={busy}
          />
          <Field
            label="รหัสผ่าน" type="password" value={password}
            onChange={handlePasswordChange} placeholder="••••••••"
            onKeyDown={handleKey} disabled={busy}
          />
        </div>

        {err && <ErrorBanner message={err} />}

        <button
          onClick={submit}
          disabled={busy}
          style={{
            marginTop: 16, width: '100%', height: 46, borderRadius: 10, border: 'none',
            background: busy ? 'rgba(255,255,255,0.08)' : accent,
            color: busy ? window.VH_DIM : '#fff',
            fontSize: 14.5, fontWeight: 600,
            cursor: busy ? 'not-allowed' : 'pointer',
            boxShadow: busy ? 'none' : `0 6px 20px ${accent}55`,
            fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            transition: 'background 200ms, box-shadow 200ms',
          }}
        >
          {busy && <Spinner />}
          {busy ? 'กำลังดำเนินการ…' : (mode === 'signin' ? 'เข้าสู่ระบบ' : 'สร้างบัญชี')}
        </button>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, margin: '16px 0',
          color: window.VH_DIM2, fontSize: 11, letterSpacing: 0.5,
        }}>
          <div style={{ flex: 1, height: 0.5, background: window.VH_HAIRLINE }}/>
          <span>หรือ</span>
          <div style={{ flex: 1, height: 0.5, background: window.VH_HAIRLINE }}/>
        </div>

        <button
          onClick={google}
          disabled={busy}
          style={{
            width: '100%', height: 44, borderRadius: 10,
            cursor: busy ? 'not-allowed' : 'pointer',
            background: 'rgba(255,255,255,0.07)', color: window.VH_TEXT,
            border: '0.5px solid rgba(255,255,255,0.12)',
            fontSize: 14, fontWeight: 600, fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            opacity: busy ? 0.5 : 1,
            transition: 'opacity 200ms',
          }}
        >
          <GoogleGlyph/>
          ดำเนินการต่อด้วย Google
        </button>

        <div style={{ marginTop: 18, textAlign: 'center', fontSize: 12.5, color: window.VH_DIM }}>
          {mode === 'signin' ? (
            <>ยังไม่มีบัญชี?{' '}
              <a onClick={() => switchMode('signup')} style={{ color: accent, cursor: 'pointer', fontWeight: 600 }}>
                สมัครสมาชิก
              </a>
            </>
          ) : (
            <>มีบัญชีแล้ว?{' '}
              <a onClick={() => switchMode('signin')} style={{ color: accent, cursor: 'pointer', fontWeight: 600 }}>
                เข้าสู่ระบบ
              </a>
            </>
          )}
        </div>

        <div style={{
          marginTop: 14, padding: '8px 10px', borderRadius: 8,
          background: 'rgba(255,255,255,0.03)', border: `0.5px solid ${window.VH_HAIRLINE}`,
          fontSize: 11, color: window.VH_DIM2, lineHeight: 1.5, textAlign: 'center',
        }}>
          {window.VHFirebase.mode === 'mock'
            ? 'โหมด Demo · ข้อมูลเก็บในเบราว์เซอร์นี้เท่านั้น'
            : 'Firebase Auth · ข้อมูลส่วนตัวและเป็นความลับ'}
        </div>
      </div>
    </ModalShell>
  );
}

// ─── Error banner with icon ───────────────────────────────────────
function ErrorBanner({ message }) {
  return (
    <div style={{
      marginTop: 12, padding: '10px 12px', borderRadius: 9,
      background: 'rgba(225,29,72,0.10)',
      border: '0.5px solid rgba(225,29,72,0.35)',
      display: 'flex', alignItems: 'flex-start', gap: 8,
    }}>
      <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0, marginTop: 1 }}>
        <circle cx="7" cy="7" r="6.5" stroke="#f87171" strokeWidth="1.3"/>
        <path d="M7 4v3.5" stroke="#f87171" strokeWidth="1.4" strokeLinecap="round"/>
        <circle cx="7" cy="10" r="0.7" fill="#f87171"/>
      </svg>
      <span style={{ color: '#fca5b1', fontSize: 12.5, lineHeight: 1.5 }}>{message}</span>
    </div>
  );
}

// ─── Loading spinner ──────────────────────────────────────────────
function Spinner() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" style={{ animation: 'vhSpin 0.7s linear infinite' }}>
      <circle cx="8" cy="8" r="6" fill="none" stroke="rgba(255,255,255,0.3)" strokeWidth="2"/>
      <path d="M8 2a6 6 0 016 6" fill="none" stroke="rgba(255,255,255,0.85)" strokeWidth="2" strokeLinecap="round"/>
    </svg>
  );
}

// ─── Field ────────────────────────────────────────────────────────
function Field({ label, type = 'text', value, onChange, placeholder, onKeyDown, disabled }) {
  return (
    <label style={{ display: 'block' }}>
      <div style={{
        fontSize: 11, letterSpacing: 0.8, textTransform: 'uppercase',
        color: window.VH_DIM2, fontWeight: 600, marginBottom: 5,
      }}>{label}</div>
      <input
        type={type} value={value}
        onChange={e => onChange(e.target.value)}
        onKeyDown={onKeyDown}
        placeholder={placeholder}
        disabled={disabled}
        autoComplete={type === 'password' ? 'current-password' : 'email'}
        style={{
          width: '100%', height: 42, padding: '0 12px', borderRadius: 10,
          background: disabled ? 'rgba(255,255,255,0.02)' : 'rgba(255,255,255,0.04)',
          color: window.VH_TEXT,
          border: `0.5px solid ${window.VH_HAIRLINE}`,
          fontSize: 14, fontFamily: 'inherit', outline: 'none',
          boxSizing: 'border-box',
          opacity: disabled ? 0.6 : 1,
          transition: 'opacity 200ms',
        }}
      />
    </label>
  );
}

// ─── Modal shell ──────────────────────────────────────────────────
function ModalShell({ children, onClose }) {
  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(10px)',
        WebkitBackdropFilter: 'blur(10px)',
        display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
        animation: 'vhFadeIn 200ms ease-out',
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: 480, maxHeight: '90vh', overflowY: 'auto',
          background: '#15151a',
          borderTopLeftRadius: 22, borderTopRightRadius: 22,
          border: '0.5px solid rgba(255,255,255,0.08)',
          borderBottom: 'none',
          boxShadow: '0 -20px 60px rgba(0,0,0,0.6)',
          animation: 'vhSlideUp 280ms cubic-bezier(.2,.7,.2,1)',
        }}
      >
        <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0 0' }}>
          <div style={{ width: 36, height: 4, borderRadius: 99, background: 'rgba(255,255,255,0.18)' }}/>
        </div>
        {children}
      </div>
    </div>
  );
}

// ─── Google logo glyph ────────────────────────────────────────────
function GoogleGlyph() {
  return (
    <svg width="16" height="16" viewBox="0 0 18 18">
      <path fill="#EA4335" d="M9 3.48c1.69 0 2.85.73 3.5 1.34l2.56-2.5C13.46 1.06 11.43 0 9 0 5.48 0 2.44 2.02.96 4.96l2.91 2.26C4.6 5.05 6.62 3.48 9 3.48z"/>
      <path fill="#4285F4" d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.49h4.84c-.21 1.12-.84 2.07-1.79 2.71l2.83 2.2c1.65-1.52 2.76-3.77 2.76-6.56z"/>
      <path fill="#FBBC05" d="M3.87 10.78a5.4 5.4 0 010-3.47L.96 5.05A8.99 8.99 0 000 9c0 1.45.35 2.82.96 4.04l2.91-2.26z"/>
      <path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.83-2.2c-.78.52-1.79.83-3.13.83-2.38 0-4.4-1.57-5.13-3.74l-2.91 2.26C2.44 15.98 5.48 18 9 18z"/>
    </svg>
  );
}

Object.assign(window, { AuthModal, getAuthErrorMessage });
