import React, { useState } from 'react' import { setToken } from '../api.js' export default function Login({ onSuccess }) { const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [error, setError] = useState(null) const [busy, setBusy] = useState(false) async function submit(e) { e.preventDefault() setBusy(true) setError(null) try { const res = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }), }) if (!res.ok) throw new Error(res.status === 401 ? 'Wrong username or password' : `Login failed (${res.status})`) const { token } = await res.json() setToken(token) onSuccess() } catch (err) { setError(err.message) } finally { setBusy(false) } } return (