document.addEventListener('DOMContentLoaded', async () => {
    const addBtn = document.getElementById('pk-add-btn');
    const statusEl = document.getElementById('pk-add-status');
    const deviceNameInput = document.getElementById('pk-device-name');

    if (!addBtn) return;

    const supported = await passkeySupported();
    if (!supported) {
        addBtn.disabled = true;
        addBtn.textContent = 'Not supported on this browser';
        if (statusEl) {
            statusEl.textContent = 'Your browser does not support passkeys. Try Safari on iOS 16+, Chrome 108+, or Edge 108+.';
            statusEl.className = 'mt-2 small mb-0 text-muted';
        }
        return;
    }

    addBtn.addEventListener('click', async () => {
        const name = deviceNameInput.value.trim();
        addBtn.disabled = true;
        addBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Follow the prompt…';
        if (statusEl) { statusEl.textContent = ''; statusEl.className = 'mt-2 small mb-0'; }

        const result = await registerPasskey(name);

        if (result.success) {
            if (statusEl) {
                statusEl.textContent = '✓ Passkey added! Reloading…';
                statusEl.className = 'mt-2 small mb-0 text-success';
            }
            setTimeout(() => window.location.reload(), 1200);
        } else {
            addBtn.disabled = false;
            addBtn.innerHTML = '<i class="bi bi-plus-circle me-1"></i>Add Passkey';
            if (statusEl) {
                statusEl.textContent = result.error || 'Setup failed. Please try again.';
                statusEl.className = 'mt-2 small mb-0 text-danger';
            }
        }
    });
});
