function renderSearchTabContent(results) {
    const searchTab = document.getElementById("microsoft-search-tab");

    // 🔁 Prepare the wrapper with filter-toggle and filter-section
    searchTab.innerHTML = `
        <div class="tab-content-wrapper">
            <div class="filter-wrapper">
                <div class="filter-section" id="industry-filter-microsoft-search"></div>
            </div>
            <div class="products-section"></div>
        </div>
    `;

    // 🟨 Show filter skeleton while loading
    const filterContainer = document.getElementById("industry-filter-microsoft-search");
    filterContainer.innerHTML = getFilterSkeleton();

    // 🟨 Store results in map
    microsoftProductMap['search'] = {
        rawElements: results,
        filtered: results,
        currentPage: 1
    };

    // 🟨 Load filters and initial search results
    renderIndustryCategoryFilter('industry-filter-microsoft-search');
    renderSearchCards(results, searchTab, 1, 8);
}

function handleSearch(event) {
    const input = document.getElementById("searchInput");
    const query = input.value.trim().toLowerCase();
    const searchTab = document.getElementById("microsoft-search-tab");

    if (!lastActiveTabId) {
        const activeTab = document.querySelector('.microsoft-tab-content.active');
        if (activeTab) lastActiveTabId = activeTab.id;
    }

    if (query === '') {
        searchTab.style.display = 'none';
        searchTab.classList.remove('active');

        if (lastActiveTabId) {
            const previousTab = document.getElementById(lastActiveTabId);
            if (previousTab) {
                previousTab.style.display = 'block';
                previousTab.classList.add('active');
            }
        }

        const lastSlug = lastActiveTabId?.replace('microsoft-', '');
        const previousTabButton = document.querySelector(`.microsoft-tab[data-tab="${lastSlug}"]`);
        if (previousTabButton) previousTabButton.classList.add('active');

        return;
    }

    const isEnterKey = event.type === 'keyup' && event.key === 'Enter';
    const isIconClick = event.type === 'click';

    if ((isEnterKey || isIconClick) && query) {
        const allProductElements = document.querySelectorAll('.msft-product-card');
        const seenTitles = new Set();
        const results = [];

        allProductElements.forEach(card => {
            const title = card.querySelector('.msft-product-name')?.textContent.toLowerCase();
            const desc = card.querySelector('.msft-product-blurb')?.textContent.toLowerCase();

            if ((title.includes(query) || (desc && desc.includes(query))) && !seenTitles.has(title)) {
                seenTitles.add(title);

                const clonedCard = card.cloneNode(true);

                // ✅ Copy data-industry-ids attribute for filtering
                const industryIds = card.getAttribute('data-industry-ids');
                if (industryIds) clonedCard.setAttribute('data-industry-ids', industryIds);

                results.push(clonedCard);
            }
        });

        microsoftProductMap['search'] = {
            rawElements: results,
            currentPage: 1
        };

        // Hide all tabs
        document.querySelectorAll('.microsoft-tab-content').forEach(tab => {
            tab.style.display = 'none';
            tab.classList.remove('active');
        });

        document.querySelectorAll('.microsoft-tab').forEach(tab => tab.classList.remove('active'));

        renderSearchTabContent(results);
        searchTab.style.display = 'block';
        searchTab.classList.add('active');
    }
}

function renderSearchCards(results, container, currentPage = 1, pageSize = 8) {
    const productContainer = container.querySelector('.products-section');
    if (!productContainer) return;
    const screenWidth = window.innerWidth;
    if (screenWidth <= 480) {
        pageSize = 4;
    } else if (screenWidth <= 1024) {
        pageSize = 6;
    } else {
        pageSize = 8;
    }

    const existingPagination = container.querySelector('.pagination-layout');
    if (existingPagination) existingPagination.remove();

    if (!results || results.length === 0) {
        productContainer.innerHTML = `
            <div class="no-products-message" style="padding: 1rem; color: #444;">
                No products found.
            </div>
        `;
        return;
    }

    productContainer.innerHTML = '';
    const start = (currentPage - 1) * pageSize;
    const paginated = results.slice(start, start + pageSize);

    paginated.forEach(card => productContainer.appendChild(card.cloneNode(true)));

    if (results.length > pageSize) {
        renderSearchPagination(container, results.length, currentPage, pageSize);
    }
}

