document.addEventListener('DOMContentLoaded', function() {
    // Anime HTML//

    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;
});

    async function fetchAnimeList() {
        try {
            const response = await fetch('json/anime_list.json');
            const animeList = await response.json();
            return animeList;
        } catch (error) {
            console.error('Error fetching anime list:', error);
            return [];
        }
    }

    async function populateAnimeList() {
        const animeList = await fetchAnimeList();
        const genres = new Set();
        const formats = new Set();
        const countries = new Set();

        animeList.forEach(list => {
            let sectionId;
            switch (list.name) {
                case "Watching":
                    sectionId = "watching";
                    break;
                case "Completed":
                    sectionId = "completed";
                    break;
                case "Dropped":
                    sectionId = "dropped";
                    break;
                case "Paused":
                    sectionId = "paused";
                    break;
                case "Planning":
                    sectionId = "planning";
                    break;
                case "Rewatching":
                    sectionId = "rewatching";
                    break;
                default:
                    return;
            }
            const section = document.getElementById(sectionId);
            const ul = section.querySelector('.anime-list');

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

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

                if (anime.status === "RELEASING") {
                    const statusDot = document.createElement('div');
                    statusDot.classList.add('status-dot');
                    li.appendChild(statusDot);
                }

                const img = document.createElement('img');
                img.src = anime.coverImage;
                img.alt = anime.title;
                li.appendChild(img);

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

                const infoDiv = document.createElement('div');
                infoDiv.classList.add('anime-info');

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

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

                const episodes = document.createElement('p');
                episodes.innerHTML = `Episodes<br><span>${anime.progress}/${anime.episodes}</span>`;
                infoDiv.appendChild(episodes);

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

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

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

                // Add Anilist logo and link
                const anilistLink = document.createElement('a');
                anilistLink.href = anime.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);
            });
        });

        populateFilterOptions(genres, 'genreFilter');
        populateFilterOptions(formats, 'formatFilter');
        populateFilterOptions(countries, 'countryFilter');
    }

    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);
        });
    }

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

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

    // Filter functions
    function filterAnimeList() {
        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('.anime-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';
            }
        });
    }

    document.getElementById('searchBar').addEventListener('input', filterAnimeList);
    document.getElementById('genreFilter').addEventListener('change', filterAnimeList);
    document.getElementById('formatFilter').addEventListener('change', filterAnimeList);
    document.getElementById('countryFilter').addEventListener('change', filterAnimeList);

    populateAnimeList();

    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 animeStats = data.data.User.statistics.anime;
                const mangaStats = data.data.User.statistics.manga;

                document.getElementById('anime-count').textContent = animeStats.count;
                document.getElementById('anime-meanScore').textContent = animeStats.meanScore;
                const daysWatched = (animeStats.minutesWatched / 60 / 24).toFixed(2);
                document.getElementById('anime-daysWatched').textContent = daysWatched;
                document.getElementById('anime-episodesWatched').textContent = animeStats.episodesWatched;

                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}`;
        });
});