/**
 * Internal Links review actions.
 * Handles single-row apply/remove actions and client-side filtering.
 */

(function ($) {
    'use strict';

    if (typeof CPANALYZER_INTERNAL_LINKS === 'undefined') {
        return;
    }

    var strings = CPANALYZER_INTERNAL_LINKS.strings || {};

    function collectRow($tr) {
        return {
            source_id: parseInt($tr.data('source-id'), 10),
            target_id: parseInt($tr.data('target-id'), 10),
            anchor_text: String($tr.data('anchor-text') || ''),
            context: String($tr.data('context') || '')
        };
    }

    function showMessage(message, type) {
        var $container = $('#cpanalyzer-links-status-message');
        var className = type === 'success' ? 'notice-success' : 'notice-error';

        $container.html(
            '<div class="notice ' + className + ' is-dismissible"><p>' + message + '</p>' +
            '<button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss</span></button></div>'
        );

        setTimeout(function () {
            $container.find('.notice').fadeOut(300);
        }, 5000);
    }

    function updateSummaryCounts() {
        var totalRows = $('.cpanalyzer-suggestion-row').length;
        var cardsWithRows = $('.cpanalyzer-post-suggestions').filter(function () {
            return $(this).find('.cpanalyzer-suggestion-row').length > 0;
        }).length;

        $('#cpanalyzer-total-suggestions').text(totalRows);
        $('#cpanalyzer-posts-with-suggestions').text(cardsWithRows);
    }

    function renderEmptyState(message) {
        $('.cpanalyzer-il-results').replaceWith(
            '<section class="cpanalyzer-il-panel cpanalyzer-il-empty-state">' +
            '<h2>No suggestions remain</h2>' +
            '<p>' + message + '</p>' +
            '</section>'
        );
        updateSummaryCounts();
    }

    function removeRowAndCleanup($row, emptyMessage) {
        var $card = $row.closest('.cpanalyzer-post-suggestions');

        $row.fadeOut(200, function () {
            $row.remove();

            if ($card.find('.cpanalyzer-suggestion-row').length === 0) {
                $card.fadeOut(180, function () {
                    $card.remove();
                    updateSummaryCounts();

                    if ($('.cpanalyzer-post-suggestions').length === 0) {
                        renderEmptyState(emptyMessage);
                    }
                });
                return;
            }

            updateSummaryCounts();
        });
    }

    function setRowBusy($row, busy, label) {
        var $buttons = $row.find('.cpanalyzer-apply-one, .cpanalyzer-remove-one');
        $buttons.prop('disabled', !!busy);

        if (busy && label) {
            $row.find('.cpanalyzer-apply-one, .cpanalyzer-remove-one').filter(':focus').text(label);
        } else {
            $row.find('.cpanalyzer-apply-one').text(strings.applyButton || 'Apply');
            $row.find('.cpanalyzer-remove-one').text(strings.removeButton || 'Remove');
        }
    }

    function filterSuggestions(query) {
        var needle = String(query || '').toLowerCase().trim();

        $('.cpanalyzer-suggestion-row').each(function () {
            var $row = $(this);
            var haystack = String($row.data('search-text') || '').toLowerCase();
            var visible = needle === '' || haystack.indexOf(needle) !== -1;
            $row.toggle(visible);
        });

        $('.cpanalyzer-post-suggestions').each(function () {
            var $card = $(this);
            var hasVisibleRows = $card.find('.cpanalyzer-suggestion-row:visible').length > 0;
            $card.toggle(hasVisibleRows);
        });
    }

    $(document).ready(function () {
        $('#cpanalyzer-suggestions-search').on('input', function () {
            filterSuggestions($(this).val());
        });

        $(document).on('click', '.cpanalyzer-apply-one', function () {
            var $button = $(this);
            var $row = $button.closest('tr');
            var item = collectRow($row);

            if (!window.confirm(strings.applyConfirm || 'Apply this internal link suggestion?')) {
                return;
            }

            setRowBusy($row, true);
            $button.text(strings.applying || 'Applying...');

            $.post(CPANALYZER_INTERNAL_LINKS.ajax_url, {
                action: 'cpanalyzer_apply_single_internal_link',
                source_id: item.source_id,
                target_id: item.target_id,
                anchor_text: item.anchor_text,
                context: item.context,
                nonce: CPANALYZER_INTERNAL_LINKS.nonce,
                nonce_name: CPANALYZER_INTERNAL_LINKS.nonce_name,
                [CPANALYZER_INTERNAL_LINKS.nonce_name]: CPANALYZER_INTERNAL_LINKS.nonce
            }).done(function (response) {
                if (response && response.success) {
                    showMessage((response.data && response.data.message) || strings.applySuccess || 'Suggestion applied successfully.', 'success');
                    removeRowAndCleanup($row, strings.emptyApplied || 'All reviewed suggestions are done. Run a new analysis to discover more opportunities.');
                } else {
                    showMessage((response && response.data && response.data.message) || strings.networkError || 'Network error', 'error');
                    setRowBusy($row, false);
                }
            }).fail(function (xhr) {
                showMessage((xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) || strings.networkError || 'Network error', 'error');
                setRowBusy($row, false);
            });
        });

        $(document).on('click', '.cpanalyzer-remove-one', function () {
            var $button = $(this);
            var $row = $button.closest('tr');
            var item = collectRow($row);

            if (!window.confirm(strings.removeConfirm || 'Remove this suggestion from the review list?')) {
                return;
            }

            setRowBusy($row, true);
            $button.text(strings.removing || 'Removing...');

            $.post(CPANALYZER_INTERNAL_LINKS.ajax_url, {
                action: 'cpanalyzer_remove_suggestion',
                source_id: item.source_id,
                target_id: item.target_id,
                anchor_text: item.anchor_text,
                context: item.context,
                [CPANALYZER_INTERNAL_LINKS.nonce_name]: CPANALYZER_INTERNAL_LINKS.nonce
            }).done(function (response) {
                if (response && response.success) {
                    showMessage((response.data && response.data.message) || strings.removeSuccess || 'Suggestion removed successfully.', 'success');
                    removeRowAndCleanup($row, strings.emptyRemoved || 'All suggestions have been cleared. Run a new analysis to generate fresh opportunities.');
                } else {
                    showMessage((response && response.data && response.data.message) || strings.networkError || 'Network error', 'error');
                    setRowBusy($row, false);
                }
            }).fail(function (xhr) {
                showMessage((xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) || strings.networkError || 'Network error', 'error');
                setRowBusy($row, false);
            });
        });
    });
})(jQuery);