function renderSearchPagination(container, totalItems, currentPage, pageSize) {
    const totalPages = Math.ceil(totalItems / pageSize);
    if (totalPages <= 1) return;

    const existing = container.querySelector('.pagination-layout');
    if (existing) existing.remove();

    const layout = document.createElement('div');
    layout.className = 'pagination-layout';

    const countDisplay = document.createElement('div');
    countDisplay.className = 'product-count';
    countDisplay.textContent = `${totalItems} Result${totalItems !== 1 ? 's' : ''}`;
    layout.appendChild(countDisplay);

    const controls = document.createElement('div');
    controls.className = 'pagination-controls';

    const prev = document.createElement('button');
    prev.textContent = '<';
    prev.disabled = currentPage === 1;
    prev.onclick = () => changeSearchPage(container, currentPage - 1);
    controls.appendChild(prev);

    for (let page = 1; page <= totalPages; page++) {
        const btn = document.createElement('button');
        btn.textContent = page;
        if (page === currentPage) {
            btn.style.backgroundColor = '#0078d4';
            btn.style.color = '#fff';
        }
        btn.onclick = () => changeSearchPage(container, page);
        controls.appendChild(btn);
    }

    const next = document.createElement('button');
    next.textContent = '>';
    next.disabled = currentPage === totalPages;
    next.onclick = () => changeSearchPage(container, currentPage + 1);
    controls.appendChild(next);

    layout.appendChild(controls);
    container.appendChild(layout);
}

function slugify(text) {
    return text
        .toLowerCase()
        .trim()
        .replace(/[^\w\s-]/g, '')  // Remove special characters
        .replace(/\s+/g, '-');     // Replace spaces with hyphens
}

function scrollTabIntoView(tab) {
    const wrapper = document.getElementById("microsoftTabsWrapper");
    const offset = tab.offsetLeft - wrapper.offsetWidth / 2 + tab.offsetWidth / 2;
    wrapper.scrollTo({ left: offset, behavior: "smooth" });
}

let lastActiveTabId = null;

function changeSearchPage(container, page) {
    const searchData = microsoftProductMap['search'];
    if (!searchData) return;

    const dataToRender = searchData.filtered || searchData.rawElements;

    searchData.currentPage = page;
    renderSearchCards(dataToRender, container, page, 8);
}

function handleSearchIndustryFilterChange(filterContainerId) {
    const filterContainer = document.getElementById(filterContainerId);
    if (!filterContainer) return;
    const screenWidth = window.innerWidth;
    if (screenWidth <= 480) {
        pageSize = 4;
    } else if (screenWidth <= 1024) {
        pageSize = 6;
    } else {
        pageSize = 8;
    }

    const searchData = microsoftProductMap['search'];
    if (!searchData || !searchData.rawElements) return;

    const rawCards = searchData.rawElements;

    const checkedValues = Array.from(
        filterContainer.querySelectorAll('input[name="industry-filter"]:checked')
    ).map(input => input.value);

    let filteredCards;

    if (checkedValues.length > 0) {
        // Filter cloned DOM nodes based on data-industry-ids
        filteredCards = rawCards.filter(card => {
            const industryTag = card.getAttribute('data-industry-ids');
            if (!industryTag) return false;
            const tagList = industryTag.split(',');
            return tagList.some(id => checkedValues.includes(id));
        });
    } else {
        // ✅ If no filters, restore full result
        filteredCards = rawCards;
    }

    searchData.filtered = filteredCards;
    searchData.currentPage = 1;

    // ✅ Always find the correct search tab container
    const wrapper = document.getElementById('microsoft-search-tab');
    renderSearchCards(filteredCards, wrapper, 1, 8);
}

fetchMicrosoftCategories();

