/**
 
/* global sitsHFAdmin, jQuery */
(function ($) {
    'use strict';

    var cfg = window.sitsHFAdmin || {};
    var s   = cfg.strings || {};

    /* ====================================================================
     * AJAX helper
     * ==================================================================== */
    function sitsAjax(data, onSuccess, onError) {
        $.ajax({
            url: cfg.ajaxurl, type: 'POST', data: data,
            success: function (res) {
                if (res.success) { onSuccess(res); }
                else { onError(res.data && res.data.message ? res.data.message : s.error, res.data); }
            },
            error: function () { onError(s.error, {}); }
        });
    }

    function sitsRedirectOrReload(res) {
        window.location.href = (res.data && res.data.redirect) ? res.data.redirect : window.location.href;
    }

    function showListNotice(msg, type) {
        var cls = type === 'error' ? 'notice-error' : 'notice-success';
        var $n = $('<div class="notice ' + cls + ' is-dismissible" style="margin:5px 0 15px;"><p>' + msg + '</p></div>');
        $('.wp-list-table').before($n);
        setTimeout(function () { $n.fadeOut(400, function(){ $n.remove(); }); }, 8000);
    }

    /* ====================================================================
     * Activate / Deactivate – row action links
     * ==================================================================== */
    $(document).on('click', '.sits-activate-hf-link', function (e) {
        e.preventDefault();
        var $link = $(this), url = new URL($link.attr('href'), window.location.origin);
        var tid = url.searchParams.get('template_id'), type = url.searchParams.get('type'), nonce = url.searchParams.get('_wpnonce');
        if (!tid || !type || !nonce) { alert(s.error); return; }
        var orig = $link.html();
        $link.html('<span class="spinner is-active" style="float:none;display:inline-block;margin:0;vertical-align:middle;"></span>');
        sitsAjax({ action: 'sits_activate_hf_template', template_id: tid, type: type, _wpnonce: nonce },
            function (res) { sitsRedirectOrReload(res); },
            function (msg, data) { $link.html(orig); showListNotice(data && data.conflict ? msg : (s.error + ': ' + msg), 'error'); }
        );
    });

    $(document).on('click', '.sits-deactivate-hf-link', function (e) {
        e.preventDefault();
        if (!confirm(s.confirm_deactivate)) { return; }
        var $link = $(this), url = new URL($link.attr('href'), window.location.origin);
        var tid = url.searchParams.get('template_id'), type = url.searchParams.get('type'), nonce = url.searchParams.get('_wpnonce');
        var orig = $link.html();
        $link.html('<span class="spinner is-active" style="float:none;display:inline-block;margin:0;vertical-align:middle;"></span>');
        sitsAjax({ action: 'sits_deactivate_hf_template', template_id: tid, type: type, _wpnonce: nonce },
            function (res) { sitsRedirectOrReload(res); },
            function (msg) { $link.html(orig); alert(msg); }
        );
    });

    $(document).on('click', '.sits-deactivate-template', function (e) {
        e.preventDefault();
        if (!confirm(s.confirm_deactivate)) { return; }
        var $btn = $(this), tid = $btn.data('template-id'), type = $btn.data('template-type');
        var nonce = (new URL($btn.data('deactivate-url'), window.location.origin)).searchParams.get('_wpnonce');
        $btn.prop('disabled', true).text(s.deactivating);
        sitsAjax({ action: 'sits_deactivate_hf_template', template_id: tid, type: type, _wpnonce: nonce },
            function (res) { $btn.text(s.deactivated); setTimeout(function () { sitsRedirectOrReload(res); }, 900); },
            function (msg) { $btn.prop('disabled', false).text('Deactivate This Template'); alert(msg); }
        );
    });

    /* ====================================================================
     * Condition row helpers — TWO-LEVEL archive dropdown
     * ==================================================================== */

    // All supported template types for the popup type selector
    var TYPE_OPTIONS = [
        { val: 'header',      label: s.header      || 'Header'      },
        { val: 'footer',      label: s.footer      || 'Footer'      },
        { val: 'archive',     label: s.archiveType || 'Archive'     },
        { val: 'single_page', label: s.singlePage  || 'Single Page' },
        { val: 'single_post', label: s.singlePost  || 'Single Post' },
        { val: '404_page',    label: s.page404     || '404 Page'    },
    ];

    // Main condition types (archive sub-types excluded from this list)
    var MAIN_CONDS = [
        { val: 'all',           label: s.entireSite   || 'Entire Website'              },
        { val: 'front_page',    label: 'Front Page'                                     },
        { val: 'blog',          label: s.blogIndexPage || 'Blog Index / Posts Listing Page' },
        { val: 'singular',      label: 'All Singular (Posts & Pages)'                  },
        { val: 'singular_post', label: s.singularPost  || 'All Single Posts'           },
        { val: 'singular_page', label: s.singularPage  || 'All Single Pages'           },
        { val: 'archive',       label: s.archive || 'All Archives'                     },
        { val: '404',           label: '404 Page'                                      }
    ];

    // Archive sub-types that support specific-item search (categories, tags, authors)
    var ARCHIVE_SPECIFIC_TYPES = ['archive_category', 'archive_tag', 'archive_author'];

    // Map archive sub-type to human-friendly search placeholder
    var ARCHIVE_SEARCH_PLACEHOLDER = {
        'archive_category': 'Search categories…',
        'archive_tag':      'Search tags…',
        'archive_author':   'Search authors…'
    };

    // Archive sub-types — shown in a second dropdown when "All Archives" selected
    var ARCHIVE_SUBS = [
        { val: '',                 label: s.archiveAll      || 'All Archives'    },
        { val: 'archive_post',     label: s.archivePost     || 'Posts Archive'   },
        { val: 'archive_author',   label: s.archiveAuthor   || 'Author Archive'  },
        { val: 'archive_date',     label: s.archiveDate     || 'Date Archive'    },
        { val: 'archive_search',   label: s.archiveSearch   || 'Search Results'  },
        { val: 'archive_category', label: s.archiveCategory || 'Post Categories' },
        { val: 'archive_tag',      label: s.archiveTag      || 'Post Tags'       }
    ];

    var ARCHIVE_SUB_VALS = ['archive_post','archive_author','archive_date','archive_search','archive_category','archive_tag'];

    function getAllowedMainConds(templateType) {
        if (templateType === 'single_post') {
            return [
                MAIN_CONDS[0], // all
                MAIN_CONDS[3], // singular
                MAIN_CONDS[4], // singular_post
                MAIN_CONDS[6], // archive
                MAIN_CONDS[7]  // 404
            ];
        }

        if (templateType === '404_page') {
            return [
                MAIN_CONDS[7] // 404
            ];
        }

        return MAIN_CONDS;
    }

    function buildMainOpts(selected, templateType) {
        return getAllowedMainConds(templateType).map(function (c) {
            return '<option value="' + c.val + '"' + (c.val === selected ? ' selected' : '') + '>' + c.label + '</option>';
        }).join('');
    }

    function buildSubOpts(selected, templateType) {
        if (templateType === 'single_post') {
            return '<option value=""' + (selected === '' ? ' selected' : '') + '>' + (s.archiveAll || 'All Archives') + '</option>';
        }

        return ARCHIVE_SUBS.map(function (c) {
            return '<option value="' + c.val + '"' + (c.val === selected ? ' selected' : '') + '>' + c.label + '</option>';
        }).join('');
    }

    /**
     * Build a condition row.
     * row.condition can be a main key or an archive sub-type.
     * row.archSpecific holds pre-selected term/author items for archive sub-types.
     */
    function buildConditionRow(row, templateType) {
        row = row || { include: 'include', condition: 'all', specific: [], archSpecific: [] };

        var isArchiveSub = ARCHIVE_SUB_VALS.indexOf(row.condition) !== -1;
        var mainCond     = isArchiveSub ? 'archive' : row.condition;
        var subCond      = isArchiveSub ? row.condition : '';
        var allowedMain  = getAllowedMainConds(templateType).map(function (c) { return c.val; });

        if (allowedMain.indexOf(mainCond) === -1) {
            mainCond = templateType === 'single_post' ? 'singular_post' : allowedMain[0];
        }

        var specificHtml = '';
        if (row.specific && row.specific.length) {
            $.each(row.specific, function (i, item) { specificHtml += buildSpecificItem(item.id, item.title, item.type); });
        }

        // Fix 4: archive-specific items (categories / tags / authors)
        var showArchSpecific = ARCHIVE_SPECIFIC_TYPES.indexOf(subCond) !== -1;
        var archSpecificHtml = '';
        if (row.archSpecific && row.archSpecific.length) {
            $.each(row.archSpecific, function (i, item) { archSpecificHtml += buildArchSpecificItem(item.id, item.title, item.type); });
        }
        var archLabel = subCond === 'archive_author' ? 'authors' : (subCond === 'archive_tag' ? 'tags' : 'categories');
        var archPlaceholder = ARCHIVE_SEARCH_PLACEHOLDER[subCond] || 'Search\u2026';

        return (
            '<div class="sits-pub-condition-row">' +
                '<select class="sits-pub-include-exclude">' +
                    '<option value="include"' + (row.include !== 'exclude' ? ' selected' : '') + '>Include</option>' +
                    '<option value="exclude"' + (row.include === 'exclude' ? ' selected' : '') + '>Exclude</option>' +
                '</select>' +
                '<select class="sits-pub-condition-type">' + buildMainOpts(mainCond, templateType) + '</select>' +
                '<select class="sits-pub-archive-sub"' + (mainCond !== 'archive' ? ' style="display:none"' : '') + '>' +
                    buildSubOpts(subCond, templateType) +
                '</select>' +
                '<button type="button" class="sits-pub-remove-row" title="Remove">&times;</button>' +
                '<div class="sits-pub-singular-specific"' + (mainCond !== 'singular' ? ' style="display:none"' : '') + '>' +
                    '<input type="text" class="sits-pub-search-specific" placeholder="Search posts or pages\u2026" autocomplete="off">' +
                    '<div class="sits-pub-search-results"></div>' +
                    '<div class="sits-pub-specific-list">' + specificHtml + '</div>' +
                '</div>' +
                '<div class="sits-pub-archive-specific"' + (!showArchSpecific ? ' style="display:none"' : '') +
                    ' data-archive-type="' + (subCond || '') + '">' +
                    '<p style="margin:6px 0 4px;font-size:12px;color:#555;">Narrow to specific ' + archLabel + ' (leave empty to match all):</p>' +
                    '<input type="text" class="sits-pub-search-archive-item" placeholder="' + archPlaceholder + '" autocomplete="off">' +
                    '<div class="sits-pub-archive-search-results"></div>' +
                    '<div class="sits-pub-archive-specific-list">' + archSpecificHtml + '</div>' +
                '</div>' +
            '</div>'
        );
    }

    function syncConditionRowVisibility($row) {
        var val = $row.find('.sits-pub-condition-type').val();
        var subVal = $row.find('.sits-pub-archive-sub').val();
        var showArchSpecific = val === 'archive' && ARCHIVE_SPECIFIC_TYPES.indexOf(subVal) !== -1;
        $row.find('.sits-pub-archive-sub')[val === 'archive' ? 'slideDown' : 'slideUp'](200);
        $row.find('.sits-pub-singular-specific')[val === 'singular' ? 'slideDown' : 'slideUp'](200);
        $row.find('.sits-pub-archive-specific')[showArchSpecific ? 'slideDown' : 'slideUp'](200)
            .attr('data-archive-type', showArchSpecific ? subVal : '');
    }

    function refreshConditionRowsForTemplateType($popup, templateType) {
        var allowed = getAllowedMainConds(templateType).map(function (c) { return c.val; });
        var fallback = templateType === 'single_post' ? 'singular_post' : allowed[0];

        $popup.find('.sits-pub-condition-row').each(function () {
            var $row = $(this);
            var $select = $row.find('.sits-pub-condition-type');
            var $subSelect = $row.find('.sits-pub-archive-sub');
            var current = $select.val();
            var currentSub = $subSelect.val();
            var next = current;

            if (allowed.indexOf(current) === -1) {
                next = fallback;
            }

            $select.html(buildMainOpts(next, templateType));
            $select.val(next);
            $subSelect.html(buildSubOpts(currentSub, templateType));
            if (templateType === 'single_post') {
                $subSelect.val('');
            }
            syncConditionRowVisibility($row);
        });
    }

    function buildSpecificItem(id, title, type) {
        return (
            '<div class="sits-pub-specific-item" data-id="' + id + '">' +
                '<span><strong>' + title + '</strong> <em>(' + type + ')</em></span>' +
                '<button type="button" class="sits-pub-remove-specific" data-id="' + id + '">&times;</button>' +
            '</div>'
        );
    }

    // Fix 4: chip for a selected archive-specific item (category/tag/author)
    function buildArchSpecificItem(id, title, type) {
        return (
            '<div class="sits-pub-specific-item sits-pub-arch-item" data-id="' + id + '" data-type="' + type + '">' +
                '<span><strong>' + title + '</strong> <em>(' + type + ')</em></span>' +
                '<button type="button" class="sits-pub-remove-arch-item" data-id="' + id + '">&times;</button>' +
            '</div>'
        );
    }

    /**
     * Gather all conditions from a popup.
     * Resolves the two-level archive dropdown into the correct condition key.
     */
    function gatherConditions($popup) {
        var display_on = [], exclude_on = [], specific_ids = [], exclude_ids = [];
        var archive_terms_include = {}, archive_terms_exclude = {};

        $popup.find('.sits-pub-condition-row').each(function () {
            var $row = $(this);
            var inc  = $row.find('.sits-pub-include-exclude').val();
            var cond = $row.find('.sits-pub-condition-type').val();
            var ids  = [];

            // Resolve archive sub-type
            if (cond === 'archive') {
                var sub = $row.find('.sits-pub-archive-sub').val();
                if (sub) { cond = sub; }
            }

            if (cond === 'singular') {
                $row.find('.sits-pub-specific-item').each(function () { ids.push($(this).data('id')); });
            }

            // Fix 4: collect archive-specific term IDs (categories/tags/authors)
            if (ARCHIVE_SPECIFIC_TYPES.indexOf(cond) !== -1) {
                var archIds = [];
                $row.find('.sits-pub-archive-specific-list .sits-pub-arch-item').each(function () {
                    archIds.push(String($(this).data('id')));
                });
                if (archIds.length) {
                    if (inc === 'exclude') { archive_terms_exclude[cond] = archIds; }
                    else                   { archive_terms_include[cond] = archIds; }
                }
            }

            if (inc === 'exclude') {
                if ($.inArray(cond, exclude_on) === -1) exclude_on.push(cond);
                if (cond === 'singular') exclude_ids = exclude_ids.concat(ids);
            } else {
                if ($.inArray(cond, display_on) === -1) display_on.push(cond);
                if (cond === 'singular') specific_ids = specific_ids.concat(ids);
            }
        });
        return {
            display_on: display_on,
            exclude_on: exclude_on,
            specific_ids: specific_ids,
            exclude_ids: exclude_ids,
            archive_terms_include: archive_terms_include,
            archive_terms_exclude: archive_terms_exclude
        };
    }

    /* ====================================================================
     * Popup error helpers
     * ==================================================================== */
    function showPopupError($popup, msg) {
        var $err = $popup.find('.sits-pub-error-msg'), $body = $popup.find('.sits-pub-modal-body');
        $err.html('<span class="sits-err-icon">&#9888;</span> ' + msg).show();
        $body.animate({ scrollTop: $body[0].scrollHeight }, 250);
    }
    function hidePopupError($popup) { $popup.find('.sits-pub-error-msg').hide().empty(); }

    
    function buildPopupHtml(data, isCreate) {
        var currentTitle = (data && data.post_title)    || '';
        var currentType  = (data && data.template_type) || '';
        var conditions   = (data && data.conditions)    || [];
        var condHtml = conditions.length ? '' : buildConditionRow(null, currentType);
        $.each(conditions, function (i, row) { condHtml += buildConditionRow(row, currentType); });

        var headingText = isCreate
            ? (s.createTemplate || 'CREATE TEMPLATE')
            : 'TEMPLATE SETTINGS';
        var saveLbl = isCreate
            ? (s.createAndEdit || 'Create &amp; Edit with Elementor')
            : 'Save Settings';

        // Title field — only shown for Create Template popup
        var titleSection = isCreate
            ? ('<div class="sits-pub-section">' +
                '<div class="sits-pub-section-icon sits-icon-title">&#9998;</div>' +
                '<div class="sits-pub-section-content">' +
                    '<label class="sits-pub-section-label">' + (s.templateTitle || 'Template Title') + '</label>' +
                    '<input type="text" class="sits-pub-template-title widefat" placeholder="' + (s.templateTitlePlaceholder || 'Enter template title…') + '" value="' + currentTitle + '" autocomplete="off">' +
                '</div>' +
              '</div>')
            : '';

        var typeOptionsHtml = TYPE_OPTIONS.map(function (t) {
            return '<option value="' + t.val + '"' + (currentType === t.val ? ' selected' : '') + '>' + t.label + '</option>';
        }).join('');

        return (
            '<div class="sits-pub-overlay">' +
                '<div class="sits-pub-modal">' +
                    '<div class="sits-pub-modal-header">' +
                        '<span class="sits-pub-modal-icon">&#9881;</span>' +
                        '<h2>' + headingText + '</h2>' +
                        '<button type="button" class="sits-pub-modal-close">&times;</button>' +
                    '</div>' +
                    '<div class="sits-pub-modal-body">' +
                        titleSection +
                        '<div class="sits-pub-section">' +
                            '<div class="sits-pub-section-icon sits-icon-type">&#9776;</div>' +
                            '<div class="sits-pub-section-content">' +
                                '<label class="sits-pub-section-label">Template Type</label>' +
                                '<select class="sits-pub-type-select">' +
                                    '<option value="">\u2014 Select Type \u2014</option>' +
                                    typeOptionsHtml +
                                '</select>' +
                            '</div>' +
                        '</div>' +
                    '<div class="sits-pub-section sits-pub-section-conditions">' +
                            '<div class="sits-pub-section-icon sits-icon-cond">&#9654;</div>' +
                            '<div class="sits-pub-section-content" style="flex:1">' +
                                '<label class="sits-pub-section-label">Where do you want to display your template?</label>' +
                                '<p class="sits-pub-section-desc">Set the conditions that determine where your template is displayed.<br>For example, choose \u2018Entire Website\u2019 to display everywhere.</p>' +
                                '<div class="sits-pub-conditions-list">' + condHtml + '</div>' +
                                '<button type="button" class="sits-pub-add-cond-btn"><span class="dashicons dashicons-plus-alt2"></span> Add condition</button>' +
                            '</div>' +
                        '</div>' +
                        '<div class="sits-pub-error-msg" style="display:none"></div>' +
                        '<div class="sits-pub-force-save-wrap" style="display:none;margin-top:12px;padding:10px 14px;background:#083d490a;border:1px solid #083d49;border-radius:4px;">' +
                            '<label style="display:flex;align-items:center;gap:8px;color:#083d49;font-size:12px;cursor:pointer;">' +
                                '<input type="checkbox" class="sits-pub-force-save-cb" style="margin:0;"> ' +
                                'Override conflict \u2014 the conflicting template will be set to Draft and deactivated automatically.' +
                            '</label>' +
                        '</div>' +
                    '</div>' +
                    '<div class="sits-pub-modal-footer">' +
                        '<button type="button" class="sits-pub-btn sits-pub-cancel-btn">Cancel</button>' +
                        '<button type="button" class="sits-pub-btn sits-pub-save-btn">' + saveLbl + '</button>' +
                    '</div>' +
                '</div>' +
            '</div>'
        );
    }

    /* ====================================================================
     * attachPopupEvents
     * postId     – WP post ID (0 for new-template flow until draft is created)
     * isCreate   – true → draft creation flow; false → edit-existing flow
     * onSuccess  – callback(saveRes) after successful save; null → reload listing
     * ==================================================================== */
    function attachPopupEvents($popup, postId, isCreate, onSuccess) {
        var searchTimers = {};

        $popup.on('click', '.sits-pub-modal-close, .sits-pub-cancel-btn', function () { closePopup($popup); });
        $popup.on('click', function (e) { if ($(e.target).is('.sits-pub-overlay')) closePopup($popup); });
        $popup.on('change', '.sits-pub-force-save-cb', function () {
            if ($(this).is(':checked')) { $popup.find('.sits-pub-error-msg').hide(); }
        });

        $popup.on('click', '.sits-pub-remove-row', function () {
            var $rows = $popup.find('.sits-pub-condition-row');
            if ($rows.length > 1) $(this).closest('.sits-pub-condition-row').remove();
            else $(this).closest('.sits-pub-condition-row').replaceWith(buildConditionRow(null, $popup.find('.sits-pub-type-select').val()));
        });

        $popup.on('change', '.sits-pub-condition-type', function () {
            syncConditionRowVisibility($(this).closest('.sits-pub-condition-row'));
        });

        $popup.on('change', '.sits-pub-type-select', function () {
            refreshConditionRowsForTemplateType($popup, $(this).val());
        });

        // Fix 4: when archive sub-type dropdown changes, show/hide archive-specific search
        $popup.on('change', '.sits-pub-archive-sub', function () {
            var $row   = $(this).closest('.sits-pub-condition-row');
            var subVal = $(this).val();
            var $arch  = $row.find('.sits-pub-archive-specific');
            var showSearch = ARCHIVE_SPECIFIC_TYPES.indexOf(subVal) !== -1;
            $arch.attr('data-archive-type', subVal || '');
            if (showSearch) {
                // Update placeholder text
                var label = subVal === 'archive_author' ? 'authors' : (subVal === 'archive_tag' ? 'tags' : 'categories');
                var placeholder = ARCHIVE_SEARCH_PLACEHOLDER[subVal] || 'Search\u2026';
                $arch.find('.sits-pub-search-archive-item').attr('placeholder', placeholder);
                $arch.find('p').text('Narrow to specific ' + label + ' (leave empty to match all):');
                $arch.slideDown(200);
            } else {
                $arch.slideUp(200);
            }
        });

        $popup.on('click', '.sits-pub-add-cond-btn', function () {
            $popup.find('.sits-pub-conditions-list').append(buildConditionRow(null, $popup.find('.sits-pub-type-select').val()));
        });

        $popup.on('keyup', '.sits-pub-search-specific', function () {
            var $input = $(this), $row = $input.closest('.sits-pub-condition-row');
            var $results = $row.find('.sits-pub-search-results'), sv = $input.val();
            var idx = $popup.find('.sits-pub-condition-row').index($row);
            clearTimeout(searchTimers[idx]);
            if (sv.length < 2) { $results.hide().empty(); return; }
            searchTimers[idx] = setTimeout(function () {
                $.post(cfg.ajaxurl, { action: 'sits_search_posts_pages', search: sv, nonce: cfg.nonce }, function (r) {
                    if (!r.success) return;
                    $results.empty();
                    $.each(r.data.results || [], function (i, item) {
                        if ($row.find('.sits-pub-specific-list [data-id="' + item.id + '"]').length) return;
                        $('<div class="sits-pub-search-result-item" data-id="' + item.id + '" data-title="' + item.title + '" data-type="' + item.type + '"><strong>' + item.title + '</strong> <em>(' + item.type + ')</em></div>').appendTo($results);
                    });
                    r.data.results && r.data.results.length ? $results.show() : $results.html('<div class="sits-pub-no-results">No results found</div>').show();
                });
            }, 300);
        });

        $popup.on('click', '.sits-pub-search-result-item', function () {
            var $item = $(this), $row = $item.closest('.sits-pub-condition-row');
            var id = $item.data('id'), title = $item.data('title'), type = $item.data('type');
            if (!$row.find('.sits-pub-specific-list [data-id="' + id + '"]').length) {
                $row.find('.sits-pub-specific-list').append(buildSpecificItem(id, title, type));
            }
            $item.closest('.sits-pub-search-results').hide().empty();
            $row.find('.sits-pub-search-specific').val('');
        });

        $popup.on('click', '.sits-pub-remove-specific', function () { $(this).closest('.sits-pub-specific-item').remove(); });

        // Fix 4: archive-specific item search (categories / tags / authors)
        $popup.on('keyup', '.sits-pub-search-archive-item', function () {
            var $input    = $(this);
            var $row      = $input.closest('.sits-pub-condition-row');
            var $archWrap = $input.closest('.sits-pub-archive-specific');
            var archType  = $archWrap.attr('data-archive-type') || '';
            var $results  = $archWrap.find('.sits-pub-archive-search-results');
            var sv        = $input.val();
            var idx       = $popup.find('.sits-pub-condition-row').index($row) + '_arch';
            clearTimeout(searchTimers[idx]);
            if (sv.length < 1) { $results.hide().empty(); return; }
            searchTimers[idx] = setTimeout(function () {
                $.post(cfg.ajaxurl, { action: 'sits_search_archive_items', type: archType, search: sv, nonce: cfg.nonce }, function (r) {
                    if (!r.success) return;
                    $results.empty();
                    $.each(r.data.results || [], function (i, item) {
                        var itemId = String(item.id);
                        if ($archWrap.find('.sits-pub-archive-specific-list [data-id="' + itemId + '"]').length) return;
                        $('<div class="sits-pub-search-result-item sits-pub-arch-result" data-id="' + itemId + '" data-title="' + item.title + '" data-type="' + item.type + '"><strong>' + item.title + '</strong></div>').appendTo($results);
                    });
                    r.data.results && r.data.results.length
                        ? $results.show()
                        : $results.html('<div class="sits-pub-no-results">No results found</div>').show();
                });
            }, 300);
        });

        $popup.on('click', '.sits-pub-arch-result', function () {
            var $item     = $(this);
            var $archWrap = $item.closest('.sits-pub-archive-specific');
            var id        = String($item.data('id'));
            var title     = $item.data('title');
            var type      = $item.data('type');
            if (!$archWrap.find('.sits-pub-archive-specific-list [data-id="' + id + '"]').length) {
                $archWrap.find('.sits-pub-archive-specific-list').append(buildArchSpecificItem(id, title, type));
            }
            $item.closest('.sits-pub-archive-search-results').hide().empty();
            $archWrap.find('.sits-pub-search-archive-item').val('');
        });

        $popup.on('click', '.sits-pub-remove-arch-item', function () { $(this).closest('.sits-pub-arch-item').remove(); });

        $(document).on('click.sitsSettingsDoc', function (e) {
            if (!$(e.target).closest('.sits-pub-singular-specific').length) { $popup.find('.sits-pub-search-results').hide(); }
            if (!$(e.target).closest('.sits-pub-archive-specific').length)  { $popup.find('.sits-pub-archive-search-results').hide(); }
        });

        /* ---- Save / Create button ---- */
        $popup.on('click', '.sits-pub-save-btn', function () {
            var $btn = $(this);
            hidePopupError($popup);

            var templateType = $popup.find('.sits-pub-type-select').val();
            if (!templateType) {
                showPopupError($popup, s.errorSelectType || 'Please select a template type.');
                return;
            }

            if ($popup.find('.sits-pub-error-msg').is(':visible') && !$popup.find('.sits-pub-force-save-cb').is(':checked')) {
                $popup.find('.sits-pub-modal-body').animate({ scrollTop: $popup.find('.sits-pub-modal-body')[0].scrollHeight }, 250);
                return;
            }

            var forceSave = $popup.find('.sits-pub-force-save-cb').is(':checked') ? 1 : 0;
            var btnLabel  = isCreate ? (s.creating || 'Creating…') : (s.saving || 'Saving…');
            $btn.prop('disabled', true).text(btnLabel);

            function doSave(pid, elementorUrl) {
                var conditions = gatherConditions($popup);
                $.post(cfg.ajaxurl, {
                    action:        'sits_save_hf_template_settings',
                    post_id:       pid,
                    template_type: templateType,
                    conditions:    JSON.stringify(conditions),
                    force_save:    forceSave,
                    _wpnonce:      cfg.nonce
                }, function (saveRes) {
                    if (!saveRes.success) {
                        var msg = saveRes.data && saveRes.data.message ? saveRes.data.message : 'Save failed.';
                        showPopupError($popup, msg);
                        if (saveRes.data && saveRes.data.conflict) { $popup.find('.sits-pub-force-save-wrap').show(); }
                        $btn.prop('disabled', false).text(isCreate ? (s.createAndEdit || 'Create & Edit with Elementor') : 'Save Settings');
                        return;
                    }
                    closePopup($popup);
                    if (typeof onSuccess === 'function') {
                        onSuccess(saveRes, elementorUrl, pid, templateType);
                    } else {
                        showListNotice(s.settingsSaved || 'Settings saved successfully!', 'success');
                        setTimeout(function () { window.location.reload(); }, 1200);
                    }
                }).fail(function () {
                    showPopupError($popup, 'Connection error.');
                    $btn.prop('disabled', false).text(isCreate ? (s.createAndEdit || 'Create & Edit with Elementor') : 'Save Settings');
                });
            }

            if (isCreate) {
                // If a draft was already created on a previous attempt (e.g. user is retrying after a conflict),
                // reuse it — do NOT create another draft, which would leave orphaned rows.
                if (postId) {
                    doSave(postId, $popup.data('elementor-url') || '');
                    return;
                }

                // First attempt: create the draft, then save settings
                var postTitle = $.trim($popup.find('.sits-pub-template-title').val()) || '';
                $.post(cfg.ajaxurl, { action: 'sits_create_hf_draft', post_title: postTitle, _wpnonce: cfg.nonce }, function (r) {
                    if (!r.success) {
                        showPopupError($popup, r.data && r.data.message ? r.data.message : (s.error || 'Could not create template.'));
                        $btn.prop('disabled', false).text(s.createAndEdit || 'Create & Edit with Elementor');
                        return;
                    }
                    // Cache the draft so retries reuse it
                    postId = r.data.post_id;
                    $popup.data('elementor-url', r.data.elementor_url);
                    // Disable the title field so the user can't change it on retry
                    $popup.find('.sits-pub-template-title').prop('disabled', true);
                    doSave(r.data.post_id, r.data.elementor_url);
                }).fail(function () {
                    showPopupError($popup, 'Connection error.');
                    $btn.prop('disabled', false).text(s.createAndEdit || 'Create & Edit with Elementor');
                });
            } else {
                doSave(postId, null);
            }
        });
    }

    function closePopup($popup) {
        $(document).off('click.sitsSettingsDoc');
        $popup.removeClass('sits-pub-overlay--visible');
        setTimeout(function () { $popup.remove(); }, 300);
    }

    /* ====================================================================
     * "Add New Template" — show popup immediately (no pre-AJAX)
     * ==================================================================== */
    $(document).on('click', 'a[href*="post-new.php"][href*="sits_hf_template"]', function (e) {
        e.preventDefault();
        var $popup = $(buildPopupHtml({}, true));
        $('body').append($popup);
        setTimeout(function () { $popup.addClass('sits-pub-overlay--visible'); }, 10);

        // Focus the title field
        setTimeout(function () { $popup.find('.sits-pub-template-title').trigger('focus'); }, 150);

        attachPopupEvents($popup, 0, true, function (saveRes, elementorUrl, postId, templateType) {
            // After draft created + settings saved, show template library popup
            closePopup($popup);
            if (typeof window.sitsShowTemplateLibrary === 'function' && postId && templateType) {
                window.sitsShowTemplateLibrary(postId, templateType);
            } else if (elementorUrl) {
                window.location.href = elementorUrl;
            } else {
                window.location.reload();
            }
        });
    });

    /* ====================================================================
     * "Settings" row action → open settings popup for existing template
     * ==================================================================== */
    $(document).on('click', '.sits-open-settings', function (e) {
        e.preventDefault();
        var postId = $(this).data('post-id'), $link = $(this), orig = $link.html();
        $link.html('<span class="spinner is-active" style="float:none;display:inline-block;margin:0;vertical-align:middle;"></span>');

        $.post(cfg.ajaxurl, { action: 'sits_get_hf_settings', post_id: postId, _wpnonce: cfg.nonce }, function (r) {
            $link.html(orig);
            if (!r.success) { alert(s.error); return; }
            var $popup = $(buildPopupHtml(r.data, false));
            $('body').append($popup);
            setTimeout(function () { $popup.addClass('sits-pub-overlay--visible'); }, 10);
            attachPopupEvents($popup, postId, false, null);
        }).fail(function () { $link.html(orig); alert(s.error); });
    });

    /* ====================================================================
     * Legacy meta box: mutual-exclusivity Display On ↔ Exclude From
     * ==================================================================== */
    function syncMutualExclusivity() {
        $('.sits-display-cb').each(function () {
            var cond = $(this).data('condition');
            if (cond === 'all') return;
            var $other = $('.sits-exclude-cb[data-condition="' + cond + '"]');
            if ($(this).is(':checked')) $other.prop('checked', false).prop('disabled', true).closest('label').css('color', '#bbb');
            else if (!$('.sits-display-cb[data-condition="' + cond + '"]').is(':disabled')) $other.prop('disabled', false).closest('label').css('color', '');
        });
        $('.sits-exclude-cb').each(function () {
            var cond   = $(this).data('condition');
            var $other = $('.sits-display-cb[data-condition="' + cond + '"]');
            if ($(this).is(':checked')) $other.prop('checked', false).prop('disabled', true).closest('label').css('color', '#bbb');
            else $other.prop('disabled', false).closest('label').css('color', '');
        });
    }
    syncMutualExclusivity();
    $(document).on('change', '.sits-display-cb, .sits-exclude-cb', syncMutualExclusivity);
    $(document).on('change', '.sits-display-cb[data-condition="all"]', function () {
        var checked = $(this).is(':checked');
        $('.sits-display-cb').not(this).prop('disabled', checked);
        if (checked) $('.sits-display-cb').not(this).prop('checked', false);
        syncMutualExclusivity();
    });
    if ($('.sits-display-cb[data-condition="all"]').is(':checked')) {
        $('.sits-display-cb').not('[data-condition="all"]').prop('disabled', true);
    }
    $(document).on('change', '.sits-display-cb[data-condition="singular"]', function () {
        $(this).is(':checked') ? $('#sits-specific-selection').slideDown() : $('#sits-specific-selection').slideUp();
    });
    $('#sits_use_specific').on('change', function () {
        $(this).is(':checked') ? $('#sits-specific-posts-wrapper').slideDown() : $('#sits-specific-posts-wrapper').slideUp();
    });
    $(document).on('click', function (e) {
        if (!$(e.target).closest('#sits-search-posts, #sits-search-results').length) { $('#sits-search-results').hide(); }
    });

    /* ====================================================================
     * Tabs — move to Row 2 then reveal, then wrap content in panel div.
     * ==================================================================== */
    $(document).ready(function () {
        var $tabs = $('#sits-type-tabs-container');
        if ( ! $tabs.length ) { return; }

        var $anchor = $('.wp-header-end');
        if ( $anchor.length ) {
            $anchor.after( $tabs );   // physically move to Row 2
        }
        $tabs[0].style.removeProperty('display'); // reveal — CSS flex takes over

        // Wrap the subsubsub + tablenav + list-table in a panel div so they
        // visually appear as a unified card beneath the tabs.
        var $sub    = $( '.subsubsub' ).first();
        var $filter = $( '#posts-filter, #post-query-submit' ).closest('form').first();

        // Target the form wrapping the list table (WP uses id="posts-filter")
        var $form = $( '#posts-filter' );
        if ( $form.length && $sub.length ) {
            // Insert panel wrapper before subsubsub
            $sub.before('<div class="sits-builder-panel-wrap"></div>');
            var $panel = $( '.sits-builder-panel-wrap' );
            // Move subsubsub and the list-table form into the panel
            $panel.append( $sub ).append( $form );
        } else if ( $form.length ) {
            $form.before('<div class="sits-builder-panel-wrap"></div>');
            $( '.sits-builder-panel-wrap' ).append( $form );
        }
    });

}(jQuery));
