(function ($, Drupal) {
  Drupal.behaviors.moWebauthnLogin = {
    attach: function (context, settings) {
      let utiliity= Drupal.moWebAuthnUtility;
      $(once('webauthn-popoup', '#web_authn_submit', context)).on('click', async function () {
        const username = $('input[name="web_authn_username"]').val();
        console.log(username);

        if (!username) return;

        try {
          const response = await fetch('/mo-webauthn/assertion', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-Requested-With': 'XMLHttpRequest',
            },
            credentials: 'same-origin',
            body: JSON.stringify({ username: username }),
          });

          if (!response.ok) throw new Error('Failed to fetch assertion options');
          const options = await response.json();

          // Decode challenge and credential IDs
          options.challenge = utiliity.base64urlToUint8Array(options.challenge);
          if (options.allowCredentials) {
            options.allowCredentials = options.allowCredentials.map((cred) => ({
              ...cred,
              id: utiliity.base64urlToUint8Array(cred.id),
            }));
          }

          const credential = await navigator.credentials.get({ publicKey: options });

          const assertionResponse = {
            id: credential.id,
            type: credential.type,
            rawId: utiliity.uint8ArrayToBase64url(credential.rawId),
            response: {
              authenticatorData: utiliity.uint8ArrayToBase64url(credential.response.authenticatorData),
              clientDataJSON: utiliity.uint8ArrayToBase64url(credential.response.clientDataJSON),
              signature: utiliity.uint8ArrayToBase64url(credential.response.signature),
              userHandle: credential.response.userHandle
                ? utiliity.uint8ArrayToBase64url(credential.response.userHandle)
                : null,
            },
          };

          const verify = await fetch('/mo-webauthn/assertion/login', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-Requested-With': 'XMLHttpRequest',
            },
            credentials: 'same-origin',
            body: JSON.stringify(assertionResponse),
          });

          const result = await verify.json();

          if (result.success) {
            console.log('Authenticated with WebAuthn');
            window.location.replace(Drupal.url('user/'))

          } else {
            console.error('❌ WebAuthn failed', result.error);
          }

        } catch (e) {
          console.error('WebAuthn error:', e);
        }
      });

    },
  };
})(jQuery, Drupal);
