jQuery(window).on('elementor/frontend/init', function() {
    elementorFrontend.hooks.addAction('frontend/element_ready/sifency_advanced_particles.default', function($scope) {
        
        const $hold = $scope.find('.sifency-advanced-particles-hold');
        const config = $hold.data('config');
        const widgetId = $scope.data('id');

        if (!config) return;

        let $target;
        if (config.target === 'custom' && config.target_id) {
            let cleanId = config.target_id.replace('#', '');
            $target = jQuery('#' + cleanId);
        } else {
            $target = $scope.closest('.e-con, .elementor-section, .elementor-top-section, .elementor-column');
        }

        if (!$target || !$target.length) return;

        $target.css({
            'position': 'relative',
            'overflow': 'hidden' 
        });

        const layers = ['deep', 'middle', 'top'];
        const zIndexes = { 'deep': -2, 'middle': -1, 'top': 1 };

        layers.forEach(layerKey => {
            const layerData = config.layers[layerKey];
            if (!layerData || layerData.enabled !== 'yes') return;

            const layerInstanceId = `particles-${layerKey}-${widgetId}`;
            
            $target.find(`#${layerInstanceId}`).remove();

            const $layerDiv = jQuery(`<div id="${layerInstanceId}" class="sifency-particle-layer layer-${layerKey}"></div>`);
            $layerDiv.css({
                'position': 'absolute',
                'top': '0',
                'left': '0',
                'width': '100%',
                'height': '100%',
                'z-index': zIndexes[layerKey],
                'pointer-events': 'none'
            });

            $target.prepend($layerDiv);

            let options = {};
            if (layerData.type === 'json' && layerData.json) {
                try {
                    options = JSON.parse(layerData.json);
                } catch (e) {
                    console.error("Sifency Particles: Invalid JSON in " + layerKey);
                }
            } else {
                options = getSifencyPresets(layerData.preset);
            }

            if (typeof tsParticles !== 'undefined') {
                tsParticles.load(layerInstanceId, options);
            }
        });

        function getSifencyPresets(name) {
            const presets = {
                nasa: {
                    particles: {
                        number: { value: 160, density: { enable: true, area: 800 } },
                        color: { value: "#ffffff" },
                        shape: { type: "circle" },
                        opacity: { value: { min: 0.1, max: 0.8 }, animation: { enable: true, speed: 1, sync: false } },
                        size: { value: { min: 1, max: 3 } },
                        move: { enable: true, speed: 0.5, direction: "none", random: true, outModes: "out" }
                    }
                },
                lines: {
                    particles: {
                        number: { value: 90, density: { enable: true, area: 800 } },
                        color: { value: "#ffffff" },
                        links: { enable: true, distance: 150, color: "#ffffff", opacity: 0.4, width: 1 },
                        move: { enable: true, speed: 1.5 },
                        size: { value: 1 }
                    },
                    interactivity: { events: { onHover: { enable: true, mode: "grab" } } }
                },
                snow: {
                    particles: {
                        number: { value: 150 },
                        color: { value: "#fff" },
                        opacity: { value: 0.7 },
                        size: { value: { min: 1, max: 4 } },
                        move: { enable: true, speed: 1, direction: "bottom", straight: false, outModes: "out" }
                    }
                },
                bubbles: {
                    particles: {
                        number: { value: 30 },
                        color: { value: "#ffffff" },
                        opacity: { value: 0.3 },
                        size: { value: { min: 10, max: 40 } },
                        move: { enable: true, speed: 1, direction: "top", outModes: "out" },
                        shape: { type: "circle" }
                    }
                },
                fireflies: {
                    particles: {
                        number: { value: 40 },
                        color: { value: "#ffcc00" },
                        opacity: { value: { min: 0.2, max: 0.9 }, animation: { enable: true, speed: 2, sync: false } },
                        size: { value: 3 },
                        move: { enable: true, speed: 1, random: true, outModes: "bounce" },
                        shadow: { enable: true, color: "#ffcc00", blur: 10 }
                    }
                },
                confetti: {
                    particles: {
                        number: { value: 60 },
                        color: { value: ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff"] },
                        shape: { type: ["circle", "square"] },
                        opacity: { value: 1 },
                        size: { value: { min: 2, max: 4 } },
                        move: { enable: true, speed: 4, direction: "bottom", outModes: "out" }
                    }
                },
                bokeh: {
                    particles: {
                        number: { value: 20 },
                        color: { value: "#ffffff" },
                        shape: { type: "circle" },
                        opacity: { value: 0.2 },
                        size: { value: { min: 40, max: 80 } },
                        move: { enable: true, speed: 0.5, direction: "none", outModes: "out" }
                    }
                },
                polygon: {
                    particles: {
                        number: { value: 50 },
                        color: { value: "#ffffff" },
                        links: { enable: true, distance: 150, color: "#ffffff", opacity: 0.2, width: 1, triangles: { enable: true, opacity: 0.1 } },
                        move: { enable: true, speed: 1.5 },
                        size: { value: 1 }
                    }
                },
                fountain: {
                    particles: {
                        number: { value: 100 },
                        color: { value: "#ff4400" },
                        size: { value: { min: 1, max: 3 } },
                        move: { enable: true, speed: 3, direction: "top", outModes: "out" },
                        opacity: { animation: { enable: true, speed: 1, minimumValue: 0, sync: false } }
                    }
                },
                parallax: {
                    particles: {
                        number: { value: 40 },
                        color: { value: "#ffffff" },
                        shape: { type: ["circle", "triangle", "polygon"] },
                        opacity: { value: 0.5 },
                        size: { value: { min: 3, max: 6 } },
                        move: { enable: true, speed: 2, parallax: { enable: true, smooth: 10, force: 60 } }
                    }
                },
                sea: {
                    particles: {
                        number: { value: 100 },
                        color: { value: "#00d4ff" },
                        shape: { type: "circle" },
                        opacity: { value: 0.5 },
                        size: { value: 2 },
                        move: { 
                            enable: true, 
                            speed: 1, 
                            direction: "none", 
                            path: { enable: true, delay: { value: 0.1 }, generator: "sinePathGenerator" } 
                        }
                    }
                },
                dark_matter: {
                    particles: {
                        number: { value: 100 },
                        color: { value: "#555555" },
                        shape: { type: "circle" },
                        opacity: { value: { min: 0.1, max: 0.4 } },
                        size: { value: { min: 1, max: 10 } },
                        move: { enable: true, speed: 1, attract: { enable: true, rotateX: 600, rotateY: 1200 } }
                    }
                }
            };

            const baseConfig = {
                fullScreen: { enable: false },
                background: { color: "transparent" },
                fpsLimit: 60,
                detectRetina: true
            };

            return jQuery.extend(true, {}, baseConfig, presets[name] || presets['nasa']);
        }
    });
});