document.addEventListener('DOMContentLoaded', function () {
    let lastScrollTop = 0;
const topbar = document.getElementById('topbar');

window.addEventListener('scroll', function() {
    let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    if (scrollTop > lastScrollTop) {
        topbar.style.transform = 'translateY(-100%)';
        topbar.classList.add('transparent');
    } else {
        topbar.style.transform = 'translateY(0)';
        if (scrollTop === 0) {
            topbar.classList.remove('transparent');
        }
    }
    lastScrollTop = scrollTop;
});

    // Fetch manga list from JSON
    async function fetchMangaList() {
        try {
            const response = await fetch('json/manga_list.json');
            const mangaList = await response.json();
            return mangaList;
        } catch (error) {
            console.error('Error fetching manga list:', error);
            return [];
        }
    }

    // Populate manga list on the page
    async function populateMangaList() {
        const mangaList = await fetchMangaList();
        const genres = new Set();
        const formats = new Set();
        const countries = new Set();

        mangaList.forEach(list => {
            let sectionId;
            switch (list.name) {
                case "Reading":
                    sectionId = "reading";
                    break;
                case "Completed":
                    sectionId = "completed";
                    break;
                case "Dropped":
                    sectionId = "dropped";
                    break;
                case "Paused":
                    sectionId = "paused";
                    break;
                case "Planning":
                    sectionId = "planning";
                    break;
                default:
                    return;
            }
            const section = document.getElementById(sectionId);
            const ul = section.querySelector('.manga-list');

            list.entries.forEach(manga => {
                manga.genres.forEach(genre => genres.add(genre));
                formats.add(manga.format);
                countries.add(manga.country);

                const li = document.createElement('li');
                li.classList.add('manga-item', 'fade-in');

                // Add status dot for releasing manga
                if (manga.status === "RELEASING") {
                    const statusDot = document.createElement('div');
                    statusDot.classList.add('status-dot');
                    li.appendChild(statusDot);
                }

                // Add manga cover image
                const img = document.createElement('img');
                img.src = manga.coverImage;
                img.alt = manga.title;
                li.appendChild(img);

                // Add country flag
                const flagImg = document.createElement('img');
                flagImg.src = `https://flagcdn.com/${manga.country.toLowerCase()}.svg`;
                flagImg.alt = manga.country;
                flagImg.classList.add('flag');
                li.appendChild(flagImg);

                // Add manga info
                const infoDiv = document.createElement('div');
                infoDiv.classList.add('manga-info');

                const title = document.createElement('h3');
                title.textContent = manga.title;
                infoDiv.appendChild(title);

                const score = document.createElement('p');
                score.innerHTML = `Score<br><span>${manga.personalScore || 'N/A'}</span>`;
                infoDiv.appendChild(score);

                const chapters = document.createElement('p');
                chapters.innerHTML = `Chapters<br><span>${manga.progress}/${manga.chapters || 'Unknown'}</span>`;
                infoDiv.appendChild(chapters);

                const genre = document.createElement('p');
                genre.innerHTML = `Genres<br><span>${manga.genres.join(', ')}</span>`;
                infoDiv.appendChild(genre);

                const format = document.createElement('p');
                format.innerHTML = `Format<br><span>${manga.format}</span>`;
                infoDiv.appendChild(format);

                li.appendChild(infoDiv);
                ul.appendChild(li);

                // Add Anilist logo and link
                const anilistLink = document.createElement('a');
                anilistLink.href = manga.links.anilist;
                anilistLink.target = '_blank';
                const anilistLogo = document.createElement('img');
                anilistLogo.src = 'images/AniList.svg.png';
                anilistLogo.alt = 'Anilist Logo';
                anilistLogo.style.width = '20px';
                anilistLogo.style.height = '20px';
                anilistLink.appendChild(anilistLogo);
                li.appendChild(anilistLink);
            });
        });

        // Populate filter options
        populateFilterOptions(genres, 'genreFilter');
        populateFilterOptions(formats, 'formatFilter');
        populateFilterOptions(countries, 'countryFilter');
    }

    // Populate filter dropdowns
    function populateFilterOptions(options, elementId) {
        const filterElement = document.getElementById(elementId);
        options.forEach(option => {
            const opt = document.createElement('option');
            opt.value = option;
            opt.textContent = option;
            filterElement.appendChild(opt);
        });
    }

    // Toggle section visibility
    function toggleSection(event) {
        const section = event.target.closest('.section');
        const mangaList = section.querySelector('.manga-list');
        if (mangaList.style.display === "block") {
            mangaList.style.display = "none";
            section.classList.add('collapsed');
        } else {
            mangaList.style.display = "block";
            section.classList.remove('collapsed');
        }
    }

    // Attach toggle event to section headers
    document.querySelectorAll('.section h2').forEach(header => {
        header.addEventListener('click', toggleSection);
        header.click(); // Collapse all sections on load
    });

    // Filter manga list based on search and filters
    function filterMangaList() {
        const searchBar = document.getElementById('searchBar').value.toLowerCase();
        const genreFilter = document.getElementById('genreFilter').value;
        const formatFilter = document.getElementById('formatFilter').value;
        const countryFilter = document.getElementById('countryFilter').value;

        document.querySelectorAll('.manga-item').forEach(item => {
            const title = item.querySelector('h3').textContent.toLowerCase();
            const genre = item.querySelector('p:nth-child(4) span').textContent.toLowerCase();
            const format = item.querySelector('p:nth-child(5) span').textContent.toLowerCase();
            const country = item.querySelector('.flag').alt.toLowerCase();

            const matchesSearch = title.includes(searchBar);
            const matchesGenre = genreFilter ? genre.includes(genreFilter.toLowerCase()) : true;
            const matchesFormat = formatFilter ? format.includes(formatFilter.toLowerCase()) : true;
            const matchesCountry = countryFilter ? country.includes(countryFilter.toLowerCase()) : true;

            if (matchesSearch && matchesGenre && matchesFormat && matchesCountry) {
                item.style.display = 'flex';
            } else {
                item.style.display = 'none';
            }
        });
    }

    // Attach filter events
    document.getElementById('searchBar').addEventListener('input', filterMangaList);
    document.getElementById('genreFilter').addEventListener('change', filterMangaList);
    document.getElementById('formatFilter').addEventListener('change', filterMangaList);
    document.getElementById('countryFilter').addEventListener('change', filterMangaList);

    // Populate manga list on page load
    populateMangaList();

    // Fetch and display manga stats
    fetch('json/stats.json')
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data && data.data && data.data.User && data.data.User.statistics) {
                const mangaStats = data.data.User.statistics.manga;

                document.getElementById('manga-count').textContent = mangaStats.count;
                document.getElementById('manga-meanScore').textContent = mangaStats.meanScore;
                document.getElementById('manga-chaptersRead').textContent = mangaStats.chaptersRead;
                document.getElementById('manga-volumesRead').textContent = mangaStats.volumesRead;
            } else {
                throw new Error('Invalid data structure');
            }
        })
        .catch(error => {
            console.error('Error fetching stats:', error);
            document.getElementById('error-message').textContent = `Error: ${error.message}`;
        });
});