function fetchMicrosoftCategories() {
    const apiUrl = `https://genuitysandbox.byappdirect.com/api/marketplace/v1/navigator`;

    fetch(apiUrl)
        .then(response => response.json())
        .then(data => {
            const categories = data?.categories;
            if (!categories) return console.warn("No categories found");

            const tabsContainer = document.getElementById("microsoftTabs");
            const tabShowMoreBtn = document.getElementById("tabMainContainer");
            const contentContainer = document.getElementById("microsoftTabContent");

            tabsContainer.innerHTML = '';
            contentContainer.innerHTML = '';

            const desiredOrder = [
                "Microsoft 365",
                "Dynamics 365",
                "Microsoft Azure",
                "Power Platform",
                "Microsoft Copilot",
                "Microsoft Security",
                "Perpetual or Software Subscription"
            ];

            const sortedCategories = desiredOrder
                .map(name => categories.find(cat => cat.name === name))
                .filter(Boolean);

            // --- Static Microsoft Overview Tab ---
            const overviewSlug = 'microsoft';
            const overviewTabButton = document.createElement("button");
            overviewTabButton.className = 'microsoft-tab active';
            overviewTabButton.textContent = 'Microsoft';
            overviewTabButton.setAttribute('data-tab', overviewSlug);
            // overviewTabButton.onclick = (e) => {
            //     openMicrosoftTab(e, overviewSlug);
            //     scrollTabIntoView(e.currentTarget);
            // };
            overviewTabButton.onclick = (e) => {
                openMicrosoftTab(e, overviewSlug, true);
                scrollTabIntoView(e.currentTarget);
            };
            tabsContainer.appendChild(overviewTabButton);

            const overviewContentDiv = document.createElement("div");
            overviewContentDiv.id = `microsoft-${overviewSlug}`;
            overviewContentDiv.className = `microsoft-tab-content active`;
            overviewContentDiv.style.display = "block";

            const overviewCards = [
                {
                    title: "Microsoft 365",
                    image: "https://nulodgic-static-assets.s3.us-east-1.amazonaws.com/app_direct/images/microsoft/image-1.svg",
                    description: "Modem business demands balancing tools, teams, and time and that's where Microsoft 365 helps. This cloud-based suite brings your essentials together in one place: from email and calendars to video meetings, file sharing, and top-tier security. It streamlines your workflow, letting you concentrate on what truly matters-growing your business. With Microsoft 365 Copilot, your Al assistant, you'll work smarter, move faster, and accomplish more with less effort. Ready to level up your productivity? Switch to Microsoft 365 today"
                },
                {
                    title: "Dynamics 365",
                    image: "https://nulodgic-static-assets.s3.us-east-1.amazonaws.com/app_direct/images/microsoft/image-2.svg",
                    description: "Optimize your operations, strengthen customer relationships, and accelerate growth with Microsoft Dynamics 365-a unified cloud sulte combining ERP and CRM tools. Built for flexibility. Dynamics 365 is modular, scalable, and fully customizable to fit your industry and business needs. Gain faster, smarter insights with a platform designed for today and built to scale with your future"
                },
                {
                    title: "Microsoft Azure",
                    image: "https://nulodgic-static-assets.s3.us-east-1.amazonaws.com/app_direct/images/microsoft/image-3.svg",
                    description: "Want to build smarter, move faster, and stay flexible? Microsoft Azure is your springboard. Develop, deploy, and manage applications across multiple clouds, on-premises, or at the edge-uning the tools and frameworks you already know and trust. With access to over 200 cloud products and services, Azure empowers you to tackle today's challenges and turn tomorrow's ideas into reality."
                },
                {
                    title: "Power Platform",
                    image: "https://nulodgic-static-assets.s3.us-east-1.amazonaws.com/app_direct/images/microsoft/image-4.svg",
                    description: "Tap into the potential of low-code with Microsoft Power Platforma powerful toolkit that turns ideas into real impact. From automating processes and analyzing data to building custom apps and deploying virtual agents, Power Platform makes it simple and fast. Fully integrated with Microsoft 365, Azure, Dynamics 365, and beyond, it gives you everything you need to innovate-without writing a single line of code."
                },
                {
                    title: "Microsoft Copilot",
                    image: "https://nulodgic-static-assets.s3.us-east-1.amazonaws.com/app_direct/images/microsoft/image-5.svg",
                    description: "Leave behind the busywork and focus on what really counts with Microsoft 365 Copilot. Seamlessly embedded in your everyday apps-Word, Excel, PowerPoint, Outlook, and Teams-Copilot uses Al and your Microsoft 365 data to help you work more efficiently, creatively, and effectively. With Microsoft's trusted security and responsible Al, you'll have more time to serve your customers and grow your business"
                },
                {
                    title: "Microsoft Security",
                    image: "https://nulodgic-static-assets.s3.us-east-1.amazonaws.com/app_direct/images/microsoft/image-6.svg",
                    description: "Safeguard your people, data, and infrastructure with Microsoft Security-a comprehensive solution offering. end-to-end protection across cloud and hybrid environments. With Al-powered threat detection, identity and access management, compliance tools, and endpoint security, it covers all the bases. Fully integrated with Microsoft 365, Azure, and third-party platforms, it's the trusted choice for organizations around the world to stay secure and resilient."
                },
                {
                    title: "Perpetual or Software Subscription",
                    image: "https://nulodgic-static-assets.s3.us-east-1.amazonaws.com/app_direct/images/microsoft/image-7.svg",
                    description: "Microsoft offers flexible licensing options to suit your business needs and budget. Choose Perpetual Licensing for a one-time purchase-ideal for long-term use and owning your software outright, like Office 2021. Or opt for Software Subscriptions, such as Microsoft 365 or Dynamics 365, for a pay as you go model that includes the latest features, cloud services, and automatic updates. Whether you prioritize stability or adaptability, Microsoft has a licensing solution that fits your goals."
                }
            ];

            const overviewCardsWrapper = document.createElement("div");
            overviewCardsWrapper.className = "microsoft-overview-cards";

            overviewCards.forEach(card => {
                const cardDiv = document.createElement("div");
                cardDiv.className = "microsoft-overview-card";

                const img = document.createElement("img");
                img.src = card.image;
                img.alt = card.title;

                const contentDiv = document.createElement("div");
                contentDiv.className = "card-content";

                const title = document.createElement("h3");
                title.textContent = card.title;

                const desc = document.createElement("p");
                desc.textContent = card.description;

                contentDiv.appendChild(title);
                contentDiv.appendChild(desc);

                cardDiv.style.cursor = "pointer";
                cardDiv.onclick = () => {
                    const matchingTab = [...document.querySelectorAll(".microsoft-tab")]
                        .find(tab => tab.textContent.trim() === card.title);
                    if (matchingTab) matchingTab.click();
                };

                cardDiv.appendChild(img);
                cardDiv.appendChild(contentDiv);
                overviewCardsWrapper.appendChild(cardDiv);
            });

            overviewContentDiv.appendChild(overviewCardsWrapper);
            contentContainer.appendChild(overviewContentDiv);

            // --- Dynamic Tabs ---
            let firstTabSet = true;
            sortedCategories.forEach((category) => {
                const categoryName = category.name;
                const categoryId = category.id;
                const slug = slugify(categoryName);
                const isActive = !firstTabSet ? 'active' : '';
                firstTabSet = true;

                if (tabsContainer.children.length > 0) {
                    const dot = document.createElement("span");
                    dot.className = "dot-separator";
                    dot.textContent = "•";
                    tabsContainer.appendChild(dot);
                }

                const tabButton = document.createElement("button");
                tabButton.className = `microsoft-tab ${isActive}`;
                tabButton.textContent = category.name;
                tabButton.setAttribute('data-tab', slug);
                // tabButton.onclick = (e) => {
                //     openMicrosoftTab(e, slug);
                //     scrollTabIntoView(e.currentTarget);
                // };
                tabButton.onclick = (e) => {
                    openMicrosoftTab(e, slug, true);  // Enable URL sync
                    scrollTabIntoView(e.currentTarget);
                };
                tabsContainer.appendChild(tabButton);

                const contentDiv = document.createElement("div");
                contentDiv.id = `microsoft-${slug}`;
                contentDiv.className = `microsoft-tab-content ${isActive}`;
                contentDiv.style.display = isActive ? "block" : "none";

                const productRow = document.createElement("div");
                productRow.id = `microsoft-${slug}-products`;
                productRow.className = `microsoft-products-container`;

                contentDiv.appendChild(productRow);
                contentContainer.appendChild(contentDiv);

                fetchMicrosoftProducts(categoryId, productRow.id);
            });
            const urlParams = new URLSearchParams(window.location.search);
            const activeTabSlug = urlParams.get('tab');
            if (activeTabSlug) {
                const tabToActivate = document.querySelector(`.microsoft-tab[data-tab="${activeTabSlug}"]`);
                if (tabToActivate) {
                    tabToActivate.click(); // Triggers openMicrosoftTab
                }
            }

            // --- Show More Button Outside ---
            const showMoreBtn = document.createElement("button");
            showMoreBtn.className = "microsoft-tab show-more-tab";
            showMoreBtn.textContent = "See More";
            showMoreBtn.onclick = openCategoryPanel;
            tabShowMoreBtn.appendChild(showMoreBtn);
        })
        .catch(err => console.error("Failed to fetch Microsoft categories:", err));
}

