(function() {
    'use strict';

    var csInterface = null;
    var registeredPlugins = new Set();
    var clickHandler = null;

    var MENU_IDS = {
        SEP_LINE: 'SEP_LINE',
        HLP_GUIDE: 'HLP_GUIDE',
        MORE_TOOLS: 'MORE_TOOLS',
        JH_WORK: 'JH_WORK'
    };

    var HELP_GUIDE_URLS = {
        'comp-o-rama': 'https://www.jonhanlan.me/tools/comporama/help-guide/'
    };

    function openURL(url) {
        if (csInterface) {
            csInterface.openURLInDefaultBrowser(url);
        }
    }

    function createMenuXML(pluginSlug) {
        return '<Menu>' +
            '<MenuItem Id="' + MENU_IDS.SEP_LINE + '" Label="––––––––––––––––" Enabled="false"/>' +
            '<MenuItem Id="' + MENU_IDS.HLP_GUIDE + '" Label="help guide"/>' +
            '<MenuItem Id="' + MENU_IDS.MORE_TOOLS + '" Label="more tools"/>' +
            '<MenuItem Id="' + MENU_IDS.JH_WORK + '" Label="jon hanlan\'s work"/>' +
            '</Menu>';
    }

    function handleMenuClick(pluginSlug, menuId) {
        switch (menuId) {
            case MENU_IDS.HLP_GUIDE:
                if (window.HanlanCore && window.HanlanCore.helpDocs && window.HanlanCore.helpDocs._initialized) {
                    window.HanlanCore.helpDocs.show();
                } else {
                    openURL(HELP_GUIDE_URLS[pluginSlug] || ('https://www.jonhanlan.me/tools/' + pluginSlug + '/help-guide'));
                }
                break;
            case MENU_IDS.MORE_TOOLS:
                openURL('https://www.jonhanlan.me/tools');
                break;
            case MENU_IDS.JH_WORK:
                openURL('https://www.jonhanlan.me');
                break;
        }
    }

    function setupClickListener(pluginSlug) {
        if (clickHandler) {
            return;
        }

        var debounceTimeout = null;
        clickHandler = function(event) {
            if (debounceTimeout) {
                return;
            }

            debounceTimeout = setTimeout(function() {
                debounceTimeout = null;
            }, 100);

            var menuId = event.data.menuId;
            if (Object.values(MENU_IDS).indexOf(menuId) !== -1) {
                handleMenuClick(pluginSlug, menuId);
            }
        };

        csInterface.addEventListener('com.adobe.csxs.events.flyoutMenuClicked', clickHandler);
    }

    function removeOldMenuItems() {
        Object.values(MENU_IDS).forEach(function(id) {
            try {
                csInterface.removeMenuItem(id);
            } catch(e) {}
        });
    }

    function registerHanlanLinks(pluginSlug) {
        if (!pluginSlug || registeredPlugins.has(pluginSlug)) {
            return;
        }

        if (typeof CSInterface === 'undefined') {
            console.error('HanlanCore Panel Links: CSInterface not available');
            return;
        }

        if (!csInterface) {
            csInterface = new CSInterface();
        }

        removeOldMenuItems();

        var menuXML = createMenuXML(pluginSlug);
        csInterface.setPanelFlyoutMenu(menuXML);

        setupClickListener(pluginSlug);

        registeredPlugins.add(pluginSlug);
        console.log('HanlanCore Panel Links registered for:', pluginSlug);
    }

    // Auto-initialize when ready
    function autoInit() {
        // Get slug from: window.HANLAN_PLUGIN_SLUG, body data attribute, or extension ID
        var slug = window.HANLAN_PLUGIN_SLUG ||
                   (document.body && document.body.dataset.pluginSlug) ||
                   null;

        // Fallback: try to get from CSInterface extension ID
        if (!slug && typeof CSInterface !== 'undefined') {
            try {
                var cs = new CSInterface();
                var extId = cs.getExtensionID();
                // Extract slug from extension ID (e.g., "com.jonhanlan.comp-o-rama" -> "comp-o-rama")
                if (extId) {
                    var parts = extId.split('.');
                    slug = parts[parts.length - 1];
                }
            } catch(e) {}
        }

        if (slug) {
            registerHanlanLinks(slug);
        }
    }

    // Auto-init on DOMContentLoaded or immediately if already loaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', autoInit);
    } else {
        // Small delay to ensure CSInterface is available
        setTimeout(autoInit, 100);
    }

    // Expose to global scope for manual registration if needed
    window.registerHanlanLinks = registerHanlanLinks;
})();
