/**
 * Modernized WPT Control JavaScript
 * Converted to modular ES6+ object style
 */

(function($) {
    'use strict';

    const WPTControl = {
        // State & config
        state: {
            ownFragmentLoad: 0,
            paginatedVal: 0,
            resetSearchClicked: 'no',
            wcFragmentLoad: 0,
            fragmentHandleLoad: 0,
            isMob: false,
            isDesk: false,
            currentWidth: $(window).width(),
        },
        config: {
            pluginUrl: WPT_DATA.plugin_url,
            includeUrl: WPT_DATA.include_url,
            contentUrl: WPT_DATA.content_url,
            ajaxUrl: WPT_DATA.ajax_url,
            siteUrl: WPT_DATA.site_url,
            nonce: WPT_DATA.nonce,
        },

        // Init function
        init: function() {
            this.state.currentWidth = $(window).width();
            if (this.state.currentWidth <= 500) {
                this.state.isMob = true;
                this.state.isDesk = false;
            } else {
                this.state.isMob = false;
                this.state.isDesk = true;
            }
            
            this.bindEvents();
            this.initExportEvents();
            $(document.body).append('<div class="wpt-new-footer-cart footer-cart-empty"></div>');
        },

        bindEvents: function() {
            const self = this;

            $(document.body).on('click', '.wpt_pagination_ajax .wpt_my_pagination a', function(e) {
                e.preventDefault();
                self.handlePaginationClick($(this));
            });

            $(document.body).on('click', 'button.button.wpt_load_more', function(e) {
                e.preventDefault();
                self.handleLoadMore($(this));
            });

            $(document.body).on('click', '.wpt-search-products', function() {
                self.handleSearchProducts($(this));
            });

            $(document.body).on('click', '.wpt-query-reset-button', function() {
                self.handleResetSearch($(this));
            });

            // Checkbox filter events
            $(document.body).on('change', '.wpt-checkbox-input', function() {
                self.handleCheckboxChange($(this));
            });

            $(document.body).on('click', '.wpt-selected-tag-remove', function() {
                self.handleSelectedTagRemove($(this));
            });

            $(document).on('wc_fragments_refreshed wc_fragments_refresh wc_fragment_refresh removed_from_cart wpt_fragment_load', function() {
                self.fragmentLoad();
            });

            $(document.body).on('wpt_ajax_loaded', function() {
                self.state.paginatedVal = 0;
                $('.wpt_varition_section.variations').change();
            });

            $(document.body).on('click', '.wpt-cart-remove', function() {
                self.handleCartRemove($(this));
            });

            $(document.body).on('click', '.wpt_empty_cart_btn', function(e) {
                e.preventDefault();
                self.handleEmptyCart();
            });

            $(document.body).on('click', '.wpt-fcart-coll-expand,.wpt-cart-contents span.count', function() {
                self.toggleFooterCart();
            });

            $(document.body).on('mouseover', '.wpt-new-footer-cart.wpt-foooter-cart-stats-on a.wpt-view-n', function() {
                self.toggleFooterCartHover();
            });

            $(window).scroll(function() {
                self.handleInfiniteScroll();
            });
        },

        handlePaginationClick: function($el) {
            const thisPagination = $el.closest('.wpt_my_pagination');
            const page_number = parseInt($el.text().replace(/,/g, ''), 10);
            const table_id = thisPagination.data('table_id');
            const args = this.getSearchQueriedArgs(table_id);
            this.ajaxTableLoad(table_id, args, { page_number, isMob: this.state.isMob });
        },

        handleLoadMore: function($btn) {
            const table_id = $btn.data('table_id');
            $btn.html($btn.data('text_loading'));
            const page_number = $btn.attr('data-page_number');
            const args = this.getSearchQueriedArgs(table_id);
            this.ajaxTableLoad(table_id, args, { page_number, isMob: this.state.isMob, type: 'load_more' });
        },

        handleSearchProducts: function($btn) {
            const table_id = $btn.data('table_id');
            const args = this.getSearchQueriedArgs(table_id);
            this.ajaxTableLoad(table_id, args, { page_number: 1, isMob: this.state.isMob });
        },

        handleResetSearch: function($btn) {
            $btn.closest('.wpt-search-full-wrapper').find('.query_box_direct_value').val('');
            $btn.closest('.wpt-search-full-wrapper').find('select').val('').change();
            // Reset checkbox filters
            $btn.closest('.wpt-search-full-wrapper').find('.wpt-checkbox-input').prop('checked', false);
            $btn.closest('.wpt-search-full-wrapper').find('.wpt-checkbox-item').removeClass('wpt-checkbox-checked');
            $btn.closest('.wpt-search-full-wrapper').find('.wpt-selected-items').empty();
            this.state.resetSearchClicked = 'yes';
            $btn.closest('.wpt-search-full-wrapper').find('.wpt-search-products').trigger('click');
        },

        /**
         * Handle checkbox change event
         * Updates the selected items display and triggers search
         */
        handleCheckboxChange: function($checkbox) {
            const $wrapper = $checkbox.closest('.wpt-checkbox-filter-wrapper');
            const $searchBox = $checkbox.closest('.wpt_search_box');
            const taxonomy = $wrapper.data('key');
            const tableId = $wrapper.data('table-id');
            const termId = $checkbox.val();
            const termName = $checkbox.data('term-name');
            const isChecked = $checkbox.is(':checked');
            const $item = $checkbox.closest('.wpt-checkbox-item');
            const $selectedItemsContainer = $searchBox.find('.wpt-selected-items-' + taxonomy);

            // Toggle checked class on item
            if (isChecked) {
                $item.addClass('wpt-checkbox-checked');
                // Add selected tag
                this.addSelectedTag($selectedItemsContainer, termId, termName, taxonomy);
            } else {
                $item.removeClass('wpt-checkbox-checked');
                // Remove selected tag
                this.removeSelectedTag($selectedItemsContainer, termId);
            }

            // Auto trigger search when checkbox changes
            $searchBox.find('.wpt-search-products').trigger('click');
        },

        /**
         * Handle removing a selected tag
         */
        handleSelectedTagRemove: function($removeBtn) {
            const $tag = $removeBtn.closest('.wpt-selected-tag');
            const termId = $tag.data('term-id');
            const taxonomy = $tag.data('taxonomy');
            const $searchBox = $removeBtn.closest('.wpt_search_box');
            
            // Uncheck the corresponding checkbox
            const $checkbox = $searchBox.find('.wpt-checkbox-input[value="' + termId + '"]');
            $checkbox.prop('checked', false);
            $checkbox.closest('.wpt-checkbox-item').removeClass('wpt-checkbox-checked');
            
            // Remove the tag
            $tag.remove();
            
            // Trigger search
            $searchBox.find('.wpt-search-products').trigger('click');
        },

        /**
         * Add a selected tag to the display area
         */
        addSelectedTag: function($container, termId, termName, taxonomy) {
            // Check if tag already exists
            if ($container.find('.wpt-selected-tag[data-term-id="' + termId + '"]').length > 0) {
                return;
            }

            // Create elements safely to avoid XSS
            const $tag = $('<span class="wpt-selected-tag"></span>')
                .attr('data-term-id', termId)
                .attr('data-taxonomy', taxonomy);
            
            const $tagText = $('<span class="wpt-selected-tag-text"></span>')
                .text(termName); // Using .text() sanitizes HTML
            
            const $removeBtn = $('<button type="button" class="wpt-selected-tag-remove" title="Remove">&times;</button>');
            
            $tag.append($tagText).append($removeBtn);
            $container.append($tag);
        },

        /**
         * Remove a selected tag from the display area
         */
        removeSelectedTag: function($container, termId) {
            $container.find('.wpt-selected-tag[data-term-id="' + termId + '"]').remove();
        },

        handleCartRemove: function($el) {
            $el.parent('li').fadeOut();
            this.footerCartAnimation();
            $el.addClass('wpt_spin');
            const product_id = $el.data('product_id');
            const cart_item_key = $el.attr('data-cart_item_key');
            const data = {
                action: 'wpt_remove_from_cart',
                product_id,
                cart_item_key,
                nonce: this.config.nonce
            };
            $.ajax({
                type: 'POST',
                url: this.config.ajaxUrl,
                data,
                success: (result) => {
                    $('.wpt-cart-remove.wpt-cart-remove-' + product_id).remove();
                    $('#product_id_' + product_id + ' a.added_to_cart.wc-forward').remove();
                    $(document.body).trigger('wpt_ajax_loaded');
                    $(document.body).trigger('added_to_cart');
                    $(document.body).trigger('updated_cart_totals');
                    $(document.body).trigger('wc_fragments_refreshed');
                    $(document.body).trigger('wc_fragments_refresh');
                    $(document.body).trigger('wc_fragment_refresh');
                    $(document.body).trigger('update_checkout');
                }
            });
        },

        handleEmptyCart: function() {
            this.footerCartAnimation();
            const cart_message_box = $('.wpt-wrap div.tables_cart_message_box');
            cart_message_box.addClass('wpt-ajax-loading');
            $.ajax({
                type: 'POST',
                url: this.config.ajaxUrl,
                data: { action: 'wpt_fragment_empty_cart' },
                complete: function() {
                    cart_message_box.removeClass('wpt-ajax-loading');
                },
                success: function() {
                    $(document.body).trigger('wpt_ajax_loaded');
                    $(document.body).trigger('wc_fragment_refresh');
                    $(document.body).trigger('removed_from_cart');
                },
                error: function() {
                    $(document.body).trigger('wc_fragment_refresh');
                    $(document.body).trigger('wpt_ajax_loaded');
                    console.log('Unable to empty your cart.');
                }
            });
        },

        toggleFooterCart: function() {
            $('body').toggleClass('wpt-footer-cart-expand');
            if ($('body').hasClass('wpt-footer-cart-expand')) {
                $('.wpt-lister').fadeIn('slow');
            } else {
                $('.wpt-lister').fadeOut('slow');
            }
        },

        toggleFooterCartHover: function() {
            $('body').toggleClass('wpt-footer-cart-expand');
            if ($('body').hasClass('wpt-footer-cart-expand')) {
                $('.wpt-lister').fadeIn('medium');
            } else {
                $('.wpt-lister').fadeOut('medium');
            }
        },

        handleInfiniteScroll: function() {
            const infinitScrollButton = $('button.button.wpt_load_more.wpt-load-pagination-infinite_scroll');
            if (infinitScrollButton.length < 1) return;
            const scrollTop = $(window).scrollTop();
            const myTable = $('.wpt-wrap');
            let myTableHeight = myTable.height();
            myTableHeight = myTableHeight - 500;
            if (scrollTop > myTableHeight && this.state.paginatedVal === 0) {
                infinitScrollButton.trigger('click');
                this.state.paginatedVal++;
                setTimeout(() => {
                    this.state.paginatedVal = 0;
                }, 20000);
            }
        },

        ajaxTableLoad: function(table_id, args, others = {}) {
            const thisTable = $('#table_id_' + table_id);
            const TableTagWrap = thisTable.find('.wpt_table_tag_wrapper');
            const SearchWrap = thisTable.find('.wpt-search-full-wrapper');
            const data_json = thisTable.data('basic_settings');
            if (!thisTable.length) {
                console.log('Error on: ajaxTableLoad. Table not found!');
                this.showNotification('Error on: ajaxTableLoad. Table not found!', 'error');
                return;
            }
            this.showNotification('<i class="wpt-spin6 animate-spin"></i>', 'success', 'top_right', 20000);
            others.reset_search_clicked = this.state.resetSearchClicked;
            const data = {
                action: 'wpt_load_both',
                table_id,
                others,
                args,
                atts: data_json.atts,
                nonce: this.config.nonce,
            };
            TableTagWrap.addClass('wpt-ajax-loading');
            SearchWrap.addClass('wpt-ajax-loading');
            $.ajax({
                type: 'POST',
                url: this.config.ajaxUrl,
                data,
                success: (result) => {
                    this.removeNotification();
                    if (typeof result === 'string') {
                        thisTable.find('#wpt_table.wpt-table-tag tbody').html(result);
                        return;
                    }
                    if (typeof result !== 'object') return;

                    let page_number = others.page_number || 1;
                    thisTable.attr('data-page_number', page_number);
                    const load_type = others.type;
                    if (result && load_type !== 'load_more') {
                        $.each(result, function(key, value) {
                            if (typeof key === 'string') {
                                let selectedElement = $('#table_id_' + table_id + ' ' + key);
                                if (typeof selectedElement === 'object') {
                                    selectedElement.html(value);
                                }
                            }
                        });
                    } else if (result && load_type === 'load_more') {
                        const thisButton = $('#wpt_load_more_wrapper_' + table_id + '>button');
                        const text_btn = thisButton.data('text_btn');
                        let page_number = thisButton.attr('data-page_number');
                        page_number++;
                        thisButton.attr('data-page_number', page_number);
                        thisButton.html(text_btn);
                        $.each(result, function(key, value) {
                            if (typeof key === 'string') {
                                let selectedElement = $('#table_id_' + table_id + ' ' + key);
                                if (typeof selectedElement === 'object' && key === '.wpt-table-tag.wpt-tbl>.wpt-tbody-tag') {
                                    $('#table_id_' + table_id + ' .wpt-table-tag.wpt-tbl>.wpt-tbody-tag').append(value);
                                } else if (typeof selectedElement === 'object') {
                                    selectedElement.html(value);
                                }
                            }
                        });
                    }

                    $(document.body).trigger('wc_fragments_refreshed');
                    $(document.body).trigger('wpt_ajax_loaded');
                    $(document.body).trigger('wpt_ajax_load_data', data);
                    TableTagWrap.removeClass('wpt-ajax-loading');
                    SearchWrap.removeClass('wpt-ajax-loading');
                },
                complete: () => {
                    TableTagWrap.removeClass('wpt-ajax-loading');
                    SearchWrap.removeClass('wpt-ajax-loading');
                    this.state.resetSearchClicked = 'no';
                },
                error: (error) => {
                    TableTagWrap.removeClass('wpt-ajax-loading');
                    SearchWrap.removeClass('wpt-ajax-loading');
                    console.log('Error on: ajaxTableLoad. Error on Ajax load!', error);
                    this.showNotification('Error on: ajaxTableLoad. Error on Ajax load!', 'error');
                }
            });
        },

        getSearchQueriedArgs: function(table_id) {
            let base_link = $('.wpt-my-pagination-' + table_id).data('base_link');
            let texonomies = {};
            
            // Collect from select dropdowns
            $('#search_box_' + table_id + ' .search_select.query').each(function() {
                const key = $(this).data('key');
                const value = $(this).val();
                if (value !== "") texonomies[key] = value;
            });

            // Collect from checkbox filters
            $('#search_box_' + table_id + ' .wpt-checkbox-filter-wrapper').each(function() {
                const key = $(this).data('key');
                const checkedValues = [];
                $(this).find('.wpt-checkbox-input:checked').each(function() {
                    checkedValues.push($(this).val());
                });
                if (checkedValues.length > 0) {
                    texonomies[key] = checkedValues;
                }
            });

            let tax_query = {};
            Object.keys(texonomies).forEach(function(aaa) {
                var key = aaa + '_IN';
                if (texonomies[aaa] !== null && Object.keys(texonomies[aaa]).length > 0) {
                    tax_query[key] = {
                        taxonomy: aaa,
                        field: 'id',
                        terms: texonomies[aaa],
                        operator: 'IN'
                    };
                }
            });

            let custom_field = {}, meta_query = {}, multiple_attr = {};
            $('#search_box_' + table_id + ' .search_select.cf_query').each(function() {
                const attr = $(this).attr('multiple');
                const key = $(this).data('key');
                const value = $(this).val();
                if (value !== "") {
                    custom_field[key] = value;
                    multiple_attr[key] = attr;
                }
            });
            Object.keys(custom_field).forEach(function(key) {
                if (Object.keys(custom_field[key]).length > 0) {
                    var compare = multiple_attr[key];
                    if (!compare) {
                        meta_query[key] = {
                            key: key,
                            value: custom_field[key],
                            compare: 'LIKE'
                        };
                    } else {
                        meta_query[key] = {
                            key: key,
                            value: custom_field[key]
                        };
                    }
                }
            });

            let s = $('#search_box_' + table_id + ' .search_single_direct .query-keyword-input-box').val();
            let orderby = $('#search_box_' + table_id + ' .search_single_order_by select').val();
            let on_sale = $('#search_box_' + table_id + ' .search_single_order select').val();

            return {
                s: s,
                tax_query: tax_query,
                orderby: orderby,
                on_sale: on_sale,
                meta_query: meta_query,
                base_link: base_link,
            };
        },

        fragmentLoad: function() {
            if (this.state.ownFragmentLoad > 0) return;
            setInterval(() => {
                this.state.ownFragmentLoad = 0;
            }, 1000);
            this.state.ownFragmentLoad++;
            $.ajax({
                type: 'POST',
                url: this.config.ajaxUrl,
                data: { action: 'wpt_wc_fragments' },
                success: (ownFragment) => this.wcFragmentHandle(ownFragment)
            });
        },

        wcFragmentHandle: function(ownFragment) {
            if (typeof ownFragment !== 'object') return;
            try {
                this.ownFragmentPerItemsHandle(ownFragment);
                $(document.body).trigger('wpt_fragents_loaded', ownFragment);
            } catch (e) {
                console.log('Something went wrong on ownFragment loads.', ownFragment);
                this.showNotification('Something went wrong on ownFragment loads.', 'error');
            }
        },

        ownFragmentPerItemsHandle: function(ownFragment) {
            const perItems = ownFragment.per_items || {};
            $('.wpt_row').each(function() {
                const thisRow = $(this);
                const product_id = thisRow.data('product_id');
                if (perItems[product_id] !== undefined) {
                    thisRow.addClass('wpt-added-to-cart');
                    const item = perItems[product_id];
                    const quantity = item.quantity;
                    const cart_item_key = item.cart_item_key;
                    let Bubble = thisRow.find('.wpt_ccount');
                    if (Bubble.length == 0) {
                        thisRow.find('a.add_to_cart_button').append('<span class="wpt_ccount wpt_ccount_' + product_id + '">' + quantity + '</span>');
                        thisRow.find('.single_add_to_cart_button').append('<span class="wpt_ccount wpt_ccount_' + product_id + '">' + quantity + '</span>');
                    } else {
                        Bubble.html(quantity);
                    }
                    let crossButton = thisRow.find('.wpt-cart-remove');
                    if (crossButton.length == 0) {
                        thisRow.find('a.add_to_cart_button').after('<span data-cart_item_key="' + cart_item_key + '" data-product_id="' + product_id + '" class="wpt-cart-remove wpt-cart-remove-' + product_id + '"></span>');
                        thisRow.find('.single_add_to_cart_button').after('<span data-cart_item_key="' + cart_item_key + '" data-product_id="' + product_id + '" class="wpt-cart-remove wpt-cart-remove-' + product_id + '"></span>');
                    }
                } else {
                    thisRow.removeClass('wpt-added-to-cart');
                    thisRow.find('.wpt_ccount').remove();
                    thisRow.find('.wpt-cart-remove').remove();
                }
            });
        },

        footerCartAnimation: function() {
            $('a.wpt-view-n .wpt-bag').addClass('wpt-spin4 animate-spin');
            $('.wpt-new-footer-cart').addClass('wpt-fcart-anim');
            $('.wpt-fcart-coll-expand').addClass('animated');
        },

        // =========================
        // Notification System
        // =========================

        showNotification: function (message, type = 'info', position = 'top_right', timeout = 3000) {
            const $notification = $(`<div class="wcmmq-notification wcmmq-notification-${type}">${message}</div>`);

            // style for notification
            $notification.css({
                background: type === 'success' ? 'var(--wpt_cart_highliter)' : (type === 'error' ? 'var(--wpt_danger)' : 'var(--wpt_thead_bg)'),
                color: 'white',
                padding: '10px 18px',
                borderRadius: '4px',
                fontSize: '13px',
                fontWeight: '500',
                boxShadow: '0 2px 5px rgba(0,0,0,0.2)',
                transform: 'translateX(120%)',
                transition: 'transform 0.3s ease',
                cursor: 'pointer'
            });

            // container for stacking
            let $container = $('.wcmmq-notification-container');
            if (!$container.length) {
                $container = $('<div class="wcmmq-notification-container"></div>').css({
                    position: 'fixed',
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'flex-end',
                    gap: '10px',
                    zIndex: 1000000
                });
                // position wise styles
                switch (position) {
                    case 'top_left':
                        $container.css({ top: '52px', left: '20px', alignItems: 'flex-start' });
                        break;
                    case 'bottom_right':
                        $container.css({ bottom: '20px', right: '20px', alignItems: 'flex-end' });
                        break;
                    case 'bottom_left':
                        $container.css({ bottom: '20px', left: '20px', alignItems: 'flex-start' });
                        break;
                    default: // top_right
                        $container.css({ top: '52px', right: '20px', alignItems: 'flex-end' });
                }

                $('body').append($container);
            }

            // add to container
            $container.append($notification);

            // animate in
            setTimeout(() => $notification.css('transform', 'translateX(0)'), 30);

            // auto remove after 3s
            setTimeout(() => {
                $notification.css('transform', 'translateX(120%)');
                setTimeout(() => $notification.remove(), 300);
            }, timeout);
            $notification.on('click', function() {
                $(this).css('transform', 'translateX(100%)');
                setTimeout(() => $(this).remove(), 300);
            });
        },
        //Remove full notification
        removeNotification: function() {
            $('.wcmmq-notification-container').remove();
        },

        // =========================
        // Export Feature System
        // =========================

        /**
         * MIME types mapping for export formats
         */
        exportMimeTypes: {
            html: 'text/html',
            csv: 'text/csv;charset=utf-8',
            excel: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            xml: 'application/xml',
            json: 'application/json',
            ods: 'application/vnd.oasis.opendocument.spreadsheet',
            pdf: 'text/html'
        },

        /**
         * Initialize export button events
         */
        initExportEvents: function() {
            const self = this;
            $(document.body).on('click', '.wpt-export-btn[data-format]', (e) => self.handleExportClick(e));
        },

        /**
         * Handle export button click
         * @param {Event} e Click event
         */
        handleExportClick: function(e) {
            e.preventDefault();
            
            const $btn = $(e.currentTarget);
            const format = $btn.data('format');
            const tableId = $btn.data('table_id');
            const $icon = $btn.find('.wpt-export-icon');
            const $text = $btn.find('.wpt-export-text');
            const $spinner = $btn.find('.wpt-export-btn-spinner');
            
            // Prevent double click
            if ($btn.hasClass('wpt-export-loading')) {
                return;
            }
            
            // Show loading state
            this.setExportButtonLoading($btn, $icon, $text, $spinner, true);
            
            // Make AJAX request
            $.ajax({
                type: 'POST',
                url: this.config.ajaxUrl,
                data: {
                    action: 'wpt_export_table',
                    table_id: tableId,
                    format: format,
                    nonce: this.config.nonce
                },
                success: (response) => this.handleExportSuccess(response, $btn, $icon, $text, $spinner),
                error: () => this.handleExportError($btn, $icon, $text, $spinner)
            });
        },

        /**
         * Set export button loading state
         */
        setExportButtonLoading: function($btn, $icon, $text, $spinner, isLoading) {
            if (isLoading) {
                $btn.addClass('wpt-export-loading');
                $icon.hide();
                $text.hide();
                $spinner.show();
            } else {
                $btn.removeClass('wpt-export-loading');
                $spinner.hide();
                $icon.show();
                $text.show();
            }
        },

        /**
         * Handle successful export response
         */
        handleExportSuccess: function(response, $btn, $icon, $text, $spinner) {
            this.setExportButtonLoading($btn, $icon, $text, $spinner, false);
            
            if (!response.success) {
                const errorMsg = response.data?.message || 
                    (WPT_DATA.export?.export_error || 'Export failed');
                this.showNotification(errorMsg, 'error');
                return;
            }

            const { type: fileType, content, filename, encoding } = response.data;
            const mimeType = this.exportMimeTypes[fileType] || 'text/html';
            const isBase64 = encoding === 'base64';

            // Handle PDF - open in new tab for printing
            if (fileType === 'pdf') {
                this.handlePdfExport(content);
                return;
            }

            // Download file
            if (isBase64) {
                this.downloadBase64File(content, filename, mimeType);
            } else {
                this.downloadFile(content, filename, mimeType);
            }

            // Show success notification
            if (WPT_DATA.export?.export_success) {
                this.showNotification(WPT_DATA.export.export_success, 'success');
            }
        },

        /**
         * Handle export error
         */
        handleExportError: function($btn, $icon, $text, $spinner) {
            this.setExportButtonLoading($btn, $icon, $text, $spinner, false);
            const errorMsg = WPT_DATA.export?.export_error || 'Export failed. Please try again.';
            this.showNotification(errorMsg, 'error');
        },

        /**
         * Handle PDF export - opens in new tab
         */
        handlePdfExport: function(content) {
            const printWindow = window.open('', '_blank');
            if (printWindow) {
                printWindow.document.write(content);
                printWindow.document.close();
            }
            if (WPT_DATA.export?.export_success) {
                this.showNotification(WPT_DATA.export.export_success, 'success');
            }
        },

        /**
         * Download file with content
         * @param {string} content File content
         * @param {string} filename File name
         * @param {string} mimeType MIME type
         */
        downloadFile: function(content, filename, mimeType) {
            const blob = new Blob([content], { type: mimeType });
            
            if (typeof URL !== 'undefined' && URL.createObjectURL) {
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            } else {
                // Fallback for older browsers
                const reader = new FileReader();
                reader.onloadend = function() {
                    const win = window.open(reader.result, '_blank');
                    if (win) win.focus();
                };
                reader.readAsDataURL(blob);
            }
        },

        /**
         * Download base64 encoded file (for binary files like XLSX, ODS)
         * @param {string} base64Content Base64 encoded content
         * @param {string} filename File name
         * @param {string} mimeType MIME type
         */
        downloadBase64File: function(base64Content, filename, mimeType) {
            const binaryString = atob(base64Content);
            const bytes = new Uint8Array(binaryString.length);
            
            for (let i = 0; i < binaryString.length; i++) {
                bytes[i] = binaryString.charCodeAt(i);
            }
            
            const blob = new Blob([bytes], { type: mimeType });
            
            if (typeof URL !== 'undefined' && URL.createObjectURL) {
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            } else {
                // Fallback for older browsers
                const dataUrl = `data:${mimeType};base64,${base64Content}`;
                const win = window.open(dataUrl, '_blank');
                if (win) win.focus();
            }
        }
    };

    $(document).ready(function() {
        const config_json = $('#wpt_table').data('config_json');
        if (typeof config_json === 'undefined') return false;
        WPTControl.init();
    });

    window.WPTControl = WPTControl;

})(jQuery);