/**
 * Newsroom OS — Author Performance dashboard (Settings → perf tab).
 */
(function ($) {
    'use strict';

    function __(text) {
        if (typeof newsai_vars !== 'undefined' && newsai_vars.ui_text && newsai_vars.ui_text[text]) {
            return newsai_vars.ui_text[text];
        }
        return text;
    }

    function switchApTab($btn) {
        var tab = $btn.attr('data-ap-tab');
        if (!tab) {
            return;
        }
        var $wrap = $btn.closest('.nros-ap-tabs');
        if (!$wrap.length) {
            return;
        }
        $wrap.find('.nros-ap-tabs__btn').removeClass('is-on').attr('aria-selected', 'false');
        $btn.addClass('is-on').attr('aria-selected', 'true');
        $wrap.find('.nros-ap-tab-panel').removeClass('is-active');
        $wrap.find('.nros-ap-tab-panel[data-ap-panel="' + tab + '"]').addClass('is-active');
    }

    function initTabsIn($root) {
        $root.find('.nros-ap-tabs').each(function () {
            var $tabs = $(this);
            var $active = $tabs.find('.nros-ap-tabs__btn.is-on').first();
            if (!$active.length) {
                $active = $tabs.find('.nros-ap-tabs__btn').first();
            }
            switchApTab($active);
        });
    }

    // Tab switching is always bound — even if newsai_vars is unavailable.
    $(document).on('click', '.nros-author-perf .nros-ap-tabs__btn', function (e) {
        e.preventDefault();
        e.stopPropagation();
        switchApTab($(this));
    });

    function getApPanel() {
        return $('#nros-ap-print-area');
    }

    function getApAjaxUrl($panel) {
        if (typeof newsai_vars !== 'undefined' && newsai_vars.ajax_url) {
            return newsai_vars.ajax_url;
        }
        if (typeof window.ajaxurl === 'string' && window.ajaxurl) {
            return window.ajaxurl;
        }
        return String($panel.attr('data-ajax-url') || '');
    }

    function filterAuthorsInPanel($panel) {
        var q = String($panel.find('.nros-ap-search').val() || '').toLowerCase().trim();
        var sort = String($panel.find('.nros-ap-sort').val() || 'posts');
        var $container = $panel.find('.nros-author-perf-list, .nros-author-perf-grid').first();
        if (!$container.length) {
            return;
        }
        var $cards = $container.find('.nros-author-perf-card').detach();
        $cards = $cards.filter(function () {
            var name = String($(this).attr('data-author-name') || '');
            return q === '' || name.indexOf(q) !== -1;
        });
        $cards.sort(function (a, b) {
            var $a = $(a);
            var $b = $(b);
            if (sort === 'name') {
                return String($a.attr('data-author-name')).localeCompare(String($b.attr('data-author-name')));
            }
            var key = sort === 'clicks' || sort === 'web' ? 'clicks' : sort === 'focus' ? 'focus' : sort === 'readiness' ? 'readiness' : sort === 'discover' ? 'discover' : 'posts';
            return (parseInt($b.attr('data-' + key), 10) || 0) - (parseInt($a.attr('data-' + key), 10) || 0);
        });
        $container.append($cards);
    }

    function loadExpandedForPrint($card, days, nonce, lang, ajaxUrl) {
        var def = $.Deferred();
        var $expand = $card.find('.nros-author-perf-expand');
        var userId = parseInt($card.attr('data-user-id'), 10) || 0;
        if (!userId || !ajaxUrl) {
            def.resolve($card);
            return def.promise();
        }
        if ($expand.attr('data-loaded') === '1' && parseInt($expand.attr('data-days-loaded'), 10) === days) {
            def.resolve($card);
            return def.promise();
        }
        $.post(ajaxUrl, {
            action: 'newsai_pro_author_perf_expanded',
            nonce: nonce,
            user_id: userId,
            days: days,
            lang: lang
        })
            .done(function (resp) {
                if (resp && resp.success && resp.data && typeof resp.data.html === 'string') {
                    $expand.find('.nros-author-perf-expand-body').html(resp.data.html);
                    $expand.attr('data-loaded', '1').attr('data-days-loaded', String(days));
                    def.resolve($card);
                } else {
                    def.reject('load');
                }
            })
            .fail(function () {
                def.reject('network');
            });
        return def.promise();
    }

    function loadPrintCardsSequential($cards, days, nonce, lang, ajaxUrl, index) {
        if (index >= $cards.length) {
            return $.Deferred().resolve().promise();
        }
        return loadExpandedForPrint($cards.eq(index), days, nonce, lang, ajaxUrl).then(function () {
            return loadPrintCardsSequential($cards, days, nonce, lang, ajaxUrl, index + 1);
        });
    }

    function resetCardTabs($scope) {
        $scope.find('.nros-ap-tabs').each(function () {
            var $tabs = $(this);
            $tabs.find('.nros-ap-tab-panel').removeClass('is-active');
            $tabs.find('.nros-ap-tab-panel[data-ap-panel="summary"]').addClass('is-active');
            $tabs.find('.nros-ap-tabs__btn').removeClass('is-on').attr('aria-selected', 'false');
            $tabs.find('.nros-ap-tabs__btn[data-ap-tab="summary"]').addClass('is-on').attr('aria-selected', 'true');
        });
    }

    function applyPrintTabLabels($panel, $scope) {
        var labels = {
            summary: $panel.attr('data-tab-summary') || 'Summary',
            articles: $panel.attr('data-tab-articles') || 'Articles',
            coaching: $panel.attr('data-tab-coaching') || 'Coaching'
        };
        $scope.find('[data-ap-panel]').each(function () {
            var key = String($(this).attr('data-ap-panel') || '');
            if (labels[key]) {
                $(this).attr('data-ap-panel-label', labels[key]);
            }
        });
    }

    window.nrosApPrintSnapshot = null;

    function restoreApPrintState() {
        var snapshot = window.nrosApPrintSnapshot;
        var $panel = getApPanel();
        if (!snapshot || !$panel.length) {
            document.body.classList.remove('nros-ap-printing');
            return;
        }
        document.body.classList.remove('nros-ap-printing');
        $panel.find('.nros-ap-print-cover').remove();
        $panel.find('.nros-author-perf-card').removeClass('nros-ap-print-include');
        snapshot.forEach(function (s) {
            var $card = $panel.find('.nros-author-perf-card[data-user-id="' + s.userId + '"]');
            if (!$card.length) {
                return;
            }
            var $expand = $card.find('.nros-author-perf-expand');
            var $toggle = $card.find('.nros-author-perf-toggle');
            var $label = $toggle.find('.nros-author-perf-toggle-label');
            $card.removeClass('is-expanded');
            if (s.wasExpanded) {
                $card.addClass('is-expanded');
                $expand.show();
                $toggle.attr('aria-expanded', 'true');
                $label.text('▴');
            } else {
                $expand.hide();
                $toggle.attr('aria-expanded', 'false');
                $label.text('▾');
                if (s.clearLoaded) {
                    $expand.attr('data-loaded', '0').removeAttr('data-days-loaded');
                    $expand.find('.nros-author-perf-expand-body').empty();
                }
            }
            resetCardTabs($card);
        });
        window.nrosApPrintSnapshot = null;
        $('#nros-ap-export-pdf').prop('disabled', false);
        $('#nros-ap-export-status').text('');
    }

    if (!window.nrosApPrintBound) {
        window.nrosApPrintBound = true;
        window.addEventListener('afterprint', restoreApPrintState);
    }

    // Export PDF — always bound (does not depend on newsai_vars / ap-bound).
    $(document).on('click', '#nros-ap-export-pdf', function (e) {
        e.preventDefault();
        var $btn = $(this);
        var $panel = getApPanel();
        var $status = $('#nros-ap-export-status');
        if (!$panel.length) {
            return;
        }
        var scope = String($('#nros-ap-export-scope').val() || '10');
        var days = parseInt($panel.attr('data-days'), 10) || 30;
        var nonce = String($panel.attr('data-nonce') || '');
        var lang = String($panel.attr('data-lang') || 'en');
        var ajaxUrl = getApAjaxUrl($panel);
        var preparing = $panel.attr('data-export-preparing') || 'Preparing PDF export…';
        var readyMsg = $panel.attr('data-export-ready') || 'Opening print dialog…';
        var errMsg = $panel.attr('data-export-error') || 'Could not prepare export.';

        if (!ajaxUrl || !nonce) {
            $status.text(errMsg);
            return;
        }

        filterAuthorsInPanel($panel);
        var $cards = $panel.find('.nros-author-perf-body .nros-author-perf-card');
        var $targets = scope === 'all' ? $cards : $cards.slice(0, 10);
        if (!$targets.length) {
            $status.text(errMsg);
            return;
        }

        window.nrosApPrintSnapshot = $cards.map(function () {
            var $card = $(this);
            var $expand = $card.find('.nros-author-perf-expand');
            return {
                userId: parseInt($card.attr('data-user-id'), 10) || 0,
                wasExpanded: $expand.is(':visible'),
                clearLoaded: false
            };
        }).get();

        $btn.prop('disabled', true);
        $status.text(preparing);

        loadPrintCardsSequential($targets, days, nonce, lang, ajaxUrl, 0)
            .done(function () {
                $targets.each(function () {
                    var $card = $(this);
                    var uid = parseInt($card.attr('data-user-id'), 10) || 0;
                    window.nrosApPrintSnapshot.forEach(function (s) {
                        if (s.userId === uid && !s.wasExpanded) {
                            s.clearLoaded = true;
                        }
                    });
                });

                $cards.removeClass('nros-ap-print-include');
                $targets.addClass('nros-ap-print-include is-expanded');
                $targets.find('.nros-author-perf-expand').show();
                applyPrintTabLabels($panel, $targets);
                $targets.find('.nros-ap-tab-panel').addClass('is-active');

                var site = $panel.attr('data-site-name') || '';
                var title = $panel.attr('data-report-title') || 'Author Performance Report';
                var scopeLabel = scope === 'all'
                    ? ($('#nros-ap-export-scope option[value="all"]').text() || 'All authors')
                    : ($('#nros-ap-export-scope option[value="10"]').text() || 'Top 10 authors');
                var when = new Date().toLocaleString();
                $panel.find('.nros-ap-print-cover').remove();
                $panel.find('.nros-ap-panel__body').prepend(
                    '<div class="nros-ap-print-cover">' +
                    '<h2 class="nros-ap-print-cover__title">' + $('<div/>').text(title).html() + '</h2>' +
                    '<p class="nros-ap-print-cover__meta">' +
                    $('<div/>').text(site).html() + ' · ' + days + 'd · ' + $('<div/>').text(when).html() +
                    '</p>' +
                    '<div class="nros-ap-print-cover__scope">' + $('<div/>').text(scopeLabel).html() + '</div>' +
                    '</div>'
                );

                $status.text(readyMsg);
                document.body.classList.add('nros-ap-printing');
                window.setTimeout(function () {
                    window.print();
                }, 400);
            })
            .fail(function () {
                restoreApPrintState();
                $status.text(errMsg);
            });
    });

    $(function () {
        var $panel = $('.nros-author-perf');
        if (!$panel.length) {
            return;
        }
        if ($panel.data('ap-bound')) {
            return;
        }
        $panel.data('ap-bound', 1);

        initTabsIn($panel);

        if (typeof newsai_vars === 'undefined') {
            return; // no AJAX features without vars, but tabs still work above
        }

        function getNonce() {
            return $panel.attr('data-nonce') || '';
        }
        function getLang() {
            return String($panel.attr('data-lang') || 'en');
        }

        // (no duplicate tab handler here)

        $panel.on('click', '.nros-author-perf-range-btn', function (e) {
            e.preventDefault();
            var $btn = $(this);
            var days = parseInt($btn.attr('data-days'), 10) || 30;
            if ($btn.hasClass('is-on')) {
                return;
            }
            var $body = $panel.find('.nros-author-perf-body');
            $panel.find('.nros-author-perf-range-btn').each(function () {
                var on = parseInt($(this).attr('data-days'), 10) === days;
                $(this).toggleClass('is-on', on);
            });
            $panel.attr('data-days', days);
            $body.css('opacity', 0.5);
            $.post(newsai_vars.ajax_url, {
                action: 'newsai_pro_author_perf_grid',
                nonce: getNonce(),
                days: days,
                lang: getLang()
            })
                .done(function (resp) {
                    if (resp && resp.success && resp.data && typeof resp.data.html === 'string') {
                        $body.html(resp.data.html);
                        initTabsIn($body);
                    } else {
                        $body.html('<p class="nros-ap-note is-bad">Load error.</p>');
                    }
                })
                .fail(function () {
                    $body.html('<p class="nros-ap-note is-bad">Network error.</p>');
                })
                .always(function () {
                    $body.css('opacity', 1);
                });
        });

        function filterAndSortAuthors() {
            filterAuthorsInPanel($panel);
        }

        $panel.on('input', '.nros-ap-search', filterAndSortAuthors);
        $panel.on('change', '.nros-ap-sort', filterAndSortAuthors);

        $panel.on('click', '#nros-ap-filters-toggle', function (e) {
            e.preventDefault();
            var $btn = $(this);
            var $filters = $('#nros-ap-filters');
            var open = $filters.prop('hidden');
            $filters.prop('hidden', !open);
            $btn.attr('aria-expanded', open ? 'true' : 'false');
            $btn.toggleClass('is-on', open);
        });

        $panel.on('click', '.nros-author-perf-toggle', function (e) {
            e.preventDefault();
            e.stopPropagation();
            if (typeof e.stopImmediatePropagation === 'function') {
                e.stopImmediatePropagation();
            }
            var $btn = $(this);
            var $card = $btn.closest('.nros-author-perf-card');
            var $expand = $card.find('.nros-author-perf-expand');
            var $label = $btn.find('.nros-author-perf-toggle-label');
            var userId = parseInt($card.attr('data-user-id'), 10) || 0;
            var days = parseInt($panel.attr('data-days'), 10) || 30;
            if (!userId) {
                return;
            }
            if ($expand.is(':animated') || $btn.data('apBusy') === 1) {
                return;
            }
            $btn.data('apBusy', 1);

            if ($expand.is(':visible')) {
                $expand.slideUp(150, function () {
                    $card.removeClass('is-expanded');
                    $btn.data('apBusy', 0);
                });
                $btn.attr('aria-expanded', 'false');
                $label.text('▾');
                return;
            }

            $card.addClass('is-expanded');
            $expand.slideDown(150);
            $btn.attr('aria-expanded', 'true');
            $label.text('▴');

            if ($expand.attr('data-loaded') === '1' && parseInt($expand.attr('data-days-loaded'), 10) === days) {
                initTabsIn($expand);
                $btn.data('apBusy', 0);
                return;
            }

            $expand.find('.nros-author-perf-expand-body').html(
                '<div class="nros-ap-loading"><span class="spinner is-active" style="float:none;margin:0;"></span> Loading…</div>'
            );

            $.post(newsai_vars.ajax_url, {
                action: 'newsai_pro_author_perf_expanded',
                nonce: getNonce(),
                user_id: userId,
                days: days,
                lang: getLang()
            })
                .done(function (resp) {
                    if (resp && resp.success && resp.data && typeof resp.data.html === 'string') {
                        var $body = $expand.find('.nros-author-perf-expand-body');
                        $body.html(resp.data.html);
                        $expand.attr('data-loaded', '1').attr('data-days-loaded', String(days));
                        initTabsIn($body);
                    } else {
                        $expand.find('.nros-author-perf-expand-body').html('<p class="nros-ap-note is-bad">Load error.</p>');
                    }
                })
                .fail(function () {
                    $expand.find('.nros-author-perf-expand-body').html('<p class="nros-ap-note is-bad">Network error.</p>');
                })
                .always(function () {
                    $btn.data('apBusy', 0);
                });
        });

        $panel.on('click', '#nros-ap-ai-overview-btn', function (e) {
            e.preventDefault();
            if ($panel.attr('data-ai-ready') !== '1') {
                return;
            }
            function apEsc(text) {
                return $('<div/>').text(String(text || '')).html();
            }
            var $btnAi = $(this);
            var $outAi = $('#nros-ap-ai-overview-output');
            if (!$outAi.length) {
                return;
            }
            var days = parseInt($panel.attr('data-days'), 10) || 30;
            var loadingMsg = String($panel.attr('data-ai-loading') || 'Building AI desk overview…');
            var errMsg = String($panel.attr('data-ai-error') || 'Could not generate overview.');
            var origAi = $btnAi.text();
            $btnAi.prop('disabled', true).text('⏳ ' + loadingMsg.replace(/^⏳\s*/, ''));
            $outAi.prop('hidden', false).html('<p class="nros-ap-ai-overview__loading"><span class="spinner is-active" style="float:none;margin:0 8px 0 0;"></span>' + loadingMsg + '</p>');
            $.post(newsai_vars.ajax_url, {
                action: 'newsai_ai_author_desk_overview',
                nonce: newsai_vars.nonce,
                days: days
            })
                .done(function (resp) {
                    if (resp && resp.success && resp.data && typeof resp.data.html === 'string') {
                        $outAi.html(resp.data.html);
                    } else {
                        var msg = (resp && resp.data && resp.data.message) || errMsg;
                        $outAi.html('<p class="nros-ap-note is-bad">' + apEsc(msg) + '</p>');
                    }
                })
                .fail(function (xhr) {
                    var msg = (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) || errMsg;
                    $outAi.html('<p class="nros-ap-note is-bad">' + apEsc(msg) + '</p>');
                })
                .always(function () {
                    $btnAi.prop('disabled', false).text(origAi);
                });
        });
    });
})(jQuery);
