(function () {
    'use strict';

    let selectedTemplateId = null;

    document.addEventListener('DOMContentLoaded', function () {

        restoreTemplateSelection();
        // applyStep1ParentDefaultFilter();
        initCategoryFilters();
        document.querySelectorAll('.template-card').forEach(card => {

            // Card click
            card.addEventListener('click', function (e) {

                // Ignore preview click
                if (e.target.closest('.btn-preview')) {
                    return;
                }

                // Ignore select button (handled separately)
                if (e.target.closest('.btn-select')) {
                    return;
                }

                selectTemplate(card);
            });

            // ✅ Preview button handling
            const previewBtn = card.querySelector('.btn-preview');
            if (previewBtn) {
                previewBtn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    openTemplatePreview(card);
                });
            }

            // ✅ Explicit Select button handling
            const selectBtn = card.querySelector('.btn-select');
            if (selectBtn) {
                selectBtn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    // Mark this as a direct select button click
                    window.directSelectClick = true;
                    selectTemplate(card);
                    window.directSelectClick = false;
                });
            }
        });
    });

    /**
     * Open template preview in new tab
     */
    function openTemplatePreview(card) {
        const templateId = card.dataset.template;
        const templateName = card.dataset.name || 'Template';
        const demoUrl = card.dataset.demoUrl;

        // If demo URL is stored in data attribute, use it
        if (demoUrl && demoUrl.trim()) {
            window.open(demoUrl, '_blank');
            return;
        }

        // Otherwise, try to fetch it from API
        console.log('Fetching demo URL for template:', templateId);

        // Show loading state
        const previewBtn = card.querySelector('.btn-preview');
        const originalText = previewBtn.innerHTML;
        previewBtn.innerHTML = '⏳ Loading...';
        previewBtn.disabled = true;

        // Fetch template details from API
        fetch('https://templates.wp-turbo.com/api/v1/templates/' + templateId, {
            method: 'GET',
            headers: { 'Accept': 'application/json' }
        })
        .then(response => response.json())
        .then(data => {
            if (data.data && data.data.demo_url) {
                window.open(data.data.demo_url, '_blank');
            } else {
                // Fallback: try template packs API
                return fetch('https://templates.wp-turbo.com/api/v1/template-packs/' + templateId, {
                    method: 'GET',
                    headers: { 'Accept': 'application/json' }
                }).then(response => response.json());
            }
        })
        .then(data => {
            if (data && data.data && data.data.demo_url) {
                window.open(data.data.demo_url, '_blank');
            } else {
                alert('Demo URL not available for this template.');
            }
        })
        .catch(error => {
            console.error('Error fetching template preview:', error);
            alert('Could not load preview. Please try again.');
        })
        .finally(() => {
            previewBtn.innerHTML = originalText;
            previewBtn.disabled = false;
        });
    }

    /**
     * Select template card
     */
    function selectTemplate(card) {
        document.querySelectorAll('.template-card')
            .forEach(c => c.classList.remove('selected'));

        card.classList.add('selected');

        selectedTemplateId = card.dataset.template;
        const templateName = card.dataset.name;
        const templateIsPro = card.dataset.pro === 'true' ? 'pro' : 'free';

        // Save locally
        sessionStorage.setItem('trstemp_template_id', selectedTemplateId);
        sessionStorage.setItem('trstemp_template_name', templateName);
        sessionStorage.setItem('trstemp_template_access_type', templateIsPro);

        // Update Continue button to show it's ready
        const continueBtn = document.getElementById('trstemp-next-btn');
        if (continueBtn) {
            continueBtn.textContent = 'Continue with ' + templateName + ' →';
            continueBtn.classList.add('template-selected');
        }

        // Save server-side then redirect only if this was a direct select button click
        if (window.directSelectClick) {
            fetch(trstempStep2.ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:
                    'action=trstemp_save_step_data' +
                    '&step=' + trstempStep2.step +
                    '&nonce=' + trstempStep2.nonce +
                    '&data=' + encodeURIComponent(JSON.stringify({
                        template_id: selectedTemplateId,
                        template_name: templateName
                    }))
            })
            .finally(() => {
                // ✅ Redirect AFTER save attempt
                window.location.href =
                    window.location.pathname +
                    '?page=turbo-starter-templates&ci=3' +
                    '&template=' + selectedTemplateId +
                    '&name=' + encodeURIComponent(templateName);
            });
        } else {
            // Just save the selection for the Continue button to use
            fetch(trstempStep2.ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body:
                    'action=trstemp_save_step_data' +
                    '&step=' + trstempStep2.step +
                    '&nonce=' + trstempStep2.nonce +
                    '&data=' + encodeURIComponent(JSON.stringify({
                        template_id: selectedTemplateId,
                        template_name: templateName
                    }))
            });
        }
    }

    /**
     * Restore previously selected template
     */
    function restoreTemplateSelection() {

        const savedId = sessionStorage.getItem('trstemp_template_id');
        const savedName = sessionStorage.getItem('trstemp_template_name');
        if (!savedId) return;

        const card = document.querySelector(
            `.template-card[data-template="${savedId}"]`
        );

        if (card) {
            card.classList.add('selected');
            selectedTemplateId = savedId;
            
            // Update Continue button
            const continueBtn = document.getElementById('trstemp-next-btn');
            if (continueBtn && savedName) {
                continueBtn.textContent = 'Continue with ' + savedName + ' →';
                continueBtn.classList.add('template-selected');
            }
        }
    }

    // function applyStep1ParentDefaultFilter() {
    //     const savedType = sessionStorage.getItem('trstemp_website_type'); // e.g. business
    //     if (!savedType) {
    //         document.querySelectorAll('.template-card')
    //             .forEach(card => card.style.display = 'none');
    //         return;
    //     }

    //     const parentBtn = document.querySelector(
    //         `.trstemp-filter[data-category="${savedType}"][data-category-id]`
    //     );

    //     if (parentBtn) {
    //         parentBtn.click(); // triggers filtering
    //     }
    // }

    function clearTemplateSelectionSession() {
        sessionStorage.removeItem('trstemp_template_id');
        sessionStorage.removeItem('trstemp_template_name');
        sessionStorage.removeItem('trstemp_template_access_type');
        

        // UI reset
        document.querySelectorAll('.template-card')
            .forEach(c => c.classList.remove('selected'));

        const continueBtn = document.getElementById('trstemp-next-btn');
        if (continueBtn) {
            continueBtn.textContent = 'Continue →';
            continueBtn.classList.remove('template-selected');
        }
    }


    function initCategoryFilters() {

        let activeParentId = null;
        let activeChildId  = null;

        const parentBtns = document.querySelectorAll('.trstemp-filter[data-category-id]');
        const childBtns  = document.querySelectorAll('.subfilter[data-category-id]');
        const cards      = document.querySelectorAll('.template-card');

        if (!cards.length) return;

        // ✅ STEP-1 parent auto apply (NO click simulation)
        const savedType = sessionStorage.getItem('trstemp_website_type'); // business
        console.log('STEP-1 SELECTED TYPE:', savedType);
        parentBtns.forEach(btn => {
        if (savedType && btn.dataset.category !== savedType) {
                const wrapper = btn.closest('.trstemp-filter-dropdown');
                if (wrapper) {
                    wrapper.style.display = 'none';
                } else {
                    btn.style.display = 'none';
                }
            }
        });
        if (savedType) {
            const parentBtn = document.querySelector(
                `.trstemp-filter[data-category="${savedType}"][data-category-id]`
            );

            if (parentBtn) {
                activeParentId = parentBtn.dataset.categoryId;

                parentBtns.forEach(b => b.classList.remove('trstemp-active'));
                parentBtn.classList.add('trstemp-active');
            }
        }

        // Apply initial filter
        applyFilter();

        // Parent click
        parentBtns.forEach(btn => {
            btn.addEventListener('click', function () {
                clearTemplateSelectionSession(); // 🔥 ADD THIS
                activeParentId = this.dataset.categoryId;
                activeChildId  = null;

                parentBtns.forEach(b => b.classList.remove('trstemp-active'));
                this.classList.add('trstemp-active');

                childBtns.forEach(b => b.classList.remove('active'));

                applyFilter();
            });
        });

        // Child click
        childBtns.forEach(btn => {
            btn.addEventListener('click', function (e) {
                e.preventDefault();
                e.stopPropagation();
                clearTemplateSelectionSession(); // 🔥 ADD THIS
                activeChildId = this.dataset.categoryId;

                childBtns.forEach(b => b.classList.remove('active'));
                this.classList.add('active');

                applyFilter();
            });
        });

        function applyFilter() {

            cards.forEach(card => {

                const parentId = card.dataset.parentId || '';
                const childId  = card.dataset.childId || '';

                // Parent only
                if (activeParentId && !activeChildId) {
                    card.style.display =
                        parentId === activeParentId ? '' : 'none';
                    return;
                }

                // Parent + Child
                if (activeParentId && activeChildId) {
                    card.style.display =
                        parentId === activeParentId && childId === activeChildId
                            ? ''
                            : 'none';
                    return;
                }

                // No parent selected → hide
                card.style.display = 'none';
            });
            // 🔔 fallback check
            const visibleCards = Array.from(cards).filter(
                card => card.style.display !== 'none'
            );

            const fallbackBox = document.getElementById('trstemp-no-templates');

            if (fallbackBox) {
                fallbackBox.style.display =
                    visibleCards.length === 0 ? 'block' : 'none';
            }
        }

        // 🔍 Search filter (client-side only)
        const searchInput = document.getElementById('trstemp-template-search');

        if (searchInput) {
            searchInput.addEventListener('input', function () {

                const keyword = this.value.toLowerCase().trim();
                clearTemplateSelectionSession();
                // 🔁 If search cleared → re-apply category filter
                if (!keyword) {
                    applyFilter();
                    return;
                }

                let visibleCount = 0;

                cards.forEach(card => {

                    // Only search inside category-visible cards
                    const parentId = card.dataset.parentId || '';
                    const childId  = card.dataset.childId || '';

                    let allowedByCategory = false;

                    if (activeParentId && !activeChildId) {
                        allowedByCategory = parentId === activeParentId;
                    } else if (activeParentId && activeChildId) {
                        allowedByCategory =
                            parentId === activeParentId && childId === activeChildId;
                    }

                    if (!allowedByCategory) {
                        card.style.display = 'none';
                        return;
                    }

                    const name = (card.dataset.name || '').toLowerCase();

                    if (name.includes(keyword)) {
                        card.style.display = '';
                        visibleCount++;
                    } else {
                        card.style.display = 'none';
                    }
                });

                // 🔔 fallback check
                const fallbackBox = document.getElementById('trstemp-no-templates');
                if (fallbackBox) {
                    fallbackBox.style.display =
                        visibleCount === 0 ? 'block' : 'none';
                }
            });

        }

        /* ================================
        Template Type Filter (Dropdown)
        ================================ */

        const typeSelect = document.getElementById('template-type');

        if (typeSelect) {
            typeSelect.addEventListener('change', function () {
                clearTemplateSelectionSession();
                const selectedType = this.value; // all | pack | single
                let visibleCount = 0;

                cards.forEach(card => {

                    const cardType = card.dataset.templateType; // pack | single

                    // Respect category filter first
                    const parentId = card.dataset.parentId || '';
                    const childId  = card.dataset.childId || '';

                    let allowedByCategory = false;

                    if (activeParentId && !activeChildId) {
                        allowedByCategory = parentId === activeParentId;
                    } else if (activeParentId && activeChildId) {
                        allowedByCategory =
                            parentId === activeParentId && childId === activeChildId;
                    }

                    if (!allowedByCategory) {
                        card.style.display = 'none';
                        return;
                    }

                    // 🔹 All types
                    if (selectedType === 'all') {
                        card.style.display = '';
                        visibleCount++;
                        return;
                    }

                    // 🔹 Match specific type
                    if (cardType === selectedType) {
                        card.style.display = '';
                        visibleCount++;
                    } else {
                        card.style.display = 'none';
                    }
                });

                // 🔔 No templates fallback
                const fallbackBox = document.getElementById('trstemp-no-templates');
                if (fallbackBox) {
                    fallbackBox.style.display =
                        visibleCount === 0 ? 'block' : 'none';
                }
            });
        }

        /* ================================
        Free / Pro Filter Buttons
        ================================ */

        const typeButtons = document.querySelectorAll('.type-filter');

        typeButtons.forEach(btn => {
            btn.addEventListener('click', function () {
                clearTemplateSelectionSession(); // 🔥 ADD THIS
                const selectedType = this.dataset.type; // all | free | pro

                // UI active state
                typeButtons.forEach(b => b.classList.remove('active'));
                this.classList.add('active');

                let visibleCount = 0;

                cards.forEach(card => {

                    const cardIsPro = card.dataset.pro === 'true';

                    // 🔹 Respect category filter first
                    const parentId = card.dataset.parentId || '';
                    const childId  = card.dataset.childId || '';

                    let allowedByCategory = false;

                    if (activeParentId && !activeChildId) {
                        allowedByCategory = parentId === activeParentId;
                    } else if (activeParentId && activeChildId) {
                        allowedByCategory =
                            parentId === activeParentId && childId === activeChildId;
                    }

                    if (!allowedByCategory) {
                        card.style.display = 'none';
                        return;
                    }

                    // 🔹 ALL
                    if (selectedType === 'all') {
                        card.style.display = '';
                        visibleCount++;
                        return;
                    }

                    // 🔹 FREE
                    if (selectedType === 'free' && cardIsPro === false) {
                        card.style.display = '';
                        visibleCount++;
                        return;
                    }

                    // 🔹 PRO
                    if (selectedType === 'pro' && cardIsPro === true) {
                        card.style.display = '';
                        visibleCount++;
                        return;
                    }

                    card.style.display = 'none';
                });

                // 🔔 fallback message
                const fallbackBox = document.getElementById('trstemp-no-templates');
                if (fallbackBox) {
                    fallbackBox.style.display =
                        visibleCount === 0 ? 'block' : 'none';
                }
            });
        });

    }


})();
