/**
 * Tag Filters - Client-side tag filtering for blog posts
 * Filters posts within the current page without navigation
 */

(function() {
    'use strict';

    // Prevent double initialization
    if (window.tagFiltersInitialized) {
        return;
    }

    let activeTagFilters = new Set();

    // Global function to filter posts by tag (supports multi-selection)
    window.filterPostsByTag = function(tagName) {
        console.log(`🏷️ Filtering posts by tag: ${tagName}`);

        if (activeTagFilters.has(tagName)) {
            // If tag is already selected, remove it
            activeTagFilters.delete(tagName);
            console.log(`🏷️ Removed tag "${tagName}" from selection`);
        } else {
            // Add tag to selection
            activeTagFilters.add(tagName);
            console.log(`🏷️ Added tag "${tagName}" to selection`);
        }

        if (activeTagFilters.size === 0) {
            showAllPosts();
            updateTagButtonStates(activeTagFilters);
        } else {
            filterPostsByTags(activeTagFilters);
            updateTagButtonStates(activeTagFilters);
        }
    };

    // Global function to clear all tag filters
    window.clearAllTagFilters = function() {
        console.log('🏷️ Clearing all tag filters');
        activeTagFilters.clear();
        showAllPosts();
        updateTagButtonStates(activeTagFilters);
        updateShowAllButton(true);
    };

    function filterPostsByTags(selectedTags) {
        const postCards = document.querySelectorAll('article');
        let visibleCount = 0;
        const tagArray = Array.from(selectedTags);

        postCards.forEach(card => {
            const tagElements = card.querySelectorAll('.ds-badge-ghost');
            const postTags = Array.from(tagElements).map(el => el.textContent.trim().toLowerCase());

            // Check if post has ALL selected tags (AND logic)
            // Change to hasAnyTag for OR logic if preferred
            const hasAllTags = tagArray.every(selectedTag =>
                postTags.includes(selectedTag.toLowerCase())
            );

            if (hasAllTags) {
                card.style.display = '';
                card.classList.remove('filter-hidden');
                visibleCount++;
            } else {
                card.style.display = 'none';
                card.classList.add('filter-hidden');
            }
        });

        const tagList = tagArray.join('", "');
        console.log(`🏷️ Multi-tag filter result: ${visibleCount} posts visible with tags ["${tagList}"]`);

        // Show a message if no posts found
        const filterText = tagArray.length === 1
            ? `tagged with "${tagArray[0]}"`
            : `tagged with all of: "${tagList}"`;
        showFilterMessage(visibleCount, filterText);
        updateShowAllButton(false);
    }

    function showAllPosts() {
        const postCards = document.querySelectorAll('article');
        postCards.forEach(card => {
            card.style.display = '';
            card.classList.remove('filter-hidden');
        });

        hideFilterMessage();
        updateShowAllButton(true);
        console.log('🏷️ Tag filter cleared: all posts visible');
    }

    function updateTagButtonStates(activeTagFilters) {
        const tagButtons = document.querySelectorAll('button[data-filter-type="tag"]');

        tagButtons.forEach(button => {
            const tagValue = button.getAttribute('data-filter-value');

            if (activeTagFilters.has(tagValue)) {
                // Active tag button styling
                button.classList.remove('ds-btn-outline');
                button.classList.add('ds-btn-primary');
                button.classList.add('tag-filter-active');
            } else {
                // Inactive tag button styling
                button.classList.add('ds-btn-outline');
                button.classList.remove('ds-btn-primary');
                button.classList.remove('tag-filter-active');
            }
        });
    }

    function updateShowAllButton(isActive) {
        const showAllButton = document.querySelector('button[data-filter-type="show-all"]');
        if (showAllButton) {
            if (isActive) {
                // Active "Show All" button styling
                showAllButton.classList.remove('ds-btn-outline');
                showAllButton.classList.add('ds-btn-primary');
                showAllButton.classList.add('show-all-active');
            } else {
                // Inactive "Show All" button styling
                showAllButton.classList.add('ds-btn-outline');
                showAllButton.classList.remove('ds-btn-primary');
                showAllButton.classList.remove('show-all-active');
            }
        }
    }

    function showFilterMessage(count, filterText) {
        // Remove any existing message
        hideFilterMessage();

        if (count === 0) {
            const message = document.createElement('div');
            message.className = 'tag-filter-message';
            message.innerHTML = `
                <div class="text-center py-8 text-gray-600">
                    <p class="text-lg">No posts found ${filterText}.</p>
                    <button onclick="window.clearAllTagFilters()" class="mt-2 text-blue-600 hover:text-blue-800 underline">
                        Show All Posts
                    </button>
                </div>
            `;

            // Insert after the filter container
            const filterContainer = document.querySelector('.filter-container');
            if (filterContainer) {
                filterContainer.parentNode.insertBefore(message, filterContainer.nextSibling);
            }
        }
    }

    function hideFilterMessage() {
        const existing = document.querySelector('.tag-filter-message');
        if (existing) {
            existing.remove();
        }
    }

    // Initialize tag filtering when DOM is ready
    function initializeTagFilters() {
        console.log('🏷️ Tag filters initialized');
    }

    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initializeTagFilters);
    } else {
        initializeTagFilters();
    }

    // Also try after hydration
    setTimeout(initializeTagFilters, 500);

    window.tagFiltersInitialized = true;

})();
