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

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

        const savedView = localStorage.getItem('mealViewMode');
        $scope.viewMode = savedView === 'card' || savedView === 'list' ? savedView : 'card';
        $scope.tooltip = {};
        $scope.meals = [];
        $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.loadMeals = function () {
            console.log("Hämtar måltider...");
            return $http.get('/api/mealMenuApi/getMeals')
                .then(res => {
                    console.log("Måltider hämtade:", res.data);
                    $scope.meals = res.data;
                    console.log("Alla måltider med bilder:", $scope.meals);
                    return res;
                })
                .catch(err => console.error("Fel vid hämtning av måltider:", err));
        };

        $scope.loadMenu = function () {
            console.log("Hämtar meny för vecka:", $scope.selectedWeek, $scope.selectedYear);
            $http.get('/api/mealMenuApi/menu', {
                params: { weekNumber: $scope.selectedWeek, year: $scope.selectedYear }
            }).then(res => {
                console.log("Menyposter hämtade:", res.data);
                $scope.menu = {};

                res.data.forEach(item => {
                    const dayIndex = item.DayOfWeek - 1;
                    if (dayIndex < 0 || dayIndex >= $scope.daysOfWeek.length) {
                        console.warn("Ogiltig dag:", item.DayOfWeek);
                        return;
                    }

                    const day = $scope.daysOfWeek[dayIndex];
                    $scope.menu[day] = {};

                    ['breakfast', 'lunch', 'dinner'].forEach(type => {
                        // Konvertera till PascalCase
                        const capitalType = type.charAt(0).toUpperCase() + type.slice(1);
                        const idKey = capitalType + 'MealId';
                        const nameKey = capitalType + 'MealName';

                        if (item[idKey]) {
                            const m = $scope.meals.find(x => x.Id == item[idKey]);
                            console.log(`Match för ${type} (${day}):`, m);

                            $scope.menu[day][type + 'MealId'] = item[idKey];
                            $scope.menu[day][type + 'MealName'] = m?.Name || item[nameKey] || 'Okänd rätt';

                            if (m && !$scope.menu[day].imageUrl) {
                                if (m.ImageData) {
                                    const mime = m.ImageMimeType || "image/jpeg";
                                    $scope.menu[day].imageUrl = `data:${mime};base64,${m.ImageData}`;
                                } else if (m.ImageUrl) {
                                    $scope.menu[day].imageUrl = m.ImageUrl.startsWith('/')
                                        ? m.ImageUrl
                                        : '/' + m.ImageUrl;
                                }
                            }

                        }
                    });
                });

                console.log("Byggd meny:", $scope.menu);
            }).catch(err => console.error("Fel vid hämtning av veckomeny:", err));
        };

        $scope.openMeal = function (mealId) {
            if (!mealId) return;
            window.open('/Meal/View/' + mealId, '_blank');
        };

        $scope.getDayImage = function (day) {
            return $scope.menu[day]?.imageUrl || '/images/default-meal.jpg';
        };

        $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); // ← spara läget

            $timeout(() => {
                const viewBtn = document.getElementById('toggle-view');
                if (viewBtn) viewBtn.textContent = $scope.getViewIcon();
            }, 0);

        };



        console.log("Initierar måltidsladdning...");
        $scope.loadMeals().then(() => {
            console.log("Laddar meny efter måltider...");
            $scope.loadMenu();
            setTimeout(() => {
                const viewBtn = document.getElementById('toggle-view');
                if (viewBtn) viewBtn.textContent = $scope.getViewIcon();
            }, 0);

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

    // Initiera ikon för vy
    
});
