/* Theme Scripts */
(function ($) {
    'use strict';

    var doc = document;
    var win = window;
    var $window = $(win);
    var $document = $(doc);
    var $main = $('main');
    var submenuLabel = $('.navbar').first().data('submenu-label') || 'Toggle submenu';
    var $navbarCollapse = $('.navbar-collapse');
    var $navbarToggler = $('.navbar-toggler');
    var $mobileMenuClose = $('.mobile-menu-close');
    var $searchToggle = $('#blueboxed-search-toggle');
    var $searchForm = $('#blueboxed-search-field');
    var $searchInput = $searchForm.find('input[name="s"]');
    var searchOpenClass = 'form-active';

    doc.documentElement.classList.add('bb-js');

    function setSearchState(open) {
        if (!$searchForm.length || !$searchToggle.length) {
            return;
        }

        $searchForm.toggleClass(searchOpenClass, open);
        $searchForm.attr('aria-hidden', open ? 'false' : 'true');
        $searchToggle.attr('aria-expanded', open ? 'true' : 'false');

        if (open) {
            win.setTimeout(function () {
                $searchInput.trigger('focus');
            }, 140);
        }
    }

    function closeSearch() {
        setSearchState(false);
    }

    if ($searchToggle.length) {
        $searchToggle.on('click', function (event) {
            event.preventDefault();
            setSearchState(!$searchForm.hasClass(searchOpenClass));
        });
    }

    $window.on('scroll', function () {
        closeSearch();
    });

    $document.on('click', function (event) {
        if (!$(event.target).closest('.header-search').length) {
            closeSearch();
        }
    });

    $document.on('keydown', function (event) {
        if (event.key === 'Escape') {
            closeSearch();
            if ($navbarCollapse.hasClass('show')) {
                $navbarCollapse.removeClass('show');
                $main.removeAttr('aria-hidden').show();
                $navbarToggler.attr('aria-expanded', 'false').trigger('focus');
            }
        }
    });

    $navbarCollapse.on('shown.bs.collapse', function () {
        if ($window.width() < 992) {
            $main.attr('aria-hidden', 'true').hide();
        }
    });

    $navbarCollapse.on('hidden.bs.collapse', function () {
        $main.removeAttr('aria-hidden').show();
        $navbarToggler.attr('aria-expanded', 'false');
    });

    $mobileMenuClose.on('click', function () {
        $navbarCollapse.removeClass('show');
        $main.removeAttr('aria-hidden').show();
        $navbarToggler.attr('aria-expanded', 'false').trigger('focus');
    });

    $window.on('resize', function () {
        if ($window.width() >= 992) {
            $main.removeAttr('aria-hidden').show();
            $navbarCollapse.removeClass('show');
            $navbarToggler.attr('aria-expanded', 'false');
        }
    });

    if ($('.navbar ul ul').length > 0) {
        $('.navbar ul ul').each(function () {
            var $submenu = $(this);
            var submenuId = $submenu.attr('id');
            if (!submenuId) {
                submenuId = 'submenu-' + Math.random().toString(36).slice(2, 9);
                $submenu.attr('id', submenuId);
            }

            if (!$submenu.prev('.submenu-caret').length) {
                $submenu.before('<button class="submenu-caret" type="button" aria-expanded="false" aria-controls="' + submenuId + '" aria-label="' + submenuLabel + '"></button>');
            }
        });
    }

    $document.on('click', '.submenu-caret', function () {
        var $button = $(this);
        var $submenu = $button.next('ul');
        var isExpanded = $button.attr('aria-expanded') === 'true';

        $button.attr('aria-expanded', isExpanded ? 'false' : 'true');
        $submenu.slideToggle();

        $button.parent().siblings().find('> .submenu-caret').attr('aria-expanded', 'false');
        $button.parent().siblings().find('ul').slideUp();
    });

    function parseRgbColor(color) {
        if (!color) {
            return null;
        }

        var rgbaMatch = color.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);
        if (!rgbaMatch) {
            return null;
        }

        return {
            r: parseInt(rgbaMatch[1], 10),
            g: parseInt(rgbaMatch[2], 10),
            b: parseInt(rgbaMatch[3], 10)
        };
    }

    function getLuminance(rgb) {
        function normalizeChannel(channel) {
            var value = channel / 255;
            return value <= 0.03928 ? value / 12.92 : Math.pow((value + 0.055) / 1.055, 2.4);
        }

        var r = normalizeChannel(rgb.r);
        var g = normalizeChannel(rgb.g);
        var b = normalizeChannel(rgb.b);

        return (0.2126 * r) + (0.7152 * g) + (0.0722 * b);
    }

    function applyAutoContrast() {
        var targets = doc.querySelectorAll('.menu, .blueboxed-page article, .content-posts .entry-content, .search-field-form');

        targets.forEach(function (target) {
            target.classList.add('bb-auto-contrast-target');

            var computed = win.getComputedStyle(target);
            var rgb = parseRgbColor(computed.backgroundColor);
            if (!rgb) {
                return;
            }

            var isDarkSurface = getLuminance(rgb) < 0.36;
            target.classList.toggle('bb-surface-dark', isDarkSurface);
            target.classList.toggle('bb-surface-light', !isDarkSurface);
        });
    }

    function setupScrollReveal() {
        var reduceMotion = win.matchMedia('(prefers-reduced-motion: reduce)').matches;
        var revealTargets = doc.querySelectorAll('.blueboxed-page article, .content-posts .entry-content, .content-posts .post-thumbnail');

        revealTargets.forEach(function (element, index) {
            element.classList.add('bb-reveal');
            element.style.setProperty('--bb-reveal-delay', ((index % 6) * 70) + 'ms');
        });

        if (reduceMotion || !('IntersectionObserver' in win)) {
            revealTargets.forEach(function (element) {
                element.classList.add('bb-in-view');
            });
            return;
        }

        var observer = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (entry.isIntersecting) {
                    entry.target.classList.add('bb-in-view');
                    observer.unobserve(entry.target);
                }
            });
        }, {
            threshold: 0.12,
            rootMargin: '0px 0px -6% 0px'
        });

        revealTargets.forEach(function (element) {
            observer.observe(element);
        });
    }

    applyAutoContrast();
    setupScrollReveal();
    $window.on('resize', applyAutoContrast);
})(jQuery);
