<?php $pageTitle = t('totp_settings'); ?>
<div class="page-header">
    <div class="page-header-left">
        <a href="/settings" class="btn btn-ghost btn-sm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
            <?= t('settings') ?>
        </a>
        <h1 class="page-title"><?= t('totp_settings') ?></h1>
    </div>
</div>

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

<div class="settings-grid">

<?php if ($user['totp_enabled']): ?>
    <!-- ── TOTP is active ── -->
    <div class="card">
        <div class="card-header">
            <h2 class="card-title"><?= t('totp_settings') ?></h2>
            <span class="badge badge-success"><?= t('totp_active') ?></span>
        </div>
        <div class="card-body">
            <p class="text-muted" style="margin-bottom:1.25rem"><?= t('totp_active_desc') ?></p>
            <form method="POST">
                <?= Helper::csrf() ?>
                <input type="hidden" name="action" value="totp_disable">
                <div class="form-group">
                    <label class="form-label"><?= t('totp_code') ?></label>
                    <input type="text" name="totp_code" class="form-input totp-input"
                           maxlength="6" pattern="\d{6}" inputmode="numeric"
                           autocomplete="one-time-code" placeholder="000000" required>
                    <span class="form-hint"><?= t('totp_disable_hint') ?></span>
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('current_password_label') ?></label>
                    <input type="password" name="confirm_password" class="form-input"
                           autocomplete="current-password" required>
                </div>
                <button type="submit" class="btn btn-danger"><?= t('totp_disable') ?></button>
            </form>
        </div>
    </div>

<?php elseif (!$stepUpOk): ?>
    <!-- ── Email step-up: prove ownership before TOTP setup ── -->
    <div class="card">
        <div class="card-header">
            <h2 class="card-title"><?= t('totp_setup_step_up_title') ?></h2>
            <span class="badge badge-neutral"><?= t('totp_inactive') ?></span>
        </div>
        <div class="card-body">
            <p class="text-muted" style="margin-bottom:1.25rem">
                <?= Helper::e(Lang::get('totp_setup_step_up_desc', ['email' => $emailHint])) ?>
            </p>
            <?php if (!$codeSent): ?>
            <form method="POST">
                <?= Helper::csrf() ?>
                <input type="hidden" name="action" value="totp_step_up_send">
                <button type="submit" class="btn btn-primary"><?= t('totp_setup_step_up_send_btn') ?></button>
            </form>
            <?php else: ?>
            <form method="POST" style="margin-bottom:1rem">
                <?= Helper::csrf() ?>
                <input type="hidden" name="action" value="totp_step_up_verify">
                <div class="form-group">
                    <label class="form-label"><?= t('totp_setup_step_up_code_label') ?></label>
                    <input type="text" name="step_up_code" class="form-input totp-input"
                           maxlength="6" pattern="\d{6}" inputmode="numeric"
                           autocomplete="one-time-code" placeholder="000000" required autofocus>
                </div>
                <div class="form-row" style="gap:.75rem">
                    <button type="submit" class="btn btn-primary"><?= t('totp_setup_step_up_verify_btn') ?></button>
                </div>
            </form>
            <form method="POST">
                <?= Helper::csrf() ?>
                <input type="hidden" name="action" value="totp_step_up_send">
                <button type="submit" class="btn btn-ghost btn-sm"><?= t('totp_setup_step_up_resend') ?></button>
            </form>
            <?php endif; ?>
        </div>
    </div>

<?php elseif ($user['totp_secret']): ?>
    <!-- ── Secret generated, waiting for confirmation ── -->
    <div class="card">
        <div class="card-header">
            <h2 class="card-title"><?= t('totp_setup') ?></h2>
        </div>
        <div class="card-body">
            <p style="margin-bottom:1rem"><?= t('totp_scan_desc') ?></p>

            <!-- QR code -->
            <div id="qrcode" class="totp-qr"></div>

            <!-- Manual secret -->
            <div class="totp-secret-box">
                <span class="form-label"><?= t('totp_manual_key') ?></span>
                <code class="totp-secret-code" id="totpSecret"><?= Helper::e(chunk_split($user['totp_secret'], 4, ' ')) ?></code>
                <button type="button" class="btn btn-ghost btn-xs" data-click="copySecret"><?= t('totp_copy') ?></button>
            </div>

            <!-- Confirm form -->
            <form method="POST" style="margin-top:1.5rem">
                <?= Helper::csrf() ?>
                <input type="hidden" name="action" value="totp_enable">
                <input type="hidden" name="totp_secret" value="<?= Helper::e($user['totp_secret']) ?>">
                <div class="form-group">
                    <label class="form-label"><?= t('totp_confirm_code') ?></label>
                    <input type="text" name="totp_code" class="form-input totp-input"
                           maxlength="6" pattern="\d{6}" inputmode="numeric"
                           autocomplete="one-time-code" placeholder="000000" required autofocus>
                    <span class="form-hint"><?= t('totp_confirm_hint') ?></span>
                </div>
                <div class="form-row" style="gap:.75rem">
                    <button type="submit" class="btn btn-primary"><?= t('totp_enable') ?></button>
                    <a href="/settings/totp" class="btn btn-ghost"><?= t('cancel') ?></a>
                </div>
            </form>
        </div>
    </div>

