(function($) {
    $(document).ready(function() {
        const $scanButton = $('#fluentc-scan-site');
        const $translateButton = $('#fluentc-translate-site');
        const $cancelButton = $('#fluentc-cancel-translation');
        const $lastScanTime = $('#fluentc-last-scan-time');
        const $translationTable = $('#fluentc-translation-table');
        const $translationStatus = $('#fluentc-translation-status');

        function updateLastScanTime() {
            $.ajax({
                url: fluentcTranslation.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'fluentc_get_last_scan_time',
                    nonce: fluentcTranslation.nonce
                },
                success: function(response) {
                    if (response.success) {
                        $lastScanTime.text(response.data.message);
                        updateButtonStates(response.data.canTranslate);
                    }
                }
            });
        }

        function updateButtonStates(canTranslate) {
            $scanButton.prop('disabled', !canTranslate);
            $translateButton.prop('disabled', !canTranslate);
            $cancelButton.toggle(!canTranslate);
        }


        function loadTranslationTable() {
            $.ajax({
                url: fluentcTranslation.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'fluentc_get_translation_table',
                    nonce: fluentcTranslation.nonce
                },
                success: function(response) {
                    if (response.success && response.data.urls) {
                        renderTranslationTable(response.data.urls);
                    }
                }
            });
        }

        $translateButton.on('click', function() {
            $.ajax({
                url: fluentcTranslation.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'fluentc_translate_site',
                    nonce: fluentcTranslation.nonce
                },
                success: function(response) {
                    if (response.success) {
                        $translationStatus.text('Translation Starting - Fetching Pages');
                        renderTranslationTable(response.data.urls);
                        checkTranslationStatus();
                    }
                }
            });
        });

        function translationTableTemplate(urls) {
            let activeTableHtml = '<h3>Active URLs</h3><table class="wp-list-table widefat fixed striped">';
            activeTableHtml += '<thead><tr><th>Original URL</th><th>Translations</th></tr></thead><tbody>';
        
            let inactiveTableHtml = '<h3>Inactive URLs</h3><table class="wp-list-table widefat fixed striped">';
            inactiveTableHtml += '<thead><tr><th>Original URL</th><th>Translations</th></tr></thead><tbody>';
        
            for (let originalUrl in urls) {
                let data = urls[originalUrl];
                let rowHtml = '<tr>';
                rowHtml += '<td>' + originalUrl + '<br/> <a href="#" class="fluentc-toggle-status" data-url="' + originalUrl + '">' + (data.status === 'active' ? 'Deactivate' : 'Activate') + '</a></td>';
                rowHtml += '<td>';
        
                if (data.translations && data.translations.length > 0) {
                    rowHtml += '<table class="nested-translations">';
                    rowHtml += '<thead><tr><th>Translated URL</th><th>Language</th><th>Status</th></tr></thead><tbody>';
        
                    data.translations.forEach(function(translation) {
                        rowHtml += '<tr>';
                        rowHtml += '<td><a href="' + translation.url + '" target="_blank">' + translation.url + ' <span class="dashicons dashicons-external"></span></a></td>';
                        rowHtml += '<td>' + translation.language + '</td>';
                        rowHtml += '<td><span class="translation-status ' + translation.status + '">' + (translation.status === 'translated' ? 'Translated' : 'Not Translated') + '</span></td>';
                        rowHtml += '</tr>';
                    });
        
                    rowHtml += '</tbody></table>';
                } else {
                    rowHtml += 'No translations available';
                }
        
                rowHtml += '</td>';
                rowHtml += '</tr>';
        
                if (data.status === 'active') {
                    activeTableHtml += rowHtml;
                } else {
                    inactiveTableHtml += rowHtml;
                }
            }
        
            activeTableHtml += '</tbody></table>';
            inactiveTableHtml += '</tbody></table>';
        
            return activeTableHtml + inactiveTableHtml;
        }
        
        function renderTranslationTable(urls) {
            $translationTable.html(translationTableTemplate(urls));
        
            $('.fluentc-toggle-status').on('click', function(e) {
                e.preventDefault();
                const url = $(this).data('url');
                $.ajax({
                    url: fluentcTranslation.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'fluentc_toggle_url_status',
                        nonce: fluentcTranslation.nonce,
                        url: url
                    },
                    success: function(response) {
                        if (response.success) {
                            loadTranslationTable();
                        }
                    }
                });
            });
        }

        function initializeTableActions() {
            $('.fluentc-toggle-status').on('click', function(e) {
                e.preventDefault();
                const url = $(this).data('url');
                $.ajax({
                    url: fluentcTranslation.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'fluentc_toggle_url_status',
                        nonce: fluentcTranslation.nonce,
                        url: url
                    },
                    success: function(response) {
                        if (response.success) {
                            loadTranslationTable();
                        }
                    }
                });
            });
        }

       /* function checkTranslationStatus() {
            $.ajax({
                url: fluentcTranslation.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'fluentc_get_translation_status',
                    nonce: fluentcTranslation.nonce
                },
                success: function(response) {
                    if (response.success) {
                        $translationStatus.text(response.data.message + ' (' + response.data.completed + '/' + response.data.total + ')');
                        updateButtonStates(response.data.status !== 'in_progress');
        
                        if (response.data.status === 'in_progress') {
                            setTimeout(checkTranslationStatus, 2000);
                        } else if (response.data.status === 'cancelled') {
                            alert('Translation has been cancelled.');
                            loadTranslationTable();
                        } else {
                            loadTranslationTable();
                        }
                    }
                }
            });
        } */

        $cancelButton.on('click', function() {
            $.ajax({
                url: fluentcTranslation.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'fluentc_cancel_translation',
                    nonce: fluentcTranslation.nonce
                },
                success: function(response) {
                    if (response.success) {
                        alert(response.data.message);
                        loadTranslationTable();
                      
                    }
                }
            });
        });

        $scanButton.on('click', function() {
            $.ajax({
                url: fluentcTranslation.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'fluentc_scan_site',
                    nonce: fluentcTranslation.nonce
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    }
                }
            });
        });

        let currentPage = 1;

        function loadSavedUrls(page = 1) {
            $.ajax({
                url: fluentcTranslation.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'fluentc_get_saved_urls',
                    nonce: fluentcTranslation.nonce,
                    page: page
                },
                success: function(response) {
                    if (response.success && response.data.urls) {
                        renderTranslationTable(response.data.urls);
                        renderPagination(response.data.total_pages, response.data.current_page);
                        currentPage = response.data.current_page;
                    }
                }
            });
        }

        function renderPagination(totalPages, currentPage) {
            let paginationHtml = '<div class="pagination">';
            for (let i = 1; i <= totalPages; i++) {
                paginationHtml += `<a href="#" class="page-number ${i === currentPage ? 'current' : ''}" data-page="${i}">${i}</a>`;
            }
            paginationHtml += '</div>';
            $('#fluentc-translation-pagination').html(paginationHtml);

            $('.page-number').on('click', function(e) {
                e.preventDefault();
                loadSavedUrls($(this).data('page'));
            });
        }

        // Initialize
        //updateLastScanTime();
       // loadTranslationTable();
        //checkTranslationStatus();
       
        
    });
})(jQuery);