/**
 * LoginForm — username/password form using sw.auth.login()
 *
 * Props:
 *   onSuccess — called after successful login (optional, default: redirect to /)
 */
const { html } = window;
const { useState, useRef, useCallback } = hooks;

export function LoginForm({ onSuccess }) {
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);
    const userRef = useRef(null);
    const passRef = useRef(null);

    const BASE = window.__BASE__ || '';

    const doLogin = useCallback(async () => {
        const username = userRef.current?.value?.trim();
        const password = passRef.current?.value;
        if (!username || !password) {
            setError('Enter username and password');
            return;
        }
        setError('');
        setLoading(true);
        try {
            await sw.auth.login(username, password);
            if (onSuccess) {
                onSuccess();
            } else {
                window.location.href = BASE + '/';
            }
        } catch (e) {
            setError(e.message || 'Login failed');
            setLoading(false);
        }
    }, [onSuccess]);

    const onUserKey = useCallback((e) => {
        if (e.key === 'Enter') passRef.current?.focus();
    }, []);

    const onPassKey = useCallback((e) => {
        if (e.key === 'Enter') doLogin();
    }, [doLogin]);

    return html`
        <div class="login-anim login-anim-a3">
            <div class="login-form-field">
                <label for="loginUsername">Username</label>
                <input type="text" id="loginUsername" ref=${userRef}
                       placeholder="Enter username" autocomplete="username"
                       autofocus onKeyDown=${onUserKey} />
            </div>
            <div class="login-form-field">
                <label for="loginPassword">Password</label>
                <input type="password" id="loginPassword" ref=${passRef}
                       placeholder="Enter password" autocomplete="current-password"
                       onKeyDown=${onPassKey} />
            </div>
            ${error && html`<p class="login-auth-error">${error}</p>`}
            <button class="login-btn" disabled=${loading} onClick=${doLogin}>
                ${loading ? 'Logging in\u2026' : 'Log In'}
            </button>
        </div>
    `;
}