<?php else: ?>
    <!-- ── TOTP not set up ── -->
    <div class="card">
        <div class="card-header">
            <h2 class="card-title"><?= t('totp_settings') ?></h2>
            <span class="badge badge-neutral"><?= t('totp_inactive') ?></span>
        </div>
        <div class="card-body">
            <p class="text-muted" style="margin-bottom:1.25rem"><?= t('totp_setup_desc') ?></p>
            <form method="POST">
                <?= Helper::csrf() ?>
                <input type="hidden" name="action" value="totp_generate">
                <button type="submit" class="btn btn-primary"><?= t('totp_setup') ?></button>
            </form>
        </div>
    </div>
<?php endif; ?>

    <!-- ── Email MFA card ── -->
    <div class="card">
        <div class="card-header">
            <h2 class="card-title"><?= t('email_mfa_settings') ?></h2>
            <?php if ($user['email_mfa_enabled']): ?>
            <span class="badge badge-success"><?= t('email_mfa_active') ?></span>
            <?php else: ?>
            <span class="badge badge-neutral"><?= t('email_mfa_inactive') ?></span>
            <?php endif; ?>
        </div>
        <div class="card-body">
            <?php if ($user['email_mfa_enabled']): ?>
            <p class="text-muted" style="margin-bottom:1.25rem"><?= t('email_mfa_disable_desc') ?></p>
            <form method="POST">
                <?= Helper::csrf() ?>
                <input type="hidden" name="action" value="email_mfa_disable">
                <div class="form-group">
                    <label class="form-label"><?= t('current_password_label') ?></label>
                    <input type="password" name="confirm_password" class="form-input"
                           autocomplete="current-password" required>
                </div>
                <button type="submit" class="btn btn-danger"><?= t('email_mfa_disable_btn') ?></button>
            </form>
            <?php else: ?>
            <p class="text-muted" style="margin-bottom:1.25rem"><?= t('email_mfa_enable_desc') ?></p>
            <form method="POST">
                <?= Helper::csrf() ?>
                <input type="hidden" name="action" value="email_mfa_enable">
                <button type="submit" class="btn btn-primary"><?= t('email_mfa_enable_btn') ?></button>
            </form>
            <?php endif; ?>
        </div>
    </div>

    <!-- ── Security Keys (WebAuthn) ── -->
    <div class="card">
        <div class="card-header">
            <h2 class="card-title"><?= t('webauthn_settings') ?></h2>
            <?php if (!empty($webauthnCredentials)): ?>
            <span class="badge badge-success"><?= count($webauthnCredentials) ?> <?= t('webauthn_registered_count') ?></span>
            <?php else: ?>
            <span class="badge badge-neutral"><?= t('totp_inactive') ?></span>
            <?php endif; ?>
        </div>
        <div class="card-body">
            <p class="text-muted" style="margin-bottom:1.25rem"><?= t('webauthn_desc') ?></p>

            <?php if (!empty($webauthnCredentials)): ?>
            <div style="margin-bottom:1.25rem;display:flex;flex-direction:column;gap:8px">
                <?php foreach ($webauthnCredentials as $key): ?>
                <div style="display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--bg-secondary);border-radius:8px">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18" style="flex-shrink:0;color:var(--color-primary)"><rect x="2" y="8" width="20" height="12" rx="2"/><path d="M12 8V4m0 0a2 2 0 1 0 0-4 2 2 0 0 0 0 4z" fill="currentColor"/></svg>
                    <div style="flex:1;min-width:0">
                        <div style="font-weight:600;font-size:.875rem"><?= Helper::e($key['name']) ?></div>
                        <div style="font-size:.75rem;color:var(--text-secondary)">
                            <?= t('webauthn_registered_on') ?> <?= Helper::formatDateTime($key['created_at']) ?>
                            <?php if ($key['last_used_at']): ?>
                            · <?= t('webauthn_last_used') ?> <?= Helper::formatDateTime($key['last_used_at']) ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    <button type="button" class="icon-btn-sm danger" data-click="deleteKey" data-key-id="<?= $key['id'] ?>" title="<?= t('delete') ?>">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
                    </button>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <div style="display:flex;gap:8px;align-items:flex-end">
                <div class="form-group" style="flex:1;margin-bottom:0">
                    <label class="form-label"><?= t('webauthn_key_name') ?></label>
                    <input type="text" id="webauthnKeyName" class="form-input" placeholder="<?= t('webauthn_key_name_ph') ?>" maxlength="60">
                </div>
                <button type="button" class="btn btn-primary" data-click="registerKey" id="webauthnRegBtn">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M12 5v14M5 12h14"/></svg>
                    <?= t('webauthn_add_key') ?>
                </button>
            </div>
            <div id="webauthnMsg" style="display:none;margin-top:10px;padding:10px 14px;border-radius:8px;font-size:.875rem"></div>
        </div>
    </div>


