/**
 * SEO Fury — Elementor Editor Panel (v3 — body-fixed approach)
 *
 * The panel is appended to <body> with position:fixed, positioned to
 * exactly overlay #elementor-panel. This completely bypasses Elementor's
 * CSS and DOM management.
 */
(function ($) {
    'use strict';

    if (typeof seoFuryElementor === 'undefined') {
        return;
    }

    var active   = false;
    var saving   = false;
    var $overlay = null;
    var ready    = false;
    var observer = null;

    /* ═══════════════════════════════════════════════
     *  BOOT
     * ═══════════════════════════════════════════════ */
    function boot() {
        var tries = 0;
        var poll = setInterval(function () {
            tries++;
            if (
                typeof elementor !== 'undefined' &&
                document.getElementById('elementor-panel') &&
                document.getElementById('seo-fury-elementor-panel')
            ) {
                clearInterval(poll);
                initialize();
            }
            if (tries > 200) clearInterval(poll);
        }, 250);
    }

    /* ═══════════════════════════════════════════════
     *  INITIALIZE
     * ═══════════════════════════════════════════════ */
    function initialize() {
        if (ready) return;
        ready = true;

        buildPanel();

        waitForNav(function () {
            injectTab();
            startObserver();
            hookSave();
            listenOtherClicks();
        });
    }

    /* ═══════════════════════════════════════════════
     *  WAIT FOR NAV
     * ═══════════════════════════════════════════════ */
    function waitForNav(cb) {
        var n = 0;
        var poll = setInterval(function () {
            n++;
            if (getNav().length) {
                clearInterval(poll);
                cb();
            } else if (n > 80) {
                clearInterval(poll);
                injectHeaderBtn();
                hookSave();
            }
        }, 250);
    }

    function getNav() {
        var $n = $('#elementor-panel-elements-navigation');
        if ($n.length) return $n;
        var $c = $('#elementor-panel-page-elements .elementor-panel-navigation');
        return $c.length ? $c.first() : $();
    }

    /* ═══════════════════════════════════════════════
     *  BUILD PANEL — appended to <body>, position:fixed
     * ═══════════════════════════════════════════════ */
    function buildPanel() {
        if ($overlay) return;

        var $source = $('#seo-fury-elementor-panel');
        var brand   = seoFuryElementor.brand_name || 'SEO Fury';

        $overlay = $('<div id="seo-fury-el-overlay"></div>');

        /* Header */
        var $hdr = $(
            '<div class="seo-fury-el-ov-hdr">' +
                '<button type="button" class="seo-fury-el-ov-back" title="Back">' +
                    '<i class="eicon-chevron-left"></i>' +
                '</button>' +
                '<span class="seo-fury-el-ov-title">' +
                    '<i class="eicon-search-bold"></i> ' + brand +
                '</span>' +
            '</div>'
        );
        $hdr.find('.seo-fury-el-ov-back').on('click', deactivate);

        /* Scrollable body */
        var $body = $('<div class="seo-fury-el-ov-body"></div>');

        if ($source.length) {
            var $srcBody = $source.find('.seo-fury-el-panel-body');
            if ($srcBody.length && $srcBody.children().length > 0) {
                $body.append($srcBody.children());
            }
        }

        $overlay.append($hdr).append($body);
        $('body').append($overlay);
    }

    /* ═══════════════════════════════════════════════
     *  INJECT TAB
     * ═══════════════════════════════════════════════ */
    function injectTab() {
        if (document.getElementById('seo-fury-el-tab')) {
            syncTabState();
            return;
        }

        var $nav = getNav();
        if (!$nav.length) return;

        var btn = document.createElement('button');
        btn.id = 'seo-fury-el-tab';
        btn.type = 'button';
        btn.className = 'seo-fury-nav-tab';
        btn.textContent = 'SEO';

        btn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();
            active ? deactivate() : activate();
            return false;
        }, true);

        $nav[0].appendChild(btn);
        syncTabState();
    }

    function syncTabState() {
        var tab = document.getElementById('seo-fury-el-tab');
        if (!tab) return;
        tab.classList.toggle('seo-fury-nav-tab-active', active);
    }

    /* ═══════════════════════════════════════════════
     *  HEADER BUTTON (fallback)
     * ═══════════════════════════════════════════════ */
    function injectHeaderBtn() {
        if (document.getElementById('seo-fury-el-tab')) return;
        var $h = $('#elementor-panel-header');
        if (!$h.length) return;

        var $btn = $('<button>', {
            id:    'seo-fury-el-tab',
            type:  'button',
            'class': 'seo-fury-el-header-btn',
            title: seoFuryElementor.brand_name || 'SEO Fury',
            html:  '<span class="eicon-search-bold"></span> SEO'
        }).on('click', function (e) {
            e.stopPropagation();
            active ? deactivate() : activate();
        });
        $h.append($btn);
    }

    /* ═══════════════════════════════════════════════
     *  ACTIVATE
     * ═══════════════════════════════════════════════ */
    function activate() {
        active = true;
        if (!$overlay) return;

        positionOverlay();
        $overlay.addClass('seo-fury-el-ov-visible');
        getNav().find('.elementor-component-tab').removeClass('elementor-active');
        syncTabState();
    }

    /* ═══════════════════════════════════════════════
     *  POSITION OVERLAY — full height from panel top to viewport bottom
     * ═══════════════════════════════════════════════ */
    function positionOverlay() {
        var elPanel = document.getElementById('elementor-panel');
        if (!elPanel || !$overlay) return;

        var rect = elPanel.getBoundingClientRect();
        $overlay.css({
            top:    rect.top + 'px',
            left:   rect.left + 'px',
            width:  rect.width + 'px',
            height: (window.innerHeight - rect.top) + 'px'
        });
    }

    $(window).on('resize', function () {
        if (active) positionOverlay();
    });

    /* ═══════════════════════════════════════════════
     *  DEACTIVATE
     * ═══════════════════════════════════════════════ */
    function deactivate() {
        if (!active) return;
        active = false;

        if ($overlay) {
            $overlay.removeClass('seo-fury-el-ov-visible');
        }

        var $nav = getNav();
        var $first = $nav.find('.elementor-component-tab').first();
        if ($first.length && !$first.hasClass('elementor-active')) {
            $first.trigger('click');
        }

        syncTabState();
    }

    /* ═══════════════════════════════════════════════
     *  OBSERVER
     * ═══════════════════════════════════════════════ */
    function startObserver() {
        if (observer) return;
        var el = document.getElementById('elementor-panel');
        if (!el) return;

        observer = new MutationObserver(function () {
            if (!document.getElementById('seo-fury-el-tab') && getNav().length) {
                injectTab();
            }
        });

        observer.observe(el, { childList: true, subtree: true });
    }

    /* ═══════════════════════════════════════════════
     *  LISTEN OTHER CLICKS
     * ═══════════════════════════════════════════════ */
    function listenOtherClicks() {
        $(document).on('click', '#elementor-panel .elementor-component-tab', function () {
            if (active) deactivate();
        });

        try {
            elementor.getPanelView().on('set:page', function () {
                if (active) deactivate();
            });
        } catch (e) {}
    }

    /* ═══════════════════════════════════════════════
     *  MARK DIRTY — activate Update button when SEO fields change
     * ═══════════════════════════════════════════════ */
    function markEditorDirty() {
        try {
            if (typeof elementor === 'undefined') return;

            // Method 1: $e.internal command (Elementor 3.x+)
            if (typeof $e !== 'undefined' && $e.internal) {
                $e.internal('document/save/set-is-modified', { status: true });
                return;
            }

            // Method 2: saver.setFlagEditorChange (Elementor 2.x – 3.x)
            if (elementor.saver && elementor.saver.setFlagEditorChange) {
                elementor.saver.setFlagEditorChange(true);
                return;
            }

            // Method 3: Trigger the footer saver button directly
            var $btn = $('#elementor-panel-saver-button-publish, #elementor-panel-saver-button-save-options');
            if ($btn.length) {
                $btn.removeClass('elementor-disabled');
            }
        } catch (e) {}
    }

    function hookFieldChanges() {
        $(document).on(
            'input change',
            '#seo-fury-el-overlay input, #seo-fury-el-overlay select, #seo-fury-el-overlay textarea,' +
            '#seo-fury-elementor-panel input, #seo-fury-elementor-panel select, #seo-fury-elementor-panel textarea',
            function () {
                markEditorDirty();
            }
        );
    }

    /* ═══════════════════════════════════════════════
     *  SAVE
     * ═══════════════════════════════════════════════ */
    function hookSave() {
        var n = 0;
        var poll = setInterval(function () {
            n++;
            if (typeof elementor !== 'undefined' && elementor.saver) {
                clearInterval(poll);

                // Primary: $e.hooks after-action (Elementor 2.9+)
                var hooked = false;
                if (typeof $e !== 'undefined' && $e.hooks) {
                    try {
                        $e.hooks.addAction('document/save/save', function () {
                            saveSeoData();
                        }, 'seo-fury');
                        hooked = true;
                    } catch (e) { hooked = false; }
                }

                // Fallback: legacy event emitter (Elementor 2.x)
                if (!hooked) {
                    try {
                        elementor.saver.on('after:save', saveSeoData);
                        hooked = true;
                    } catch (e) {}
                }

                // Extra safety: also bind directly to the Publish/Update button click
                // so the save fires even when hooks are unavailable or fired too late.
                $(document).on('click', '#elementor-panel-saver-button-publish, ' +
                    '#elementor-panel-saver-button-save-options, ' +
                    '.elementor-saver-button', function () {
                    // Short delay to let schemaItems be flushed to the hidden field
                    // before the Elementor AJAX fires so our AJAX goes after.
                    setTimeout(saveSeoData, 300);
                });

                hookFieldChanges();
            }
            if (n > 60) clearInterval(poll);
        }, 500);
    }

    function saveSeoData() {
        if (saving) return;
        saving = true;

        var $fields = $('#seo-fury-el-overlay, #seo-fury-elementor-panel')
                        .find('input, select, textarea');
        if (!$fields.length) { saving = false; return; }

        var payload = $fields.serialize() +
            '&action=seo_fury_elementor_save' +
            '&_el_nonce=' + encodeURIComponent(seoFuryElementor.nonce) +
            '&post_id='  + seoFuryElementor.post_id;

        // Use fetch with keepalive so the request survives a page redirect
        // (e.g. first-time publish that changes the URL in Elementor).
        if (typeof fetch !== 'undefined' && typeof FormData !== 'undefined') {
            var body = new FormData();
            payload.split('&').forEach(function (pair) {
                var idx = pair.indexOf('=');
                if (idx < 0) return;
                body.append(
                    decodeURIComponent(pair.slice(0, idx)),
                    decodeURIComponent(pair.slice(idx + 1).replace(/\+/g, ' '))
                );
            });
            fetch(seoFuryElementor.ajax_url, { method: 'POST', body: body, keepalive: true })
                .then(function (r) { return r.json(); })
                .then(function (r) { saving = false; if (r.success) toast('SEO saved'); })
                .catch(function ()  { saving = false; });
        } else {
            $.ajax({
                url:    seoFuryElementor.ajax_url,
                method: 'POST',
                data:   payload,
                success: function (r) { saving = false; if (r.success) toast('SEO saved'); },
                error:   function ()  { saving = false; }
            });
        }
    }

    function toast(msg) {
        var $t = $('<div class="seo-fury-el-toast">' + msg + '</div>');
        $('body').append($t);
        setTimeout(function () { $t.addClass('seo-fury-el-toast-show'); }, 50);
        setTimeout(function () {
            $t.removeClass('seo-fury-el-toast-show');
            setTimeout(function () { $t.remove(); }, 300);
        }, 2500);
    }

    /* ═══════════════════════════════════════════════
     *  START
     * ═══════════════════════════════════════════════ */
    boot();

})(jQuery);
