function setTheme(mode) {
    document.documentElement.setAttribute('data-theme', mode);
    localStorage.setItem('theme', mode);
}

angular.module('mealMenuApp', ['ngSanitize'])
    .controller('MealMenuController', function ($scope, $http, $sce, $timeout) {
        console.log("Controller initierad");

        const savedView = localStorage.getItem('mealViewMode');
        $scope.viewMode = savedView === 'card' || savedView === 'list' ? savedView : 'card';
        $scope.tooltip = {};
        $scope.menu = {};
        const today = new Date();
        $scope.selectedWeek = getWeek(today);
        $scope.selectedYear = today.getFullYear();
        $scope.daysOfWeek = ["Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"];

        $scope.loadMenu = function () {
            //console.log("Hämtar meny för vecka:", $scope.selectedWeek, $scope.selectedYear);
        
            $http.get('/api/mealMenuApi/getWeeklyMenu', {
                params: { weekNumber: $scope.selectedWeek, year: $scope.selectedYear }
            }).then(res => {
                const rawMenu = res.data;
                $scope.menu = {};
        
                rawMenu.forEach(item => {
                    const dayIndex = item.DayOfWeek - 1;
                    const day = $scope.daysOfWeek[dayIndex];
                    //console.warn("Item:", item);
                    //console.log("day: " + day + "(" + dayIndex + " ) item: " + item.DinnerMealName);
                    const thumb = item.DinnerMealThumbnail;
        
                    $scope.menu[day] = {
                        breakfastMealId: item.BreakfastMealId,
                        breakfastMealName: item.BreakfastMealName,
                        lunchMealId: item.LunchMealId,
                        lunchMealName: item.LunchMealName,
                        dinnerMealId: item.DinnerMealId,
                        dinnerMealName: item.DinnerMealName,
                        imageUrl: thumb ? `data:image/webp;base64,${thumb}` : ''
                    };
                });
        
            }).catch(err => console.error("Fel vid hämtning av meny:", err));
            $scope.loadSchoolMeals(); 

        };
        $scope.schoolMeals = [];
        $scope.schoolMealsBySchool = [];

        $scope.schoolSensors = [
            { name: "William – Engelbrektsskolan", entity: "sensor.engelbrektsskolan" },
            { name: "Louise - Nyeds skolan", entity: "sensor.nyedsskola" },
            { name: "Ludwig - Skogsgläntan", entity: "sensor.skogsglantan" }
        ];
        
        $scope.schoolMealsBySchool = [];
        
        $scope.loadSchoolMeals = function () {
            const savedExpanded = JSON.parse(localStorage.getItem("expandedSchools") || "{}");
        
            $scope.schoolMealsBySchool = $scope.schoolSensors.map(sensor => ({
                name: sensor.name,
                entity: sensor.entity,
                days: [],
                expanded: savedExpanded[sensor.entity] || false
            }));
        
            $scope.schoolMealsBySchool.forEach(school => {
                $http.get(`/api/mealmenuapi/skolmat?week=${$scope.selectedWeek}&sensor=${school.entity}`)
                    .then(res => {
                        school.days = res.data;
                    })
                    .catch(() => {
                        school.days = [];
                    });
            });
        };
        $scope.toggleSchoolExpanded = function (school) {
            school.expanded = !school.expanded;
        
            const expandedState = {};
            $scope.schoolMealsBySchool.forEach(s => {
                expandedState[s.entity] = s.expanded;
            });
        
            localStorage.setItem("expandedSchools", JSON.stringify(expandedState));
        };
        
        
        


        $scope.openMeal = function (mealId) {
            if (mealId) {
                const page = document.querySelector('.meal-menu-page');
                page.classList.add('fade-out');
                setTimeout(() => {
                    window.location.href = "/Meal/View/" + mealId;
                }, 400); // matchar CSS-transition
            }
        };

        $scope.getDayImage = function (day) {
            return $scope.menu[day]?.imageUrl || '';
        };

        $scope.getMealIdByDay = function (day) {
            const item = $scope.menu[day] || {};
            return item.dinnerMealId || item.lunchMealId || item.breakfastMealId || null;
        };

        $scope.goToPreviousWeek = function () {
            if ($scope.selectedWeek === 1) {
                $scope.selectedYear--;
                $scope.selectedWeek = 52;
            } else {
                $scope.selectedWeek--;
            }
            $scope.loadMenu();
        };

        $scope.goToNextWeek = function () {
            if ($scope.selectedWeek === 52) {
                $scope.selectedYear++;
                $scope.selectedWeek = 1;
            } else {
                $scope.selectedWeek++;
            }
            $scope.loadMenu();
        };

        function getWeek(d) {
            d = new Date(d.getFullYear(), d.getMonth(), d.getDate());
            const dayNum = d.getDay() || 7;
            d.setDate(d.getDate() + 4 - dayNum);
            const yearStart = new Date(d.getFullYear(), 0, 1);
            return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
        }

        $scope.getViewIcon = function () {
            return $scope.viewMode === 'list' ? '🗒️' : '▣';
        };

        $scope.toggleView = function () {
            $scope.viewMode = $scope.viewMode === 'list' ? 'card' : 'list';
            localStorage.setItem('mealViewMode', $scope.viewMode);
            $timeout(() => {
                const viewBtn = document.getElementById('toggle-view');
                if (viewBtn) viewBtn.textContent = $scope.getViewIcon();
            }, 0);
        };
        $scope.isLoggedIn = true; // sätt till true/false beroende på användarstatus
        $scope.showWishForm = false;
        $scope.showRecipeField = true; // kan styras av autocomplete
        $scope.newWishName = "";
        $scope.newWishRecipe = "";

        $scope.showWishFlyout = false;

        $scope.toggleWishFlyout = function () {
            $scope.showWishFlyout = !$scope.showWishFlyout;
        }

        $scope.closeWishFlyout = function () {
            $scope.showWishFlyout = false;
            $scope.newWishName = "";
            $scope.newWishRecipe = "";
            $scope.showRecipeField = true;
        }

        $scope.existingMeals = [];
        $scope.selectedMeal = null;

        $scope.checkExistingMeal = function () {
            if (!$scope.newWishName || $scope.newWishName.length < 2) {
                $scope.existingMeals = [];
                $scope.showRecipeField = true;
                return;
            }

            fetch('/api/MealWish/search?name=' + encodeURIComponent($scope.newWishName))
                .then(res => res.json())
                .then(data => {
                    $scope.existingMeals = data;
                    $scope.$apply(); // viktigt annars uppdateras inte ng-repeat
                })
                .catch(err => console.error(err));
        }

        $scope.selectExistingMeal = function (meal) {
            $scope.newWishName = meal.Name;
            $scope.selectedMeal = meal;
            $scope.showRecipeField = true;
            $scope.existingMeals = [];
        }

        $scope.submitWish = function () {
            if (!$scope.newWishName) return;
            if ($scope.existingMeal) {
                wish.LinkedMealId = $scope.existingMeal.Id;
                wish.Recipe = $scope.Recipe;
            }
            const payload = {
                Name: $scope.newWishName,
                Recipe: $scope.newWishRecipe
            };

            fetch('/api/MealWish/create', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            })
                .then(res => res.json())
                .then(data => {
                    console.log("Önskan skickad:", data);
                    $scope.closeWishFlyout();
                    $scope.$apply();
                })
                .catch(err => console.error(err));
        }


        console.log("Initierar meny och måltidsladdning...");
        $scope.loadMenu();
    });

document.addEventListener("DOMContentLoaded", function () {
    const themeBtn = document.getElementById('toggle-theme');
    const viewBtn = document.getElementById('toggle-view');

    if (themeBtn) {
        themeBtn.addEventListener('click', () => {
            const current = document.documentElement.getAttribute('data-theme');
            const newTheme = current === 'dark' ? 'light' : 'dark';
            setTheme(newTheme);
            themeBtn.textContent = newTheme === 'dark' ? '🌙' : '☀️';
        });
    }

    const saved = localStorage.getItem('theme');
    if (saved) {
        setTheme(saved);
    } else {
        const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        setTheme(systemPrefersDark ? 'dark' : 'light');
    }
});
