(() => {
    const ns = window.MiracleAccounts = window.MiracleAccounts || {};

    const ensureFixedStrategy = instance => {
        if (!instance || !instance._popper) {
            return;
        }

        instance._popper.setOptions(options => {
            const next = { ...(options ?? {}), strategy: "fixed" };
            const modifiers = Array.isArray(options?.modifiers) ? [...options.modifiers] : [];
            if (!modifiers.some(mod => mod && mod.name === "preventOverflow")) {
                modifiers.push({
                    name: "preventOverflow",
                    options: { boundary: "viewport" }
                });
            }

            next.modifiers = modifiers;
            return next;
        });

        instance._popper.update();
    };

    ns.ensureDropdownsFixed = root => {
        const element = root instanceof HTMLElement ? root : document.querySelector(root);
        if (!element || !window.bootstrap?.Dropdown) {
            return;
        }

        const Dropdown = window.bootstrap.Dropdown;

        element.querySelectorAll('[data-bs-toggle="dropdown"]').forEach(toggle => {
            const config = {
                boundary: document.body,
                reference: "toggle",
                popperConfig: defaultConfig => {
                    const base = defaultConfig || {};
                    const modifiers = Array.isArray(base.modifiers) ? [...base.modifiers] : [];
                    if (!modifiers.some(mod => mod && mod.name === "preventOverflow")) {
                        modifiers.push({
                            name: "preventOverflow",
                            options: { boundary: "viewport" }
                        });
                    }

                    return {
                        ...base,
                        strategy: "fixed",
                        modifiers
                    };
                }
            };

            const instance = Dropdown.getInstance(toggle) ?? new Dropdown(toggle, config);
            toggle.dataset.dropdownFixed = "true";
            ensureFixedStrategy(instance);
        });
    };

    document.addEventListener("shown.bs.dropdown", event => {
        const toggle = event.target;
        if (!toggle?.dataset?.dropdownFixed) {
            return;
        }

        const instance = window.bootstrap?.Dropdown?.getInstance(toggle);
        if (!instance) {
            return;
        }

        ensureFixedStrategy(instance);
    });
})();
