// Discord Navigation Sidebar
// This file can be deleted to remove the navigation sidebar from all HTML exports

(function() {
    'use strict';

    // SVG Icons
    const ICONS = {
        arrow: '<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M9.29 15.88L13.17 12 9.29 8.12a.996.996 0 1 1 1.41-1.41l4.59 4.59c.39.39.39 1.02 0 1.41L10.7 17.3a.996.996 0 0 1-1.41 0c-.38-.39-.39-1.03 0-1.42z"/></svg>',
        channel: '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M5.88657 21C5.57547 21 5.3399 20.7189 5.39427 20.4126L6.00001 17H2.59511C2.28449 17 2.04905 16.7198 2.10259 16.4138L2.27759 15.4138C2.31946 15.1746 2.52722 15 2.77011 15H6.35001L7.41001 9H4.00511C3.69449 9 3.45905 8.71977 3.51259 8.41381L3.68759 7.41381C3.72946 7.17456 3.93722 7 4.18011 7H7.76001L8.39677 3.41262C8.43914 3.17391 8.64664 3 8.88907 3H9.87344C10.1845 3 10.4201 3.28107 10.3657 3.58738L9.76001 7H15.76L16.3968 3.41262C16.4391 3.17391 16.6466 3 16.8891 3H17.8734C18.1845 3 18.4201 3.28107 18.3657 3.58738L17.76 7H21.1649C21.4755 7 21.711 7.28023 21.6574 7.58619L21.4824 8.58619C21.4406 8.82544 21.2328 9 20.9899 9H17.41L16.35 15H19.7549C20.0655 15 20.301 15.2802 20.2474 15.5862L20.0724 16.5862C20.0306 16.8254 19.8228 17 19.5799 17H16L15.3632 20.5874C15.3209 20.8261 15.1134 21 14.8709 21H13.8866C13.5755 21 13.3399 20.7189 13.3943 20.4126L14 17H8.00001L7.36325 20.5874C7.32088 20.8261 7.11337 21 6.87094 21H5.88657ZM9.41045 9L8.35045 15H14.3504L15.4104 9H9.41045Z"/></svg>'
    };

    // Load and initialize navigation
    function initDiscordNav() {
        // Try to read from embedded script tag first (works with file:// protocol)
        const embeddedData = document.getElementById('discord-nav-data');
        if (embeddedData) {
            try {
                const base64Json = embeddedData.getAttribute('data-json');
                if (base64Json) {
                    const jsonText = atob(base64Json);
                    const data = JSON.parse(jsonText);
                    buildNavigation(data);
                    return;
                }
            } catch (e) {
                console.error('Failed to parse embedded navigation data:', e);
            }
        }

        // Fallback: try to fetch from file (won't work with file:// protocol)
        fetch('channels-index.json')
            .then(response => {
                if (!response.ok) {
                    throw new Error('HTTP ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                if (data) {
                    buildNavigation(data);
                }
            })
            .catch(err => {
                console.log('No channels-index.json found, Discord navigation will not be shown');
            });
    }

    // Build the navigation sidebar
    function buildNavigation(data) {
        // Create toggle button
        const toggleBtn = document.createElement('button');
        toggleBtn.className = 'discord-nav-toggle';
        toggleBtn.textContent = '☰ Channels';
        toggleBtn.onclick = toggleSidebar;
        document.body.appendChild(toggleBtn);

        // Create sidebar container
        const sidebar = document.createElement('div');
        sidebar.id = 'discord-nav-sidebar';
        sidebar.innerHTML = `
            <div class="discord-nav-header">
                <div class="discord-nav-guild-name">${escapeHtml(data.guild || 'Discord')}</div>
                <div class="discord-nav-search">
                    <input type="text" placeholder="Search" id="discord-nav-search-input">
                </div>
            </div>
            <div class="discord-nav-channels" id="discord-nav-channels-list"></div>
        `;
        document.body.appendChild(sidebar);

        // Build channel list
        const channelsList = document.getElementById('discord-nav-channels-list');
        const currentFile = getCurrentFileName();

        data.categories.forEach(category => {
            const categoryEl = createCategory(category, currentFile);
            channelsList.appendChild(categoryEl);
        });

        // Setup search
        const searchInput = document.getElementById('discord-nav-search-input');
        searchInput.addEventListener('input', handleSearch);

        document.body.classList.add('discord-nav-active');
    }

    // Create a category element
    function createCategory(category, currentFile) {
        const categoryEl = document.createElement('div');
        categoryEl.className = 'discord-nav-category';

        const header = document.createElement('div');
        header.className = 'discord-nav-category-header';
        header.innerHTML = `
            <span class="discord-nav-category-arrow">${ICONS.arrow}</span>
            <span class="discord-nav-category-name">${escapeHtml(category.name)}</span>
        `;
        header.onclick = () => toggleCategory(categoryEl);

        const channelsContainer = document.createElement('div');
        channelsContainer.className = 'discord-nav-category-channels';

        category.channels.forEach(channel => {
            const channelEl = createChannel(channel, category.name, currentFile);
            channelsContainer.appendChild(channelEl);
        });

        categoryEl.appendChild(header);
        categoryEl.appendChild(channelsContainer);

        return categoryEl;
    }

    // Create a channel element
    function createChannel(channel, categoryName, currentFile) {
        const channelEl = document.createElement('a');
        channelEl.className = 'discord-nav-channel';
        channelEl.href = channel.file;
        channelEl.dataset.channelName = channel.name.toLowerCase();
        channelEl.dataset.categoryName = categoryName ? categoryName.toLowerCase() : '';

        if (channel.file === currentFile) {
            channelEl.classList.add('active');
        }

        channelEl.innerHTML = `
            <span class="discord-nav-channel-icon">${ICONS.channel}</span>
            <span class="discord-nav-channel-name">${escapeHtml(channel.name)}</span>
        `;

        return channelEl;
    }

    // Toggle sidebar visibility
    function toggleSidebar() {
        const sidebar = document.getElementById('discord-nav-sidebar');
        const isHidden = sidebar.classList.contains('hidden');

        if (isHidden) {
            sidebar.classList.remove('hidden');
            document.body.classList.add('discord-nav-active');
        } else {
            sidebar.classList.add('hidden');
            document.body.classList.remove('discord-nav-active');
        }
    }

    // Toggle category collapsed state
    function toggleCategory(categoryEl) {
        categoryEl.classList.toggle('collapsed');
    }

    // Handle search input
    function handleSearch(e) {
        const query = e.target.value.toLowerCase().trim();
        const channels = document.querySelectorAll('.discord-nav-channel');
        const categories = document.querySelectorAll('.discord-nav-category');

        if (!query) {
            // Show all
            channels.forEach(ch => ch.classList.remove('discord-nav-hidden'));
            categories.forEach(cat => {
                cat.classList.remove('discord-nav-hidden');
                cat.classList.remove('collapsed');
            });
            hideNoResultsMessage();
            return;
        }

        let hasResults = false;

        categories.forEach(cat => {
            const categoryChannels = cat.querySelectorAll('.discord-nav-channel');
            let categoryHasVisibleChannel = false;

            categoryChannels.forEach(ch => {
                const channelName = ch.dataset.channelName;
                const matches = channelName.includes(query);

                if (matches) {
                    ch.classList.remove('discord-nav-hidden');
                    categoryHasVisibleChannel = true;
                    hasResults = true;
                } else {
                    ch.classList.add('discord-nav-hidden');
                }
            });

            if (categoryHasVisibleChannel) {
                cat.classList.remove('discord-nav-hidden');
                cat.classList.remove('collapsed'); // Expand categories with matches
            } else {
                cat.classList.add('discord-nav-hidden');
            }
        });

        if (!hasResults) {
            showNoResultsMessage();
        } else {
            hideNoResultsMessage();
        }
    }

    // Show "no results" message
    function showNoResultsMessage() {
        if (document.getElementById('discord-nav-no-results')) return;

        const channelsList = document.getElementById('discord-nav-channels-list');
        const noResults = document.createElement('div');
        noResults.id = 'discord-nav-no-results';
        noResults.className = 'discord-nav-no-results';
        noResults.textContent = 'No channels found';
        channelsList.appendChild(noResults);
    }

    // Hide "no results" message
    function hideNoResultsMessage() {
        const noResults = document.getElementById('discord-nav-no-results');
        if (noResults) noResults.remove();
    }

    // Get current HTML filename
    function getCurrentFileName() {
        const path = window.location.pathname;
        const filename = path.substring(path.lastIndexOf('/') + 1);
        return filename || 'index.html';
    }

    // Escape HTML to prevent XSS
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

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