/**
 * Track 404s Admin JavaScript
 */

(function($) {
    'use strict';

    const Track404s = {
        currentPage: 0,
        pageSize: 50,
        orderBy: 'last_seen',
        order: 'DESC',
        search: '',
        filter: 'pages_only',
        total: 0,

        init: function() {
            this.bindEvents();
            this.loadStats();
            this.loadLogs();
        },

        bindEvents: function() {
            const self = this;

            // Search
            let searchTimeout;
            $('#track-404s-search').on('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(function() {
                    self.search = $('#track-404s-search').val();
                    self.currentPage = 0;
                    self.loadLogs();
                }, 500);
            });

            // Filter toggle
            $(document).on('click', '.track-404s-filter-btn', function() {
                var $btn = $(this);
                if ($btn.hasClass('active')) return;

                $('.track-404s-filter-btn').removeClass('active');
                $btn.addClass('active');

                self.filter = $btn.data('filter');
                self.currentPage = 0;
                self.loadLogs();
                self.loadStats();
            });

            // Sorting
            $(document).on('click', '#track-404s-table th.sortable', function() {
                const column = $(this).data('column');

                if (self.orderBy === column) {
                    // Toggle order
                    self.order = self.order === 'DESC' ? 'ASC' : 'DESC';
                } else {
                    // New column
                    self.orderBy = column;
                    self.order = 'DESC';
                }

                self.currentPage = 0;
                self.loadLogs();
            });

            // Pagination
            $('#track-404s-prev').on('click', function() {
                if (self.currentPage > 0) {
                    self.currentPage--;
                    self.loadLogs();
                }
            });

            $('#track-404s-next').on('click', function() {
                if ((self.currentPage + 1) * self.pageSize < self.total) {
                    self.currentPage++;
                    self.loadLogs();
                }
            });

            // Export
            $('#track-404s-export').on('click', function() {
                self.exportCSV();
            });

            // Delete all
            $('#track-404s-delete-all').on('click', function() {
                if (confirm('Are you sure you want to delete ALL 404 logs? This cannot be undone.')) {
                    self.deleteAll();
                }
            });

            // Delete single
            $(document).on('click', '.action-delete', function() {
                const id = $(this).data('id');
                if (confirm('Delete this 404 entry?')) {
                    self.deleteSingle(id);
                }
            });

            // Copy URL
            $(document).on('click', '.url-copy-btn', function(e) {
                e.preventDefault();
                const btn = $(this);
                const url = btn.data('url');

                // Copy to clipboard
                navigator.clipboard.writeText(url).then(function() {
                    // Show feedback
                    const originalHTML = btn.html();
                    btn.html('<span class="dashicons dashicons-yes"></span>')
                        .addClass('copied');

                    // Reset after 2 seconds
                    setTimeout(function() {
                        btn.html(originalHTML).removeClass('copied');
                    }, 2000);
                }).catch(function(err) {
                    console.error('Failed to copy:', err);
                });
            });

            // Open URL
            $(document).on('click', '.url-open-btn', function(e) {
                e.preventDefault();
                const btn = $(this);
                const url = btn.data('url');
                const fullUrl = track404sAdmin.siteUrl + url;

                window.open(fullUrl, '_blank', 'noopener,noreferrer');
            });
        },

        loadStats: function() {
            const self = this;

            $.ajax({
                url: track404sAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'track_404s_get_stats',
                    nonce: track404sAdmin.nonce,
                    filter: self.filter
                },
                success: function(response) {
                    if (response.success) {
                        const data = response.data;

                        // Update stat cards
                        $('#stat-total-hits').text(data.total_hits.toLocaleString());
                        $('#stat-unique-urls').text(data.unique_urls.toLocaleString());
                        $('#stat-new-today').text(data.new_today.toLocaleString());

                        // Top 404 hit count
                        const topHitCount = data.top_404s && data.top_404s.length > 0 ? data.top_404s[0].hit_count : 0;
                        $('#stat-top-hit-count').text(topHitCount.toLocaleString());

                        // Render top 404s box
                        self.renderTop404s(data.top_404s);

                        // Render recent 404s box
                        self.renderRecent404s(data.recent_404s);
                    }
                }
            });
        },

        renderTop404s: function(top404s) {
            const container = $('#top-404s-container');
            container.empty();

            if (!top404s || top404s.length === 0) {
                container.html('<div class="sb-module-empty"><div class="sb-module-empty-icon"></div><p class="sb-module-empty-desc">No 404 errors tracked yet</p></div>');
                return;
            }

            const table = $('<table class="sb-module-table">');
            table.append('<thead><tr><th>URL</th><th style="width: 80px;">Hits</th><th style="width: 120px;">Last Seen</th></tr></thead>');
            const tbody = $('<tbody>');

            top404s.forEach(function(item) {
                const row = $('<tr>');

                // URL with copy and open buttons
                const urlCell = $('<td class="url-cell">');
                const urlWrapper = $('<div class="url-cell-wrapper">');
                const urlText = $('<span class="url-text">').text(item.url);
                const copyBtn = $('<button type="button" class="url-copy-btn" title="Copy URL">')
                    .html('<span class="dashicons dashicons-admin-page"></span>')
                    .attr('data-url', item.url);
                const openBtn = $('<button type="button" class="url-open-btn" title="Open URL">')
                    .html('<span class="dashicons dashicons-external"></span>')
                    .attr('data-url', item.url);
                urlWrapper.append(urlText, openBtn, copyBtn);
                urlCell.append(urlWrapper);

                row.append(urlCell);
                row.append($('<td>').text(item.hit_count));
                row.append($('<td>').text(Track404s.formatDate(item.last_seen)));
                tbody.append(row);
            });

            table.append(tbody);
            container.append(table);
        },

        renderRecent404s: function(recent404s) {
            const container = $('#recent-404s-container');
            container.empty();

            if (!recent404s || recent404s.length === 0) {
                container.html('<div class="sb-module-empty"><div class="sb-module-empty-icon"></div><p class="sb-module-empty-desc">No recent 404 errors</p></div>');
                return;
            }

            const table = $('<table class="sb-module-table">');
            table.append('<thead><tr><th>URL</th><th style="width: 80px;">Hits</th><th style="width: 120px;">Last Seen</th></tr></thead>');
            const tbody = $('<tbody>');

            recent404s.forEach(function(item) {
                const row = $('<tr>');

                // URL with copy and open buttons
                const urlCell = $('<td class="url-cell">');
                const urlWrapper = $('<div class="url-cell-wrapper">');
                const urlText = $('<span class="url-text">').text(item.url);
                const copyBtn = $('<button type="button" class="url-copy-btn" title="Copy URL">')
                    .html('<span class="dashicons dashicons-admin-page"></span>')
                    .attr('data-url', item.url);
                const openBtn = $('<button type="button" class="url-open-btn" title="Open URL">')
                    .html('<span class="dashicons dashicons-external"></span>')
                    .attr('data-url', item.url);
                urlWrapper.append(urlText, openBtn, copyBtn);
                urlCell.append(urlWrapper);

                row.append(urlCell);
                row.append($('<td>').text(item.hit_count));
                row.append($('<td>').text(Track404s.formatDate(item.last_seen)));
                tbody.append(row);
            });

            table.append(tbody);
            container.append(table);
        },

        loadLogs: function() {
            const self = this;

            $.ajax({
                url: track404sAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'track_404s_get_logs',
                    nonce: track404sAdmin.nonce,
                    orderby: self.orderBy,
                    order: self.order,
                    search: self.search,
                    filter: self.filter,
                    offset: self.currentPage * self.pageSize
                },
                beforeSend: function() {
                    $('#track-404s-tbody').html('<tr><td colspan="6" class="sb-module-empty" style="padding: 40px;"><div class="sb-module-empty-icon"></div><p class="sb-module-empty-desc">Loading...</p></td></tr>');
                },
                success: function(response) {
                    if (response.success) {
                        self.total = response.data.total;
                        self.renderLogs(response.data.logs);
                        self.updatePagination();
                        self.updateSortIndicators();
                    }
                },
                error: function() {
                    $('#track-404s-tbody').html('<tr><td colspan="6" class="sb-module-empty" style="padding: 40px;"><div class="sb-module-empty-icon"></div><p class="sb-module-empty-desc">Failed to load logs.</p></td></tr>');
                }
            });
        },

        renderLogs: function(logs) {
            const tbody = $('#track-404s-tbody');
            tbody.empty();

            if (!logs || logs.length === 0) {
                tbody.html('<tr><td colspan="6" class="sb-module-empty" style="padding: 40px;"><div class="sb-module-empty-icon"></div><p class="sb-module-empty-desc">No 404 errors found.</p><p class="sb-module-empty-desc" style="margin-top: 8px; font-size: 13px; color: #64748b;">When visitors hit broken links, they\'ll appear here.</p></td></tr>');
                return;
            }

            logs.forEach(function(log) {
                const row = $('<tr>');

                // URL with copy and open buttons
                const urlCell = $('<td class="url-cell">');
                const urlWrapper = $('<div class="url-cell-wrapper">');
                const urlText = $('<span class="url-text">').text(log.url);
                const copyBtn = $('<button type="button" class="url-copy-btn" title="Copy URL">')
                    .html('<span class="dashicons dashicons-admin-page"></span>')
                    .attr('data-url', log.url);
                const openBtn = $('<button type="button" class="url-open-btn" title="Open URL">')
                    .html('<span class="dashicons dashicons-external"></span>')
                    .attr('data-url', log.url);
                urlWrapper.append(urlText, openBtn, copyBtn);
                urlCell.append(urlWrapper);
                row.append(urlCell);

                // Hit count
                row.append($('<td class="hit-count">').text(log.hit_count));

                // First seen
                row.append($('<td class="date-cell">').text(Track404s.formatDate(log.first_seen)));

                // Last seen
                row.append($('<td class="date-cell">').text(Track404s.formatDate(log.last_seen)));

                // Referrer
                if (log.referrer) {
                    row.append($('<td class="referrer-cell">').html('<a href="' + log.referrer + '" target="_blank" rel="noopener">' + Track404s.truncate(log.referrer, 40) + '</a>'));
                } else {
                    row.append($('<td class="no-referrer">').text('Direct'));
                }

                // Actions
                const actionsCell = $('<td>');
                const deleteBtn = $('<button type="button" class="sb-module-button sb-module-button-danger sb-module-button-sm action-delete">')
                    .attr('data-id', log.id)
                    .attr('title', 'Delete')
                    .html('<span class="dashicons dashicons-trash"></span>');
                actionsCell.append(deleteBtn);
                row.append(actionsCell);

                tbody.append(row);
            });
        },

        updatePagination: function() {
            const start = this.currentPage * this.pageSize + 1;
            const end = Math.min((this.currentPage + 1) * this.pageSize, this.total);

            $('#track-404s-page-info').text('Showing ' + start + ' - ' + end + ' of ' + this.total);

            // Disable/enable buttons
            $('#track-404s-prev').prop('disabled', this.currentPage === 0);
            $('#track-404s-next').prop('disabled', end >= this.total);
        },

        updateSortIndicators: function() {
            // Remove all active classes
            $('#track-404s-table th.sortable').removeClass('active asc desc');

            // Add active class to current column
            const th = $('#track-404s-table th[data-column="' + this.orderBy + '"]');
            th.addClass('active');
            th.addClass(this.order.toLowerCase());
        },

        formatDate: function(dateString) {
            if (!dateString) return '-';

            const date = new Date(dateString);
            const now = new Date();
            const diff = now - date;
            const seconds = Math.floor(diff / 1000);
            const minutes = Math.floor(seconds / 60);
            const hours = Math.floor(minutes / 60);
            const days = Math.floor(hours / 24);

            if (days > 7) {
                return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
            } else if (days > 0) {
                return days + ' day' + (days > 1 ? 's' : '') + ' ago';
            } else if (hours > 0) {
                return hours + ' hour' + (hours > 1 ? 's' : '') + ' ago';
            } else if (minutes > 0) {
                return minutes + ' min' + (minutes > 1 ? 's' : '') + ' ago';
            } else {
                return 'Just now';
            }
        },

        truncate: function(str, length) {
            if (str.length <= length) return str;
            return str.substring(0, length) + '...';
        },

        exportCSV: function() {
            window.location.href = track404sAdmin.ajaxUrl + '?action=track_404s_export&nonce=' + track404sAdmin.nonce;
        },

        deleteAll: function() {
            const self = this;

            $.ajax({
                url: track404sAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'track_404s_delete_all',
                    nonce: track404sAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        self.currentPage = 0;
                        self.loadLogs();
                        self.loadStats();
                        alert('All 404 logs have been deleted.');
                    } else {
                        alert('Failed to delete logs: ' + (response.data || 'Unknown error'));
                    }
                }
            });
        },

        deleteSingle: function(id) {
            const self = this;

            $.ajax({
                url: track404sAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'track_404s_delete',
                    nonce: track404sAdmin.nonce,
                    id: id
                },
                success: function(response) {
                    if (response.success) {
                        self.loadLogs();
                        self.loadStats();
                    } else {
                        alert('Failed to delete: ' + (response.data || 'Unknown error'));
                    }
                }
            });
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        Track404s.init();
    });

})(jQuery);