function openMicrosoftTab(event, slug, pushToUrl = true) {
    const tabs = document.querySelectorAll(".microsoft-tab");
    const contents = document.querySelectorAll(".microsoft-tab-content");
    const heading = document.querySelector(".microsoft-title h1");

    tabs.forEach(tab => tab.classList.remove("active"));
    contents.forEach(content => {
        content.style.display = "none";
        content.classList.remove("active");
    });

    const activeTab = document.querySelector(`.microsoft-tab[data-tab="${slug}"]`);
    if (activeTab) activeTab.classList.add("active");

    const activeContent = document.getElementById(`microsoft-${slug}`);
    if (activeContent) {
        activeContent.style.display = "block";
        activeContent.classList.add("active");
    }

    if (heading && activeTab) {
        heading.textContent = activeTab.textContent;
    }

    // 🔁 Update the URL
    if (pushToUrl) {
        const params = new URLSearchParams(window.location.search);
        params.set('tab', slug);
        window.history.replaceState({}, '', `${location.pathname}?${params.toString()}`);
    }

    const input = document.getElementById("searchInput");
    if (input) input.value = '';
}

function openCategoryPanel() {
    const panel = document.getElementById("categorySidePanel");
    const list = document.getElementById("sidePanelCategoryList");

    panel.classList.add("open");
    list.innerHTML = '';

    const tabs = [...document.querySelectorAll(".microsoft-tab:not(.show-more-tab)")];
    tabs.forEach(tab => {
        const btn = document.createElement("button");
        btn.textContent = tab.textContent;
        btn.onclick = () => {
            tab.click();
            closeCategoryPanel();
        };
        list.appendChild(btn);
    });

    setTimeout(() => {
        document.addEventListener('click', handleOutsideClick);
    }, 0);
}

