import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from '../services/api';

function LoginForm() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const navigate = useNavigate();

  const login = async () => {
    try {
      const res = await axios.post('/api/login', { username, password });
      localStorage.setItem('token', res.data.token);
      localStorage.setItem('role', res.data.role);
      navigate('/', { replace: true });
      // ensure nav + route state reflect the new token immediately
      window.location.href = '/';
    } catch (err) {
      alert('Login fehlgeschlagen');
    }
  };

  return (
    <div className="main-content">
      <h2>Login</h2>
      <input
        value={username}
        onChange={e => setUsername(e.target.value)}
        placeholder="Benutzername"
      />
      <input
        type="password"
        value={password}
        onChange={e => setPassword(e.target.value)}
        placeholder="Passwort"
      />
      <button onClick={login}>Anmelden</button>
    </div>
  );
}

export default LoginForm;
