document.addEventListener('DOMContentLoaded', () => {
    const isTouch = window.matchMedia('(hover: none)').matches;

    const updatePanelPosition = (item, panel) => {
        const widthMode = panel.dataset.width || 'container';
        const isMobile = window.innerWidth <= 768;

        // Get styling options from data attributes
        const bgColor = panel.dataset.bgColor || '#ffffff';
        const borderRadius = panel.dataset.borderRadius || '0';
        const margin = panel.dataset.margin || '0';
        const padding = panel.dataset.padding || '20';

        // Apply styling
        panel.style.backgroundColor = bgColor;
        panel.style.borderRadius = `${borderRadius}px`;
        panel.style.padding = `${padding}px`;

        // Find the parent navigation container
        const nav = item.closest('nav') || item.closest('header') || item.closest('.site-header');

        // Get the bottom of the navigation area + margin
        let top;
        if (nav) {
            const navRect = nav.getBoundingClientRect();
            top = navRect.bottom + parseInt(margin);
        } else {
            const rect = item.getBoundingClientRect();
            top = rect.bottom + parseInt(margin);
        }

        panel.style.top = `${top}px`;

        // Reset all positioning styles
        panel.style.left = '';
        panel.style.right = '';
        panel.style.width = '';
        panel.style.marginLeft = '';
        panel.style.transform = '';

        if (isMobile) {
            // Mobile: full width
            panel.style.width = '100vw';
            panel.style.left = '0';
        } else {
            // Desktop: always centered
            if (widthMode === 'container') {
                // Container width: centered 1200px max
                const containerWidth = Math.min(1200, window.innerWidth * 0.95);
                panel.style.width = `${containerWidth}px`;
                panel.style.left = '50%';
                panel.style.marginLeft = `-${containerWidth / 2}px`;
            } else if (widthMode === 'custom') {
                // Custom width: user-specified value, centered
                const customWidth = panel.dataset.customWidth || '800px';
                panel.style.width = customWidth;
                panel.style.left = '50%';
                panel.style.transform = 'translateX(-50%)';

                // Check if it goes offscreen
                setTimeout(() => {
                    const panelRect = panel.getBoundingClientRect();
                    if (panelRect.left < 10) {
                        panel.style.left = '10px';
                        panel.style.transform = 'none';
                    } else if (panelRect.right > window.innerWidth - 10) {
                        panel.style.left = 'auto';
                        panel.style.right = '10px';
                        panel.style.transform = 'none';
                    }
                }, 10);
            }
        }

        // Calculate available height
        const availableHeight = window.innerHeight - top - 20;
        panel.style.maxHeight = `${availableHeight}px`;
    };

    document.querySelectorAll('.roardev-mmb-has-mega').forEach(item => {
        const panel = item.querySelector('.roardev-mmb-panel');
        if (!panel) return;

        let trigger = panel.dataset.trigger;
        if (isTouch) trigger = 'click';

        const show = () => {
            // Prevent mega menu from opening on mobile and tablet devices
            if (window.innerWidth <= 1024) {
                return;
            }
            item.classList.add('roardev-mmb-open');
            updatePanelPosition(item, panel);
        };

        const hide = () => {
            item.classList.remove('roardev-mmb-open');
        };

        if (trigger === 'hover') {
            let timeout;
            item.addEventListener('mouseenter', () => {
                clearTimeout(timeout);
                show();
            });
            item.addEventListener('mouseleave', () => {
                timeout = setTimeout(hide, 150);
            });
            panel.addEventListener('mouseenter', () => clearTimeout(timeout));
            panel.addEventListener('mouseleave', () => {
                timeout = setTimeout(hide, 150);
            });
        }

        if (trigger === 'click') {
            const link = item.querySelector('a');
            if (link) {
                link.addEventListener('click', e => {
                    const isInsidePanel = e.target.closest('.roardev-mmb-panel');
                    if (isInsidePanel) return;

                    e.preventDefault();
                    if (item.classList.contains('roardev-mmb-open')) {
                        hide();
                    } else {
                        document.querySelectorAll('.roardev-mmb-has-mega.roardev-mmb-open').forEach(i => i.classList.remove('roardev-mmb-open'));
                        show();
                    }
                });
            }
        }
    });

    // Re-calculate on scroll/resize
    window.addEventListener('scroll', () => {
        const openItem = document.querySelector('.roardev-mmb-has-mega.roardev-mmb-open');
        if (openItem) {
            const panel = openItem.querySelector('.roardev-mmb-panel');
            if (panel) updatePanelPosition(openItem, panel);
        }
    }, { passive: true });

    window.addEventListener('resize', () => {
        const openItem = document.querySelector('.roardev-mmb-has-mega.roardev-mmb-open');
        if (openItem) {
            const panel = openItem.querySelector('.roardev-mmb-panel');
            if (panel) updatePanelPosition(openItem, panel);
        }
    });
});