function handleOutsideClick(event) {
    const panel = document.getElementById('categorySidePanel');

    if (panel.classList.contains('open') && !panel.contains(event.target)) {
        closeCategoryPanel();
        document.removeEventListener('click', handleOutsideClick); // ✅ Remove listener
    }
}

function closeCategoryPanel() {
    document.getElementById("categorySidePanel").classList.remove("open");
    document.removeEventListener('click', handleOutsideClick); // ✅ Ensure it's removed
}

const microsoftProductMap = {};

function fetchMicrosoftProducts(id, containerId) {
    const apiUrl = `https://genuitysandbox.byappdirect.com/api/internal/storefront/v1/listingPage?cat=${id}&order=POPULARITY&page=1&locale=en-US`;

    const mainContainer = document.getElementById(containerId);
    if (!mainContainer) {
        console.error(`❌ Container with ID '${containerId}' not found.`);
        return;
    }

    // Clear previous content
    mainContainer.innerHTML = '';

    // Create wrapper layout
    const layoutWrapper = document.createElement('div');
    layoutWrapper.className = 'tab-content-wrapper';

    // 🔽 Create filter wrapper
    const filterWrapper = document.createElement('div');
    filterWrapper.className = 'filter-wrapper';

    // 🔽 Create filter section (NO toggle button now)
    const filterBox = document.createElement('div');
    filterBox.className = 'filter-section';
    filterBox.id = `industry-filter-${containerId}`;
    filterBox.innerHTML = getFilterSkeleton(); // Skeleton while loading

    // Append only filter section to wrapper
    filterWrapper.appendChild(filterBox);

    // 🔽 Create products section
    const productList = document.createElement('div');
    productList.className = 'products-section';
    productList.innerHTML = getSkeletonLayout(); // Product skeleton

    // Append all to main layout
    layoutWrapper.appendChild(filterWrapper);
    layoutWrapper.appendChild(productList);
    mainContainer.appendChild(layoutWrapper);

    // ✅ Fetch and render filters
    renderIndustryCategoryFilter(filterBox.id);

    // ✅ Fetch and render products
    fetch(apiUrl)
        .then(response => response.json())
        .then(data => {
            const products = data?.listingProducts?.items;
            if (!products || !Array.isArray(products)) {
                productList.innerHTML = `<p style="padding: 1rem;">No products found.</p>`;
                return;
            }

            const mainContainerId = containerId.replace('-products', '');
            microsoftProductMap[mainContainerId] = {
                products,
                currentPage: 1
            };

            // Responsive page size logic
            const screenWidth = window.innerWidth;
            const pageSize = screenWidth <= 480 ? 4 : (screenWidth <= 1024 ? 6 : 8);

            renderProductCards(products, productList, 1, pageSize, mainContainer);
        })
        .catch(error => {
            console.error("Microsoft Product Fetch Error:", error);
            productList.innerHTML = `<p style="padding: 1rem; color: red;">Failed to load products.</p>`;
        });
}

