@model IEnumerable<Aberwyn.Models.BudgetItem>

<aside class="right-sidebar">
    <!-- Loading Spinner -->
    <div id="loadingSpinner" style="display:none;">Loading...</div>
    <!-- Error Message Placeholder -->
    <div id="errorMessage" style="color:red; display:none;"></div>
    
    <!-- Budget Section -->
    <div class="sidebar-section" id="budgetItemsContainer">
        <h3 class="sidebar-header" onclick="toggleBudgetSection()">
            <span>Budget this month:</span>
            <span class="total-budget-amount">0</span>
        </h3>
        <div class="sidebar-container">
            <p>Loading budget items...</p>
        </div>
    </div>
</aside>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const loadingSpinner = document.getElementById("loadingSpinner");
    const errorMessage = document.getElementById("errorMessage");
    const budgetItemsContainer = document.getElementById("budgetItemsContainer");
    const totalBudgetAmount = budgetItemsContainer.querySelector(".total-budget-amount");
    const sidebarContent = budgetItemsContainer.querySelector(".sidebar-container");

    // Show loading spinner
    loadingSpinner.style.display = "block";
    errorMessage.style.display = "none"; // Hide error message initially

    // Fetch current month and year
    const currentDate = new Date();
    const month = currentDate.getMonth() + 1; // getMonth() returns 0-11, hence +1
    const year = currentDate.getFullYear(); 

    // Fetch data using AJAX
    const fetchUrl = `/api/budgetapi/items?month=${month}&year=${year}`;

    fetch(fetchUrl)
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => { throw new Error(err.message); });
            }
            return response.json();
        })
        .then(data => {
            loadingSpinner.style.display = "none"; // Hide loading spinner

            if (data.length > 0) {
                let totalAmount = 0;
                sidebarContent.innerHTML = ''; // Clear existing items

                // Group and display items
                const groupedItems = data.reduce((acc, item) => {
                    acc[item.category] = acc[item.category] || [];
                    acc[item.category].push(item);
                    return acc;
                }, {});

                // Create accordion for each category
                for (const [category, items] of Object.entries(groupedItems)) {
                    const amount = items.reduce((sum, item) => sum + item.amount, 0);
                    totalAmount += amount; // Sum total amounts

                    // Create accordion element
                    const itemElement = `
                        <div class="accordion-item">
                            <div class="accordion-header" onclick="toggleAccordion(this)">
                                <span class="accordion-title">${category}</span>
                                <span class="item-amount">(${amount.toFixed(2)})</span>
                                <i class="fas fa-chevron-down"></i>
                            </div>
                            <div class="accordion-content">
                                ${items.map(item => `<div class="item-name">${item.name}: <span class="item-amount">${item.amount.toFixed(2)}</span></div>`).join('')}
                            </div>
                        </div>`;
                    sidebarContent.insertAdjacentHTML('beforeend', itemElement);
                }

                // Update total amount
                totalBudgetAmount.textContent = totalAmount.toFixed(2); // Format total amount
            } else {
                sidebarContent.innerHTML = "<p>No categories available.</p>";
            }
        })
        .catch(error => {
            console.error("Error fetching data:", error);
            errorMessage.textContent = error.message; // Display error message
            errorMessage.style.display = "block"; // Show error message
        });
});

// Function to toggle accordion visibility
function toggleAccordion(header) {
    const content = header.nextElementSibling;
    const allContents = document.querySelectorAll(".accordion-content");
    
    // Close all other accordion items
    allContents.forEach(item => {
        if (item !== content) {
            item.style.display = "none";
        }
    });

    // Toggle current accordion item
    content.style.display = content.style.display === "block" ? "none" : "block";
}

// Function to toggle the budget section visibility
function toggleBudgetSection() {
    const sidebarContainer = document.querySelector(".sidebar-container");
    sidebarContainer.classList.toggle('collapsed'); // Add 'collapsed' class to toggle visibility
}
</script>
