// auth-page.jsx — LoginPage + reset password
// Affiché tant que /api/auth/me ne renvoie pas un user. Remplace window.ME hardcodé.

const { useState: _auUseS, useEffect: _auUseE } = React;

function LoginPage({ onLogin }) {
  const [mode, setMode] = _auUseS('login');     // 'login' | 'forgot' | 'reset'
  const [email, setEmail] = _auUseS('');
  const [password, setPassword] = _auUseS('');
  const [newPassword, setNewPassword] = _auUseS('');
  const [resetToken, setResetToken] = _auUseS('');
  const [busy, setBusy] = _auUseS(false);
  const [msg, setMsg] = _auUseS(null);
  const [err, setErr] = _auUseS(null);
  const API = (window.AE_API && window.AE_API.BASE) || '';

  // Auto-remplir le token depuis l'URL hash (#/reset?token=…)
  _auUseE(() => {
    const hash = window.location.hash || '';
    const m = hash.match(/[?&]token=([^&]+)/);
    if (m) { setResetToken(m[1]); setMode('reset'); }
  }, []);

  const submitLogin = async (e) => {
    e.preventDefault();
    setBusy(true); setErr(null); setMsg(null);
    try {
      const r = await fetch(`${API}/api/auth/login`, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      }).then(r => r.json());
      if (!r.ok) throw new Error(r.error || 'Erreur');
      onLogin(r.user);
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const submitForgot = async (e) => {
    e.preventDefault();
    setBusy(true); setErr(null); setMsg(null);
    try {
      const r = await fetch(`${API}/api/auth/forgot-password`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      }).then(r => r.json());
      setMsg(r.message + (r._devUrl ? `\n\n[DEV] ${r._devUrl}` : ''));
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const submitReset = async (e) => {
    e.preventDefault();
    setBusy(true); setErr(null); setMsg(null);
    try {
      const r = await fetch(`${API}/api/auth/reset-password`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token: resetToken, newPassword }),
      }).then(r => r.json());
      if (!r.ok) throw new Error(r.error || 'Erreur');
      setMsg('✓ Mot de passe réinitialisé — connectez-vous');
      setMode('login');
      setNewPassword(''); setResetToken('');
      window.location.hash = '';
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const inputStyle = { padding: '10px 12px', fontSize: 13, border: '1px solid var(--line-2)', borderRadius: 6, background: 'var(--paper-2)', fontFamily: 'inherit', width: '100%', boxSizing: 'border-box' };

  return (
    <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', background: 'var(--paper)', padding: 20 }}>
      <div style={{ width: 'min(420px, 100%)', background: 'var(--paper-2)', border: '1px solid var(--line)', borderRadius: 12, padding: 32, boxShadow: 'var(--shadow-3)' }}>
        {/* Logo + brand */}
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <img
            src="/logo-audits-energies.png"
            alt="Audits Énergies"
            style={{ height: 56, width: 'auto', display: 'inline-block', maxWidth: '70%' }}
          />
          <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 12, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 500 }}>Cockpit CEE · Plateforme SaaS</div>
        </div>

        {/* Mode tabs */}
        <div style={{ display: 'flex', gap: 4, marginBottom: 20, padding: 3, background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 6 }}>
          {[
            { k: 'login', label: 'Connexion' },
            { k: 'forgot', label: 'Mot de passe oublié' },
          ].map(t => (
            <button key={t.k} onClick={() => { setMode(t.k); setMsg(null); setErr(null); }} style={{
              flex: 1, padding: '7px 10px', fontSize: 12, fontWeight: mode === t.k ? 600 : 500,
              background: mode === t.k ? 'var(--paper-2)' : 'transparent',
              color: mode === t.k ? 'var(--ink)' : 'var(--ink-4)',
              border: mode === t.k ? '1px solid var(--line-2)' : '1px solid transparent',
              borderRadius: 4,
            }}>{t.label}</button>
          ))}
        </div>

        {msg && <div style={{ padding: 10, marginBottom: 14, background: 'var(--signal-tint)', color: 'var(--signal-deep)', border: '1px solid var(--signal-soft)', borderRadius: 5, fontSize: 12, whiteSpace: 'pre-wrap' }}>{msg}</div>}
        {err && <div style={{ padding: 10, marginBottom: 14, background: 'var(--rouge-tint)', color: 'var(--rouge)', border: '1px solid var(--rouge)', borderRadius: 5, fontSize: 12 }}>⚠ {err}</div>}

        {mode === 'login' && (
          <form onSubmit={submitLogin} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <label>
              <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 600, marginBottom: 4 }}>Email</div>
              <input type="email" required value={email} onChange={e => setEmail(e.target.value)} style={inputStyle} autoFocus autoComplete="username" />
            </label>
            <label>
              <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 600, marginBottom: 4 }}>Mot de passe</div>
              <input type="password" required value={password} onChange={e => setPassword(e.target.value)} style={inputStyle} autoComplete="current-password" />
            </label>
            <button type="submit" disabled={busy} style={{
              padding: '11px 16px', fontSize: 13, fontWeight: 600,
              background: busy ? 'var(--paper-3)' : 'var(--ink)',
              color: 'var(--paper)', border: 'none', borderRadius: 6,
              cursor: busy ? 'wait' : 'pointer', marginTop: 6,
            }}>
              {busy ? 'Connexion…' : 'Se connecter →'}
            </button>
          </form>
        )}

        {mode === 'forgot' && (
          <form onSubmit={submitForgot} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>
              Saisissez votre email — si le compte existe, un lien de réinitialisation vous sera envoyé.
            </div>
            <label>
              <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 600, marginBottom: 4 }}>Email</div>
              <input type="email" required value={email} onChange={e => setEmail(e.target.value)} style={inputStyle} autoFocus />
            </label>
            <button type="submit" disabled={busy} style={{
              padding: '11px 16px', fontSize: 13, fontWeight: 600,
              background: busy ? 'var(--paper-3)' : 'var(--signal)', color: 'var(--ink)',
              border: 'none', borderRadius: 6, cursor: busy ? 'wait' : 'pointer', marginTop: 6,
            }}>
              {busy ? '…' : 'Envoyer le lien'}
            </button>
          </form>
        )}

        {mode === 'reset' && (
          <form onSubmit={submitReset} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5 }}>
              Définissez un nouveau mot de passe (8 caractères minimum).
            </div>
            <label>
              <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 600, marginBottom: 4 }}>Token</div>
              <input type="text" required value={resetToken} onChange={e => setResetToken(e.target.value)} style={{ ...inputStyle, fontFamily: 'var(--font-mono)' }} />
            </label>
            <label>
              <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 600, marginBottom: 4 }}>Nouveau mot de passe</div>
              <input type="password" required minLength={8} value={newPassword} onChange={e => setNewPassword(e.target.value)} style={inputStyle} autoComplete="new-password" />
            </label>
            <button type="submit" disabled={busy} style={{
              padding: '11px 16px', fontSize: 13, fontWeight: 600,
              background: busy ? 'var(--paper-3)' : 'var(--ink)', color: 'var(--paper)',
              border: 'none', borderRadius: 6, cursor: busy ? 'wait' : 'pointer', marginTop: 6,
            }}>{busy ? '…' : 'Réinitialiser'}</button>
          </form>
        )}

        <div style={{ marginTop: 22, paddingTop: 16, borderTop: '1px solid var(--line)', fontSize: 11, color: 'var(--ink-4)', textAlign: 'center' }}>
          Premier login ? Demandez à votre administrateur de créer votre compte.<br/>
          <span className="mono">node scripts/seed-admin.js [email] [password]</span>
        </div>
      </div>
    </div>
  );
}

