/**
 * RegisterForm — registration flow using sw.api.auth.register()
 *
 * Props:
 *   onPending  — called when account needs admin approval
 *   onSuccess  — called after auto-login on successful registration
 */
const { html } = window;
const { useState, useRef, useCallback } = hooks;

export function RegisterForm({ onPending, onSuccess }) {
    const [error, setError] = useState('');
    const [errorCls, setErrorCls] = useState('');
    const [loading, setLoading] = useState(false);
    const userRef = useRef(null);
    const emailRef = useRef(null);
    const passRef = useRef(null);
    const confirmRef = useRef(null);

    const BASE = window.__BASE__ || '';

    const doRegister = useCallback(async () => {
        const username = userRef.current?.value?.trim();
        const email = emailRef.current?.value?.trim();
        const password = passRef.current?.value;
        const confirm = confirmRef.current?.value;

        if (!username || !password) {
            setError('Username and password are required');
            setErrorCls('');
            return;
        }
        if (password.length < 8) {
            setError('Password must be at least 8 characters');
            setErrorCls('');
            return;
        }
        if (password !== confirm) {
            setError('Passwords do not match');
            setErrorCls('');
            return;
        }

        setError('');
        setLoading(true);
        try {
            const data = await sw.api.auth.register(username, email, password);
            if (data.pending) {
                setError('Account created \u2014 pending admin approval.');
                setErrorCls('success');
                if (onPending) setTimeout(onPending, 3000);
            } else {
                // Auto-login: store tokens via auth module
                sw.auth._setAuth(data);
                if (onSuccess) {
                    onSuccess();
                } else {
                    window.location.href = BASE + '/';
                }
            }
        } catch (e) {
            setError(e.message || 'Registration failed');
            setErrorCls('');
        } finally {
            setLoading(false);
        }
    }, [onPending, onSuccess]);

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

    return html`
        <div>
            <div class="login-form-field">
                <label for="regUsername">Username</label>
                <input type="text" id="regUsername" ref=${userRef}
                       placeholder="Choose a username" autocomplete="username" />
            </div>
            <div class="login-form-field">
                <label for="regEmail">Email</label>
                <input type="email" id="regEmail" ref=${emailRef}
                       placeholder="you@example.com" autocomplete="email" />
            </div>
            <div class="login-form-field">
                <label for="regPassword">Password</label>
                <input type="password" id="regPassword" ref=${passRef}
                       placeholder="Min 8 characters" autocomplete="new-password" />
            </div>
            <div class="login-form-field">
                <label for="regConfirm">Confirm Password</label>
                <input type="password" id="regConfirm" ref=${confirmRef}
                       placeholder="Re-enter password" autocomplete="new-password"
                       onKeyDown=${onConfirmKey} />
            </div>
            ${error && html`<p class="login-auth-error ${errorCls}">${error}</p>`}
            <button class="login-btn" disabled=${loading} onClick=${doRegister}>
                ${loading ? 'Creating account\u2026' : 'Create Account'}
            </button>
        </div>
    `;
}
