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;
    });
   
    let allActivities = [];
    let activitiesToShow = 25;
    const excludedStatuses = [
        "paused watching", 
        "paused reading", 
        "dropped", 
        "plans to read", 
        "plans to watch"
    ];

    fetch('json/activityHistory.json')
        .then(response => response.json())
        .then(activityData => {
            const currentDate = new Date();
            const last365Days = [];

            for (let i = 0; i < 365; i++) {
                const date = new Date(currentDate);
                date.setDate(date.getDate() - i);
                last365Days.push(date.toISOString().split('T')[0]);
            }

            last365Days.forEach(dateString => {
                const activities = (activityData[dateString] || []).filter(activity => 
                    !excludedStatuses.includes(activity.status?.toLowerCase())
                );
                allActivities.push(...activities);
            });

            allActivities.sort((a, b) => b.createdAt - a.createdAt);
            displayActivities();
            displayHeatmap(activityData);
        })
        .catch(error => console.error('Error loading activity data:', error));

        function displayActivities() {
            const activityList = document.getElementById('activityList');
            if (!activityList) {
              console.error('Activity list element not found!');
              return;
            }
            console.log('Activity List Element:', activityList); // Debugging: Log the element
          
            const activitiesToDisplay = allActivities.slice(0, activitiesToShow);
            console.log('Activities to Display:', activitiesToDisplay); // Debugging: Log the activities
          
            activitiesToDisplay.forEach(activity => {
              const activityDiv = document.createElement('div');
              activityDiv.className = 'activity';
              const title = activity.media?.title?.english || activity.media?.title?.romaji || 'No title available';
              const cover = activity.media?.coverImage?.large || 'default-cover.jpg';
              const progress = activity.progress ? `Episode ${activity.progress}` : '';
              const time = new Date(activity.createdAt * 1000).toLocaleString('en-US', { timeZone: 'America/Chicago' });
              const siteUrl = activity.media?.siteUrl || '#';
          
              console.log('Activity:', { title, cover, progress, time, siteUrl }); // Debugging: Log each activity
          
              activityDiv.innerHTML = `
                <img src="${cover}" alt="${title}" onclick="window.open('${siteUrl}', '_blank')">
                <div class="activity-details">
                  <p class="activity-title" onclick="window.open('${siteUrl}', '_blank')">${title}</p>
                  <p class="activity-meta">${progress}</p>
                  <p class="activity-time">${time}</p>
                </div>
              `;
              activityList.appendChild(activityDiv);
            });
          }

    function displayHeatmap(activityData) {
        const heatmap = document.getElementById('heatmap');
        if (!heatmap) {
            console.error('Heatmap element not found!');
            return;
        }
        const daysInYear = 365;
        const currentYear = new Date().getFullYear();

        for (let i = 0; i < daysInYear; i++) {
            const date = new Date(currentYear, 0, 1 + i);
            const dateString = date.toISOString().split('T')[0];
            const activities = (activityData[dateString] || []).filter(activity => 
                !excludedStatuses.includes(activity.status?.toLowerCase())
            );
            const activityCount = activities.length;
            let activityLevel = 0;

            if (activityCount > 0) activityLevel = 1;
            if (activityCount > 2) activityLevel = 2;
            if (activityCount > 5) activityLevel = 3;
            if (activityCount > 10) activityLevel = 4;

            const dayDiv = document.createElement('div');
            dayDiv.className = 'day';
            dayDiv.dataset.activity = activityLevel;
            dayDiv.innerHTML = `<span class="tooltip">${dateString}: ${activityCount} activities</span>`;
            heatmap.appendChild(dayDiv);
        }
    }

    const loadMoreBtn = document.getElementById('loadMoreBtn');
    if (loadMoreBtn) {
        loadMoreBtn.addEventListener('click', () => {
            activitiesToShow += 10;
            displayActivities();
        });
    } else {
        console.error('Load more button not found!');
    }

    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);
            const errorMessage = document.getElementById('error-message');
            if (errorMessage) {
                errorMessage.textContent = `Error: ${error.message}`;
            }
        });

    fetch('json/storygraph_stats.json')
        .then(response => response.json())
        .then(data => {
            document.getElementById('books-read').textContent = data.totalBooksRead;
            document.getElementById('pages-read').textContent = data.totalPagesRead;
            document.getElementById('minutes-listened').textContent = data.totalMinutesListened;
        })
        .catch(error => console.error('Error loading book stats:', error));

    fetch('json/genreOverview.json')
        .then(response => response.json())
        .then(data => {
            const genres = data.anime.genres;
            const topGenres = genres.sort((a, b) => b.count - a.count).slice(0, 5);

            const topGenresContainer = document.getElementById('top-genres');
            if (topGenresContainer) {
                topGenres.forEach(genre => {
                    const genreDiv = document.createElement('div');
                    genreDiv.textContent = `${genre.genre}: ${genre.count}`;
                    topGenresContainer.appendChild(genreDiv);
                });
            }

            const ctx = document.getElementById('genreChart')?.getContext('2d');
            if (ctx) {
                const chartData = {
                    labels: genres.map(genre => genre.genre),
                    datasets: [{
                        label: 'Percentage of Anime Watched',
                        data: genres.map(genre => genre.count),
                        backgroundColor: genres.map(() => `#${Math.floor(Math.random()*16777215).toString(16)}`)
                    }]
                };

                new Chart(ctx, {
                    type: 'bar',
                    data: chartData,
                    options: {
                        scales: {
                            x: {
                                beginAtZero: true
                            },
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            }
        })
        .catch(error => console.error('Error loading genre overview:', error));

    fetch('json/favorites.json')
        .then(response => response.json())
        .then(data => {
            displayFavorites(data.anime.nodes, 'anime-favorites', 'title', 'coverImage', 'siteUrl');
            displayFavorites(data.manga.nodes, 'manga-favorites', 'title', 'coverImage', 'siteUrl');
            displayFavorites(data.characters.nodes, 'character-favorites', 'name', 'image', 'siteUrl');
            displayFavorites(data.staff.nodes, 'staff-favorites', 'name', 'image', 'siteUrl');
        })
        .catch(error => console.error('Error loading favorites:', error));

    function displayFavorites(favorites, containerId, titleKey, imageKey, urlKey) {
        const container = document.getElementById(containerId);
        if (!container) {
            console.error(`Container with ID '${containerId}' not found!`);
            return;
        }
        container.innerHTML = '';

        favorites.forEach(favorite => {
            const favoriteDiv = document.createElement('div');
            favoriteDiv.className = 'favorite-item';
            const title = favorite[titleKey].english || favorite[titleKey].romaji || favorite[titleKey].full;
            const subtitle = favorite[titleKey].romaji || favorite[titleKey].native || '';
            const cover = favorite[imageKey].large;
            const url = favorite[urlKey];

            favoriteDiv.innerHTML = `
                <img src="${cover}" alt="${title}" onclick="window.open('${url}', '_blank')">
                <div class="favorite-details">
                    <p class="favorite-title" onclick="window.open('${url}', '_blank')">${title}</p>
                    <p class="favorite-meta">${subtitle}</p>
                </div>
            `;
            container.appendChild(favoriteDiv);
        });
    }
});