import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext.jsx';

export default function Register() {
  const { register } = useAuth();
  const navigate = useNavigate();
  const [form, setForm] = useState({ email: '', password: '', displayName: '' });
  const [err, setErr] = useState(null);
  const [busy, setBusy] = useState(false);

  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const submit = async (e) => {
    e.preventDefault();
    setErr(null); setBusy(true);
    try {
      await register(form.email, form.password, form.displayName || undefined);
      navigate('/');
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  return (
    <div className="login-shell">
      <form className="card login-card" onSubmit={submit}>
        <h2 style={{ marginTop: 0 }}>Créer un compte</h2>
        {err && <div className="error">{err}</div>}
        <label>Nom d'affichage</label>
        <input value={form.displayName} onChange={set('displayName')} placeholder="Olivier" />
        <div style={{ height: 10 }} />
        <label>Email</label>
        <input type="email" required value={form.email} onChange={set('email')} />
        <div style={{ height: 10 }} />
        <label>Mot de passe (8 car. min.)</label>
        <input type="password" required minLength={8} value={form.password} onChange={set('password')} />
        <div style={{ height: 16 }} />
        <button className="primary" type="submit" disabled={busy} style={{ width: '100%' }}>
          {busy ? '…' : 'Créer le compte'}
        </button>
        <p className="text-muted" style={{ marginTop: 16, textAlign: 'center' }}>
          Déjà inscrit ? <Link to="/login">Se connecter</Link>
        </p>
      </form>
    </div>
  );
}
