(function ($) {
    "use strict";

    if (typeof SifencyData === 'undefined') {
        console.error("SifencyData is missing.");
        return;
    }

    let allTemplates = []; 
    let favorites = JSON.parse(localStorage.getItem('sifency_favs')) || [];
    let sifencyObserver = null;

    $(window).on("elementor:init", function () {
        elementor.on("preview:loaded", function () {
            const $iframe = elementor.$previewContents;
            
            function addSifencyButton() {
                const $targetArea = $iframe.find(".elementor-add-new-section");
                $targetArea.each(function () {
                    const $folderBtn = $(this).find(".elementor-add-template-button");
                    if (!$folderBtn.length) return;
                    
                    const $container = $folderBtn.parent();
                    if ($container.find(".sifency-get-template-trigger").length > 0) return;

                    const buttonHTML = `
                        <div class="elementor-add-section-area-button sifency-get-template-trigger" 
                             title="Sifency Library" role="button" tabindex="0">
                             <img src="${SifencyData.logoUrl}" class="sifency-icon-img" style="width:24px; height:auto;" alt="Sifency">
                        </div>
                    `;
                    $folderBtn.after(buttonHTML);
                });
            }
            
            addSifencyButton();

            if (sifencyObserver) sifencyObserver.disconnect();
            
            if ($iframe.length > 0 && $iframe[0].body) {
                sifencyObserver = new MutationObserver(addSifencyButton);
                sifencyObserver.observe($iframe[0].body, { childList: true, subtree: true });
            }

            $iframe.on("click", ".sifency-get-template-trigger", function () {
                window.parent.SifencyOpenModal();
            });
        });
    });

    window.SifencyOpenModal = function () {
        $("#sifency-modal").fadeIn(200);
        if (allTemplates.length === 0) {
            fetchLibrary();
        }
    };

    function fetchLibrary() {
        $("#sifency-loader").show();
        $.ajax({
            url: SifencyData.ajaxurl,
            type: "POST",
            data: { action: "sifency_fetch_library", nonce: SifencyData.nonce },
            success: function (res) {
                if (res.success && res.data) {
                    allTemplates = res.data;
                    generateSidebar();
                    renderGrid();
                } else {
                    $("#sifency-grid").html('<div class="sifency-empty">Failed to load templates. Please try again.</div>');
                }
            },
            error: function () {
                $("#sifency-grid").html('<div class="sifency-empty">Server Error. Please check your internet connection.</div>');
            },
            complete: function() {
                $("#sifency-loader").hide();
            }
        });
    }

    function generateSidebar() {
        const categories = new Set();
        
        allTemplates.forEach(item => {
            if (item.category && item.category.trim() !== "") {
                categories.add(item.category.toLowerCase());
            }
        });

        const sortedCats = Array.from(categories).sort();
        let html = '<li class="active" data-cat="all">All</li>';
        
        sortedCats.forEach(cat => {
            const label = cat.charAt(0).toUpperCase() + cat.slice(1);
            html += `<li data-cat="${cat}">${label}</li>`;
        });

        $("#sifency-cat-list").html(html);
    }

    function renderGrid() {
        const activeTab = $(".sifency-tab.active").data("tab");
        const activeCat = $("#sifency-cat-list li.active").data("cat");
        const searchVal = $("#sifency-search-input").val().toLowerCase();
        let html = "";
        
        const filtered = allTemplates.filter(item => {
            if (activeTab === 'saved') return favorites.includes(item.id);
            if (item.type !== activeTab) return false;
            
            if (activeCat && activeCat !== 'all') {
                if (item.category.toLowerCase() !== activeCat) return false;
            }
            
            if (searchVal && !item.title.toLowerCase().includes(searchVal)) return false;
            return true;
        });
        
        if (filtered.length === 0) {
            $("#sifency-grid").html('<div class="sifency-empty">No templates found.</div>');
            return;
        }

        filtered.forEach(item => {
            const isFav = favorites.includes(item.id) ? 'active' : '';
            const isProTemplate = (item.is_pro === true || item.is_pro === "true");
            const userIsPro = SifencyData.isPro;

            const proBadge = isProTemplate ? '<span class="badge-pro">PRO</span>' : '';
            
            let btnClass = "btn-import";
            let btnText = "Insert";
            let lockIcon = "";

            if (isProTemplate && !userIsPro) {
                btnClass = "btn-locked";
                btnText = "Go Pro";
                lockIcon = '<i class="eicon-lock"></i> ';
            }

            html += `
            <div class="sifency-card">
                <div class="sifency-card-img">
                    <img src="${item.image}" alt="${item.title}" loading="lazy">
                    <div class="sifency-overlay">
                        <button class="${btnClass}" data-id="${item.id}" data-pro="${isProTemplate}">
                            ${lockIcon}${btnText}
                        </button>
                    </div>
                    ${proBadge}
                </div>
                <div class="sifency-card-footer">
                    <span>${item.title}</span>
                    <i class="eicon-heart ${isFav}" data-id="${item.id}" role="button" title="Favorite"></i>
                </div>
            </div>`;
        });
        
        $("#sifency-grid").html(html);
    }

    function debounce(func, wait) {
        let timeout;
        return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), wait);
        };
    }

    $(document).ready(function() {
        const $modal = $("#sifency-modal");

        $("#sifency-modal-close").on("click", function() { $modal.fadeOut(200); });

        $(document).on("keyup", function(e) {
            if (e.key === "Escape" && $modal.is(":visible")) {
                $modal.fadeOut(200);
            }
        });

        $(".sifency-tab").on("click", function() {
            $(".sifency-tab").removeClass("active");
            $(this).addClass("active");
            $("#sifency-cat-list li").removeClass("active");
            $('[data-cat="all"]').addClass("active");
            
            renderGrid();
        });

        $(document).on("click", "#sifency-cat-list li", function() {
            $("#sifency-cat-list li").removeClass("active");
            $(this).addClass("active");
            renderGrid();
        });

        $("#sifency-search-input").on("input", debounce(function() { 
            renderGrid(); 
        }, 300));

        $(document).on("click", ".eicon-heart", function() {
            const id = $(this).data("id");
            if (favorites.includes(id)) {
                favorites = favorites.filter(fav => fav !== id);
                $(this).removeClass("active");
            } else {
                favorites.push(id);
                $(this).addClass("active");
            }
            localStorage.setItem('sifency_favs', JSON.stringify(favorites));
            if($(".sifency-tab.active").data("tab") === 'saved') renderGrid();
        });

        $(document).on("click", ".btn-import", function() {
            const $btn = $(this);
            const id = $btn.data("id");
            const isPro = $btn.data("pro");

            $btn.text("Importing...").prop("disabled", true);

            $.ajax({
                url: SifencyData.ajaxurl,
                type: "POST",
                data: { 
                    action: "sifency_import_template", 
                    template_id: id, 
                    is_pro: isPro,
                    nonce: SifencyData.nonce 
                },
                success: function(res) {
                    try {
                        if (res.success && res.data && res.data.content) {
                            let content = res.data.content;
                            if (!Array.isArray(content)) content = [content];

                            content.forEach(function (elementModel) {
                                $e.run('document/elements/create', {
                                    model: elementModel,
                                    container: elementor.documents.getCurrent().container 
                                });
                            });
                            $modal.fadeOut(200);
                        } else {
                            alert(res.data || "Import failed.");
                        }
                    } catch (error) {
                        alert("Error: " + error.message);
                    } finally {
                        $btn.text("Insert").prop("disabled", false);
                    }
                },
                error: function(xhr) {
                    alert("Server Error: " + xhr.statusText);
                    $btn.text("Insert").prop("disabled", false);
                }
            });
        });

        $(document).on("click", ".btn-locked", function() {
            alert(SifencyData.proNotice || "This template requires a Pro license."); 
            window.open('https://sifency.com/sifency-addons', '_blank');
        });

        $("#sifency-local-import").on("change", function(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const json = JSON.parse(e.target.result);
                    let content = json.content || json;
                    
                    if (!Array.isArray(content)) content = [content];

                    content.forEach(function (elementModel) {
                        $e.run('document/elements/create', {
                            model: elementModel,
                            container: elementor.documents.getCurrent().container 
                        });
                    });

                    $modal.fadeOut(200);
                } catch (err) { 
                    alert("Invalid JSON file. Ensure it is a valid Elementor Template."); 
                    console.error("Local Import Error: ", err);
                } finally {
                    $("#sifency-local-import").val('');
                }
            };
            reader.readAsText(file);
        });
    });

})(jQuery);