</div>

<script nonce="<?= csp_nonce() ?>">
const _csrf = <?= json_encode(Auth::generateCsrfToken()) ?>;

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;
}
function decodeCreateArgs(opts) {
    opts.publicKey.challenge = b64uToBuf(opts.publicKey.challenge);
    opts.publicKey.user.id  = b64uToBuf(opts.publicKey.user.id);
    if (opts.publicKey.excludeCredentials) {
        opts.publicKey.excludeCredentials = opts.publicKey.excludeCredentials.map(c => ({...c, id: b64uToBuf(c.id)}));
    }
    return opts;
}

async function registerKey() {
    const btn = document.getElementById('webauthnRegBtn');
    const msg = document.getElementById('webauthnMsg');
    const name = document.getElementById('webauthnKeyName').value.trim();
    btn.disabled = true;
    showMsg(msg, <?= json_encode(t('webauthn_touch_key')) ?>, 'info');

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

        decodeCreateArgs(opts);
        const cred = await navigator.credentials.create(opts);

        const res = await fetch('<?= APP_BASE ?>/webauthn/register-verify', {
            method: 'POST',
            headers: {'Content-Type': 'application/json', 'X-CSRF-Token': _csrf},
            body: JSON.stringify({
                csrf_token: _csrf,
                name,
                id: cred.id,
                response: {
                    clientDataJSON:  bufToB64u(cred.response.clientDataJSON),
                    attestationObject: bufToB64u(cred.response.attestationObject),
                },
                type: cred.type,
            })
        }).then(r => r.json());

        if (res.ok) {
            showMsg(msg, <?= json_encode(t('webauthn_register_success')) ?>, 'success');
            setTimeout(() => location.reload(), 1200);
        } else {
            throw new Error(res.error || <?= json_encode(t('webauthn_register_error')) ?>);
        }
    } catch (e) {
        showMsg(msg, e.message || <?= json_encode(t('webauthn_register_error')) ?>, 'error');
    } finally {
        btn.disabled = false;
    }
}

async function deleteKey(btn) {
    if (!confirm(<?= json_encode(t('confirm_delete')) ?>)) return;
    btn.disabled = true;
    const fd = new FormData();
    fd.append('csrf_token', _csrf);
    fd.append('credential_id', btn.dataset.keyId);
    const res = await fetch('<?= APP_BASE ?>/webauthn/delete', {method:'POST', body: fd}).then(r => r.json());
    if (res.ok) location.reload();
    else btn.disabled = false;
}

function showMsg(el, text, type) {
    el.textContent = text;
    el.style.display = 'block';
    el.style.background = type === 'success' ? 'var(--color-success-bg,#dcfce7)' :
                          type === 'error'   ? 'var(--color-danger-bg,#fee2e2)' :
                                              'var(--bg-secondary)';
    el.style.color = type === 'success' ? 'var(--color-success,#16a34a)' :
                     type === 'error'   ? 'var(--color-danger,#dc2626)' :
                                         'var(--text-secondary)';
}
</script>

<?php if ($otpUrl): ?>
<script nonce="<?= csp_nonce() ?>" src="/assets/js/qrcode.min.js"></script>
<script nonce="<?= csp_nonce() ?>">
document.addEventListener('DOMContentLoaded', function() {
    const el = document.getElementById('qrcode');
    if (el && typeof QRCode !== 'undefined') {
        new QRCode(el, {
            text: <?= json_encode($otpUrl) ?>,
            width: 200,
            height: 200,
            colorDark: getComputedStyle(document.documentElement).getPropertyValue('--text') || '#000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.M
        });
    }
});
function copySecret() {
    const s = document.getElementById('totpSecret').textContent.replace(/\s/g,'');
    navigator.clipboard.writeText(s).then(() => {
        const btn = event.target;
        btn.textContent = '✓';
        setTimeout(() => btn.textContent = <?= json_encode(t('totp_copy')) ?>, 1500);
    });
}
</script>
<?php endif; ?>
