/**
 * KooKoa Folders — Mobile Adaptation
 * Activates only on screens ≤ 782px via matchMedia.
 * Does NOT modify admin.js — all overrides are additive.
 */
(function($) {
    'use strict';

    const MQ          = window.matchMedia('(max-width: 782px)');
    let FO          = null;   // set once KookoaWPF is ready
    let active      = false;
    let $sidebar    = null;
    let $toggleBar  = null;
    let $backdrop   = null;
    let origParent  = null;   // sidebar's original DOM parent (body)
    let origDnD     = null;   // original jstree dnd.is_draggable
    let origShowMeta = null;  // original showMetadataTooltip value
    let ctxMenuObs    = null;  // MutationObserver on context menu style
    let ctxContentObs = null; // MutationObserver on context menu content
    let ctxMenuBodyObs    = null; // MutationObserver waiting for context menu element (backdrop)
    let ctxContentBodyObs = null; // MutationObserver waiting for context menu element (flatten)
    let attachmentDragObs = null; // MutationObserver to destroy draggable on new attachments
    let longPressMoveHandler = null; // native passive touchmove handler (for removeEventListener)

    /* ================================================
       Init / Teardown
       ================================================ */

    function init() {
        if (active) return;

        FO = window.KookoaWPF;
        $sidebar = $('#kookoawpf-sidebar-wrapper');
        if (!FO || !$sidebar.length) return;

        active = true;
        origParent = $sidebar.parent();

        $('body').addClass('kookoawpf-mobile');

        relocateSidebar();
        injectToggleBar();
        collapseSidebar();
        disableTreeDnD();
        disableMediaDragDrop();
        disableMetadataTooltip();
        bindLongPress();
        bindBackdrop();
        flattenSubmenus();
        bindAutoCollapse();
    }

    function teardown() {
        if (!active) return;
        active = false;

        // Move sidebar back to original position
        if (origParent && origParent.length) {
            origParent.append($sidebar);
        }

        // Remove mobile toggle bar
        if ($toggleBar) {
            $toggleBar.remove();
            $toggleBar = null;
        }

        // Remove backdrop
        if ($backdrop) {
            $backdrop.remove();
            $backdrop = null;
        }

        // Remove mobile classes
        $('body').removeClass('kookoawpf-mobile');
        $sidebar.removeClass('kookoawpf-mobile-collapsed');

        // Restore DnD and metadata tooltip
        restoreTreeDnD();
        restoreMetadataTooltip();

        // Disconnect MutationObservers
        if (ctxMenuObs) { ctxMenuObs.disconnect(); ctxMenuObs = null; }
        if (ctxContentObs) { ctxContentObs.disconnect(); ctxContentObs = null; }
        if (ctxMenuBodyObs) { ctxMenuBodyObs.disconnect(); ctxMenuBodyObs = null; }
        if (ctxContentBodyObs) { ctxContentBodyObs.disconnect(); ctxContentBodyObs = null; }
        if (attachmentDragObs) { attachmentDragObs.disconnect(); attachmentDragObs = null; }

        // Unbind mobile events
        $(document).off('.kookoawpfMobile');
        $sidebar.off('.kookoawpfMobile');
        if (longPressMoveHandler) {
            document.removeEventListener('touchmove', longPressMoveHandler);
            longPressMoveHandler = null;
        }

        // Re-sync desktop layout
        const sidebarW = parseInt($sidebar.css('width'), 10);
        if (sidebarW && sidebarW >= 200) {
            $('#wpcontent').css('padding-left', (sidebarW + 30) + 'px');
        }
    }

    /* ================================================
       Sidebar relocation
       ================================================ */

    function relocateSidebar() {
        // Move sidebar into the content area, above the media grid
        const $wrap = $('#wpbody-content > .wrap');
        if ($wrap.length) {
            $wrap.prepend($sidebar);
        } else {
            // Fallback: prepend to #wpbody-content
            $('#wpbody-content').prepend($sidebar);
        }
    }

    /* ================================================
       Toggle bar
       ================================================ */

    function injectToggleBar() {
        $toggleBar = $(
            '<button type="button" class="kookoawpf-mobile-toggle" id="kookoawpf-mobile-toggle">' +
                '<span class="kookoawpf-mobile-toggle-brand">KK&gt;<span class="kookoawpf-mobile-cursor">_</span></span>' +
                '<span class="kookoawpf-mobile-toggle-chevron dashicons dashicons-arrow-down-alt2"></span>' +
            '</button>'
        );

        $toggleBar.on('click.kookoawpfMobile', function() {
            const collapsed = $sidebar.hasClass('kookoawpf-mobile-collapsed');
            if (collapsed) {
                expandSidebar();
            } else {
                collapseSidebar();
            }
        });

        $sidebar.before($toggleBar);
    }

    function collapseSidebar() {
        $sidebar.addClass('kookoawpf-mobile-collapsed');
        if ($toggleBar) $toggleBar.removeClass('kookoawpf-mobile-expanded');
    }

    function expandSidebar() {
        $sidebar.removeClass('kookoawpf-mobile-collapsed');
        if ($toggleBar) $toggleBar.addClass('kookoawpf-mobile-expanded');
    }

    /* ================================================
       Disable tree DnD on touch
       ================================================ */

    function disableTreeDnD() {
        try {
            const inst = $('#kookoawpf-jstree').jstree(true);
            if (inst && inst.settings && inst.settings.dnd) {
                origDnD = inst.settings.dnd.is_draggable;
                inst.settings.dnd.is_draggable = function() { return false; };
            }
        } catch (e) { /* tree not ready */ }

        // Fallback: if tree initializes later
        $(document).on('ready.jstree.kookoawpfMobile', '#kookoawpf-jstree', function() {
            if (!active) return;
            try {
                const inst = $('#kookoawpf-jstree').jstree(true);
                if (inst && inst.settings && inst.settings.dnd) {
                    if (!origDnD) origDnD = inst.settings.dnd.is_draggable;
                    inst.settings.dnd.is_draggable = function() { return false; };
                }
            } catch (e) { /* ignore */ }
        });
    }

    function restoreTreeDnD() {
        try {
            const inst = $('#kookoawpf-jstree').jstree(true);
            if (inst && inst.settings && inst.settings.dnd && origDnD) {
                inst.settings.dnd.is_draggable = origDnD;
                origDnD = null;
            }
        } catch (e) { /* ignore */ }
    }

    /* ================================================
       Disable media attachment draggable
       ================================================ */

    function disableMediaDragDrop() {
        // Prevent jQuery UI draggable init on attachment thumbnails
        $(document).on('mouseenter.kookoawpfMobile', '.attachments-browser .attachment', function(e) {
            if (active) e.stopImmediatePropagation();
        });

        // Destroy already-initialized jQuery UI draggable + sortable on attachments
        destroyAttachmentDraggables();
        destroySortable();

        // Watch for new attachments and destroy their draggable/sortable too
        const gridEl = document.querySelector('.attachments-browser .attachments');
        if (gridEl) {
            attachmentDragObs = new MutationObserver(function() {
                if (!active) return;
                destroyAttachmentDraggables();
                destroySortable();
            });
            attachmentDragObs.observe(gridEl, { childList: true });
        }
    }

    function destroyAttachmentDraggables() {
        $('.attachments-browser .attachment').each(function() {
            const $att = $(this);
            if ($att.data('fo-d')) {
                try { $att.draggable('destroy'); } catch (e) {}
                $att.removeData('fo-d');
            }
        });
    }

    function destroySortable() {
        $('.attachments-browser .attachments.ui-sortable').each(function() {
            try { $(this).sortable('destroy'); } catch (e) {}
        });
    }

    /* ================================================
       Disable metadata tooltip on mobile
       ================================================ */

    function disableMetadataTooltip() {
        if (FO && FO.data) {
            origShowMeta = FO.data.showMetadataTooltip;
            FO.data.showMetadataTooltip = false;
        }
    }

    function restoreMetadataTooltip() {
        if (FO && FO.data && origShowMeta !== null) {
            FO.data.showMetadataTooltip = origShowMeta;
            origShowMeta = null;
        }
    }

    /* ================================================
       Long-press for context menu
       ================================================ */

    function bindLongPress() {
        let timer   = null;
        let startX  = 0;
        let startY  = 0;
        const THRESHOLD = 10; // px movement cancels
        const DELAY     = 500; // ms

        $(document).on('touchstart.kookoawpfMobile', '.jstree-anchor', function(e) {
            const touch = e.originalEvent.touches[0];
            startX = touch.pageX;
            startY = touch.pageY;
            const $anchor = $(this);

            timer = setTimeout(function() {
                timer = null;

                // Prevent the subsequent click/tap
                $anchor.one('click.kookoawpfMobileLongPress', function(ev) {
                    ev.preventDefault();
                    ev.stopPropagation();
                });

                // Haptic feedback
                if (navigator.vibrate) navigator.vibrate(50);

                // Get jsTree node
                const $node = $anchor.closest('.jstree-node');
                const inst  = $('#kookoawpf-jstree').jstree(true);
                if (!inst) return;
                const node = inst.get_node($node.attr('id'));
                if (!node) return;

                // Remove previous highlight
                $('#kookoawpf-jstree .kookoawpf-context-active').removeClass('kookoawpf-context-active');
                $node.addClass('kookoawpf-context-active');

                // Show context menu — on mobile it becomes bottom sheet via CSS
                // Viewport coordinates — context menu is `position: fixed`.
                FO._showContextMenu(touch.clientX, touch.clientY, node);
            }, DELAY);
        });

        // Use native passive listener so Chrome doesn't block scrolling
        longPressMoveHandler = function(e) {
            if (!timer) return;
            const touch = e.touches[0];
            if (Math.abs(touch.pageX - startX) > THRESHOLD || Math.abs(touch.pageY - startY) > THRESHOLD) {
                clearTimeout(timer);
                timer = null;
            }
        };
        document.addEventListener('touchmove', longPressMoveHandler, { passive: true });

        $(document).on('touchend.kookoawpfMobile touchcancel.kookoawpfMobile', function() {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
        });
    }

    /* ================================================
       Backdrop for context menu (bottom sheet)
       ================================================ */

    function bindBackdrop() {
        $backdrop = $('<div class="kookoawpf-mobile-backdrop" style="display:none;"></div>');
        $('body').append($backdrop);

        // Tap backdrop to close context menu
        $backdrop.on('click.kookoawpfMobile', function() {
            $('#kookoawpf-context-menu').hide();
            $backdrop.hide();
            $('#kookoawpf-jstree .kookoawpf-context-active').removeClass('kookoawpf-context-active');
        });

        // Watch context menu visibility via MutationObserver
        const ctxEl = document.getElementById('kookoawpf-context-menu');
        if (ctxEl) {
            observeCtxMenu(ctxEl);
        } else {
            // Context menu may not exist yet — wait for it
            ctxMenuBodyObs = new MutationObserver(function(mutations) {
                for (let i = 0; i < mutations.length; i++) {
                    for (let j = 0; j < mutations[i].addedNodes.length; j++) {
                        const n = mutations[i].addedNodes[j];
                        if (n.id === 'kookoawpf-context-menu') {
                            observeCtxMenu(n);
                            ctxMenuBodyObs.disconnect();
                            ctxMenuBodyObs = null;
                            return;
                        }
                    }
                }
            });
            ctxMenuBodyObs.observe(document.body, { childList: true });
        }
    }

    function observeCtxMenu(el) {
        if (ctxMenuObs) ctxMenuObs.disconnect();
        ctxMenuObs = new MutationObserver(function() {
            if (!active || !$backdrop) return;
            const visible = el.style.display !== 'none' && el.style.display !== '';
            if (visible) {
                $backdrop.show();
            } else {
                $backdrop.hide();
            }
        });
        ctxMenuObs.observe(el, { attributes: true, attributeFilter: ['style'] });
    }

    /* ================================================
       Flatten submenus in context menu (no flyout on touch)
       ================================================ */

    function flattenSubmenus() {
        // MutationObserver: every time context menu content changes, flatten submenus
        const $ctx = $('#kookoawpf-context-menu');
        if (!$ctx.length) {
            // Wait for context menu to be created
            ctxContentBodyObs = new MutationObserver(function(mutations) {
                for (let i = 0; i < mutations.length; i++) {
                    for (let j = 0; j < mutations[i].addedNodes.length; j++) {
                        if (mutations[i].addedNodes[j].id === 'kookoawpf-context-menu') {
                            observeCtxContent($(mutations[i].addedNodes[j]));
                            ctxContentBodyObs.disconnect();
                            ctxContentBodyObs = null;
                            return;
                        }
                    }
                }
            });
            ctxContentBodyObs.observe(document.body, { childList: true });
        } else {
            observeCtxContent($ctx);
        }
    }

    function observeCtxContent($ctx) {
        if (ctxContentObs) ctxContentObs.disconnect();
        ctxContentObs = new MutationObserver(function() {
            if (!active) return;
            // Find submenu parents and flatten them
            $ctx.find('.kookoawpf-ctx-has-sub').each(function() {
                const $parent = $(this);
                const $submenu = $parent.find('.kookoawpf-ctx-submenu');
                if (!$submenu.length) return;

                // Remove separators inside submenu (keep all move items together)
                $submenu.children('.kookoawpf-ctx-sep').remove();

                // Move submenu items into main list (replaces the parent item)
                const $items = $submenu.children('li');
                $parent.before($items);

                // Add separator after "Move to Folder..." (last flattened item)
                const $moveToFolder = $ctx.find('[data-action="move-to-folder"]');
                if ($moveToFolder.length) {
                    $moveToFolder.after('<li class="kookoawpf-ctx-sep"></li>');
                }

                // Remove the parent item (Move Folder >)
                $parent.remove();

                // Clean up double separators
                $ctx.find('.kookoawpf-ctx-sep + .kookoawpf-ctx-sep').remove();
            });
        });
        ctxContentObs.observe($ctx[0], { childList: true, subtree: true });
    }

    /* ================================================
       Auto-collapse sidebar after folder selection
       ================================================ */

    function bindAutoCollapse() {
        $(document).on('select_node.jstree.kookoawpfMobile', '#kookoawpf-jstree', function() {
            if (!active) return;
            // Small delay so the user sees the selection
            setTimeout(function() {
                collapseSidebar();
            }, 300);
        });
    }

    /* ================================================
       Bootstrap
       ================================================ */

    function onReady() {
        // Listen for matchMedia changes (desktop ↔ mobile)
        if (MQ.addEventListener) {
            MQ.addEventListener('change', function(e) {
                if (e.matches) {
                    init();
                } else {
                    teardown();
                }
            });
        } else if (MQ.addListener) {
            // Safari < 14 fallback
            MQ.addListener(function(e) {
                if (e.matches) {
                    init();
                } else {
                    teardown();
                }
            });
        }

        // Init now if already mobile
        if (MQ.matches) {
            // Wait for FO to be initialized (admin.js runs on DOMReady too)
            const checkFO = setInterval(function() {
                if (window.KookoaWPF && window.KookoaWPF.tree) {
                    clearInterval(checkFO);
                    init();
                }
            }, 50);
            // Safety: stop checking after 10s
            setTimeout(function() { clearInterval(checkFO); }, 10000);
        }
    }

    // Run when DOM is ready
    $(document).ready(onReady);

})(jQuery);
