(function ($) {
    'use strict';

    // Added: Function to check if string is a valid URL
    function isValidUrl(string) {
        try {
            new URL(string);
            return true;
        } catch (_) {
            return false;
        }
    }

    $(function () {

        // DOM element caching.
        let $login_btn = $('#expandable-paywall-login-button');
        let $login_form = $('#expandable-paywall-login-form');
        let $login_status = $('#expandable-paywall-login-status');
        let $register_btn = $('#expandable-paywall-register-button');
        let $register_form = $('#expandable-paywall-register-form');
        let $register_status = $('#expandable-paywall-register-status');
        let $username = $('#user_login');
        let $password = $('#user_pass');
        let inputValue = $("input[type='hidden'][name='redirect_to']").val();
        let random_string = (Math.random() + 1).toString(36).substring(7);
        let $redirect_to = (typeof inputValue !== "undefined" && inputValue !== '') ? inputValue : ep.site_url;


        // Added: check if $redirect_to is a valid URL
        if(isValidUrl($redirect_to)){
            let url = new URL($redirect_to);
            let params = new URLSearchParams(url.search);
            params.set('cache_busting', random_string);
            $redirect_to = url.origin + url.pathname + '?' + params.toString();
        }
        // Common functionality to handle form submissions
        let handleFormSubmit = (e, action, data, $btn, $status) => {
            e.preventDefault();

            $status.show();
            $btn.val(`${action.charAt(0).toUpperCase() + action.slice(1)}...`).prop('disabled', true);

            data.action = `expandable-paywall_${action}`;
            data.nonce = ep[`${action}_nonce`];

            $.ajax({
                url: ep.ajax_url,
                type: 'post',
                dataType: 'json',
                data: data
            })
              .done(result => {
                  $status.removeClass('error').addClass('success').html(result);
                  $btn.prop('disabled', false);
                  if (action === "login") {
                      window.location = $redirect_to;
                  }
              })
                .fail(result => {
                    $btn.val(action.charAt(0).toUpperCase() + action.slice(1)).prop('disabled', false);

                    const errorMessage = result?.responseJSON?.data || 'An unknown error occurred.';

                    $status
                        .removeClass('success')
                        .addClass('error')
                        .html(`<div id="login_error" class="notice notice-error"><p>${errorMessage}</p></div>`);
                });
        };

        $login_form.submit(e => handleFormSubmit(e, 'login', {
            user_login: $username.val(),
            user_pass: $password.val()
        }, $login_btn, $login_status));

        $register_form.submit(e => handleFormSubmit(e, 'register', {
            user_login: $username.val(),
            user_pass: $password.val(),
            first_name: $('#first_name').val(),
            last_name: $('#last_name').val()
        }, $register_btn, $register_status));

    });

})(jQuery);