/**
 * Contentosapp Studio Admin — Content Hub interactions (Unified table).
 */
/* global CostudioData */
(function ($) {
    'use strict';

    var data = window.CostudioData || {};
    var ajax = data.ajax_url || '';
    var nonce = data.nonce || '';
    var i18n = data.i18n || {};
    function t(key, fallback) {
        return (typeof i18n[key] === 'string' && i18n[key].length) ? i18n[key] : fallback;
    }

    if (!$('#fos-central-table-wrap, #fos-add-plan-btn, #fos-filter-form').length) {
        return;
    }

    function esc(str) {
        return $('<div>').text(str).html();
    }

    // ── Central table (unified) ──────────────────────────────────────────────────

    var currentSortCol = '';
    var currentSortDir = '';
    var currentHubTab  = 'all';
    var currentPerPage = 10;
    var centralLoadState = {
        xhr: null,
        requestKey: '',
        requestedAt: 0
    };
    var planSuggestionAnimationTimer = null;
    var planAiSuggestions = [];
    var planAiSuggestionsKey = '';
    var planAiSuggestionXhr = null;
    var planAiSuggestionLoading = false;
    var planAiSuggestionRequestId = 0;
    var planAiError = '';
    var planAiErrorKey = '';

    function getCentralFilters() {
        var filters = {
            search: $('#fos-filter-search').val() || '',
            site_key: $('#fos-filter-site-key').val() || '',
            filter_status: $('#fos-filter-status').val() || '',
            filter_priority: $('#fos-filter-priority').val() || '',
            hub_tab: currentHubTab,
            per_page: currentPerPage
        };

        // If a specific tab is active (and not "all"), it can override or complement the status filter.
        // For now, let's keep them complementary but ensure the tab state is sent.
        
        if (currentSortCol) {
            filters.orderby = currentSortCol;
        }
        if (currentSortDir) {
            filters.order = currentSortDir;
        }
        return filters;
    }

    // Navigation Tabs Handler
    $(document).on('click', '.fos-hub-tab', function() {
        var $tab = $(this);
        var filter = $tab.data('filter') || 'all';

        $('.fos-hub-tab').removeClass('is-active');
        $tab.addClass('is-active');

        currentHubTab = filter;

        // Reset the operational status filter when switching tabs to avoid "empty intersection" bugs
        $('#fos-filter-status').val('');

        window.fosLoadCentralTable(1);
    });

    $(document).on('click', '.fos-sortable', function () {
        currentSortCol = $(this).data('orderby');
        currentSortDir = $(this).data('order');
        window.fosLoadCentralTable(1);
    });

    $(document).on('change', '#fos-per-page', function () {
        var val = parseInt($(this).val(), 10);
        if ([10, 20, 50].indexOf(val) === -1) val = 10;
        currentPerPage = val;
        window.fosLoadCentralTable(1);
    });

    /** Inline table skeleton (filters / pagination) — no spinners. */
    function fosCentralTableSkeletonHtml() {
        var th = '<div class="fos-ch-sk-thead" role="presentation">' +
            '<span class="fos-ch-sk-th fos-ch-sk-shimmer"></span>' +
            '<span class="fos-ch-sk-th fos-ch-sk-th--grow fos-ch-sk-shimmer"></span>' +
            '<span class="fos-ch-sk-th fos-ch-sk-shimmer"></span>' +
            '<span class="fos-ch-sk-th fos-ch-sk-shimmer"></span>' +
            '<span class="fos-ch-sk-th fos-ch-sk-shimmer"></span>' +
            '<span class="fos-ch-sk-th fos-ch-sk-shimmer"></span>' +
            '<span class="fos-ch-sk-th fos-ch-sk-th--actions fos-ch-sk-shimmer"></span></div>';
        var rows = '';
        var c;
        for (c = 0; c < 5; c++) {
            rows += '<div class="fos-ch-sk-tr" role="presentation">' +
                '<span class="fos-ch-sk-td fos-ch-sk-shimmer"></span>' +
                '<span class="fos-ch-sk-td fos-ch-sk-td--grow fos-ch-sk-shimmer"></span>' +
                '<span class="fos-ch-sk-td fos-ch-sk-shimmer"></span>' +
                '<span class="fos-ch-sk-td fos-ch-sk-shimmer"></span>' +
                '<span class="fos-ch-sk-td fos-ch-sk-shimmer"></span>' +
                '<span class="fos-ch-sk-td fos-ch-sk-td--badge fos-ch-sk-shimmer"></span>' +
                '<span class="fos-ch-sk-td fos-ch-sk-td--actions fos-ch-sk-shimmer"></span></div>';
        }
        return '<div class="fos-ch-sk-table fos-ch-sk-table--inline" role="presentation">' + th + rows + '</div>';
    }

    /** Reveal real KPI + hub UI after first successful central table load (or on error, so user can retry). */
    function fosRevealContentHubMain() {
        var $sk = $('#fos-content-hub-skeleton');
        if ($sk.length) {
            $sk.remove();
        }
        var $main = $('#fos-content-hub-main');
        if ($main.length && $main[0].hasAttribute && $main[0].hasAttribute('hidden')) {
            $main.removeAttr('hidden');
        }
        $('#fos-content-hub-root').attr('aria-busy', 'false');
    }

    /**
     * Load unified central table HTML + KPIs via AJAX.
     */
    window.fosLoadCentralTable = function (paged, extra) {
        // Backwards compat
        if (typeof paged === 'string') {
            paged = extra;
            extra = arguments[2];
        }

        var filters = getCentralFilters();
        
        // If an operational status filter is selected, it takes precedence over the high-level tab
        // except if the tab is meant to be the master filter. 
        // Strategy: if status is set, we ensure hub_tab reflects that or is "all".
        if (filters.filter_status && currentHubTab !== 'all') {
            // Check if status belongs to current tab. If not, reset tab to all.
            var belongs = false;
            if (currentHubTab === 'planned' && filters.filter_status === 'planned') belongs = true;
            if (currentHubTab === 'producing' && ['producing', 'queued', 'error'].indexOf(filters.filter_status) > -1) belongs = true;
            if (currentHubTab === 'completed' && ['published', 'draft'].indexOf(filters.filter_status) > -1) belongs = true;
            
            if (!belongs) {
                currentHubTab = 'all';
                $('.fos-hub-tab').removeClass('is-active');
                $('.fos-hub-tab[data-filter="all"]').addClass('is-active');
                filters.hub_tab = 'all';
            }
        }

        var params = $.extend({
            action: 'costudio_get_central_table',
            nonce: nonce,
            paged: paged || 1,
        }, filters, extra || {});
        var requestKey = JSON.stringify(params);
        var now = Date.now();

        if (centralLoadState.xhr && centralLoadState.requestKey === requestKey && (now - centralLoadState.requestedAt) < 500) {
            return;
        }
        if (centralLoadState.xhr && centralLoadState.xhr.readyState !== 4) {
            centralLoadState.xhr.abort();
        }
        centralLoadState.requestKey = requestKey;
        centralLoadState.requestedAt = now;

        var $main = $('#fos-content-hub-main');
        var shellPending = $main.length && $main[0].hasAttribute && $main[0].hasAttribute('hidden');
        if (!shellPending) {
            $('#fos-central-table-wrap').html(fosCentralTableSkeletonHtml());
        }

        centralLoadState.xhr = $.post(ajax, params)
            .done(function (res) {
                if (!res.success) {
                    var errMsg = t('error', 'Error');
                    if (res.data) {
                        if (typeof res.data === 'string') {
                            errMsg = res.data;
                        } else if (res.data.message) {
                            errMsg = res.data.message;
                        }
                    }
                    $('#fos-central-table-wrap').html(
                        '<div class="cts-panel__empty" style="padding:40px 24px;text-align:center">' +
                        esc(errMsg) + '</div>'
                    );
                    fosRevealContentHubMain();
                    return;
                }

                $('#fos-central-table-wrap').html(res.data.html);
                $(document).trigger('fos:table-loaded');

                // Update KPI values (Content Hub redesign)
                var kpis = res.data.kpis || {};
                if (kpis.articles_total_fmt !== undefined) {
                    $('#fos-kpi-articles-total').text(kpis.articles_total_fmt);
                }
                if (kpis.published_month_fmt !== undefined) {
                    $('#fos-kpi-published-month').text(kpis.published_month_fmt);
                }
                if (kpis.pub_trend_text !== undefined) {
                    $('#fos-kpi-pub-trend').text(kpis.pub_trend_text)
                        .attr('class', kpis.pub_trend_class || 'fos-kpi-trend');
                }
                if (kpis.hours_saved_fmt !== undefined) {
                    $('#fos-kpi-hours').text(kpis.hours_saved_fmt);
                }
                if (kpis.hours_sub !== undefined) {
                    $('#fos-kpi-hours-line').text(kpis.hours_sub);
                }
                if (kpis.curr_month_articles !== undefined) {
                    $('#fos-kpi-pace-current').text(kpis.curr_month_articles);
                }
                if (kpis.pace_trend_text !== undefined) {
                    $('#fos-kpi-pace-trend').text(kpis.pace_trend_text)
                        .attr('class', kpis.pace_trend_class || 'fos-kpi-trend');
                }
                if (kpis.pace_avg_line !== undefined) {
                    $('#fos-kpi-pace-avg-line').text(kpis.pace_avg_line);
                }

                fosRevealContentHubMain();

                // Re-bind paginate_links interceptor
                bindPaginationLinks();

                history.replaceState(null, '', location.pathname + '?page=costudio-studio&tab=hub&paged=' + (paged || 1));
            })
            .fail(function (xhr, statusText) {
                if (statusText === 'abort') {
                    return;
                }
                $('#fos-central-table-wrap').html(
                    '<div class="cts-panel__empty" style="padding:40px 24px;text-align:center">' +
                    t('error', 'Error') + '</div>'
                );
                fosRevealContentHubMain();
            })
            .always(function () {
                centralLoadState.xhr = null;
            });
    };

    function bindPaginationLinks() {
        $('#fos-central-table-wrap').find('.page-numbers').not('.dots').on('click', function (e) {
            e.preventDefault();
            var href = $(this).attr('href') || '';
            var match = href.match(/paged=(\d+)/);
            var pg = match ? parseInt(match[1], 10) : 1;
            window.fosLoadCentralTable(pg);
        });
    }

    // Publish draft production from Content Hub
    $(document).on('click', '.fos-publish-production-btn', function () {
        var id = $(this).data('id');
        if (!id) return;
        if (!window.confirm(t('confirm_publish', 'Publish this article to WordPress?'))) return;
        var $btn = $(this);
        $btn.prop('disabled', true);
        $.post(ajax, { action: 'costudio_publish', nonce: nonce, production_id: id })
            .done(function (res) {
                if (res.success) {
                    sessionStorage.removeItem('costudio_from_wizard');
                    window.fosLoadCentralTable(1);
                } else {
                    alert(res.data || t('error', 'Error'));
                }
            })
            .always(function () { $btn.prop('disabled', false); });
    });

    // Retry failed production from Content Hub
    $(document).on('click', '.fos-retry-production-btn', function () {
        var id = $(this).data('id');
        var fromAgent = parseInt($(this).data('from-agent'), 10) || 1;
        if (!id) return;
        var $btn = $(this);
        $btn.prop('disabled', true);
        $.post(ajax, {
            action: 'costudio_retry_agent',
            nonce: nonce,
            production_id: id,
            from_agent: fromAgent
        })
            .done(function (res) {
                if (res.success) {
                    window.fosLoadCentralTable(1);
                } else {
                    alert(res.data || t('error', 'Error'));
                }
            })
            .always(function () { $btn.prop('disabled', false); });
    });

    // ── Plan modal ───────────────────────────────────────────────────────────────

    $(document).on('click', '.fos-edit-plan-btn', function () {
        var id = $(this).data('id');
        openPlanModal(id);
    });

    $(document).on('click', '#fos-add-plan-btn', function () {
        openPlanModal(0);
    });

    $(document).on('click', '#fos-plan-modal-close, #fos-plan-modal-cancel, #fos-plan-modal', function (e) {
        if (e.target === this) $('#fos-plan-modal').fadeOut(150);
    });

    /** Priority select: left border color (high / medium / low). */
    function fosPlanPrioritySyncClass() {
        var $p = $('#fos-plan-priority');
        if (!$p.length) return;
        var v = $p.val() || 'medium';
        $p.removeClass('fos-plan-priority-select--high fos-plan-priority-select--medium fos-plan-priority-select--low');
        $p.addClass('fos-plan-priority-select--' + v);
    }

    $(document).on('change', '#fos-plan-priority', fosPlanPrioritySyncClass);

    function normalizePlanKeyword(value) {
        return $.trim(String(value || '').replace(/\s+/g, ' '));
    }

    function getPlanSuggestionContextKey() {
        return [
            normalizePlanKeyword($('#fos-plan-keyword').val()).toLowerCase(),
            $('#fos-plan-site-key').val() || '',
            normalizePlanKeyword($('#fos-plan-category').val()).toLowerCase()
        ].join('|');
    }

    function clearPlanAiSuggestions(abortRequest) {
        planAiSuggestionRequestId++;
        planAiSuggestions = [];
        planAiSuggestionsKey = '';
        planAiError = '';
        planAiErrorKey = '';
        planAiSuggestionLoading = false;

        if (abortRequest && planAiSuggestionXhr && planAiSuggestionXhr.readyState !== 4) {
            planAiSuggestionXhr.abort();
        }
        planAiSuggestionXhr = null;
    }

    function hidePlanTitleSuggestions() {
        var $box = $('#fos-plan-title-suggestions');
        if (!$box.length) return;

        if (planSuggestionAnimationTimer) {
            clearTimeout(planSuggestionAnimationTimer);
            planSuggestionAnimationTimer = null;
        }

        $box.attr('hidden', 'hidden').removeClass('is-entering').empty().data('suggestionsKey', '');
    }

    function animatePlanTitleSuggestions($box) {
        if (planSuggestionAnimationTimer) {
            clearTimeout(planSuggestionAnimationTimer);
        }

        $box.removeClass('is-entering');
        if ($box[0]) {
            $box[0].offsetHeight;
        }
        $box.addClass('is-entering');

        planSuggestionAnimationTimer = setTimeout(function () {
            $box.removeClass('is-entering');
            planSuggestionAnimationTimer = null;
        }, 520);
    }

    function getPlanAiErrorMessage(res, fallback) {
        if (res && res.responseJSON && res.responseJSON.data) {
            if (typeof res.responseJSON.data === 'string') {
                return res.responseJSON.data;
            }
            if (res.responseJSON.data.message) {
                return res.responseJSON.data.message;
            }
        }

        if (res && res.data) {
            if (typeof res.data === 'string') {
                return res.data;
            }
            if (res.data.message) {
                return res.data.message;
            }
        }

        return fallback;
    }

    function renderPlanTitleSuggestions() {
        var $box = $('#fos-plan-title-suggestions');
        if (!$box.length) return;

        if (normalizePlanKeyword($('#fos-plan-title').val()).length) {
            hidePlanTitleSuggestions();
            return;
        }

        var contextKey = getPlanSuggestionContextKey();
        var hasAiSuggestions = planAiSuggestionsKey === contextKey && planAiSuggestions.length > 0;
        var suggestions = hasAiSuggestions ? planAiSuggestions : [];
        if (!suggestions.length) {
            hidePlanTitleSuggestions();
            syncPlanTitleAiButton();
            return;
        }

        var suggestionsKey = [
            'ai',
            contextKey,
            planAiSuggestionLoading ? 'loading' : 'idle',
            planAiErrorKey === contextKey ? planAiError : '',
            suggestions.join('||')
        ].join('::');
        if (!$box.is('[hidden]') && $box.data('suggestionsKey') === suggestionsKey) {
            return;
        }

        var html = '<div class="fos-title-suggestions__head">';
        html += '<div class="fos-title-suggestions__label">' + esc(t('title_ai_suggestions_label', 'AI suggestions')) + '</div>';
        html += '</div>';
        html += '<div class="fos-title-suggestions__chips">';
        $.each(suggestions, function (_, title) {
            html += '<button type="button" class="fos-title-suggestion-chip" data-title="' + esc(title) + '">' + esc(title) + '</button>';
        });
        html += '</div>';
        if (!hasAiSuggestions && planAiErrorKey === contextKey && planAiError) {
            html += '<div class="fos-title-suggestions__notice">' + esc(planAiError) + '</div>';
        }

        $box.html(html).data('suggestionsKey', suggestionsKey).removeAttr('hidden');
        animatePlanTitleSuggestions($box);
        syncPlanTitleAiButton();
    }

    function syncPlanTitleAiButton() {
        var $btn = $('#fos-plan-title-ai-btn');
        if (!$btn.length) return;

        var canAskAi = normalizePlanKeyword($('#fos-plan-keyword').val()).length >= 4;
        $btn
            .prop('disabled', !canAskAi || planAiSuggestionLoading)
            .toggleClass('is-loading', planAiSuggestionLoading)
            .attr('aria-busy', planAiSuggestionLoading ? 'true' : 'false');
    }

    $(document).on('input', '#fos-plan-keyword', function () {
        clearPlanAiSuggestions(true);
        hidePlanTitleSuggestions();
        syncPlanTitleAiButton();
    });
    $(document).on('input', '#fos-plan-title', function () {
        if (normalizePlanKeyword($(this).val()).length) {
            hidePlanTitleSuggestions();
        } else {
            renderPlanTitleSuggestions();
        }
        syncPlanTitleAiButton();
    });
    $(document).on('change', '#fos-plan-site-key, #fos-plan-category', function () {
        clearPlanAiSuggestions(true);
        hidePlanTitleSuggestions();
        syncPlanTitleAiButton();
    });

    $(document).on('click', '#fos-plan-title-ai-btn', function () {
        var keyword = normalizePlanKeyword($('#fos-plan-keyword').val());
        if (keyword.length < 4 || planAiSuggestionLoading) return;

        var contextKey = getPlanSuggestionContextKey();
        var requestId = ++planAiSuggestionRequestId;
        planAiSuggestionLoading = true;
        planAiError = '';
        planAiErrorKey = '';
        hidePlanTitleSuggestions();
        syncPlanTitleAiButton();

        if (planAiSuggestionXhr && planAiSuggestionXhr.readyState !== 4) {
            planAiSuggestionXhr.abort();
        }

        planAiSuggestionXhr = $.post(ajax, {
            action: 'costudio_suggest_plan_titles',
            nonce: nonce,
            keyword: keyword,
            site_key: $('#fos-plan-site-key').val() || '',
            category: $('#fos-plan-category').val() || ''
        })
            .done(function (res) {
                if (requestId !== planAiSuggestionRequestId || contextKey !== getPlanSuggestionContextKey()) return;

                var suggestions = (res && res.success && res.data && $.isArray(res.data.suggestions))
                    ? res.data.suggestions
                    : [];

                if (suggestions.length) {
                    planAiSuggestions = suggestions.slice(0, 3);
                    planAiSuggestionsKey = contextKey;
                    planAiError = '';
                    planAiErrorKey = '';
                } else {
                    planAiSuggestions = [];
                    planAiSuggestionsKey = '';
                    planAiError = t('title_ai_failed_soft', 'Could not generate AI suggestions right now.');
                    planAiErrorKey = contextKey;
                }
            })
            .fail(function (res) {
                if (res && res.statusText === 'abort') return;
                if (requestId !== planAiSuggestionRequestId || contextKey !== getPlanSuggestionContextKey()) return;

                planAiSuggestions = [];
                planAiSuggestionsKey = '';
                planAiError = getPlanAiErrorMessage(res, t('title_ai_failed_soft', 'Could not generate AI suggestions right now.'));
                planAiErrorKey = contextKey;
            })
            .always(function () {
                if (requestId !== planAiSuggestionRequestId) return;

                planAiSuggestionLoading = false;
                planAiSuggestionXhr = null;
                renderPlanTitleSuggestions();
                syncPlanTitleAiButton();
            });
    });

    $(document).on('click', '.fos-title-suggestion-chip', function () {
        var title = $(this).attr('data-title') || $(this).text();
        $('#fos-plan-title').val(title).trigger('input').trigger('focus');
    });

    function openPlanModal(id) {
        clearPlanAiSuggestions(true);
        $('#fos-plan-id').val(0);
        $('#fos-plan-title, #fos-plan-keyword, #fos-plan-date').val('');
        $('#fos-plan-priority').val('medium');
        fosPlanPrioritySyncClass();
        hidePlanTitleSuggestions();
        $('#fos-plan-modal-title').text(id ? t('edit_plan', 'Edit Idea') : t('add_plan', 'New Idea'));

        if (id) {
            $.get(ajax, { action: 'costudio_get_plan', nonce: nonce, plan_id: id })
                .done(function (res) {
                    if (!res.success) return;
                    var p = res.data;
                    $('#fos-plan-id').val(p.id);
                    $('#fos-plan-title').val(p.title);
                    $('#fos-plan-keyword').val(p.keyword);
                    $('#fos-plan-site-key').val(p.site_key).trigger('change');
                    $('#fos-plan-category').val(p.category);

                    // Ensure date is in YYYY-MM-DD format for input[type="date"]
                    var dateVal = p.planned_date || '';
                    if (dateVal.indexOf(' ') > -1) {
                        dateVal = dateVal.split(' ')[0];
                    }
                    $('#fos-plan-date').val(dateVal);

                    $('#fos-plan-priority').val(p.priority);
                    fosPlanPrioritySyncClass();
                    renderPlanTitleSuggestions();
                });
        }

        $('#fos-plan-modal').fadeIn(180, function () {
            $('#fos-plan-keyword').trigger('focus');
        });
    }

    $(document).on('submit', '#fos-plan-form', function (e) {
        e.preventDefault();
        var $btn = $('#fos-plan-save-btn');
        $btn.prop('disabled', true);

        $.post(ajax, {
            action: 'costudio_save_plan',
            nonce: nonce,
            plan_id: $('#fos-plan-id').val(),
            title: $('#fos-plan-title').val(),
            keyword: $('#fos-plan-keyword').val(),
            site_key: $('#fos-plan-site-key').val(),
            category: $('#fos-plan-category').val(),
            planned_date: $('#fos-plan-date').val(),
            priority: $('#fos-plan-priority').val(),
        })
            .done(function (res) {
                if (res.success) {
                    $('#fos-plan-modal').fadeOut(150);
                    window.fosLoadCentralTable(1);
                } else {
                    alert(res.data || t('error', 'Error'));
                }
            })
            .always(function () { $btn.prop('disabled', false); });
    });

    // Plan site_key → categories cascade
    $(document).on('change', '#fos-plan-site-key', function () {
        var key = $(this).val();
        var cats = (data.site_cats || {})[key] || [];
        var $sel = $('#fos-plan-category');
        $sel.empty().append('<option value="">— ' + esc(t('any_category', 'Any Category')) + ' —</option>');
        $.each(cats, function (_, cat) {
            $sel.append('<option value="' + esc(cat) + '">' + esc(cat) + '</option>');
        });
    });

    // Delete plan row
    $(document).on('click', '.fos-delete-plan-btn', function () {
        if (!window.confirm(t('confirm_delete', 'Delete?'))) return;
        var id = $(this).data('id');
        $.post(ajax, { action: 'costudio_delete_plan', nonce: nonce, plan_id: id })
            .done(function (res) {
                if (res.success) {
                    window.fosLoadCentralTable(1);
                }
            });
    });

    // Delete production row
    $(document).on('click', '.fos-delete-production-btn', function () {
        if (!window.confirm(t('confirm_delete', 'Delete?'))) return;
        var id = $(this).data('id');
        $.post(ajax, { action: 'costudio_delete_production', nonce: nonce, production_id: id })
            .done(function (res) {
                if (res.success) {
                    window.fosLoadCentralTable(1);
                }
            });
    });

    // ── Sync remote posts ─────────────────────────────────────────────────────

    $(document).on('click', '#fos-sync-posts-btn', function () {
        var $btn = $(this);
        var orig = $btn.html();
        var site_key = $('#fos-filter-site-key').val() || '';
        $btn.html('⏳ ' + t('syncing', 'Syncing…')).prop('disabled', true);

        $.post(ajax, { action: 'costudio_sync_posts', nonce: nonce, site_key: site_key })
            .done(function (res) {
                $btn.html(orig).prop('disabled', false);
                if (res.success) {
                    var msg = t('sync_imported', 'Imported:') + ' ' + res.data.imported;
                    if (res.data.errors && res.data.errors.length) {
                        msg += ' | ' + t('sync_errors', 'Errors:') + ' ' + res.data.errors.join(', ');
                    }
                    alert(msg);
                    window.fosLoadCentralTable(1);
                } else {
                    alert(res.data || t('sync_failed', 'Sync failed.'));
                }
            })
            .fail(function () { $btn.html(orig).prop('disabled', false); });
    });

    // ── Bulk Actions & Selection Helpers ──────────────────────────────────────

    function fosGetSelectedIds() {
        var ids = [];
        $('#fos-central-table-wrap .fos-row-checkbox:checked').each(function () {
            ids.push($(this).val());
        });
        return ids;
    }

    /** Determine source (plan/production) for each selected row. */
    function fosGetSelectedItems() {
        var items = [];
        $('#fos-central-table-wrap .fos-row-checkbox:checked').each(function () {
            var $tr = $(this).closest('tr');
            items.push({
                id: $(this).val(),
                source: $tr.data('source') || 'production'
            });
        });
        return items;
    }

    function fosSyncBulkBar() {
        var count = fosGetSelectedIds().length;
        var $bar = $('#fos-bulk-bar');
        var $legacyCsv = $('#fos-export-csv-btn');

        if ($legacyCsv.length) {
            $legacyCsv.html(count > 0 ? '↓ CSV <span class="fos-csv-count">' + count + '</span>' : '↓ CSV');
        }

        if (!$bar.length) return;

        if (count > 0) {
            $bar.find('.fos-bulk-count-num').text(count);
            $bar.addClass('is-visible');
        } else {
            $bar.removeClass('is-visible');
            $('#fos-bulk-priority').val('');
        }
    }

    // Select-all checkbox in thead
    $(document).on('change', '.fos-select-all-rows', function () {
        var checked = $(this).prop('checked');
        $('#fos-central-table-wrap .fos-row-checkbox').prop('checked', checked);
        fosSyncBulkBar();
    });

    // Individual row checkbox
    $(document).on('change', '#fos-central-table-wrap .fos-row-checkbox', function () {
        var total   = $('#fos-central-table-wrap .fos-row-checkbox').length;
        var checked = $('#fos-central-table-wrap .fos-row-checkbox:checked').length;
        $('.fos-select-all-rows').prop('indeterminate', checked > 0 && checked < total)
                                 .prop('checked', checked === total && total > 0);
        fosSyncBulkBar();
    });

    // Reset selection when table reloads
    $(document).on('fos:table-loaded', function () {
        fosSyncBulkBar();
    });

    // Bulk action dispatch helper — uses data-source to determine per-row type
    function fosDispatchBulkAction(bulkAction, bulkValue) {
        var items = fosGetSelectedItems();
        if (items.length === 0) return;

        var payload = {
            action: 'costudio_bulk_action',
            nonce: nonce,
            bulk_action: bulkAction,
            items: items
        };

        if (bulkValue !== undefined) {
            payload.bulk_value = bulkValue;
        }

        $('#fos-bulk-bar').css('opacity', '0.5').css('pointer-events', 'none');

        $.post(ajax, payload)
            .done(function (res) {
                if (res.success) {
                    window.fosLoadCentralTable(1);
                } else {
                    alert(res.data || t('error', 'Error'));
                }
            })
            .always(function () {
                $('#fos-bulk-bar').css('opacity', '').css('pointer-events', '');
                $('#fos-bulk-priority').val('');
            });
    }

    // Bulk Delete
    $(document).on('click', '#fos-bulk-delete-btn', function () {
        if (!window.confirm(t('confirm_delete', 'Delete selected items?'))) return;
        fosDispatchBulkAction('delete');
    });

    // Bulk Priority
    $(document).on('change', '#fos-bulk-priority', function () {
        var val = $(this).val();
        if (!val) return;
        fosDispatchBulkAction('priority', val);
    });

    // Bulk Export CSV (reusing original logic but from bulk button + legacy button)
    $(document).on('click', '#fos-bulk-export-btn, #fos-export-csv-btn', function () {
        var $btn = $(this);
        var ids  = fosGetSelectedIds();
        $btn.prop('disabled', true);

        var payload = { action: 'costudio_export_csv', nonce: nonce };
        if (ids.length > 0) {
            payload.ids = ids;
        }

        $.post(ajax, payload)
            .done(function (res) {
                $btn.prop('disabled', false);
                if (!res.success) { alert(res.data); return; }
                var bytes = atob(res.data.content);
                var arr = new Uint8Array(bytes.length);
                for (var i = 0; i < bytes.length; i++) arr[i] = bytes.charCodeAt(i);
                var blob = new Blob([arr], { type: 'text/csv' });
                var url = URL.createObjectURL(blob);
                var a = document.createElement('a');
                a.href = url; a.download = res.data.filename;
                a.click(); URL.revokeObjectURL(url);
            })
            .fail(function () { $btn.prop('disabled', false); });
    });

    // ── Central filter form ───────────────────────────────────────────────────

    $(document).on('submit', '#fos-filter-form', function (e) {
        e.preventDefault();
        window.fosLoadCentralTable(1);
    });

    // Auto-trigger on select change
    $(document).on('change', '#fos-filter-site-key, #fos-filter-status, #fos-filter-priority', function() {
        window.fosLoadCentralTable(1);
    });

    // Debounced search on input
    var searchTimer;
    $(document).on('input', '#fos-filter-search', function() {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(function() {
            window.fosLoadCentralTable(1);
        }, 500);
    });

    // Auto-load central table on page load (if the wrapper exists).
    $(document).ready(function () {
        if ($('#fos-central-table-wrap').length) {
            window.fosLoadCentralTable(1);
        }
    });

    // Content Hub view injected via Module Hub AJAX — re-init central table loader.
    $(document).on('contentos:module-view-loaded', function (e, moduleId, viewKey) {
        if (moduleId === 'costudio' && viewKey === 'central') {
            if (typeof window.fosLoadCentralTable !== 'function') {
                return;
            }
            window.fosLoadCentralTable(1);
        }
    });


}(jQuery));
