(function ($) {
    "use strict";

    // Cache selectors.
    const $icon = $("#elmls-icon");
    const $flags = $("#elmls-flags");
    let timeoutId = null;
    let isHovered = false;

    // Initialize immediately (no document.ready).
    function init() {
        // Toggle flags on click.
        $icon.on("click", function(e) {
            e.preventDefault();
            e.stopPropagation();
            if ($flags.is(":visible")) {
                hideFlags();
            } else {
                showFlags();
            }
        });

        // Pause timer on hover.
        $flags.on("mouseenter", function() {
            isHovered = true;
            clearTimeout(timeoutId);
        });

        // Resume timer on leave.
        $flags.on("mouseleave", function() {
            isHovered = false;
            if ($flags.is(":visible")) {
                startCloseTimer();
            }
        });

        // Close on outside click - IGNORE clicks inside the flags container.
        $(document).on("click", function(e) {
            // If click is inside the flags container or on the icon, do nothing.
            if ($(e.target).closest("#elmls-flags").length > 0 || $(e.target).closest("#elmls-icon").length > 0) {
                return;
            }
            // Otherwise close the menu.
            hideFlags();
        });
    }

    // Show flags.
    function showFlags() {
        $flags.css("display", "block");
        startCloseTimer();
    }

    // Start 2-second timer.
    function startCloseTimer() {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(function() {
            if (!isHovered && $flags.is(":visible")) {
                hideFlags();
            }
        }, 2000);
    }

    // Hide flags.
    function hideFlags() {
        $flags.css("display", "none");
        clearTimeout(timeoutId);
        timeoutId = null;
    }

    // Run immediately.
    init();
})(jQuery);
