/**
 * PasskeyRegistrationPage.js
 * Handles the WebAuthn credential creation (registration) ceremony.
 */
(function () {
    'use strict';

    function base64urlToBuffer(base64url) {
        var base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
        var padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, '=');
        var binary = atob(padded);
        var buffer = new ArrayBuffer(binary.length);
        var view = new Uint8Array(buffer);
        for (var i = 0; i < binary.length; i++) {
            view[i] = binary.charCodeAt(i);
        }
        return buffer;
    }

    function bufferToBase64url(buffer) {
        var view = new Uint8Array(buffer);
        var binary = '';
        for (var i = 0; i < view.length; i++) {
            binary += String.fromCharCode(view[i]);
        }
        return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
    }

    function convertCreateOptions(options) {
        var publicKey = options.publicKey;
        if (publicKey.challenge) {
            publicKey.challenge = base64urlToBuffer(publicKey.challenge);
        }
        if (publicKey.user && publicKey.user.id) {
            publicKey.user.id = base64urlToBuffer(publicKey.user.id);
        }
        if (publicKey.excludeCredentials) {
            publicKey.excludeCredentials = publicKey.excludeCredentials.map(function (c) {
                return Object.assign({}, c, { id: base64urlToBuffer(c.id) });
            });
        }
        return options;
    }

    function encodeRegistrationResponse(credential) {
        var response = credential.response;
        return JSON.stringify({
            type: credential.type,
            id: credential.id,
            rawId: bufferToBase64url(credential.rawId),
            response: {
                attestationObject: bufferToBase64url(response.attestationObject),
                clientDataJSON: bufferToBase64url(response.clientDataJSON),
                transports: response.getTransports ? response.getTransports() : []
            },
            clientExtensionResults: credential.getClientExtensionResults
                ? credential.getClientExtensionResults()
                : {}
        });
    }

    function triggerRegistration() {
        var dataEl = document.getElementById('passkey-data');
        var statusEl = document.getElementById('passkey-status');
        var btn = document.getElementById('registerBtn');

        if (!dataEl) {
            return;
        }

        var optionsJson = dataEl.getAttribute('data-options');
        if (!optionsJson) {
            return;
        }

        var options;
        try {
            options = JSON.parse(optionsJson);
        } catch (e) {
            console.error('Failed to parse passkey creation options', e);
            return;
        }

        convertCreateOptions(options);

        btn.disabled = true;
        if (statusEl) {
            statusEl.classList.remove('d-none');
        }

        navigator.credentials.create(options)
            .then(function (credential) {
                var encoded = encodeRegistrationResponse(credential);
                document.getElementById('registrationResponse').value = encoded;
                document.getElementById('loginForm').submit();
            })
            .catch(function (err) {
                console.error('Passkey registration failed', err);
                btn.disabled = false;
                if (statusEl) {
                    statusEl.classList.add('d-none');
                }
            });
    }

    document.addEventListener('DOMContentLoaded', function () {
        if (!window.PublicKeyCredential) {
            var btn = document.getElementById('registerBtn');
            if (btn) {
                btn.disabled = true;
                btn.title = 'WebAuthn is not supported in this browser';
            }
            return;
        }

        var btn = document.getElementById('registerBtn');
        if (btn) {
            btn.addEventListener('click', triggerRegistration);
        }
    });
}());
