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

const statusColors = {
    up: 'green',       // 1 = UP
    down: 'red',       // 0 = DOWN
    pending: 'orange', // 2 = PENDING
    maintenance: 'gray', // 3 = MAINTENANCE
    unknown: 'orange'
};

// Function to fetch status data from the backend
async function fetchStatusFromBackend() {
    const backendUrl = 'https://statusmetrics.swightshome.xyz/status';

    try {
        const response = await fetch(backendUrl);
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const data = await response.json(); // Backend returns JSON
        return data;
    } catch (error) {
        console.error('Error fetching status from backend:', error);
        return null;
    }
}

// Function to update the UI based on the status
function updateUI(monitorName, status, elementId, popupId) {
    const element = document.getElementById(elementId);
    const popup = document.getElementById(popupId);

    if (!element || !popup) {
        console.error(`Element or popup not found for monitor: ${monitorName}`);
        return;
    }

    switch (status) {
        case 1: // UP
            element.style.backgroundColor = statusColors.up;
            popup.innerText = 'Status: Online';
            break;
        case 0: // DOWN
            element.style.backgroundColor = statusColors.down;
            popup.innerText = 'Status: Offline';
            break;
        case 2: // PENDING
            element.style.backgroundColor = statusColors.pending;
            popup.innerText = 'Status: Pending';
            break;
        case 3: // MAINTENANCE
            element.style.backgroundColor = statusColors.maintenance;
            popup.innerText = 'Status: Maintenance';
            break;
        default:
            element.style.backgroundColor = statusColors.unknown;
            popup.innerText = 'Status: Unknown';
    }
}

// Function to mark all services as down
function markAllServicesDown() {
    const serviceIds = [
        'redlib', 'rimgo', 'gothub', 'lingva', 'feishin',
        'jellyfin-vue', 'jellyfin', 'jellyseerr', 'navidrome',
        'audiobookshelf', 'calibre-web', 'invidious', 'beatbump',
        'biblioreads', 'mozhi', 'gitea', 'privatebin'
    ];

    serviceIds.forEach(serviceId => {
        const element = document.getElementById(`${serviceId}-status`);
        const popup = document.getElementById(`${serviceId}-popup`);

        if (element && popup) {
            element.style.backgroundColor = statusColors.down;
            popup.innerText = 'Status: Uptime Kuma Not Responding';
        }
    });
}

// Main function to check status of all services
async function checkStatus() {
    const statusMap = await fetchStatusFromBackend();

    if (!statusMap) {
        // If the backend is not responding, mark all services as down
        console.error('Backend is not responding. Marking all services as down.');
        markAllServicesDown();
        return;
    }

    // Update UI for each service
    Object.entries(statusMap).forEach(([monitorName, status]) => {
        const elementId = `${monitorName.toLowerCase().replace(/[^a-z0-9]/g, '-')}-status`;
        const popupId = `${monitorName.toLowerCase().replace(/[^a-z0-9]/g, '-')}-popup`;
        updateUI(monitorName, status, elementId, popupId);
    });
}

// On page load, check the status of all services
window.onload = function() {
    checkStatus();
};

// Typing animation function
function typeText(text, elementId, speed, callback) {
    const typingElement = document.getElementById(elementId);
    let index = 0;

    function type() {
        if (index < text.length) {
            typingElement.textContent += text.charAt(index);
            index++;
            setTimeout(type, speed); // Adjust typing speed here
        } else {
            typingElement.classList.remove('typing'); // Remove cursor after typing
            if (callback) callback(); // Call the callback function if provided
        }
    }

    typingElement.classList.add('typing'); // Add cursor before typing starts
    type();
}

// Fetch activity history
fetch('json/activityHistory.json')
    .then(response => response.json())
    .then(activityData => {
        const currentDate = new Date();
        const last365Days = [];
        const excludedStatuses = [
            "paused watching", 
            "paused reading", 
            "dropped", 
            "plans to read", 
            "plans to watch"
        ];

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

        const allActivities = [];
        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);
        displayRecentActivities(allActivities.slice(0, 3)); // Display the last three activities
    })
    .catch(error => console.error('Error loading activity data:', error));

function displayRecentActivities(activities) {
    const activityContainer = document.getElementById('activityContainer');
    activityContainer.innerHTML = '';

    activities.forEach(activity => {
        const activityDiv = document.createElement('div');
        activityDiv.className = 'activity-item';
        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 || '#';

        activityDiv.innerHTML = `
            <img src="${cover}" alt="${title}">
            <div class="activity-title" onclick="window.open('${siteUrl}', '_blank')">${title}</div>
            <div class="activity-meta">${progress}</div>
            <div class="activity-time">${time}</div>
        `;
        activityContainer.appendChild(activityDiv);
    });
}

// On page load, run all initialization functions
window.onload = function() {
    checkStatus();

    // Typing animation on load
    typeText("Welcome to Swightshome!", "typing-text-1", 60, () => {
        typeText("A website for things I host.", "typing-text-2", 70);
    });

    // Set random image
    const randomIndex = Math.floor(Math.random() * 100);
    document.getElementById('random-image').src = `images/walls/image_${randomIndex}.jpg`;
};