/**
 * Sifency Offcanvas Wrapper
 * 
 * - Handles open/close state
 * - Manages Body Scroll Locking
 * - Improves Accessibility (Focus Management)
 */
document.addEventListener('DOMContentLoaded', () => {
    'use strict';

    const SifencyOffcanvas = {
        wrapper: null,
        lastActiveElement: null,

        init() {
            this.wrapper = document.getElementById('sifency-offcanvas-wrapper');
            if (!this.wrapper) return;

            this.bindEvents();
        },

        bindEvents() {
            document.body.addEventListener('click', (e) => {
                const trigger = e.target.closest('[data-sifency-offcanvas="open"]');
                if (trigger) {
                    e.preventDefault();
                    this.open(trigger);
                }
            });

            this.wrapper.addEventListener('click', (e) => {
                const closeBtn = e.target.closest('[data-sifency-offcanvas="close"]');
                
                if (closeBtn || e.target === this.wrapper) {
                    e.preventDefault();
                    this.close();
                }
            });

            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && this.wrapper.classList.contains('sifency-open')) {
                    this.close();
                }
            });
        },

        open(triggerElement) {
            this.lastActiveElement = triggerElement || document.activeElement;

            this.wrapper.classList.add('sifency-open');
            this.wrapper.setAttribute('aria-hidden', 'false');
            document.body.style.overflow = 'hidden';

            if (triggerElement) {
                triggerElement.setAttribute('aria-expanded', 'true');
            }
            if (window.elementorFrontend) {
                setTimeout(() => {
                    window.dispatchEvent(new Event('resize'));
                    window.elementorFrontend.init();
                }, 300);
            }
        },

        close() {
            this.wrapper.classList.remove('sifency-open');
            this.wrapper.setAttribute('aria-hidden', 'true');
            document.body.style.overflow = '';

            if (this.lastActiveElement) {
                this.lastActiveElement.setAttribute('aria-expanded', 'false');
                this.lastActiveElement.focus();
                this.lastActiveElement = null;
            }
        }
    };

    // Initialize the module
    SifencyOffcanvas.init();
});