(function ($) {
    "use strict";

    const initSifencyDarkMode = ($scope) => {
        const wrapper = $scope.find('.sifency-dark-mode-wrapper')[0];
        if (!wrapper) return;

        const settings = JSON.parse(wrapper.getAttribute('data-darkmode'));
        const toggleBtn = wrapper.querySelector('.sifency-dark-toggle');
        
        let isDark = false;
        const rootHtml = document.documentElement;
        const body = document.body;
        
        const savedTheme = settings.saveCookie ? localStorage.getItem('sifency-theme') : null;
        const osPrefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

        if (savedTheme) {
            isDark = (savedTheme === 'dark');
        } else if (settings.autoMatchOs && osPrefersDark) {
            isDark = true;
        }

        let dynamicStyleTag = document.getElementById('sifency-dark-vars');
        if (!dynamicStyleTag && settings.engine === 'variables') {
            dynamicStyleTag = document.createElement('style');
            dynamicStyleTag.id = 'sifency-dark-vars';
            
            let cssRules = `body.sifency-is-dark { background-color: ${settings.bgDark} !important; color: ${settings.textDark} !important; transition: background-color 0.4s ease, color 0.4s ease; } `;
            
            for (const [variable, shade] of Object.entries(settings.overrides)) {
                cssRules += `body.sifency-is-dark { ${variable}: ${shade} !important; } `;
            }
            
            dynamicStyleTag.innerHTML = cssRules;
            document.head.appendChild(dynamicStyleTag);
        }

        let blendStyleTag = document.getElementById('sifency-dark-blend');
        if (!blendStyleTag && settings.engine === 'blend') {
            blendStyleTag = document.createElement('style');
            blendStyleTag.id = 'sifency-dark-blend';
            
            const ignoreSelectors = settings.ignore || 'img, picture, video, iframe';
            blendStyleTag.innerHTML = `
                html.sifency-is-dark { filter: invert(1) hue-rotate(180deg); background: #111; transition: filter 0.4s ease; min-height: 100vh; }
                html.sifency-is-dark ${ignoreSelectors} { filter: invert(1) hue-rotate(180deg); }
                html.sifency-is-dark .sifency-dark-mode-wrapper { filter: invert(1) hue-rotate(180deg); } /* Keep button looking normal */
            `;
            document.head.appendChild(blendStyleTag);
        }

        const applyTheme = (dark) => {
            if (dark) {
                if (settings.engine === 'blend') rootHtml.classList.add('sifency-is-dark');
                if (settings.engine === 'variables') body.classList.add('sifency-is-dark');
                wrapper.classList.add('is-active');
                
                if (toggleBtn.classList.contains('style-minimal')) {
                    toggleBtn.querySelector('.sf-text-light').style.display = 'none';
                    toggleBtn.querySelector('.sf-text-dark').style.display = 'block';
                }
                if (toggleBtn.classList.contains('style-cyber')) {
                    const cyberTxt = toggleBtn.querySelector('.sf-glitch');
                    cyberTxt.innerText = "OS:DARK";
                    cyberTxt.setAttribute('data-text', "OS:DARK");
                }
            } else {
                rootHtml.classList.remove('sifency-is-dark');
                body.classList.remove('sifency-is-dark');
                wrapper.classList.remove('is-active');
                
                if (toggleBtn.classList.contains('style-minimal')) {
                    toggleBtn.querySelector('.sf-text-light').style.display = 'block';
                    toggleBtn.querySelector('.sf-text-dark').style.display = 'none';
                }
                if (toggleBtn.classList.contains('style-cyber')) {
                    const cyberTxt = toggleBtn.querySelector('.sf-glitch');
                    cyberTxt.innerText = "OS:LIGHT";
                    cyberTxt.setAttribute('data-text', "OS:LIGHT");
                }
            }
            if (settings.saveCookie) {
                localStorage.setItem('sifency-theme', dark ? 'dark' : 'light');
            }
        };

        applyTheme(isDark);

        toggleBtn.addEventListener('click', () => {
            isDark = !isDark;
            applyTheme(isDark);
        });

        if (settings.autoMatchOs && window.matchMedia) {
            window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
                if(!localStorage.getItem('sifency-theme')) {
                    isDark = e.matches;
                    applyTheme(isDark);
                }
            });
        }
    };

    $(window).on('elementor/frontend/init', () => {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-dark-mode.default', initSifencyDarkMode);
    });

    const earlyTheme = localStorage.getItem('sifency-theme');
    if (earlyTheme === 'dark') {
        document.documentElement.classList.add('sifency-is-dark');
        document.body.classList.add('sifency-is-dark');
    }

})(jQuery);