;(function($) {
    "use strict";
    /**
     * Google Sheet Widget JavaScript
     * Handles client-side functionality for the Google Sheet widget.
     */
    class UnlockGoogleSheet {
        constructor($scope) {
            console.log('UnlockGoogleSheet: Initializing for widget in scope:', $scope);
            this.$container = $scope.find('.unlockafe-google-sheet-container');
            if (!this.$container.length) {
                console.error('UnlockGoogleSheet: Could not find .unlockafe-google-sheet-container');
                return;
            }

            this.$table = this.$container.find('.unlockafe-google-sheet-table');
            this.$tbody = this.$table.find('tbody');
            if (!this.$tbody.length) return;

            // State
            this.masterData = [];
            this.currentPage = 1;
            this.searchTerm = '';
            this.sortColumn = -1;
            this.sortDirection = 'none'; // 'asc', 'desc', 'none'
            this.entriesPerPage = parseInt(this.$container.data('entries-per-page')) || 10;

            // Controls
            this.$searchInput = this.$container.find('.unlockafe-search-input');
            this.$entriesPerPageSelect = this.$container.find('.unlockafe-entries-select');
            this.$paginationContainer = this.$container.find('.unlockafe-table-pagination');
            this.$infoContainer = this.$container.find('.unlockafe-table-info');

            this.init();
        }

        init() {
            this.parseTableData();
            this.addEventListeners();
            this.render();
        }

        destroy() {
            // Ensure properties exist before trying to remove event listeners
            if (this.$table && this.$table.length) {
                this.$table.off('click', 'thead th');
            }
            if (this.$searchInput && this.$searchInput.length) {
                this.$searchInput.off('keyup');
            }
            if (this.$entriesPerPageSelect && this.$entriesPerPageSelect.length) {
                this.$entriesPerPageSelect.off('change');
            }
            if (this.$paginationContainer && this.$paginationContainer.length) {
                this.$paginationContainer.off('click', 'a.paginate_button');
            }
        }

        parseTableData() {
            this.$tbody.find('tr').each((i, row) => {
                const rowData = {
                    cells: [],
                    searchText: $(row).text().toLowerCase(),
                    html: row.outerHTML
                };
                $(row).find('td').each((j, cell) => {
                    const $cell = $(cell);
                    const text = $cell.text().trim();
                    const html = $cell.html(); // Get inner HTML to preserve links
                    const num = parseFloat(text.replace(/[^0-9.-]+/g, ''));
                    rowData.cells.push({ 
                        text: text,
                        html: html, // Store HTML content
                        num: isNaN(num) ? null : num
                    });
                });
                this.masterData.push(rowData);
            });
            console.log(`UnlockGoogleSheet: Parsed ${this.masterData.length} rows of data.`);
        }

        addEventListeners() {
            if (this.$container.data('sorting') === true) {
                this.$table.on('click', 'thead th', this.handleSort.bind(this));
            }
            if (this.$searchInput.length) {
                this.$searchInput.on('keyup', this.handleSearch.bind(this));
            }
            if (this.$entriesPerPageSelect.length) {
                this.$entriesPerPageSelect.on('change', this.handleEntriesPerPage.bind(this));
            }
            if (this.$paginationContainer.length) {
                this.$paginationContainer.on('click', 'a.paginate_button', this.handlePagination.bind(this));
            }
        }

        handleSort(e) {
            const index = $(e.currentTarget).index();
            if (this.sortColumn === index) {
                this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
            } else {
                this.sortColumn = index;
                this.sortDirection = 'asc';
            }
            this.currentPage = 1;
            this.render();
        }

        handleSearch(e) {
            this.searchTerm = e.target.value.toLowerCase();
            this.currentPage = 1;
            this.render();
        }

        handleEntriesPerPage(e) {
            this.entriesPerPage = parseInt(e.target.value, 10);
            this.currentPage = 1;
            this.render();
        }

        handlePagination(e) {
            const page = $(e.currentTarget).data('page');
            if (page) {
                this.currentPage = parseInt(page, 10);
                this.render();
            }
        }

        getProcessedData() {
            let processedData = [...this.masterData];

            // 1. Filter
            if (this.searchTerm) {
                processedData = processedData.filter(row => row.searchText.includes(this.searchTerm));
            }

            // 2. Sort
            if (this.sortColumn !== -1 && this.sortDirection !== 'none') {
                processedData.sort((a, b) => {
                    const aCell = a.cells[this.sortColumn];
                    const bCell = b.cells[this.sortColumn];

                    let compareResult;
                    if (aCell.num !== null && bCell.num !== null) {
                        compareResult = aCell.num - bCell.num;
                    } else {
                        compareResult = aCell.text.localeCompare(bCell.text);
                    }
                    return this.sortDirection === 'asc' ? compareResult : -compareResult;
                });
            }

            return processedData;
        }

        render() {
            const processedData = this.getProcessedData();
            const filteredCount = processedData.length;

            const start = (this.currentPage - 1) * this.entriesPerPage;
            const end = start + this.entriesPerPage;
            const paginatedData = processedData.slice(start, end);

            let tableBodyHtml = '';
            paginatedData.forEach(row => {
                tableBodyHtml += '<tr>';
                row.cells.forEach(cell => {
                    tableBodyHtml += `<td>${cell.html}</td>`; // Use stored HTML for cells
                });
                tableBodyHtml += '</tr>';
            });
            this.$tbody.html(tableBodyHtml);

            this.updateInfo(filteredCount);
            this.updatePagination(filteredCount);
            this.updateSortUI();
        }

        updateInfo(filteredCount) {
            if (!this.$infoContainer.length) return;
            const start = filteredCount > 0 ? (this.currentPage - 1) * this.entriesPerPage + 1 : 0;
            const end = Math.min(start + this.entriesPerPage - 1, filteredCount);
            let infoText = `Showing ${start} to ${end} of ${filteredCount} entries`;
            if (this.masterData.length > filteredCount) {
                infoText += ` (filtered from ${this.masterData.length} total entries)`;
            }
            this.$infoContainer.text(infoText);
        }

        updatePagination(filteredCount) {
            if (!this.$paginationContainer.length) return;

            const totalPages = Math.ceil(filteredCount / this.entriesPerPage);

            if (totalPages > 1) {
                let paginationHtml = '';
                for (let i = 1; i <= totalPages; i++) {
                    const activeClass = i === this.currentPage ? 'current' : '';
                    paginationHtml += `<a href="#" class="paginate_button ${activeClass}" data-page="${i}">${i}</a>`;
                }
                this.$paginationContainer.html(paginationHtml);
            } else {
                this.$paginationContainer.empty();
            }
        }

        updateSortUI() {
            this.$table.find('thead th').removeClass('asc desc');
            if (this.sortColumn !== -1) {
                this.$table.find('thead th').eq(this.sortColumn).addClass(this.sortDirection);
            }
        }
    }

    const initializeUnlockGoogleSheet = function($scope) {
        const existingInstance = $scope.data('unlock-google-sheet-instance');
        if (existingInstance) {
            existingInstance.destroy();
        }
        $scope.data('unlock-google-sheet-instance', new UnlockGoogleSheet($scope));
    };

    // Use Elementor's recommended hook for frontend initialization.
    // This single hook handles both initial page load and editor mode.
    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-google-sheet.default', initializeUnlockGoogleSheet);
    });
})(jQuery);
