'use client';

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

export default function LoginPage() {
  const { t } = useI18n();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSuccess(false);
    setLoading(true);
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || 'Login failed');
      } else {
        try {
          setSuccess(true);
          localStorage.setItem('auth_token', data.token);
          document.cookie = `auth_token=${data.token}; path=/; SameSite=Lax`;
          window.location.href = '/';
        } catch (err) {
          // ignore storage errors
        }
      }
    } catch (err) {
      setError('Login failed');
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="panel" style={{ maxWidth: 480, margin: '40px auto' }}>
      <h1>{t('loginTitle')}</h1>
      <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('passwordLabel')}
          <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
        </label>
        <button className="button" type="submit" disabled={loading}>
          {loading ? t('loggingIn') : t('loginButton')}
        </button>
      </form>
      {success ? <p style={{ marginTop: 12, color: 'green' }}>{t('loginSuccess')}</p> : null}
      {error ? <p style={{ marginTop: 12, color: 'red' }}>{error}</p> : null}
    </main>
  );
}
