(function ($) {
    window.scrollToActiveElement = function (className) {
        const activeElement = document.querySelector(className);

        if (activeElement) {
            activeElement.scrollIntoView({
                behavior: 'smooth'
            });
        }
    };


    // check addtocart validation
    window.validateForm = function () {

        var select_at_least = $('#select_at_least').attr('href');
        var options = $('#options').attr('href');

        var isValid = true;

        $('.item_extra_list.required-section').each(function () {
            var section = $(this);
            var requiredCount = parseInt(section.data('limit'));
            var inputs = section.find('.extras:checked');

            if (inputs.length < requiredCount) {
                isValid = false;
                section.find('.errorMessage').text(`${select_at_least} ${requiredCount} ${options}`);
                scrollToActiveElement('.errorMessage');
            } else {
                section.find('.errorMessage').text('');
            }
        });
        setTimeout(() => {
            $('.errorMessage').html('');
        }, 4000);

        return isValid;
    }


    /*----------------------------------------------
         GET LATITUDE & LONGITUDE
   ----------------------------------------------*/

    window.getLocation = function () {
        if ("geolocation" in navigator) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
                if ($('[name="latitude"]').length > 0) {
                    $('[name="latitude"]').val(latitude);
                }

                if ($('[name="longitude"]').length > 0) {
                    $('[name="longitude"]').val(longitude);
                }
                console.log("Latitude: " + latitude + ", Longitude: " + longitude);
            }, function (error) {
                console.error("Error getting geolocation:", error);
            });
        } else {
            console.error("Geolocation is not supported by this browser.");
        }
    }

    window.addLangToUrl = function (url) {
        var languageType = $('meta[name="language_type"]').attr('content');
        if (languageType == 'system') {
            const lang = $('html').attr('lang');
            if (!lang) return url;
            if (url.indexOf('lang=') === -1) {
                if (url.indexOf('?') === -1) {
                    return `${url}?lang=${lang}`;
                } else {
                    return `${url}&lang=${lang}`;
                }
            }
        }

        return url;
    }
    function printWithQZ(htmlContent, printerName = null) {
        qz.websocket.connect().then(() => {
            return qz.printers.find(printerName); // Pass null for default printer
        }).then((printer) => {
            const config = qz.configs.create(printer);
            const data = [{
                type: 'html',
                format: 'plain',
                data: htmlContent
            }];
            return qz.print(config, data);
        }).catch(err => {
            console.error("QZ Tray Error:", err);
            alert("Failed to print. Is QZ Tray running?");
        });
    }


    window.formSubmit = function (e, thisForm, url = '') {
        e.preventDefault();

        const $thisForm = $(thisForm);
        const method = $thisForm.attr('method') || 'GET';
        const formUrl = url === '' ? $thisForm.attr('action') : url;

        const formData = new FormData(thisForm);
        const csrfToken = thisForm.querySelector('input[name="csrf_test_name"]').value;

        // Find submit button and show loading state
        let formBtn = $thisForm.find('[type="submit"]');
        submitBtn(formBtn, true);

        if ($thisForm.find('.errorMsg').length === 0) {
            $thisForm.prepend('<span class="errorMsg"></span>');
        }

        // Make the AJAX request
        $.ajax({
            url: formUrl,
            type: method,
            data: formData,
            dataType: 'json',
            processData: false,
            contentType: false,
            headers: {
                'csrf_test_name': csrfToken
            },
            success: function (response) {
                if (response.st === 1) {
                    if (response.msg) {
                        ajax_msg(response.msg, 1);
                    }

                    // Reset the form
                    $thisForm[0].reset();

                    setTimeout(() => {
                        // Return if no URL is provided
                        if (!response.url || response.url === '') {
                            return false;
                        }
                        // Handle modal response
                        else if (typeof response.url === "object") {
                            $(`#${response.url.modalName}`).modal('show');
                            $('.modalContent').html(response.url.result);
                        }
                        // Handle reload
                        else if (response.url === '1' || response.url == 1 || response.url == true ||
                            response.url == 'true' || response.url == 'reload') {
                            setTimeout(() => {
                                window.location.reload();
                            }, 1000);
                        }
                        // Handle AJAX URL
                        else if (isAjaxRequest(response.url)) {
                            load_by_url(response.url);
                            console.log(response.url);
                        }
                        // Handle standard redirection
                        else {
                            setTimeout(() => {
                                window.location = response.url;
                            }, 2000);
                        }
                    }, 500);
                } else {
                    console.log(response.st);
                    console.log(response.msg);
                    if (response.msg) {
                        ajax_msg(response.msg, 0);
                    }
                    submitBtn(formBtn, false);
                }
            },
            error: function (xhr) {
                // Reset button state
                submitBtn(formBtn, false);

                let errorMessage = 'An error occurred. Please try again.';

                // Handle various error responses
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                } else if (xhr.responseJSON && xhr.responseJSON.errors) {
                    const errors = xhr.responseJSON.errors;
                    errorMessage = Object.values(errors)[0][0];

                    // Mark invalid fields
                    Object.keys(errors).forEach(field => {
                        const $field = $thisForm.find(`[name="${field}"]`);
                        $field.addClass('is-invalid');
                        $field.after(`<div class="invalid-feedback">${errors[field][0]}</div>`);
                    });
                }

                // Display error message
                ajax_msg(errorMessage, 0);
            },
            complete: function () {
                // Reset button state
                submitBtn(formBtn, false);
            }
        });
    };

    // Button loading state handler
    window.submitBtn = function (currentBtn, type) {
        if (type == true) {
            currentBtn.prop('disabled', true);
            currentBtn.addClass('btn-loading');
        } else {
            currentBtn.prop('disabled', false);
            currentBtn.removeClass('btn-loading');
        }
    };

    // Function to check if URL is for AJAX request
    function isAjaxRequest(url) {
        return url.indexOf('?isAjax=1') !== -1;
    }



    window.load_by_url = function (url) {
        // Implement your AJAX content loading logic
        $.ajax({
            url: url,
            type: 'GET',
            success: function (response) {
                $('#ajaxContent').html(response);
            }
        });
    };

    window.ajax_msg = function (msg, type = 1) {

        $('.errorMsg').html(msg);

        // setTimeout(() => {
        //     $('.errorMsg').fadeOut();
        // }, 5000);
    }
})(jQuery);