/* Pagina /change-password — troca de senha pelo cliente.
   Exige: senha atual + nova senha + TOTP (se 2FA ja configurado).
   Forçada no primeiro login (must_change_password=1) após setup-2fa. */

const { useState: cp_useState } = React;


window.C7_ChangePasswordPage = function ChangePasswordPage() {
    const user = window.C7_STORE.get().user || {};
    const forced = !!user.must_change_password;

    const [current_pw, setCurrent] = cp_useState('');
    const [new_pw, setNew]         = cp_useState('');
    const [new_pw2, setNew2]       = cp_useState('');
    const [totp, setTotp]          = cp_useState('');
    const [loading, setLoading]    = cp_useState(false);
    const [err, setErr]            = cp_useState(null);

    function password_policy_issues(pw) {
        const issues = [];
        if (pw.length < 8)                    issues.push('mínimo 8 caracteres');
        if (!/[A-Z]/.test(pw))                issues.push('pelo menos 1 letra maiúscula');
        if (!/\d/.test(pw))                   issues.push('pelo menos 1 número');
        if (!/[^A-Za-z0-9]/.test(pw))         issues.push('pelo menos 1 caractere especial');
        return issues;
    }

    function validate() {
        if (!current_pw) return 'informe a senha atual';
        const pol = password_policy_issues(new_pw);
        if (pol.length) return 'senha fraca: ' + pol.join(', ');
        if (new_pw !== new_pw2) return 'as duas senhas novas não batem';
        if (new_pw === current_pw) return 'nova senha precisa ser diferente da atual';
        if (user.totp_enabled && !totp) return 'informe o código TOTP';
        return null;
    }

    async function submit(e) {
        e.preventDefault();
        const v = validate();
        if (v) { setErr(v); return; }
        setErr(null);
        setLoading(true);
        try {
            const body = {
                current_password: current_pw,
                new_password:     new_pw,
            };
            if (user.totp_enabled) body.totp_code = totp;
            await window.C7_API.post('/auth/change-password', body);
            const me = await window.C7_API.get('/auth/me');
            window.C7_STORE.set({ user: me });
            window.C7_ROUTER.navigate('/dashboard');
        } catch (e) {
            setErr(e.message || 'falha ao trocar senha');
            setLoading(false);
        }
    }

    const AppFooter = (window.C7_Layout && window.C7_Layout.AppFooter) || null;
    return (
        <div className="standalone-shell">
            <div className="standalone-center">
                <div style={{display: 'flex', flexDirection: 'column',
                              maxWidth: 440, width: '100%'}}>
                    {!forced && (
                        <button onClick={() => {
                            if (window.history.length > 1) window.history.back();
                            else window.C7_ROUTER.navigate('/perfil');
                        }} className="app-back-btn" style={{marginBottom: 10, alignSelf: 'flex-start'}}>
                            ← Voltar
                        </button>
                    )}
                <div className="change-password-card">
                <h1>{forced ? 'Defina sua senha' : 'Alterar senha'}</h1>
                {forced && (
                    <p className="change-password-intro">
                        Você acessou com uma senha temporária. Defina agora uma
                        senha definitiva pra continuar.
                    </p>
                )}

                <form onSubmit={submit}>
                    <label>
                        <span>Senha atual</span>
                        <input
                            type="password"
                            value={current_pw}
                            onChange={(e) => setCurrent(e.target.value)}
                            autoComplete="current-password"
                            required />
                    </label>

                    <label>
                        <span>Nova senha</span>
                        <input
                            type="password"
                            value={new_pw}
                            onChange={(e) => setNew(e.target.value)}
                            autoComplete="new-password"
                            minLength={8}
                            required />
                    </label>

                    {new_pw && (() => {
                        const issues = password_policy_issues(new_pw);
                        return (
                            <ul className="change-password-checklist">
                                <li className={new_pw.length >= 8 ? 'ok' : ''}>
                                    {new_pw.length >= 8 ? '✓' : '○'} mínimo 8 caracteres
                                </li>
                                <li className={/[A-Z]/.test(new_pw) ? 'ok' : ''}>
                                    {/[A-Z]/.test(new_pw) ? '✓' : '○'} 1 letra maiúscula
                                </li>
                                <li className={/\d/.test(new_pw) ? 'ok' : ''}>
                                    {/\d/.test(new_pw) ? '✓' : '○'} 1 número
                                </li>
                                <li className={/[^A-Za-z0-9]/.test(new_pw) ? 'ok' : ''}>
                                    {/[^A-Za-z0-9]/.test(new_pw) ? '✓' : '○'} 1 caractere especial
                                </li>
                            </ul>
                        );
                    })()}

                    <label>
                        <span>Confirme a nova senha</span>
                        <input
                            type="password"
                            value={new_pw2}
                            onChange={(e) => setNew2(e.target.value)}
                            autoComplete="new-password"
                            minLength={8}
                            required />
                    </label>

                    {user.totp_enabled && (
                        <label>
                            <span>Código TOTP (6 dígitos)</span>
                            <input
                                type="text"
                                value={totp}
                                onChange={(e) => setTotp(e.target.value.replace(/\D/g, '').slice(0, 6))}
                                inputMode="numeric"
                                pattern="[0-9]{6}"
                                maxLength={6}
                                autoComplete="one-time-code"
                                required />
                        </label>
                    )}

                    {err && <div className="change-password-error">{err}</div>}

                    <button type="submit" disabled={loading} className="change-password-btn">
                        {loading ? 'salvando…' : 'Confirmar'}
                    </button>
                </form>
                </div>
                </div>
            </div>
            {AppFooter && <AppFooter />}
        </div>
    );
};
