;(function ($) {
    'use strict';

    var UnlockDynamicTableHandler = function ($scope) {
        const $wrapper = $scope.find('.unlockafe-dynamic-table-wrapper');
        if (!$wrapper.length) {
            return;
        }

        const widgetId = $scope.data('id');
        const $table = $wrapper.find('#unlockafe-dynamic-table-' + widgetId);
        const settings = $wrapper.data('settings') || {};

        if (!$table.length) {
            return;
        }

        if (typeof $.fn.dataTable !== 'function') {
            console.error('Unlock Addons: DataTables.js is not loaded.');
            return;
        }
        if (settings.theme === 'vertical-style') {
            return;
        }

        initializeTable();

        function initializeTable() {
            if ($.fn.DataTable.isDataTable($table)) {
                $table.DataTable().destroy();
            }
            let domStructure = "<'ua-table-container'tr>";

            const dataTableOptions = {
                dom: domStructure,
                paging: settings.showPagination || false,
                searching: settings.showSearch || false,
                ordering: settings.showSorting || false,
                info: settings.showInfo || false,
                lengthChange: settings.showLengthMenu || false,
                pageLength: settings.entriesPerPage || 10,
                responsive: settings.responsiveMode === 'responsive',
                language: {
                    search: "_INPUT_",
                    searchPlaceholder: "Search records...",
                    lengthMenu: "_MENU_",
                    info: "Showing _START_ to _END_ of _TOTAL_ entries",
                    infoEmpty: "Showing 0 to 0 of 0 entries",
                    infoFiltered: "(filtered from _MAX_ total entries)",
                    paginate: {
                        next: "Next &raquo;",
                        previous: "&laquo; Previous",
                    },
                    emptyTable: "No data available in table",
                    zeroRecords: "No matching records found"
                },
                columnDefs: [],
                drawCallback: function() {
                    if (typeof $.fn.magnificPopup !== 'undefined' && settings.enable_lightbox === 'yes') {
                        $table.find('[data-lightbox]').magnificPopup({
                            type: 'image',
                            gallery: { enabled: true }
                        });
                    }
                }
            };
            if (settings.hideColumnsMobile && window.innerWidth <= 768) {
                const hiddenColumns = settings.hideColumnsMobile.split(',').map(col => parseInt(col.trim()) - 1);
                hiddenColumns.forEach(colIndex => {
                    if (colIndex >= 0) {
                        dataTableOptions.columnDefs.push({
                            targets: colIndex,
                            visible: false
                        });
                    }
                });
            }

            let dataTable;
            try {
                dataTable = $table.DataTable(dataTableOptions);
            } catch (error) {
                console.error('Unlock Addons: Error initializing DataTable:', error);
                return;
            }
            setupCustomControls(dataTable);
            
            if (settings.showExport && settings.exportFormats) {
                setupExportButtons($wrapper, dataTable, settings.exportFormats);
            }

            if (settings.responsiveMode === 'stack') {
                setupResponsiveStacking($table);
            }
        }

        function setupCustomControls(dataTable) {
            const $controls = $wrapper.find('.table-controls');
            $controls.find('input[type="search"]').on('keyup', function () {
                dataTable.search(this.value).draw();
            });
            $controls.find('.dataTables_length select').on('change', function () {
                dataTable.page.len(this.value).draw();
            });
            dataTable.on('draw', function() {
                const info = dataTable.page.info();
                const infoText = settings.showInfo ? `Showing ${info.start + 1} to ${info.end} of ${info.recordsTotal} entries` : '';
                $wrapper.find('.dataTables_info').html(infoText);
                const $paginationContainer = $wrapper.find('.dataTables_paginate');
                $paginationContainer.empty();
                
                if(settings.showPagination && info.pages > 1) {
                    $paginationContainer.append(
                        $('<a>', {
                            'class': 'paginate_button previous' + (info.page === 0 ? ' disabled' : ''),
                            'html': '&laquo;',
                            'title': 'Previous',
                            'aria-label': 'Previous page',
                            'click': () => { if (info.page > 0) dataTable.page('previous').draw('page'); }
                        })
                    );
                    const maxVisiblePages = 5;
                    let startPage, endPage;

                    if (info.pages <= maxVisiblePages) {
                        startPage = 0;
                        endPage = info.pages - 1;
                    } else {
                        let maxPagesBeforeCurrentPage = Math.floor(maxVisiblePages / 2);
                        let maxPagesAfterCurrentPage = Math.ceil(maxVisiblePages / 2) - 1;

                        if (info.page <= maxPagesBeforeCurrentPage) {
                            startPage = 0;
                            endPage = maxVisiblePages - 1;
                        } else if (info.page + maxPagesAfterCurrentPage >= info.pages) {
                            startPage = info.pages - maxVisiblePages;
                            endPage = info.pages - 1;
                        } else {
                            startPage = info.page - maxPagesBeforeCurrentPage;
                            endPage = info.page + maxPagesAfterCurrentPage - (maxVisiblePages % 2 === 0 ? 1 : 0);
                        }
                    }
                    if (startPage > 0) {
                        $paginationContainer.append(
                            $('<a>', {
                                'class': 'paginate_button' + (0 === info.page ? ' current' : ''),
                                'text': 1,
                                'click': () => dataTable.page(0).draw('page')
                            })
                        );
                        if (startPage > 1) {
                            $paginationContainer.append('<span class="ellipsis">...</span>');
                        }
                    }
                    for (let i = startPage; i <= endPage; i++) {
                        $paginationContainer.append(
                            $('<a>', {
                                'class': 'paginate_button' + (i === info.page ? ' current' : ''),
                                'text': i + 1,
                                'aria-label': 'Page ' + (i + 1),
                                'click': () => dataTable.page(i).draw('page')
                            })
                        );
                    }
                    if (endPage < info.pages - 1) {
                        if (endPage < info.pages - 2) {
                            $paginationContainer.append('<span class="ellipsis">...</span>');
                        }
                        $paginationContainer.append(
                            $('<a>', {
                                'class': 'paginate_button' + (info.pages - 1 === info.page ? ' current' : ''),
                                'text': info.pages,
                                'click': () => dataTable.page(info.pages - 1).draw('page')
                            })
                        );
                    }
                    $paginationContainer.append(
                        $('<a>', {
                            'class': 'paginate_button next' + (info.page === info.pages - 1 ? ' disabled' : ''),
                            'html': '&raquo;',
                            'title': 'Next',
                            'aria-label': 'Next page',
                            'click': () => { if (info.page < info.pages - 1) dataTable.page('next').draw('page'); }
                        })
                    );
                }
            });

            dataTable.draw();
        }
        function setupExportButtons($wrapper, dataTable, exportFormats) {
            $wrapper.find('.ua-export-btn').on('click', async function(e) {
                e.preventDefault();
                const format = $(this).data('format');
                const $button = $(this);
                const table = $wrapper.find('table').clone();
                table.find('.actions, .ua-export-btn, .dataTables_length, .dataTables_filter, .dataTables_info, .dataTables_paginate').remove();
                
                if (format === 'pdf') {
                    if (typeof window.jspdf === 'undefined') {
                        try {
                            // Load jsPDF
                            await new Promise((resolve, reject) => {
                                if (typeof jspdf !== 'undefined') {
                                    window.jspdf = jspdf;
                                    return resolve();
                                }
                                
                                const script = document.createElement('script');
                                script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js';
                                script.onload = () => {
                                    window.jspdf = jspdf;
                                    resolve();
                                };
                                script.onerror = reject;
                                document.head.appendChild(script);
                            });
                            await new Promise((resolve, reject) => {
                                const script = document.createElement('script');
                                script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js';
                                script.onload = resolve;
                                script.onerror = reject;
                                document.head.appendChild(script);
                            });
                        } catch (error) {
                            console.error('Failed to load PDF libraries:', error);
                            alert('Failed to load PDF export functionality. Please try again.');
                            return;
                        }
                    }
                    
                    try {
                        const { jsPDF } = window.jspdf;
                        const doc = new jsPDF({
                            orientation: 'landscape',
                            unit: 'mm',
                            format: 'a4'
                        });
                        const title = table.attr('data-title') || 'Table Export';
                        const currentDate = new Date().toLocaleDateString();
                        doc.setFont('helvetica', 'bold');
                        doc.setFontSize(16);
                        doc.text(title, 14, 20);
                        
                        doc.setFont('helvetica', 'normal');
                        doc.setFontSize(10);
                        doc.setTextColor(100);
                        doc.text(`Generated on: ${currentDate}`, 14, 26);
                        const headers = [];
                        const data = [];
                        table.find('thead th').each(function() {
                            headers.push({
                                content: $(this).text().trim(),
                                styles: {
                                    fillColor: [41, 128, 185],
                                    textColor: 255,
                                    fontStyle: 'bold',
                                    cellPadding: 3,
                                    lineWidth: 0.1
                                }
                            });
                        });
                        table.find('tbody tr').each(function() {
                            const row = [];
                            $(this).find('td').each(function() {
                                const text = $(this).clone()
                                    .children()
                                    .remove()
                                    .end()
                                    .text()
                                    .replace(/\s+/g, ' ')
                                    .trim();
                                row.push({
                                    content: text,
                                    styles: {
                                        cellPadding: 3,
                                        lineWidth: 0.1
                                    }
                                });
                            });
                            data.push(row);
                        });
                        const columnWidths = [];
                        const pageWidth = doc.internal.pageSize.getWidth() - 30;
                        const colCount = headers.length;
                        const defaultColWidth = pageWidth / Math.min(colCount, 10);
                        for (let i = 0; i < colCount; i++) {
                            columnWidths.push(defaultColWidth);
                        }
                        doc.autoTable({
                            head: [headers.map(h => h.content)],
                            body: data.map(row => row.map(cell => cell.content)),
                            startY: 30,
                            margin: { 
                                top: 30,
                                left: 15,
                                right: 15
                            },
                            styles: { 
                                fontSize: 9,
                                cellPadding: 2,
                                valign: 'middle',
                                overflow: 'linebreak',
                                lineWidth: 0.1,
                                lineColor: [200, 200, 200]
                            },
                            headStyles: {
                                fillColor: [41, 128, 185],
                                textColor: 255,
                                fontStyle: 'bold',
                                lineWidth: 0.1
                            },
                            bodyStyles: {
                                lineWidth: 0.1,
                                lineColor: [220, 220, 220]
                            },
                            alternateRowStyles: {
                                fillColor: [250, 250, 250]
                            },
                            columnStyles: {
                                0: { cellWidth: 'auto' }
                            },
                            didParseCell: function(data) {
                                if (data.section === 'head') {
                                    data.cell.styles = {
                                        ...data.cell.styles,
                                        ...headers[data.column.index].styles
                                    };
                                } else if (data.section === 'body') {
                                    data.cell.styles = {
                                        ...data.cell.styles,
                                        ...data.row.cells[data.column.index].styles
                                    };
                                }
                            },
                            willDrawPage: function(data) {
                                // Footer
                                const pageSize = doc.internal.pageSize;
                                const pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
                                doc.setFontSize(8);
                                doc.setTextColor(100);
                                doc.text(
                                    `Page ${data.pageCount}`,
                                    data.settings.margin.left,
                                    pageHeight - 10
                                );
                                doc.setDrawColor(200, 200, 200);
                                doc.setLineWidth(0.5);
                                doc.line(
                                    data.settings.margin.left,
                                    pageHeight - 15,
                                    pageSize.width - data.settings.margin.right,
                                    pageHeight - 15
                                );
                            }
                        });
                    
                        // Save the PDF
                        doc.save('table-export-' + new Date().toISOString().slice(0, 10) + '.pdf');
                    } catch (error) {
                        console.error('Error generating PDF:', error);
                        alert('Error generating PDF. Please try again.');
                    }
                    return;
                }
                const tableData = dataTable.rows({ search: 'applied' }).nodes().toArray().map(row => 
                    $(row).find('td').toArray().map(cell => $(cell).data('original-content') || $(cell).text())
                );
                const headers = dataTable.columns().header().toArray().map(th => $(th).text());
                
                $button.addClass('loading').prop('disabled', true);
                
                const finishExport = () => {
                    setTimeout(() => {
                        $button.removeClass('loading').prop('disabled', false);
                    }, 500);
                };
                
                switch (format) {
                    case 'csv':
                        exportToCSV(tableData, headers);
                        finishExport();
                        break;
                    case 'excel':
                        exportToExcel(tableData, headers);
                        finishExport();
                        break;
                    case 'pdf':
                        exportToPDF(tableData, headers).finally(finishExport);
                        break;
                    case 'json':
                        exportToJSON(tableData, headers);
                        finishExport();
                        break;
                }
            });
        }

        function exportToCSV(data, headers) {
            let csv = headers.join(',') + '\n';
            data.forEach(row => {
                const cleanRow = row.map(cell => `"${(cell || '').toString().replace(/"/g, '""')}"`);
                csv += cleanRow.join(',') + '\n';
            });
            downloadFile(csv, 'table-export.csv', 'text/csv;charset=utf-8;');
        }

        function exportToJSON(data, headers) {
            const jsonData = data.map(row => {
                const obj = {};
                headers.forEach((header, index) => {
                    obj[header] = row[index];
                });
                return obj;
            });
            downloadFile(JSON.stringify(jsonData, null, 2), 'table-export.json', 'application/json');
        }

        function exportToExcel(data, headers) {
            let excel = '<table><thead><tr>' + headers.map(h => `<th>${h}</th>`).join('') + '</tr></thead><tbody>';
            data.forEach(row => {
                excel += '<tr>' + row.map(cell => `<td>${cell || ''}</td>`).join('') + '</tr>';
            });
            excel += '</tbody></table>';
            downloadFile(excel, 'table-export.xls', 'application/vnd.ms-excel');
        }

        function exportToPDF(data, headers) {
            return new Promise((resolve, reject) => {
                 alert("PDF export functionality would be here.");
                 resolve();
            });
        }

        function downloadFile(content, filename, contentType) {
            const blob = new Blob([content], { type: contentType });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }

        function setupResponsiveStacking($table) {
            function checkResponsive() {
                if (window.innerWidth <= 768) {
                    $table.addClass('ua-stacked');
                } else {
                    $table.removeClass('ua-stacked');
                }
            }
            checkResponsive();
            $(window).on('resize', checkResponsive);
        }
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-dynamic-table.default', UnlockDynamicTableHandler);
    });

})(jQuery);
