/* ==========================================================================
   RK — Global Mobile Responsive Behaviour
   --------------------------------------------------------------------------
   Pure vanilla JS (no jQuery dependency). Self-initialising and load-order
   independent. Pairs with css/responsive-mobile.css.

   What it does on small screens:
     1. Turns the SB Admin 2 sidebar into an off-canvas drawer with a dark
        backdrop (open via the existing hamburger buttons, close on backdrop
        tap / nav-link tap / Escape).
     2. Neutralises SB Admin 2's buggy "<480px auto-toggle" by keying drawer
        visibility off `body.sidebar-open` instead of the legacy `.toggled`.
     3. Wraps every <table> in a horizontal-scroll container so wide tables
        never break the layout.
   Desktop behaviour and design are left completely unchanged.
   ========================================================================== */
(function () {
    'use strict';

    var MOBILE_MAX = 767.98;

    function isMobile() {
        return window.innerWidth <= MOBILE_MAX;
    }

    /* ----------------------------------------------------------------------
       Off-canvas drawer for the SB Admin 2 sidebar
       ---------------------------------------------------------------------- */
    function setupSidebarDrawer() {
        var sidebar = document.querySelector(
            '#accordionSidebar.sidebar, .navbar-nav.sidebar, .sidebar.sidebar-dark'
        );
        // Pages without the SB Admin sidebar (POS, custom views, print, login)
        // keep their own behaviour.
        if (!sidebar) return;

        // Backdrop element.
        var backdrop = document.querySelector('.rk-backdrop');
        if (!backdrop) {
            backdrop = document.createElement('div');
            backdrop.className = 'rk-backdrop';
            document.body.appendChild(backdrop);
        }

        function openDrawer() { document.body.classList.add('sidebar-open'); }
        function closeDrawer() { document.body.classList.remove('sidebar-open'); }
        function toggleDrawer() { document.body.classList.toggle('sidebar-open'); }

        // Hook the existing hamburger buttons (topbar + round collapse button).
        ['#sidebarToggleTop', '#sidebarToggle'].forEach(function (sel) {
            var buttons = document.querySelectorAll(sel);
            Array.prototype.forEach.call(buttons, function (btn) {
                btn.addEventListener('click', function (e) {
                    if (isMobile()) {
                        e.preventDefault();
                        toggleDrawer();
                    }
                });
            });
        });

        // Tap the backdrop to close.
        backdrop.addEventListener('click', closeDrawer);

        // Close after tapping a real navigation link (not a collapse toggle).
        sidebar.addEventListener('click', function (e) {
            var link = e.target.closest ? e.target.closest('a') : null;
            if (!link) return;
            var isCollapseToggle = link.getAttribute('data-toggle') === 'collapse';
            var href = link.getAttribute('href');
            if (!isCollapseToggle && href && href !== '' && href !== '#') {
                if (isMobile()) closeDrawer();
            }
        });

        // Escape closes the drawer.
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' || e.keyCode === 27) closeDrawer();
        });

        // Don't let the drawer get stuck when rotating / resizing to desktop.
        window.addEventListener('resize', function () {
            if (!isMobile()) closeDrawer();
        });

        // Always start closed on mobile, and clear any stale SB Admin 2 toggle
        // state so its legacy "<480px auto-toggle" can never leave the drawer
        // half-open. On desktop we leave the toggle state alone so the collapse
        // button keeps working.
        function clean() {
            if (!isMobile()) return;
            document.body.classList.remove('sidebar-open', 'sidebar-toggled');
            sidebar.classList.remove('toggled');
        }
        clean();
        window.addEventListener('load', clean);
    }

    /* ----------------------------------------------------------------------
       Wrap every table so it scrolls horizontally on small screens
       ---------------------------------------------------------------------- */
    function wrapTables() {
        var tables = document.querySelectorAll('table');
        Array.prototype.forEach.call(tables, function (table) {
            var parent = table.parentElement;
            if (!parent) return;
            // Skip if already inside a scroll/responsive wrapper.
            if (parent.classList.contains('rk-table-scroll') ||
                parent.classList.contains('table-responsive')) {
                return;
            }
            var wrap = document.createElement('div');
            wrap.className = 'rk-table-scroll';
            parent.insertBefore(wrap, table);
            wrap.appendChild(table);
        });
    }

    function init() {
        setupSidebarDrawer();
        wrapTables();
    }

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