/**
 * Internal Linking Admin JavaScript
 * Handles AJAX requests and UI updates for the extractive-only linking system
 * 
 * @package ContentPerformanceAnalyzer
 * @since 2.0.0
 */

(function($) {
    'use strict';

    // Global state
    let currentSuggestions = [];
    let currentSourceId = null;
    let currentTargetId = null;
    let currentTargetUrl = null;

    $(document).ready(function() {
        initEventHandlers();
    });

    function initEventHandlers() {
        // Fetch suggestions button
        $('#cpanalyzer_fetch_suggestions').on('click', handleFetchSuggestions);
        
        // Apply selected links button
        $(document).on('click', '#cpanalyzer_apply_selected', handleApplySelected);
        
        // Select all / deselect all
        $(document).on('change', '#cpanalyzer_select_all', handleSelectAll);
        
        // Individual checkbox changes
        $(document).on('change', '.cpanalyzer-suggestion-checkbox', updateApplyButton);
    }

    function handleFetchSuggestions() {
        const sourceId = $('#cpanalyzer_source').val();
        const targetId = $('#cpanalyzer_target').val();

        // Validation
        if (!sourceId || !targetId) {
            showMessage('Please select both source and target posts.', 'error');
            return;
        }

        if (sourceId === targetId) {
            showMessage('Source and target posts must be different.', 'error');
            return;
        }

        // Update UI state
        $('#cpanalyzer_fetch_suggestions').prop('disabled', true);
        $('#cpanalyzer_fetch_spinner').addClass('is-active');
        $('#cpanalyzer_results_container').hide();
        clearMessages();

        // Store current selections
        currentSourceId = sourceId;
        currentTargetId = targetId;
        currentTargetUrl = $('#cpanalyzer_target option:selected').data('url');

        // Make AJAX request
        $.ajax({
            url: cpanalyzer_interlinking.ajaxurl,
            type: 'POST',
            data: {
                action: 'cpanalyzer_get_interlink_suggestions',
                nonce: cpanalyzer_interlinking.nonce,
                source_post_id: sourceId,
                target_post_id: targetId
            },
            success: function(response) {
                if (response.success) {
                    handleSuggestionsSuccess(response.data);
                } else {
                    showMessage('Failed to get suggestions: ' + (response.data.message || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                showMessage('Network error: ' + error, 'error');
            },
            complete: function() {
                $('#cpanalyzer_fetch_suggestions').prop('disabled', false);
                $('#cpanalyzer_fetch_spinner').removeClass('is-active');
            }
        });
    }

    function handleSuggestionsSuccess(data) {
        currentSuggestions = data.candidates || [];
        
        if (currentSuggestions.length === 0) {
            renderNoSuggestions();
            return;
        }

        renderSuggestions(currentSuggestions, data);
        $('#cpanalyzer_results_container').show();
        $('#cpanalyzer_validation_notice').show();
    }

    function renderNoSuggestions() {
        const html = `
            <div class="cpanalyzer-no-suggestions">
                <h3>No Link Suggestions Found</h3>
                <p>No suitable linking opportunities were found between these posts.</p>
                <p>This could be because:</p>
                <ul style="text-align: left; display: inline-block;">
                    <li>The content topics don't overlap semantically</li>
                    <li>No relevant anchor text phrases were found</li>
                    <li>The AI determined no natural linking opportunities exist</li>
                </ul>
                <p>Try selecting different posts or check that both posts have substantial content.</p>
            </div>
        `;
        
        $('#cpanalyzer_results').html(html);
        $('#cpanalyzer_results_container').show();
        $('#cpanalyzer_apply_section').hide();
    }

    function renderSuggestions(suggestions, data) {
        let html = `
            <div class="cpanalyzer-suggestions-info">
                <p><strong>Source:</strong> ${escapeHtml(data.source_title)}</p>
                <p><strong>Target:</strong> ${escapeHtml(data.target_title)}</p>
                <p><strong>Found ${suggestions.length} validated suggestions:</strong></p>
            </div>
            
            <table class="cpanalyzer-suggestions-table">
                <thead>
                    <tr>
                        <th style="width: 40px;">
                            <input type="checkbox" id="cpanalyzer_select_all" checked>
                        </th>
                        <th>Anchor Text</th>
                        <th>Position</th>
                        <th>Confidence</th>
                        <th>Reason</th>
                    </tr>
                </thead>
                <tbody>
        `;

        suggestions.forEach(function(suggestion, index) {
            const confidenceClass = getConfidenceClass(suggestion.confidence);
            const confidencePercent = Math.round((suggestion.confidence || 0.5) * 100);
            
            html += `
                <tr data-index="${index}">
                    <td>
                        <input type="checkbox" class="cpanalyzer-suggestion-checkbox" checked 
                               data-index="${index}">
                    </td>
                    <td>
                        <span class="cpanalyzer-anchor-text">${escapeHtml(suggestion.anchor_text)}</span>
                    </td>
                    <td>
                        <span class="cpanalyzer-position">${suggestion.start}-${suggestion.end}</span>
                    </td>
                    <td>
                        <span class="cpanalyzer-confidence ${confidenceClass}">${confidencePercent}%</span>
                    </td>
                    <td>
                        <span class="cpanalyzer-reason">${escapeHtml(suggestion.reason || 'AI selected this as relevant')}</span>
                    </td>
                </tr>
            `;
        });

        html += `
                </tbody>
            </table>
        `;

        $('#cpanalyzer_results').html(html);
        $('#cpanalyzer_apply_section').show();
        updateApplyButton();
    }

    function handleApplySelected() {
        const selectedSuggestions = getSelectedSuggestions();
        
        if (selectedSuggestions.length === 0) {
            showMessage('Please select at least one suggestion to apply.', 'error');
            return;
        }

        // Update UI state
        $('#cpanalyzer_apply_selected').prop('disabled', true);
        $('#cpanalyzer_apply_spinner').addClass('is-active');
        clearMessages();

        // Make AJAX request
        $.ajax({
            url: cpanalyzer_interlinking.ajaxurl,
            type: 'POST',
            data: {
                action: 'cpanalyzer_apply_interlinks',
                nonce: cpanalyzer_interlinking.nonce,
                source_post_id: currentSourceId,
                target_url: currentTargetUrl,
                items: JSON.stringify(selectedSuggestions)
            },
            success: function(response) {
                if (response.success) {
                    handleApplySuccess(response.data);
                } else {
                    showMessage('Failed to apply links: ' + (response.data.message || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                showMessage('Network error: ' + error, 'error');
            },
            complete: function() {
                $('#cpanalyzer_apply_selected').prop('disabled', false);
                $('#cpanalyzer_apply_spinner').removeClass('is-active');
            }
        });
    }

    function handleApplySuccess(data) {
        const applied = data.applied || [];
        const skipped = data.skipped || [];
        
        // Remove applied suggestions from the table
        applied.forEach(function(appliedItem) {
            currentSuggestions.forEach(function(suggestion, index) {
                if (suggestion.anchor_text === appliedItem.anchor_text && 
                    suggestion.start === appliedItem.start) {
                    // Remove the row from the table
                    $(`tr[data-index="${index}"]`).fadeOut(300, function() {
                        $(this).remove();
                        updateApplyButton();
                    });
                }
            });
        });

        // Update the suggestions array
        currentSuggestions = currentSuggestions.filter(function(suggestion) {
            return !applied.some(function(appliedItem) {
                return suggestion.anchor_text === appliedItem.anchor_text && 
                       suggestion.start === appliedItem.start;
            });
        });

        // Show success message
        let message = `Successfully applied ${applied.length} links.`;
        if (skipped.length > 0) {
            message += ` ${skipped.length} links were skipped (content may have changed).`;
        }
        showMessage(message, 'success');

        // If no suggestions left, show completion message
        if (currentSuggestions.length === 0) {
            $('#cpanalyzer_results').html(`
                <div class="cpanalyzer-no-suggestions">
                    <h3>All Links Applied!</h3>
                    <p>All suggested links have been successfully applied to your content.</p>
                    <p>You can now select different posts to find more linking opportunities.</p>
                </div>
            `);
            $('#cpanalyzer_apply_section').hide();
        }
    }

    function getSelectedSuggestions() {
        const selected = [];
        
        $('.cpanalyzer-suggestion-checkbox:checked').each(function() {
            const index = parseInt($(this).data('index'));
            if (currentSuggestions[index]) {
                selected.push(currentSuggestions[index]);
            }
        });
        
        return selected;
    }

    function handleSelectAll() {
        const isChecked = $('#cpanalyzer_select_all').is(':checked');
        $('.cpanalyzer-suggestion-checkbox').prop('checked', isChecked);
        updateApplyButton();
    }

    function updateApplyButton() {
        const selectedCount = $('.cpanalyzer-suggestion-checkbox:checked').length;
        const totalCount = $('.cpanalyzer-suggestion-checkbox').length;
        
        if (selectedCount === 0) {
            $('#cpanalyzer_apply_selected').prop('disabled', true).text('Apply Selected Links');
        } else {
            $('#cpanalyzer_apply_selected').prop('disabled', false)
                .text(`Apply ${selectedCount} Selected Link${selectedCount !== 1 ? 's' : ''}`);
        }
        
        // Update select all checkbox state
        if (selectedCount === 0) {
            $('#cpanalyzer_select_all').prop('indeterminate', false).prop('checked', false);
        } else if (selectedCount === totalCount) {
            $('#cpanalyzer_select_all').prop('indeterminate', false).prop('checked', true);
        } else {
            $('#cpanalyzer_select_all').prop('indeterminate', true);
        }
    }

    function getConfidenceClass(confidence) {
        const conf = confidence || 0.5;
        if (conf >= 0.8) return 'high';
        if (conf >= 0.6) return 'medium';
        return 'low';
    }

    function showMessage(message, type) {
        const messageHtml = `
            <div class="cpanalyzer-message ${type}">
                ${escapeHtml(message)}
            </div>
        `;
        
        $('#cpanalyzer_messages').html(messageHtml);
        
        // Auto-hide success messages
        if (type === 'success') {
            setTimeout(function() {
                $('#cpanalyzer_messages .cpanalyzer-message.success').fadeOut();
            }, 5000);
        }
    }

    function clearMessages() {
        $('#cpanalyzer_messages').empty();
    }

    function escapeHtml(unsafe) {
        return $('<div>').text(unsafe).html();
    }

})(jQuery);