function getSkeletonLayout(count = 8) {
    let skeletons = '';
    const screenWidth = window.innerWidth;
    if (screenWidth <= 480) {
        count = 4;
    } else if (screenWidth <= 1024) {
        count = 6;
    } else {
        count = 8;
    }
    for (let i = 0; i < count; i++) {
        skeletons += `
            <div class="skeleton-card">
                <div class="skeleton-box"></div>
                <div class="skeleton-box-product-details">
                    <div class="skeleton-line skeleton-title"></div>
                    <div class="skeleton-line skeleton-text short"></div>
                    <div class="skeleton-line skeleton-text long"></div>
                </div>
            </div>
        `;
    }

    return `${skeletons}`;
}

function renderProductCards(filteredProducts, productContainer, currentPage = 1, pageSize = 8, mainContainer) {
    productContainer.innerHTML = '';
    const screenWidth = window.innerWidth;
    if (screenWidth <= 480) {
        pageSize = 4;
    } else if (screenWidth <= 1024) {
        pageSize = 6;
    } else {
        pageSize = 8;
    }

    if (!filteredProducts || filteredProducts.length === 0) {
        productContainer.innerHTML = `<p style="padding: 1rem; color: #444;">No products found.</p>`;
        const existing = mainContainer.querySelector('.pagination-layout');
        if (existing) existing.remove();
        return;
    }

    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    const paginated = filteredProducts.slice(start, end);

    paginated.forEach(product => {
        const productSlug = slugify(product.name);
        const productUrl = `/en-US/apps/${product.id}/${productSlug}`;
        const rating = Math.round(product.ratingsSummary?.absoluteRating || 0);

        const card = document.createElement('div');
        card.className = 'msft-product-card';

        // 🔑 Add data-industry-ids attribute
        const industryTag = product.tags?.find(tag => tag.name === "Industry");
        const industryIds = industryTag?.children?.map(child => child.id).join(',') || '';
        if (industryIds) {
            card.setAttribute('data-industry-ids', industryIds);
        }

        let starsHTML = '';
        for (let i = 1; i <= 5; i++) {
            const starClass = i <= rating ? 'rating_starItem--positive' : 'rating_starItem--neutral';
            starsHTML += `<svg fill="black" viewBox="0 0 17 16" xmlns="http://www.w3.org/2000/svg" class="rating_starItem ${starClass}"><path d="M10.797 5.644h5.607c.576 0 .815.723.35 1.056L12.217 9.94l1.733 5.24c.178.538-.447.985-.913.653L8.5 12.594l-4.536 3.24c-.466.333-1.092-.115-.913-.653l1.733-5.24-4.536-3.24C-.22 6.367.019 5.644.595 5.644h5.607L7.935.403c.177-.538.951-.538 1.129 0l1.733 5.24z"></path></svg>`;
        }

        card.innerHTML = `
            <a href="${productUrl}" class="msft-product-card-link">
                <div class="msft-product-image"><img src="${product.iconUrl}" alt="${product.name}" /></div>
                <div class="msft-product-details">
                    <h3 class="msft-product-name">${product.name}</h3>
                    <p class="msft-product-blurb">${product.blurb || ''}</p>
                    <div class="msft-prize-ratting">
                        <p class="msft-product-price">${product.startingPrice?.formattedFullPrice || 'N/A'}</p>
                    </div>
                </div>
            </a>
        `;
        productContainer.appendChild(card);
    });

    // Clean and re-render pagination
    const existing = mainContainer.querySelector('.pagination-layout');
    if (existing) existing.remove();

    if (filteredProducts.length > pageSize) {
        renderPaginationControls(mainContainer, filteredProducts.length, currentPage, pageSize);
    }
}

