/**
 * Frontend interactions for maca Restu (no jQuery — works on block themes).
 */
(function () {
    'use strict';

    function cfg() {
        return typeof window.macaMenulist === 'object' && window.macaMenulist ? window.macaMenulist : {};
    }

    function strings() {
        var c = cfg();
        return c.strings || {};
    }

    function getDisplayMode() {
        var wrap = document.querySelector('.maca-menulist-wrap');
        if (wrap && wrap.getAttribute('data-display-mode')) {
            return wrap.getAttribute('data-display-mode');
        }
        var c = cfg();
        return c.displayMode || 'inline';
    }

    function isPdfMenu(data) {
        return data && data.file_type === 'pdf' && data.file_url;
    }

    function showCloseButton() {
        var btn = document.getElementById('maca-menu-close');
        if (btn) {
            btn.style.display = 'flex';
        }
    }

    function hideCloseButton() {
        var btn = document.getElementById('maca-menu-close');
        if (btn) {
            btn.style.display = 'none';
        }
    }

    function escapeHtml(text) {
        var div = document.createElement('div');
        div.textContent = text == null ? '' : String(text);
        return div.innerHTML;
    }

    function setHtml(el, html) {
        if (el) {
            el.innerHTML = html;
        }
    }

    function renderMenuInto(container, data) {
        if (!container) {
            return;
        }

        var s = strings();

        if (!data) {
            setHtml(container, '<p>' + escapeHtml(s.noMenu || 'No menu') + '</p>');
            return;
        }

        if (data.schedule_note && data.html && data.html.indexOf('maca-menu-schedule-note') === -1) {
            data.html =
                '<p class="maca-menu-schedule-note">' +
                escapeHtml(data.schedule_note) +
                '</p>' +
                data.html;
        }

        if (data.html) {
            setHtml(container, data.html);
            return;
        }

        if (isPdfMenu(data) && window.MacaMenulistPdf) {
            container.innerHTML = '';
            var holder = document.createElement('div');
            holder.className = 'maca-pdf-js-holder';
            container.appendChild(holder);
            window.MacaMenulistPdf.render(holder, data.file_url, data.title || '', {
                loadingText: s.loading || 'Loading...',
                showTitle: !!cfg().showMenuTitle
            });
            return;
        }

        setHtml(container, '<p>' + escapeHtml(s.noMenu || 'No menu') + '</p>');
    }

    function postCategoryMenu(categoryId) {
        var c = cfg();
        var body = new URLSearchParams({
            action: 'maca_load_category_menu',
            category_id: String(categoryId),
            nonce: c.nonce || ''
        });

        return fetch(c.ajaxUrl || '', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: body.toString(),
            credentials: 'same-origin'
        }).then(function (response) {
            if (!response.ok) {
                throw new Error('HTTP ' + response.status);
            }
            return response.json();
        });
    }

    function loadCategoryMenu(categoryId) {
        var c = cfg();
        var s = strings();
        var displayMode = getDisplayMode();

        if (displayMode === 'new_page') {
            var viewerUrl =
                (c.ajaxUrl || '') +
                '?action=maca_load_category_menu' +
                '&category_id=' +
                encodeURIComponent(categoryId) +
                '&nonce=' +
                encodeURIComponent(c.nonce || '') +
                '&render_html=1';

            var newTab = window.open(viewerUrl, '_blank');
            if (!newTab) {
                window.location.href = viewerUrl;
            }
            return;
        }

        if (displayMode === 'popup') {
            var popup = document.getElementById('maca-menu-popup');
            var overlay = document.getElementById('maca-popup-overlay');
            var content = document.getElementById('maca-popup-content');

            if (!content || !popup || !overlay) {
                return;
            }

            setHtml(content, '<div class="maca-loading">' + escapeHtml(s.loading || 'Loading...') + '</div>');
            popup.classList.add('active');
            overlay.classList.add('active');
            showCloseButton();

            postCategoryMenu(categoryId)
                .then(function (response) {
                    if (response && response.success) {
                        renderMenuInto(content, response.data);
                    } else {
                        setHtml(content, '<p>' + escapeHtml(s.noMenu || 'No menu') + '</p>');
                    }
                })
                .catch(function () {
                    setHtml(content, '<p>' + escapeHtml(s.error || 'Error') + '</p>');
                });
            return;
        }

        var display = document.getElementById('maca-menu-display');
        if (!display) {
            return;
        }

        setHtml(display, '<div class="maca-loading">' + escapeHtml(s.loading || 'Loading...') + '</div>');
        showCloseButton();

        postCategoryMenu(categoryId)
            .then(function (response) {
                if (response && response.success) {
                    renderMenuInto(display, response.data);
                } else {
                    setHtml(display, '<p>' + escapeHtml(s.noMenu || 'No menu') + '</p>');
                }
            })
            .catch(function () {
                setHtml(display, '<p>' + escapeHtml(s.error || 'Error') + '</p>');
            });
    }

    function closeActiveMenu() {
        var s = strings();
        var displayMode = getDisplayMode();
        var placeholder =
            '<p class="maca-menu-placeholder">' + escapeHtml(s.selectCategory || 'Select a category') + '</p>';

        if (displayMode === 'popup') {
            var popup = document.getElementById('maca-menu-popup');
            var overlay = document.getElementById('maca-popup-overlay');
            var content = document.getElementById('maca-popup-content');
            if (popup) {
                popup.classList.remove('active');
            }
            if (overlay) {
                overlay.classList.remove('active');
            }
            if (content) {
                setHtml(content, placeholder);
            }
        } else if (displayMode === 'inline') {
            setHtml(document.getElementById('maca-menu-display'), placeholder);
        }

        document.querySelectorAll('.maca-category-button').forEach(function (btn) {
            btn.classList.remove('active');
        });
        hideCloseButton();
    }

    function onClick(event) {
        var target = event.target;

        if (target.closest && target.closest('#maca-popup-overlay')) {
            closeActiveMenu();
            return;
        }

        if (target.closest && target.closest('#maca-menu-close')) {
            closeActiveMenu();
            return;
        }

        var button = target.closest ? target.closest('.maca-category-button') : null;
        if (!button) {
            return;
        }

        var categoryId = button.getAttribute('data-category-id');
        if (!categoryId) {
            return;
        }

        document.querySelectorAll('.maca-category-button').forEach(function (btn) {
            btn.classList.remove('active');
        });
        button.classList.add('active');
        loadCategoryMenu(categoryId);
    }

    function init() {
        document.addEventListener('click', onClick);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
