/**
 * Header Footer Builder – Elementor Editor Panel Integration
 *
 * Runs in the Elementor editor parent frame for sits_hf_template posts.
 * Shows the Settings popup when clicking Publish/Update.
 *
 * Changes in this version:
 * - Archive conditions: two-level UX — "All Archives" reveals a sub-type
 *   dropdown (Posts Archive, Author Archive, etc.) instead of mixing all
 *   archive types into one long list.
 * - Exclude-only conditions allowed (no forced Include required).
 * - Never monkey-patches elementor.saver / doc.save — uses capture-phase
 *   DOM interception only, so Elementor Pro's UI is unaffected.
 *
 * @package Softech_Addons_for_Elementor
 */
/* global sitsHFPanel, jQuery */
(function ($) {
    'use strict';

    var cfg         = window.sitsHFPanel || {};
    var popupOpen   = false;
    var intercepted = false;

    if (!cfg.isHFTemplate) return;

    var str = cfg.strings || {};

    /* ------------------------------------------------------------------
     * Condition data — TWO-LEVEL archive dropdown
     * ------------------------------------------------------------------ */
    var MAIN_CONDS = [
        { val: 'all',        label: str.entireSite || 'Entire Website'   },
        { val: 'front_page', label: str.frontPage  || 'Front Page'       },
        { val: 'blog',       label: str.blog       || 'Blog / Posts Page'},
        { val: 'singular',   label: str.singular   || 'All Singular'     },
        { val: 'archive',    label: str.archive    || 'All Archives'     },
        { val: '404',        label: str.notFound   || '404 Page'         }
    ];

    var ARCHIVE_SUBS = [
        { val: '',                 label: str.archiveAll      || 'All Archives'    },
        { val: 'archive_post',     label: str.archivePost     || 'Posts Archive'   },
        { val: 'archive_author',   label: str.archiveAuthor   || 'Author Archive'  },
        { val: 'archive_date',     label: str.archiveDate     || 'Date Archive'    },
        { val: 'archive_search',   label: str.archiveSearch   || 'Search Results'  },
        { val: 'archive_category', label: str.archiveCategory || 'Post Categories' },
        { val: 'archive_tag',      label: str.archiveTag      || 'Post Tags'       }
    ];

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

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

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

    function isSinglePostMode() {
        return (cfg.templateType || '') === 'single_post';
    }

    function filterSinglePostWidgets() {
        if (!isSinglePostMode()) {
            return;
        }

        var $panel = $('#elementor-panel');

        if (!$panel.length) {
            return;
        }

        var $category = getSinglePostCategory($panel);

        if (!$category.length) {
            return;
        }

        var $firstVisibleCategory = $panel.find('.elementor-panel-category:visible').not($category).first();

        if ($firstVisibleCategory.length) {
            $category.insertBefore($firstVisibleCategory);
        } else {
            var $container = $category.closest('.elementor-panel-categories');
            if ($container.length) {
                $category.prependTo($container);
            }
        }

        var wasOpen = $category.hasClass('elementor-open') || $category.hasClass('elementor-active');

        $category
            .removeClass('elementor-closed')
            .addClass('elementor-open')
            .attr('aria-hidden', 'false')
            .show();

        $category.find('.elementor-panel-category-title, .elementor-panel-category-header').first().show();
        $category.find('.elementor-panel-category-toggle, .elementor-panel-category-icon').first().show();

        var $toggle = $category.find('.elementor-panel-category-title, .elementor-panel-category-header').first();
        if ($toggle.length && !wasOpen) {
            $toggle.trigger('click');
        }
    }

    function getSinglePostCategory($panel) {
        return $panel.find('.elementor-panel-category').filter(function () {
            var $item = $(this);
            return getCategoryTitle($item) === 'Single Post' || $item.attr('data-category') === 'sits-single-post' || $item.hasClass('sits-single-post-category');
        }).first();
    }

    function getCategoryTitle($category) {
        var title = '';

        if (!$category || !$category.length) {
            return title;
        }

        title = $.trim($category.find('.elementor-panel-category-title').first().text());

        if (!title) {
            title = $.trim($category.find('[class*="title"]').first().text());
        }

        if (!title) {
            title = $.trim($category.text());
        }

        return title;
    }

    function observeSinglePostPanel() {
        var panelElement = document.getElementById('elementor-panel');

        if (!panelElement) {
            setTimeout(observeSinglePostPanel, 400);
            return;
        }

        var timer = null;
        var observer = new MutationObserver(function () {
            if (timer) {
                clearTimeout(timer);
            }

            timer = setTimeout(function () {
                filterSinglePostWidgets();
            }, 50);
        });

        observer.observe(panelElement, {
            childList: true,
            subtree: true,
            attributes: true,
            attributeFilter: ['class', 'style', 'aria-hidden']
        });

        filterSinglePostWidgets();
        setTimeout(filterSinglePostWidgets, 150);
        setTimeout(filterSinglePostWidgets, 500);
    }

    function specItem(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">&times;</button>' +
            '</div>'
        );
    }

    function condRow(row) {
        row = row || { include: 'include', condition: 'all', specific: [] };

        var isArchiveSub = ARCHIVE_SUB_VALS.indexOf(row.condition) !== -1;
        var mainCond     = isArchiveSub ? 'archive' : row.condition;
        var subCond      = isArchiveSub ? row.condition : '';

        var specHtml = '';
        if (row.specific && row.specific.length) {
            $.each(row.specific, function (i, it) { specHtml += specItem(it.id, it.title, it.type); });
        }

        return (
            '<div class="sits-pub-condition-row">' +
                '<select class="sits-pub-include-exclude">' +
                    '<option value="include"' + (row.include !== 'exclude' ? ' selected' : '') + '>' + (str.include || 'Include') + '</option>' +
                    '<option value="exclude"' + (row.include === 'exclude' ? ' selected' : '') + '>' + (str.exclude || 'Exclude') + '</option>' +
                '</select>' +
                '<select class="sits-pub-condition-type">' + buildMainOpts(mainCond) + '</select>' +
                '<select class="sits-pub-archive-sub"' + (mainCond !== 'archive' ? ' style="display:none"' : '') + '>' +
                    buildSubOpts(subCond) +
                '</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="' + (str.searchPlaceholder || 'Search posts or pages…') + '" autocomplete="off">' +
                    '<div class="sits-pub-search-results"></div>' +
                    '<div class="sits-pub-specific-list">' + specHtml + '</div>' +
                '</div>' +
            '</div>'
        );
    }

    function buildPopupHtml() {
        var curType = cfg.templateType || '';
        var conds   = cfg.conditions   || [];
        var cHtml   = conds.length ? '' : condRow();
        $.each(conds, function (i, r) { cHtml += condRow(r); });

        return (
            '<div class="sits-pub-overlay" id="sits-el-pub-overlay">' +
                '<div class="sits-pub-modal">' +
                    '<div class="sits-pub-modal-header">' +
                        '<span class="sits-pub-modal-icon">&#9881;</span>' +
                        '<h2>' + (str.publishSettings || 'PUBLISH SETTINGS') + '</h2>' +
                        '<button type="button" class="sits-pub-modal-close">&times;</button>' +
                    '</div>' +
                    '<div class="sits-pub-modal-body">' +
                        '<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">' + (str.templateType || 'Template Type') + '</label>' +
                                '<select class="sits-pub-type-select">' +
                                    '<option value="">' + (str.selectType || '— Select Type —') + '</option>' +
                                    '<option value="header"'      + (curType === 'header'      ? ' selected' : '') + '>Header</option>' +
                                    '<option value="footer"'      + (curType === 'footer'      ? ' selected' : '') + '>Footer</option>' +
                                    '<option value="archive"'     + (curType === 'archive'     ? ' selected' : '') + '>Archive</option>' +
                                    '<option value="single_page"' + (curType === 'single_page' ? ' selected' : '') + '>Single Page</option>' +
                                    '<option value="single_post"' + (curType === 'single_post' ? ' selected' : '') + '>Single Post</option>' +
                                    '<option value="404_page"'    + (curType === '404_page'    ? ' selected' : '') + '>404 Page</option>' +
                                '</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">' + (str.displayConditions || 'Display Conditions') + '</label>' +
                                '<p class="sits-pub-section-desc">' + (str.displayConditionsDesc || 'Set conditions that determine where your template is displayed.') + '</p>' +
                                '<div class="sits-pub-conditions-list">' + cHtml + '</div>' +
                                '<button type="button" class="sits-pub-add-cond-btn">' +
                                    '<span class="dashicons dashicons-plus-alt2"></span> ' + (str.addCondition || '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">' + (str.cancel || 'Cancel') + '</button>' +
                        '<button type="button" class="sits-pub-btn sits-pub-save-btn">' + (str.savePublish || 'Save &amp; Publish') + '</button>' +
                    '</div>' +
                '</div>' +
            '</div>'
        );
    }

    function showError($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);
        $popup.find('.sits-pub-force-save-wrap').show();
    }

    function hideError($popup) {
        $popup.find('.sits-pub-error-msg').hide().empty();
        $popup.find('.sits-pub-force-save-wrap').hide();
        $popup.find('.sits-pub-force-save-cb').prop('checked', false);
    }

    function gatherConditions($popup) {
        var display_on = [], exclude_on = [], specific_ids = [], exclude_ids = [];
        $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 two-level archive dropdown
            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')); });
            }

            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 };
    }

    /* ------------------------------------------------------------------
     * Show popup
     * triggerElementorSave – callback to fire Elementor's own save after ours
     * ------------------------------------------------------------------ */
    function showPopup(triggerElementorSave) {
        if (popupOpen) return;
        popupOpen = true;

        var $popup = $(buildPopupHtml());
        $('body').append($popup);
        setTimeout(function () { $popup.addClass('sits-pub-overlay--visible'); }, 10);

        function doCancel() { closePopup($popup); }
        $popup.on('click', '.sits-pub-modal-close, .sits-pub-cancel-btn', doCancel);
        $popup.on('click', function (e) { if ($(e.target).is('#sits-el-pub-overlay')) doCancel(); });

        $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(condRow());
        });

        $popup.on('change', '.sits-pub-condition-type', function () {
            var $row = $(this).closest('.sits-pub-condition-row'), val = $(this).val();
            $row.find('.sits-pub-archive-sub')[val === 'archive' ? 'slideDown' : 'slideUp'](200);
            $row.find('.sits-pub-singular-specific')[val === 'singular' ? 'slideDown' : 'slideUp'](200);
        });

        $popup.on('click', '.sits-pub-add-cond-btn', function () {
            $popup.find('.sits-pub-conditions-list').append(condRow());
        });

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

        $popup.on('click', '.sits-pub-search-result-item', function () {
            var $it = $(this), $row = $it.closest('.sits-pub-condition-row');
            var id = $it.data('id'), title = $it.data('title'), type = $it.data('type');
            if (!$row.find('.sits-pub-specific-list [data-id="' + id + '"]').length) {
                $row.find('.sits-pub-specific-list').append(specItem(id, title, type));
            }
            $it.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(); });

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

        /* ---- Save button ---- */
        $popup.on('click', '.sits-pub-save-btn', function () {
            var $btn      = $(this);
            var forceSave = $popup.find('.sits-pub-force-save-cb').is(':checked');

            var tplType = $popup.find('.sits-pub-type-select').val();
            if (!tplType) {
                hideError($popup);
                showError($popup, str.errorSelectType || 'Please select a template type.');
                return;
            }
            var conds = gatherConditions($popup);
            // Exclude-only is allowed — no include required.

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

            $btn.prop('disabled', true).text(str.saving || 'Saving…');

            $.post(cfg.ajaxurl, {
                action:        'sits_save_hf_template_settings',
                post_id:       cfg.postId,
                template_type: tplType,
                conditions:    JSON.stringify(conds),
                force_save:    forceSave ? 1 : 0,
                publish_now:   1,
                _wpnonce:      cfg.nonce
            }, function (sv) {
                if (!sv.success) {
                    hideError($popup);
                    showError($popup, sv.data && sv.data.message ? sv.data.message : (str.saveError || 'Save failed.'));
                    $btn.prop('disabled', false).text(str.savePublish || 'Save & Publish');
                    return;
                }
                cfg.templateType  = tplType;
                cfg.settingsSaved = true;
                closePopup($popup);
                if (typeof triggerElementorSave === 'function') { triggerElementorSave(); }
            }).fail(function () {
                hideError($popup);
                showError($popup, str.saveError || 'Connection error.');
                $btn.prop('disabled', false).text(str.savePublish || 'Save & Publish');
            });
        });
    }

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

    /* ------------------------------------------------------------------
     * Publish button interceptor (capture-phase, no monkey-patching)
     * ------------------------------------------------------------------ */
    var allowNextClick = false;

    function findPublishButton() {
        return $([
            '[data-event="save_publish"]',
            '.elementor-button-success',
            '#elementor-panel-footer-saver-publish .elementor-button',
            '.elementor-panel-footer-tool.elementor-save-buttons .elementor-button-success'
        ].join(',')).filter(':visible').first();
    }

    function attachInterceptor() {
        if (intercepted) return;
        var $btn = findPublishButton();
        if (!$btn.length) return;
        intercepted = true;

        $btn[0].addEventListener('click', function sitsPublishCapture(e) {
            if (allowNextClick) { allowNextClick = false; return; }
            e.preventDefault();
            e.stopImmediatePropagation();

            showPopup(function () {
                allowNextClick = true;
                $btn[0].click();
                intercepted = false;
                setTimeout(function () { if (!intercepted) attachInterceptor(); }, 500);
            });
        }, true);
    }

    /* ------------------------------------------------------------------
     * Init
     * ------------------------------------------------------------------ */
    $(function () {
        var tries = 0, maxTries = 100;
        var boot = setInterval(function () {
            tries++;
            if (findPublishButton().length) { clearInterval(boot); attachInterceptor(); return; }
            if (tries >= maxTries) { clearInterval(boot); }
        }, 200);

        $(document).on('click', '.elementor-panel-menu-item, [data-view]', function () {
            if (!intercepted) { setTimeout(function () { attachInterceptor(); }, 400); }
        });

        observeSinglePostPanel();
    });

}(jQuery));
