/* eslint-disable react/no-unescaped-entities */
'use client';

import { useState } from 'react';
import { useI18n } from '../../components/I18nProvider';

export default function RegisterPage() {
  const { t } = useI18n();
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [password, setPassword] = useState('');
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setMessage(null);
    setLoading(true);
    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, name, password }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || 'Registration failed');
      } else {
        setMessage(t('registerSuccess'));
        setEmail('');
        setPassword('');
      }
    } catch (err) {
      setError('Registration failed');
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="panel" style={{ maxWidth: 480, margin: '40px auto' }}>
      <h1>{t('registerTitle')}</h1>
      <p style={{ marginBottom: 16 }}>{t('registerLead')}</p>
      <form onSubmit={onSubmit} style={{ display: 'grid', gap: 12 }}>
        <label>
          {t('emailLabel')}
          <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
        </label>
        <label>
          {t('nameOptional')}
          <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
        </label>
        <label>
          {t('passwordHint')}
          <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
        </label>
        <button className="button" type="submit" disabled={loading}>
          {loading ? t('registering') : t('registerButton')}
        </button>
      </form>
      {message ? <p style={{ marginTop: 12, color: 'green' }}>{message}</p> : null}
      {error ? <p style={{ marginTop: 12, color: 'red' }}>{error}</p> : null}
    </main>
  );
}
