$(document).ready(function () {
    console.log('Eternity Theme Scripts Loaded - Manual Toggle Mode');

    // Custom FAQ Toggle Handler
    // Since we removed data-toggle="collapse" from HTML, we handle it here.
    $('.glass-faq-header').on('click', function (e) {
        e.preventDefault(); // Prevent default behavior just in case
        e.stopPropagation(); // Stop bubbling

        var $this = $(this);
        var targetSelector = $this.data('target');
        var $targetContent = $(targetSelector);

        // Toggle Content via Bootstrap API
        $targetContent.collapse('toggle');

        // Toggle Visual State Manual Override
        // We do this immediately for responsiveness, but also rely on events for sync if needed
        var isExpanded = $this.attr('aria-expanded') === 'true';

        if (isExpanded) {
            // It was open, now closing
            $this.attr('aria-expanded', 'false');
            $this.addClass('collapsed');
        } else {
            // It was closed, now opening
            $this.attr('aria-expanded', 'true');
            $this.removeClass('collapsed');
        }
    });

    // Fallback: Ensure state is synced if something else toggles it
    $('.collapse').on('show.bs.collapse', function () {
        var id = $(this).attr('id');
        var $btn = $('[data-target="#' + id + '"]');
        if ($btn.attr('aria-expanded') !== 'true') {
            $btn.attr('aria-expanded', 'true');
            $btn.removeClass('collapsed');
        }
    });

    $('.collapse').on('hide.bs.collapse', function () {
        var id = $(this).attr('id');
        var $btn = $('[data-target="#' + id + '"]');
        if ($btn.attr('aria-expanded') !== 'false') {
            $btn.attr('aria-expanded', 'false');
            $btn.addClass('collapsed');
        }
    });

    // Mobile Menu: Close when clicking outside
    $(document).on('click', function (event) {
        var $navbar = $('.navbar-collapse');
        var $toggler = $('.navbar-toggler');

        // Check if click is outside navbar and toggler
        if ($navbar.hasClass('show') && !$navbar.is(event.target) && $navbar.has(event.target).length === 0 && !$toggler.is(event.target) && $toggler.has(event.target).length === 0) {
            $navbar.collapse('hide');
        }
    });

    // Mobile Menu: Also close when clicking a link (optional UX improvement)
    $('.navbar-nav .nav-link').on('click', function () {
        if ($('.navbar-toggler').is(':visible')) {
            $('.navbar-collapse').collapse('hide');
        }
    });
});
