(function ($) {
    "use strict";

    /* ===================================
        Dashboard Side Menu
    ====================================== */

    const dashboard_side_menu = $('.gn-dashboard-side-menu');

    if (dashboard_side_menu.length) {

        //Side toggle
        $(document).on('click', '.gn-side-menu-toggle', function (e) {
            e.preventDefault();
            let collapsed = !dashboard_side_menu.hasClass('gn-collapsed');
            document.cookie = `gigneo_sidebar_collapse=${collapsed}; path=/; max-age=86400`;
            dashboard_side_menu.toggleClass('gn-collapsed');
            $('.gn-dashboard-wrapper').removeClass('gn-responsive-menu-active');

        });

        //Submenu active
        $(document).on('click', '.gn-dashboard-side-menu li.gn-has-submenu > a', function (e) {
            e.preventDefault();
            let _this = $(this);
            _this.siblings('ul').slideToggle(100);
            _this.siblings('ul').toggleClass('gn-submenu-expand');
        });

        //Action menu toggle
        $(document).on('click', '.gn-dashboard-side-menu-action-wrapper .gn-user-profile-action', function () {
            $(this).parents('.gn-dashboard-side-menu-action-wrapper').toggleClass('gn-active');
        });

        $(document).on('click', function (e) {
            if (!$(e.target).closest('.gn-dashboard-side-menu-action-wrapper').length) {
                $('.gn-dashboard-side-menu-action-wrapper').removeClass('gn-active');
            }
        });

    }

    //Media slider
      if ($('.gn-service-media-slider').length) {
        $('.gn-service-media-slider').slick({
            dots: true,
            arrows: true,
            infinite: false,
            speed: 300,
            slidesToShow: 1,
            slidesToScroll: 1,
            rtl: $('html').attr('dir') === 'rtl'
        });
    }

    /* ===================================
         Dashboard Top Menu
     ====================================== */

    const dashboard_top_menu = $('.gn-dashboard-top-menu');

    if (dashboard_top_menu.length) {

        //Submenu active
        $(document).on('click', '.gn-dashboard-top-menu li.gn-has-submenu > a', function (e) {
            e.preventDefault();
            let _this = $(this);
            _this.siblings('ul').toggleClass('gn-submenu-expand');
        });

        //Action menu toggle
        $(document).on('click', '.gn-dashboard-top-menu-action-wrapper .gn-user-profile-action', function () {
            $(this).parents('.gn-dashboard-top-menu-action-wrapper').toggleClass('gn-active');
        });

        $(document).on('click', function (e) {
            if (!$(e.target).closest('.gn-dashboard-top-menu-action-wrapper').length) {
                $('.gn-dashboard-top-menu-action-wrapper').removeClass('gn-active');
            }
            if (!$(e.target).closest('.gn-dashboard-top-menu li.gn-has-submenu > a').length && !$(e.target).closest('.gn-submenu-expand').length) {
                $('.gn-submenu-expand').removeClass('gn-submenu-expand');
            }
        });

        //Top menu toggle
        $(document).on('click', '.gn-dashboard-top-menu-toggle', function () {
            dashboard_top_menu.toggleClass('gn-responsive-menu-show');
        });
    }

    /* ===================================
        Dashboard Responsive Menu
    ====================================== */

    $('.gn-responsive-menu-toggle').on('click', function (e) {
        e.preventDefault();
        $('.gn-dashboard-wrapper').toggleClass('gn-responsive-menu-active');
    });

    /* ===================================
         Tabs
    ====================================== */

    $(document).on('click', '.gn-tabs-wrapper .gn-tab:not(.active)', function (e) {
        e.preventDefault();
        let _this = $(this);
        let target = _this.data('gn-target');
        let tabs_wrapper = _this.parents('.gn-tabs-wrapper');
        let tab_content = tabs_wrapper.find(`#gn-tab-content-${target}`);

        if (tab_content.length === 0) {
            return;
        }

        tabs_wrapper.find('.gn-tab').removeClass('gn-active');
        _this.addClass('gn-active');

        tabs_wrapper.find('.gn-tab-content').removeClass('gn-active');
        tabs_wrapper.find(`#gn-tab-content-${target}`).addClass('gn-active');
    });

    /* ===================================
         Dismiss Notice
    ====================================== */

    $(document).on('click', '.gn-notice-dismissed', function (e) {
        e.preventDefault();

        let _this = $(this);
        let id = _this.attr('data-gn-notice-id');
        let notice = _this.parents('.gn-notice');

        notice.remove();

        if (id && notice.hasClass('.gn-dismissible')) {
            $.ajax({
                url: GigneoCommon.ajax_url,
                method: 'POST',
                data: {
                    action: 'gigneo_notice_dismiss',
                    id: id,
                    security: GigneoCommon.security
                },
                success: function (response) {
                },
                error: function (xhr, status, error) {
                }
            });
        }

    });

    /* ===================================
         Email Verification
    ====================================== */

    $(document).on('click', '#gn-email-verification-btn', function (e) {
        e.preventDefault();
        let _this = $(this);
        _this.addClass('gn-loading');

        $.ajax({
            url: GigneoCommon.ajax_url,
            method: 'POST',
            data: {
                action: 'gigneo_email_verification',
                security: GigneoCommon.security
            },
            success: function (response) {
                if (response.success) {
                    _this.removeClass('gn-loading');
                    if (response.data.message) {
                        GigneoAlert.toast({
                            icon: 'success',
                            title: GigneoCommon.success,
                            text: response.data.message
                        });
                    }
                }
            },
            error: function (xhr, status, error) {
                _this.removeClass('gn-loading');
                let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                GigneoAlert.toast({
                    icon: 'error',
                    title: GigneoCommon.error,
                    text: error_message
                });
            }
        });

    });

    /* ===================================
        Account Activate
    ====================================== */

    $(document).on('click', '#gn-activate-account-btn', function (e) {
        e.preventDefault();
        let _this = $(this);

        _this.addClass('gn-loading');

        $.ajax({
            url: GigneoCommon.ajax_url,
            method: 'POST',
            data: {
                action: 'gigneo_save_account_setting',
                type: 'activate_account',
                security: GigneoCommon.security
            },
            success: function (response) {
                if (response.success) {

                    _this.removeClass('gn-loading');
                    _this.parents('.gn-modal-wrapper').removeClass('gn-active');

                    if (response.data.message) {
                        GigneoAlert.toast({
                            'icon': 'success',
                            title: GigneoCommon.success,
                            'text': response.data.message
                        });
                    }

                    if (response.data.redirect) {
                        window.location.href = response.data.redirect;
                    }

                }
            },
            error: function (xhr, status, error) {
                _this.removeClass('gn-loading');
                let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                GigneoAlert.toast({
                    'icon': 'error',
                    title: GigneoCommon.error,
                    'text': error_message
                });
            }
        });

    });

    /* ===================================
       Date Range
   ====================================== */

    let date_range_wrapper = $('.gn-range-filter');

    if (date_range_wrapper.length) {

        //Date Range Dropdown
        $(document).on('click', '.gn-range-toggle', function (e) {
            e.preventDefault();
            let _this = $(this);
            _this.parents('.gn-range-filter').toggleClass('gn-active');
        });

        // Click Outside To Remove Class
        $(document).on('click', function (e) {
            if (!$(e.target).closest('.gn-range-filter').length) {
                $('.gn-range-filter').removeClass('gn-active');
            }
        });

        date_range_wrapper.each(function (index, element) {
            let _this = $(element);
            //Range Select
            _this.on('click', '.gn-range-options > button', function (e) {
                let date_range = _this.find('.gn-date-range-input');
                let flatpickr = date_range.get(0).flatpickr();
                let range_type = $(this).data('gn-range');
                let dates = getDateRange(range_type);
                flatpickr.setDate([dates.start_date, dates.end_date], true);
            });

           //Reset
            _this.on('click', 'button[type=reset]', function (e) {
                let date_range = _this.find('.gn-date-range-input');
                let flatpickr = date_range.get(0).flatpickr();
                date_range.val('').trigger('change');
                flatpickr.clear();
            });
        });

        function getDateRange(type) {
            const today = new Date();
            let start, end;

            switch (type) {
                case 'last_7_days':
                    start = new Date(today);
                    start.setDate(today.getDate() - 7);
                    end = new Date(today);
                    break;

                case 'last_30_days':
                    start = new Date(today);
                    start.setDate(today.getDate() - 30);
                    end = new Date(today);
                    break;

                case 'last_6_months':
                    start = new Date(today.getFullYear(), today.getMonth() - 6, 1);
                    end = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                    break;

                case 'last_12_months':
                    start = new Date(today.getFullYear(), today.getMonth() - 12, 1);
                    end = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                    break;

                default:
                    end = new Date(today);
                    break;
            }

            return {
                start_date: start.toISOString().split('T')[0],
                end_date: end.toISOString().split('T')[0],
            };
        }
    }

    /* ===================================
        Invoice Download
    ====================================== */

    //Order Invoice Download
    $(document).on('click', '.gn-invoice-download', function (e) {
        e.preventDefault();
        let _this = $(this);
        let invoice_id = _this.data('gn-invoice-id');

        if (invoice_id === '') {
            return false;
        }

        _this.addClass('gn-loading');

        $.ajax({
            url: GigneoCommon.ajax_url,
            method: 'POST',
            data: {
                action: 'gigneo_order_invoice_download',
                id: invoice_id,
                security: GigneoCommon.security
            },
            success: function (response) {
                _this.removeClass('gn-loading');
                if (response.data.file_data && response.data.file_name) {
                    const byteCharacters = atob(response.data.file_data);
                    const byteNumbers = new Array(byteCharacters.length);
                    for (let i = 0; i < byteCharacters.length; i++) {
                        byteNumbers[i] = byteCharacters.charCodeAt(i);
                    }
                    const byteArray = new Uint8Array(byteNumbers);
                    const blob = new Blob([byteArray], {type: 'application/pdf'});
                    const url = window.URL.createObjectURL(blob);

                    const a = document.createElement('a');
                    a.href = url;
                    a.download = response.data.file_name;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                } else {
                    GigneoAlert.toast({
                        icon: 'error', title: GigneoCommon.error, text: GigneoCommon.went_wrong
                    });
                }
            }, error: function (xhr, status, error) {
                _this.removeClass('gn-loading');
                let error_message = xhr?.responseJSON?.data.message || GigneoCommon.went_wrong;
                GigneoAlert.toast({
                    icon: 'error', title: GigneoCommon.error, text: error_message
                });
            }
        });

    });

}(jQuery));