{% block content %}
<script>
    function base64urlDecode(str) {
        str = str.replace(/-/g, "+").replace(/_/g, "/");
        while (str.length % 4) str += "=";
        const binary = atob(str);
        const bytes = new Uint8Array(binary.length);
        for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
        return bytes.buffer;
    }

    function base64urlEncode(buffer) {
        const bytes = new Uint8Array(buffer);
        let binary = "";
        for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
        return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
    }

    const didClickLogin = async (e) => {
        e.preventDefault();

        if (!navigator.credentials) {
            alert("Your browser doesn't support WebAuthn, please use a different browser.");
            return;
        }

        let options;
        try {
            const response = await fetch("{% url 'webauthin:login-begin' %}", {method: "POST"});
            options = await response.json();
        } catch (err) {
            return console.error("Error getting login options:", err);
        }

        // Decode base64url fields to ArrayBuffers for the browser API.
        options.challenge = base64urlDecode(options.challenge);
        if (options.allowCredentials) {
            options.allowCredentials = options.allowCredentials.map(cred => ({
                ...cred,
                id: base64urlDecode(cred.id),
            }));
        }

        let assertion;
        try {
            assertion = await navigator.credentials.get({publicKey: options});
        } catch (err) {
            alert("Error during authentication: " + err);
            return console.error("Error during authentication:", err);
        }

        const body = JSON.stringify({
            id: assertion.id,
            rawId: base64urlEncode(assertion.rawId),
            response: {
                authenticatorData: base64urlEncode(assertion.response.authenticatorData),
                clientDataJSON: base64urlEncode(assertion.response.clientDataJSON),
                signature: base64urlEncode(assertion.response.signature),
                userHandle: assertion.response.userHandle
                    ? base64urlEncode(assertion.response.userHandle)
                    : null,
            },
            type: assertion.type,
        });

        try {
            const response = await fetch("{% url 'webauthin:login-verify' %}", {
                method: "POST",
                headers: {"Content-Type": "application/json"},
                body: body,
            });
            const result = await response.json();
            if (result.redirect) window.location = result.redirect;
        } catch (err) {
            console.error("Error verifying authentication:", err);
        }
    };

    document.addEventListener("DOMContentLoaded", () => {
        document.querySelector("#webauthin-login").addEventListener("click", didClickLogin);
    });
</script>
{% endblock %}
