<div class="auth-content">
    <h1 class="auth-title"><?= t('login_title') ?></h1>
    <p class="auth-subtitle"><?= t('login_subtitle') ?></p>

    <?php if (!empty($success)): ?>
    <div class="alert alert-success"><?= Helper::e(Lang::get($success)) ?></div>
    <?php endif; ?>
    <?php if (!empty($error)): ?>
    <div class="alert alert-error"><?= Helper::e($error) ?></div>
    <?php endif; ?>

    <form method="POST" action="/login" class="auth-form">
        <?= Helper::csrf() ?>
        <?php if (!empty($redirectTo)): ?>
        <input type="hidden" name="redirect_to" value="<?= Helper::e($redirectTo) ?>">
        <?php endif; ?>
        <div class="form-group">
            <label for="email" class="form-label"><?= t('email') ?></label>
            <input type="email" id="email" name="email" class="form-input" required autofocus
                   value="<?= Helper::e(Helper::post('email')) ?>" autocomplete="email">
        </div>
        <div class="form-group">
            <label for="password" class="form-label"><?= t('password') ?></label>
            <div class="input-with-toggle">
                <input type="password" id="password" name="password" class="form-input" required autocomplete="current-password">
                <button type="button" class="pw-toggle" data-pw-toggle="password">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                </button>
            </div>
        </div>
        <button type="submit" class="btn btn-primary btn-block"><?= t('login_btn') ?></button>
    </form>
    <?php
        // SSO buttons (OIDC plugin and any other plugin that hooks here).
        // Each plugin renders its own button; the markup convention is a list
        // of `<a class="btn btn-secondary">` inside an outer wrapper div.
        PluginManager::fire('login_form_extras', ['view' => 'login']);
    ?>
    <?php if (Helper::getSetting('password_reset_enabled', '0') === '1'): ?>
    <p class="auth-footer-link"><a href="<?= url('forgot-password') ?>"><?= t('forgot_password') ?></a></p>
    <?php endif; ?>
    <?php if (Helper::getSetting('allow_registration', '0') === '1'): ?>
    <p class="auth-footer-link"><a href="<?= url('register') ?>"><?= t('register_link') ?></a></p>
    <?php endif; ?>

    <div style="margin-top:1.25rem;padding-top:1.25rem;border-top:1px solid var(--border-color)">
        <button type="button" class="btn btn-ghost btn-block" id="webauthnLoginBtn" data-click="loginWithKey" style="display:flex;align-items:center;justify-content:center;gap:8px">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18"><circle cx="7" cy="17" r="4"/><path d="M10.24 13.76L20 4"/><path d="M18 6l2 2"/><path d="M15 9l2 2"/></svg>
            <?= t('webauthn_login_btn') ?>
        </button>
        <div id="webauthnLoginMsg" style="display:none;margin-top:8px;padding:10px 14px;border-radius:8px;font-size:.875rem;text-align:center"></div>
    </div>
</div>
<script nonce="<?= csp_nonce() ?>">
function togglePassword(id) {
    const el = document.getElementById(id);
    el.type = el.type === 'password' ? 'text' : 'password';
}

function bufToB64u(buf) {
    let str = '';
    new Uint8Array(buf).forEach(b => str += String.fromCharCode(b));
    return btoa(str).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');
}
function b64uToBuf(s) {
    const b64 = s.replace(/-/g,'+').replace(/_/g,'/').padEnd(Math.ceil(s.length/4)*4,'=');
    return Uint8Array.from(atob(b64), c => c.charCodeAt(0)).buffer;
}

async function loginWithKey() {
    const btn = document.getElementById('webauthnLoginBtn');
    const msg = document.getElementById('webauthnLoginMsg');
    btn.disabled = true;
    showLoginMsg(<?= json_encode(t('webauthn_touch_key')) ?>, 'info');

    try {
        const opts = await fetch('<?= APP_BASE ?>/webauthn/login-challenge').then(r => r.json());
        if (opts.error) throw new Error(opts.error);

        opts.publicKey.challenge = b64uToBuf(opts.publicKey.challenge);
        if (opts.publicKey.allowCredentials) {
            opts.publicKey.allowCredentials = opts.publicKey.allowCredentials.map(c => ({...c, id: b64uToBuf(c.id)}));
        }

        const assertion = await navigator.credentials.get(opts);

        const payload = {
            id:   assertion.id,
            type: assertion.type,
            response: {
                clientDataJSON:    bufToB64u(assertion.response.clientDataJSON),
                authenticatorData: bufToB64u(assertion.response.authenticatorData),
                signature:         bufToB64u(assertion.response.signature),
                userHandle:        assertion.response.userHandle ? bufToB64u(assertion.response.userHandle) : null,
            }
        };

        const res = await fetch('<?= APP_BASE ?>/webauthn/login-verify', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(payload)
        }).then(r => r.json());

        if (res.ok) {
            showLoginMsg(<?= json_encode(t('webauthn_login_success')) ?>, 'success');
            window.location.href = res.redirect || '/dashboard';
        } else {
            throw new Error(res.error || <?= json_encode(t('login_error')) ?>);
        }
    } catch (e) {
        if (e.name === 'NotAllowedError') {
            showLoginMsg(<?= json_encode(t('webauthn_cancelled')) ?>, 'info');
        } else {
            showLoginMsg(e.message || <?= json_encode(t('login_error')) ?>, 'error');
        }
        btn.disabled = false;
    }
}

function showLoginMsg(text, type) {
    const el = document.getElementById('webauthnLoginMsg');
    el.textContent = text;
    el.style.display = 'block';
    el.style.background = type === 'success' ? '#dcfce7' : type === 'error' ? '#fee2e2' : '#f1f5f9';
    el.style.color      = type === 'success' ? '#15803d' : type === 'error' ? '#dc2626' : '#64748b';
    el.style.borderRadius = '8px';
}
</script>