window.LoginPage = LoginPage;

// AuthGate : wrapper qui affiche LoginPage tant que pas authentifié
function AuthGate({ children }) {
  const [user, setUser] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const API = (window.AE_API && window.AE_API.BASE) || '';

  React.useEffect(() => {
    fetch(`${API}/api/auth/me`, { credentials: 'include' })
      .then(r => r.json())
      .then(d => {
        if (d.ok && d.user) {
          setUser(d.user);
          window.ME = { ...d.user, name: d.user.name, role: d.user.role, initials: d.user.initials };
          window.dispatchEvent(new CustomEvent('ae:user-changed', { detail: d.user }));
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', background: 'var(--paper)' }}>
        <div style={{ fontSize: 13, color: 'var(--ink-4)' }}>Chargement…</div>
      </div>
    );
  }

  if (!user) {
    return <LoginPage onLogin={(u) => {
      setUser(u);
      window.ME = { ...u, name: u.name, role: u.role, initials: u.initials };
      window.dispatchEvent(new CustomEvent('ae:user-changed', { detail: u }));
    }} />;
  }

  return children;
}

window.AuthGate = AuthGate;

// Helper logout (utilisé dans le bouton sidebar/topbar)
window.AE_LOGOUT = async () => {
  const API = (window.AE_API && window.AE_API.BASE) || '';
  await fetch(`${API}/api/auth/logout`, { method: 'POST', credentials: 'include' }).catch(() => {});
  window.location.reload();
};