function renderPaginationControls(container, totalItems, currentPage, pageSize) {
    const screenWidth = window.innerWidth;
    if (screenWidth <= 480) {
        pageSize = 4;
    } else if (screenWidth <= 1024) {
        pageSize = 6;
    } else {
        pageSize = 8;
    }
    const totalPages = Math.ceil(totalItems / pageSize);
    if (totalPages <= 1) return;

    const existingLayout = container.querySelector('.pagination-layout');
    if (existingLayout) existingLayout.remove();

    const layout = document.createElement('div');
    layout.className = 'pagination-layout';

    const countDisplay = document.createElement('div');
    countDisplay.className = 'product-count';
    countDisplay.textContent = `${totalItems} Result${totalItems !== 1 ? 's' : ''}`;

    layout.appendChild(countDisplay);

    const controls = document.createElement('div');
    controls.className = 'pagination-controls';

    const prev = document.createElement('button');
    prev.textContent = '<';
    prev.disabled = currentPage === 1;
    prev.onclick = () => changePage(container, currentPage - 1);
    controls.appendChild(prev);

    for (let page = 1; page <= totalPages; page++) {
        const btn = document.createElement('button');
        btn.textContent = page;
        if (page === currentPage) {
            btn.style.backgroundColor = '#0078d4';
            btn.style.color = '#fff';
        }
        btn.onclick = () => changePage(container, page);
        controls.appendChild(btn);
    }

    const next = document.createElement('button');
    next.textContent = '>';
    next.disabled = currentPage === totalPages;
    next.onclick = () => changePage(container, currentPage + 1);
    controls.appendChild(next);

    layout.appendChild(controls);
    container.appendChild(layout);
}

function changePage(mainContainer, newPage) {
    if (!mainContainer || !mainContainer.id) return;

    const cleanedId = mainContainer.id.replace('-products', '');
    const mapEntry = microsoftProductMap[cleanedId];
    if (!mapEntry) return;

    const productList = mainContainer.querySelector('.products-section');
    if (!productList) return;

    const activeProducts = mapEntry.filtered || mapEntry.products;
    mapEntry.currentPage = newPage;

    renderProductCards(activeProducts, productList, newPage, 8, mainContainer);
}

function renderIndustryCategoryFilter(containerId) {
    console.log("Rendering Industry Category Filter for:", containerId);

    const container = document.getElementById(containerId);
    if (!container) return;

    // Show loader
    container.innerHTML = getFilterSkeleton();

    const apiUrl = "https://genuitysandbox.byappdirect.com/api/marketplace/v1/navigator";

    fetch(apiUrl)
        .then(response => response.json())
        .then(data => {
            console.log("Filter API response:", data);

            const categories = data.categories || [];

            const industryCategory = categories.find(cat => cat.name === "Industry");
            if (!industryCategory || !industryCategory.subCategories?.length) {
                container.innerHTML = `<p style="padding: 1rem; color: gray;">No filters found.</p>`;
                return;
            }

            // Clear loader
            container.innerHTML = '';
            container.classList.add('filter-section');

            // 🔹 Filter header
            const header = document.createElement('div');
            header.className = 'filter-header';
            header.innerHTML = `
                <h4>Filters</h4>
            `;
            header.onclick = () => {
                if (window.innerWidth > 480) return;
                const section = header.closest('.filter-section');
                if (section) {
                    section.classList.toggle('open');
                }
            }
            container.appendChild(header);

            // 🔹 Filter body wrapper
            const filterBody = document.createElement('div');
            filterBody.className = 'filter-body';

            const filterBodyHHead = document.createElement('div');
            filterBodyHHead.className = 'filter-body-head';

            // Section title
            const sectionTitle = document.createElement('div');
            sectionTitle.className = 'filter-section-title';
            sectionTitle.textContent = 'Industry';
            filterBodyHHead.appendChild(sectionTitle);

            const sectionBtn = document.createElement('span');
            sectionBtn.className = 'filter-clear';
            sectionBtn.textContent = 'Clear';
            sectionBtn.onclick = () => clearIndustryFilters(containerId);
            filterBodyHHead.appendChild(sectionBtn);

            filterBody.appendChild(filterBodyHHead);

            // 🔹 Checkboxes
            industryCategory.subCategories.forEach(subCat => {
                const wrapper = document.createElement("div");
                wrapper.className = "checkbox-item";

                const input = document.createElement("input");
                input.type = "checkbox";
                input.id = `industry-${subCat.id}-${containerId}`;
                input.value = subCat.id;
                input.name = "industry-filter";

                const label = document.createElement("label");
                label.htmlFor = input.id;
                label.textContent = subCat.name;

                const screenWidth = window.innerWidth;
                const filterSection = container.closest('.filter-section');

                if (containerId.includes('microsoft-search')) {
                    input.addEventListener('change', () => {
                        if (screenWidth <= 480 && filterSection) {
                            filterSection.classList.remove('open');
                        }
                        handleSearchIndustryFilterChange(containerId);
                    });
                } else {
                    input.addEventListener('change', () => {
                        if (screenWidth <= 480 && filterSection) {
                            filterSection.classList.remove('open');
                        }
                        handleIndustryFilterChange(containerId);
                    });
                }

                wrapper.appendChild(input);
                wrapper.appendChild(label);
                filterBody.appendChild(wrapper);
            });

            // Append body
            container.appendChild(filterBody);
        })
        .catch(error => {
            console.error("Error loading Industry filters:", error);
            container.innerHTML = `<p style="padding: 1rem; color: red;">Failed to load filters.</p>`;
        });
}

