/**
 * RANK Writer Module
 * Handles the Rank Writer tab functionality for listing and uploading articles
 */
(function($) {
    'use strict';
    
    // Module namespace
    window.rank = window.rank || {};
    rank.writer = {
        // State
        state: {
            articles: [],
            selectedIds: new Set(),
            currentPage: 1,
            totalPages: 1,
            total: 0,
            perPage: 10,
            isLoading: false
        },
        
        // DOM elements cache
        elements: {},
        
        /**
         * Initialize the module
         */
        init: function() {
            // Only initialize if we're on the Rank Writer tab
            if ($('.rank-writer-section').length === 0) {
                return;
            }
            
            this.cacheElements();
            this.bindEvents();
            this.loadArticles();
        },
        
        /**
         * Cache DOM elements for performance
         */
        cacheElements: function() {
            this.elements = {
                table: $('#rank-writer-table'),
                tbody: $('#rank-writer-tbody'),
                loading: $('#rank-writer-loading'),
                empty: $('#rank-writer-empty'),
                error: $('#rank-writer-error'),
                errorMessage: $('#rank-writer-error-message'),
                pagination: $('#rank-writer-pagination'),
                pageInfo: $('#rank-writer-page-info'),
                prevBtn: $('#rank-writer-prev'),
                nextBtn: $('#rank-writer-next'),
                selectAll: $('#rank-writer-select-all'),
                bulkActions: $('#rank-writer-bulk-actions'),
                selectedCount: $('#rank-writer-selected-count'),
                uploadBtn: $('#rank-writer-upload-btn'),
                uploadCount: $('#rank-writer-upload-count'),
                retryBtn: $('#rank-writer-retry')
            };
        },
        
        /**
         * Bind event listeners
         */
        bindEvents: function() {
            var self = this;
            
            // Select all checkbox
            this.elements.selectAll.on('change', function() {
                self.toggleSelectAll($(this).is(':checked'));
            });
            
            // Individual checkboxes (delegated)
            this.elements.tbody.on('change', '.rank-writer-checkbox', function() {
                self.handleCheckboxChange($(this));
            });
            
            // Upload button
            this.elements.uploadBtn.on('click', function() {
                self.uploadSelected();
            });
            
            // Pagination buttons
            this.elements.prevBtn.on('click', function() {
                if (self.state.currentPage > 1) {
                    self.loadArticles(self.state.currentPage - 1);
                }
            });
            
            this.elements.nextBtn.on('click', function() {
                if (self.state.currentPage < self.state.totalPages) {
                    self.loadArticles(self.state.currentPage + 1);
                }
            });
            
            // Retry button
            this.elements.retryBtn.on('click', function() {
                self.loadArticles(self.state.currentPage);
            });
        },
        
        /**
         * Load articles from API
         */
        loadArticles: function(page) {
            var self = this;
            page = page || 1;
            
            if (this.state.isLoading) {
                return;
            }
            
            this.state.isLoading = true;
            this.showLoading();
            
            $.ajax({
                url: rank_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'rank_writer_get_articles',
                    nonce: rank_ajax_obj.nonce,
                    page: page,
                    per_page: this.state.perPage
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        self.state.articles = response.data.articles || [];
                        self.state.currentPage = response.data.page || 1;
                        self.state.totalPages = response.data.total_pages || 1;
                        self.state.total = response.data.total || 0;
                        
                        self.renderTable();
                        self.renderPagination();
                    } else {
                        self.showError(response.data.message || 'Failed to load articles');
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error('RANK Writer: AJAX error', textStatus, errorThrown);
                    self.showError('Network error. Please try again.');
                },
                complete: function() {
                    self.state.isLoading = false;
                }
            });
        },
        
        /**
         * Render the articles table
         */
        renderTable: function() {
            var self = this;
            
            this.elements.loading.hide();
            this.elements.error.hide();
            
            // Clear selection when rendering new data
            this.state.selectedIds.clear();
            this.elements.selectAll.prop('checked', false);
            this.updateBulkActionBar();
            
            if (this.state.articles.length === 0) {
                this.elements.table.hide();
                this.elements.empty.show();
                this.elements.pagination.hide();
                return;
            }
            
            this.elements.empty.hide();
            this.elements.table.show();
            this.elements.tbody.empty();
            
            $.each(this.state.articles, function(index, article) {
                var isUploaded = article.is_uploaded;
                var createdDate = self.formatDate(article.createdAt);
                var title = self.escapeHtml(article.title);
                
                var $row = $('<tr></tr>')
                    .attr('data-id', article._id)
                    .addClass(isUploaded ? 'rank-writer-uploaded' : '');
                
                // Checkbox column
                var $checkboxCell = $('<td class="check-column"></td>');
                var $checkbox = $('<input type="checkbox" class="rank-writer-checkbox">')
                    .val(article._id)
                    .prop('disabled', isUploaded);
                $checkboxCell.append($checkbox);
                $row.append($checkboxCell);
                
                // Created date column
                $row.append($('<td></td>').text(createdDate));
                
                // Title column
                $row.append($('<td></td>').text(title));
                
                // Added column
                var $addedCell = $('<td class="rank-writer-added-column"></td>');
                if (isUploaded) {
                    $addedCell.html('<span class="rank-writer-check">✔️</span>');
                }
                $row.append($addedCell);
                
                self.elements.tbody.append($row);
            });
        },
        
        /**
         * Render pagination controls
         */
        renderPagination: function() {
            if (this.state.totalPages <= 1) {
                this.elements.pagination.hide();
                return;
            }
            
            this.elements.pagination.show();
            this.elements.prevBtn.prop('disabled', this.state.currentPage <= 1);
            this.elements.nextBtn.prop('disabled', this.state.currentPage >= this.state.totalPages);
            this.elements.pageInfo.text('Page ' + this.state.currentPage + ' of ' + this.state.totalPages);
        },
        
        /**
         * Toggle select all checkboxes
         */
        toggleSelectAll: function(checked) {
            var self = this;
            
            this.elements.tbody.find('.rank-writer-checkbox:not(:disabled)').each(function() {
                $(this).prop('checked', checked);
                var articleId = $(this).val();
                
                if (checked) {
                    self.state.selectedIds.add(articleId);
                } else {
                    self.state.selectedIds.delete(articleId);
                }
            });
            
            this.updateBulkActionBar();
        },
        
        /**
         * Handle individual checkbox change
         */
        handleCheckboxChange: function($checkbox) {
            var articleId = $checkbox.val();
            
            if ($checkbox.is(':checked')) {
                this.state.selectedIds.add(articleId);
            } else {
                this.state.selectedIds.delete(articleId);
            }
            
            // Update select all checkbox state
            var totalCheckboxes = this.elements.tbody.find('.rank-writer-checkbox:not(:disabled)').length;
            var checkedCheckboxes = this.elements.tbody.find('.rank-writer-checkbox:checked').length;
            this.elements.selectAll.prop('checked', totalCheckboxes > 0 && totalCheckboxes === checkedCheckboxes);
            
            this.updateBulkActionBar();
        },
        
        /**
         * Update bulk action bar visibility and counts
         */
        updateBulkActionBar: function() {
            var count = this.state.selectedIds.size;
            
            if (count > 0) {
                this.elements.bulkActions.show();
                this.elements.selectedCount.text(count + ' selected');
                this.elements.uploadCount.text(count);
            } else {
                this.elements.bulkActions.hide();
            }
        },
        
        /**
         * Upload selected articles to WordPress
         */
        uploadSelected: function() {
            var self = this;
            
            if (this.state.selectedIds.size === 0) {
                return;
            }
            
            var articleIds = Array.from(this.state.selectedIds);
            var $btn = this.elements.uploadBtn;
            var originalText = $btn.html();
            
            $btn.prop('disabled', true).text('Uploading...');
            
            $.ajax({
                url: rank_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'rank_writer_upload_to_wp',
                    nonce: rank_ajax_obj.nonce,
                    article_ids: articleIds
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        self.showNotice(response.data.message, 'success');
                        
                        // Clear selection and reload
                        self.state.selectedIds.clear();
                        self.loadArticles(self.state.currentPage);
                    } else {
                        self.showNotice(response.data.message || 'Upload failed', 'error');
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error('RANK Writer: Upload error', textStatus, errorThrown);
                    self.showNotice('Network error during upload. Please try again.', 'error');
                },
                complete: function() {
                    $btn.prop('disabled', false).html(originalText);
                    self.updateBulkActionBar();
                }
            });
        },
        
        /**
         * Show loading state
         */
        showLoading: function() {
            this.elements.table.hide();
            this.elements.empty.hide();
            this.elements.error.hide();
            this.elements.pagination.hide();
            this.elements.loading.show();
        },
        
        /**
         * Show error state
         */
        showError: function(message) {
            this.elements.loading.hide();
            this.elements.table.hide();
            this.elements.empty.hide();
            this.elements.pagination.hide();
            this.elements.errorMessage.text(message);
            this.elements.error.show();
        },
        
        /**
         * Show admin notice
         */
        showNotice: function(message, type) {
            type = type || 'info';

            // Rank Writer has its own notice target and must not depend on the
            // Health screen's shared rank.elements initialization.
            var $notice = $('<div class="notice is-dismissible"></div>')
                .addClass('notice-' + type)
                .html('<p>' + this.escapeHtml(message) + '</p>');
            
            // Remove existing notices from our module
            $('.rank-writer-section .notice').remove();
            
            // Add notice at the top of the section
            $('.rank-writer-section h2').after($notice);
            
            // Auto-dismiss after 5 seconds
            setTimeout(function() {
                $notice.fadeOut(300, function() {
                    $(this).remove();
                });
            }, 5000);
        },
        
        /**
         * Format date string
         */
        formatDate: function(dateString) {
            if (!dateString) {
                return 'N/A';
            }
            
            try {
                var date = new Date(dateString);
                return date.toLocaleDateString();
            } catch (e) {
                return dateString;
            }
        },
        
        /**
         * Escape HTML to prevent XSS
         */
        escapeHtml: function(text) {
            if (!text) {
                return '';
            }
            
            var div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    };
    
    // Initialize when document is ready
    $(document).ready(function() {
        rank.writer.init();
    });
    
})(jQuery);