/**
 * URL Management page — Content Refresh Brief generation and modal.
 *
 * Localized data: cpanalyzer_briefs { ajax_url, strings }
 */
(function($) {
    'use strict';

    var ajaxUrl = cpanalyzer_briefs.ajax_url;
    var i18n    = cpanalyzer_briefs.strings;

    /* ── Generate Refresh Brief ── */
    $(document).on('click', '.cpanalyzer-gen-brief', function() {
        var $btn    = $(this);
        var urlId   = $btn.data('url-id');
        var nonce   = $btn.data('nonce');

        $btn.prop('disabled', true)
            .html($('<span>', { 'class': 'cpanalyzer-btn-spinner' }))
            .append(document.createTextNode(i18n.generating));

        $.ajax({
            url:  ajaxUrl,
            type: 'POST',
            data: {
                action:   'cpanalyzer_generate_refresh_brief',
                url_id:   urlId,
                _wpnonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    // Replace button with "View Brief" button using returned nonce
                    var viewNonce = response.data && response.data.view_nonce ? response.data.view_nonce : '';
                    var urlSlug   = response.data && response.data.url ? response.data.url : '';
                    $btn.replaceWith(
                        $('<button>', {
                            'class':       'button button-small button-primary cpanalyzer-view-brief',
                            'data-url-id': urlId,
                            'data-url':    urlSlug,
                            'data-nonce':  viewNonce
                        }).text(i18n.view_brief)
                    );
                } else {
                    var msg = (response.data && response.data.message)
                        ? response.data.message
                        : i18n.gen_failed;
                    alert(msg);
                    $btn.prop('disabled', false).text(i18n.generate_brief);
                }
            },
            error: function() {
                alert(i18n.server_error);
                $btn.prop('disabled', false).text(i18n.generate_brief);
            }
        });
    });

    /* ── View Brief ── */
    $(document).on('click', '.cpanalyzer-view-brief', function() {
        var $btn  = $(this);
        var urlId = $btn.data('url-id');
        var url   = $btn.data('url');
        var nonce = $btn.data('nonce');

        var $modal = $('#cpanalyzer-brief-modal');
        $modal.find('.cpanalyzer-modal-url').text(url || '');

        // Clear previous content
        $modal.find('#cpanalyzer-gap-keywords, #cpanalyzer-structure-sections, #cpanalyzer-perf-ga4, #cpanalyzer-perf-psi').empty();
        $modal.find('#cpanalyzer-gap-competitor, #cpanalyzer-gap-intent, #cpanalyzer-structure-issues, #cpanalyzer-structure-outline, #cpanalyzer-perf-impact').text('');
        $modal.find('#cpanalyzer-perf-priority').text('').attr('class', 'cpanalyzer-priority-badge');

        $modal.css('display', 'flex');
        $('body').css('overflow', 'hidden');

        $.ajax({
            url:  ajaxUrl,
            type: 'POST',
            data: {
                action:   'cpanalyzer_get_refresh_brief',
                url_id:   urlId,
                _wpnonce: nonce
            },
            success: function(response) {
                if (!response.success || !response.data || !response.data.brief) {
                    alert(i18n.load_failed);
                    closeModal();
                    return;
                }

                var brief = response.data.brief;

                /* Gap Analysis */
                var gap = brief.gap_analysis || {};
                populateList($modal.find('#cpanalyzer-gap-keywords'), gap.missing_keywords);
                $modal.find('#cpanalyzer-gap-competitor').text(gap.competitor_gaps || '—');
                $modal.find('#cpanalyzer-gap-intent').text(gap.intent_mismatch || '—');

                /* Structural Plan */
                var structure = brief.structural_plan || {};
                populateList($modal.find('#cpanalyzer-structure-sections'), structure.recommended_sections);
                $modal.find('#cpanalyzer-structure-issues').text(structure.current_issues || '—');
                $modal.find('#cpanalyzer-structure-outline').text(structure.ideal_outline || '—');

                /* Performance Fixes */
                var perf = brief.performance_fixes || {};
                populateList($modal.find('#cpanalyzer-perf-ga4'), perf.ga4_actions);
                populateList($modal.find('#cpanalyzer-perf-psi'), perf.psi_actions);

                var priority = (perf.priority || '').toLowerCase();
                var $badge   = $modal.find('#cpanalyzer-perf-priority');
                $badge.text(perf.priority || '—');
                if (priority === 'high')        $badge.addClass('cpanalyzer-priority-high');
                else if (priority === 'medium') $badge.addClass('cpanalyzer-priority-medium');
                else if (priority === 'low')    $badge.addClass('cpanalyzer-priority-low');

                $modal.find('#cpanalyzer-perf-impact').text(perf.estimated_impact || '—');
            },
            error: function() {
                alert(i18n.server_error);
                closeModal();
            }
        });
    });

    /* ── Close modal ── */
    function closeModal() {
        $('#cpanalyzer-brief-modal').css('display', 'none');
        $('body').css('overflow', '');
    }

    $(document).on('click', '.cpanalyzer-modal-close, .cpanalyzer-modal-overlay', closeModal);

    $(document).on('keydown', function(e) {
        if (e.key === 'Escape') { closeModal(); }
    });

    /* ── Helper: populate <ul>/<ol> from array or string ── */
    function populateList($list, items) {
        $list.empty();
        if (!items) { $list.append($('<li>').text('—')); return; }
        if (typeof items === 'string') { items = [items]; }
        if (!Array.isArray(items) || items.length === 0) { $list.append($('<li>').text('—')); return; }
        $.each(items, function(i, item) {
            $list.append($('<li>').text(item));
        });
    }

})(jQuery);