function getFilterSkeleton() {
    if (window.innerWidth <= 480) {
        return `
            <div class="skeleton-filter-section">
                <div class="skeleton-line skeleton-text long"></div>
            </div>
        `;
    }

    return `
        <div class="skeleton-filter-section">
            <div class="skeleton-line skeleton-title" style="width: 100px;"></div>
            <div class="skeleton-line skeleton-text short"></div>
            <div class="skeleton-line skeleton-text short"></div>
            <div class="skeleton-line skeleton-text short"></div>
            <div class="skeleton-line skeleton-text short"></div>
        </div>
    `;
}

function handleIndustryFilterChange(filterContainerId) {
    const filterContainer = document.getElementById(filterContainerId);
    if (!filterContainer) {
        console.warn(`Filter container "${filterContainerId}" not found.`);
        return;
    }

    const containerId = filterContainerId.replace('industry-filter-', '');
    const cleanedId = containerId.replace('-products', '');
    const mapEntry = microsoftProductMap[cleanedId];
    if (!mapEntry) return;

    const allProducts = mapEntry.products;

    const checkedValues = Array.from(
        filterContainer.querySelectorAll('input[name="industry-filter"]:checked')
    ).map(input => input.value);

    let filtered = allProducts;

    if (checkedValues.length > 0) {
        filtered = allProducts.filter(product => {
            const tags = product.tags?.find(tag => tag.name === "Industry");
            const subCatIds = tags?.children?.map(child => child.id.toString()) || [];
            return subCatIds.some(id => checkedValues.includes(id));
        });
    }

    mapEntry.filtered = filtered;
    mapEntry.currentPage = 1;

    const wrapper = filterContainer.closest('.microsoft-tab-content');
    const productList = wrapper?.querySelector('.products-section');

    if (productList) {
        productList.innerHTML = getSkeletonLayout();
        setTimeout(() => {
            renderProductCards(filtered, productList, 1, 8, wrapper);
        }, 300);
    }
}

function clearIndustryFilters(filterContainerId) {
    document.querySelectorAll(`#${filterContainerId} input[name="industry-filter"]`)
        .forEach(input => input.checked = false);

    const container = document.querySelector(`#${filterContainerId}`).closest('.microsoft-tab-content');
    const productList = container?.querySelector('.products-section');

    if (productList) {
        productList.innerHTML = getSkeletonLayout();

        const screenWidth = window.innerWidth;
        if (screenWidth <= 480) {
            const filterSection = document.getElementById(filterContainerId);
            if (filterSection) {
                filterSection.classList.remove('open');
            }
        }

        // Let the correct handler re-render with all data
        setTimeout(() => {
            if (filterContainerId.includes('microsoft-search')) {
                handleSearchIndustryFilterChange(filterContainerId);
            } else {
                handleIndustryFilterChange(filterContainerId);
            }
        }, 300);
    }
}
