@using System.Globalization
@model Aberwyn.Models.WeeklyMenuViewModel

@{
    ViewData["Title"] = "Veckomeny";
    var days = new[] { "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag" };
}
<html lang="sv" ng-app="app">
<head>
    <meta charset="utf-8" />
    <title>Veckomeny</title>
    <link rel="stylesheet" href="~/css/Veckomeny.css" asp-append-version="true" />
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script>
        window.knownMeals = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(
                                                                (ViewBag.AvailableMeals as List<Aberwyn.Models.Meal>)?.Select(m => m.Name.Trim()).ToList() ?? new List<string>()));
    </script>
</head>
<body x-data="recentHistory()" x-init="init()">

    <div class="menu-wishlist-wrapper">

        <!-- Veckomenyn -->
        <section class="weekly-editor">
            <h1>Veckomeny - Vecka @Model.WeekNumber</h1>
            <div class="week-nav">
                <a asp-action="Veckomeny" asp-route-week="@(Model.WeekNumber - 1)" asp-route-year="@Model.Year">&larr; Föregående vecka</a>
                <span>Vecka @Model.WeekNumber</span>
                <a asp-action="Veckomeny" asp-route-week="@(Model.WeekNumber + 1)" asp-route-year="@Model.Year">Nästa vecka &rarr;</a>
            </div>

            <form method="post" asp-action="SaveVeckomeny">
                <input type="hidden" name="week" value="@Model.WeekNumber" />
                <input type="hidden" name="year" value="@Model.Year" />
                <table>
                    <thead>
                        <tr>
                            <th class="day-cell">Dag</th>
                            <th>Måltider</th>
                            <th>Kock</th>
                        </tr>
                    </thead>
                    <tbody>
                        @for (int i = 0; i < 7; i++)
                        {
                            var dinnerEntry = Model.GetMealEntry(i, "Middag");
                            var lunchEntry = Model.GetMealEntry(i, "Lunch");
                            var breakfastEntry = Model.GetMealEntry(i, "Frukost");
                        <tbody x-data="{ showExtra: false }">
                            <tr>
                                <td class="day-cell">
                                    <button type="button" x-on:click="showExtra = !showExtra">
                                        <i :class="showExtra ? 'fa-solid fa-chevron-right rotate-chevron open' : 'fa-solid fa-chevron-right rotate-chevron'"></i>
                                    </button>
                                    @days[i]
                                </td>
                                <td class="meal-cell">
                                    <div class="meal-entry-group">
                                        <div class="meal-input-group">
                                            <input type="text"
                                                   name="Meal[@i][Middag]"
                                                   value="@dinnerEntry?.DinnerMealName"
                                                   placeholder="Lägg till middag..."
                                                   list="meals-list"
                                                   class="meal-input"
                                                   :tabindex="showExtra ? 0 : -1"
                                                   x-on:input="highlightFromCurrentWeek()" />
                                            <button type="button" class="delete-btn" title="Rensa middag"
                                                    onclick="this.previousElementSibling.value=''; highlightMeal('');">
                                                <i class="fa-solid fa-xmark"></i>
                                            </button>
                                        </div>
                                    </div>
                                </td>
                                <td class="cook-cell">
                                    <select name="Cook[@i]" :tabindex="showExtra ? 0 : -1" class="meal-input">
                                        <option value="">Välj kock</option>
                                        @foreach (var user in Model.AvailableCooks)
                                        {
                                            var selected = Model.WeeklyMenus.FirstOrDefault(m => m.DayOfWeek == i + 1)?.Cook == user.Username;
                                            <option value="@user.Username" selected="@selected">@user.Name</option>
                                        }
                                    </select>
                                </td>
                            </tr>
                            <tr class="extra-row" x-show="showExtra" x-transition x-cloak>
                                <td></td>
                                <td colspan="2">
                                    <div class="extra-meals">
                                        <div class="meal-input-group">
                                            <label>Frukost:</label>
                                            <input type="text"
                                                   name="Meal[@i][Frukost]"
                                                   value="@breakfastEntry?.BreakfastMealName"
                                                   placeholder="Lägg till frukost..."
                                                   list="meals-list"
                                                   class="meal-input"
                                                   x-on:input="highlightFromCurrentWeek()" />
                                            <button type="button" class="delete-btn" title="Rensa frukost"
                                                    onclick="this.previousElementSibling.value=''; highlightMeal('');">
                                                <i class="fa-solid fa-xmark"></i>
                                            </button>
                                        </div>
                                        <div class="meal-input-group">
                                            <label>Lunch:</label>
                                            <input type="text"
                                                   name="Meal[@i][Lunch]"
                                                   value="@lunchEntry?.LunchMealName"
                                                   placeholder="Lägg till lunch..."
                                                   list="meals-list"
                                                   class="meal-input"
                                                   x-on:input="highlightFromCurrentWeek()" />
                                            <button type="button" class="delete-btn" title="Rensa lunch"
                                                    onclick="this.previousElementSibling.value=''; highlightMeal('');">
                                                <i class="fa-solid fa-xmark"></i>
                                            </button>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    }
                    </tbody>
                </table>
                <div class="form-actions">
                    <button type="submit" class="save-menu-btn">
                        Spara
                    </button>
                </div>
            </form>
            <datalist id="meals-list">
                @foreach (var meal in (ViewBag.AvailableMeals as List<Aberwyn.Models.Meal>) ?? new List<Aberwyn.Models.Meal>())
                {
                    <option value="@meal.Name.Trim()"></option>
                }
            </datalist>
        </section>

        <!-- Wishlist -->
        <aside class="wishlist" ng-controller="WishListCtrl as vm" ng-init="vm.loadWishes()">
            <h2>Önskemåltider</h2>
            <div class="wishlist-grid">
                <div class="wishlist-card" ng-repeat="wish in vm.WishList track by wish.Id">
                    <div class="wishlist-header">
                        <strong>{{wish.Name}}</strong>
                        <span class="wishlist-meta">
                            av {{wish.RequestedByUserName}} • {{wish.CreatedAt}}
                        </span>
                    </div>
                    <div class="wishlist-body" ng-if="wish.Recipe">
                        <p>{{wish.Recipe | limitTo:100}}{{wish.Recipe.length > 100 ? '...' : ''}}</p>
                    </div>
                    <div class="wishlist-actions">
                        <button type="button" ng-click="vm.importWish(wish.Id)" class="btn import">
                            <i class="fa-solid fa-plus"></i> Importera
                        </button>
                        <button type="button" ng-click="vm.archiveWish(wish.Id)" class="btn archive">
                            <i class="fa-solid fa-box-archive"></i> Arkivera
                        </button>
                    </div>
                </div>
            </div>
            <p ng-if="!vm.WishList.length">Inga önskemål just nu.</p>
        </aside>

    </div>

    <!-- Översikt senaste 4 veckor, full width -->
    <aside class="recent-history-fullwidth">
        <h2>Översikt senaste 4 veckor (middag)</h2>
        <div class="recent-table-wrapper">
            <table>
                <thead>
                    <tr>
                        <th>Vecka</th>
                        @foreach (var d in days)
                        {
                            <th>@d</th>
                        }
                    </tr>
                </thead>
                <tbody>
                    <template x-for="week in weeks" :key="week.weekNumber">
                        <tr>
                            <td x-text="week.weekNumber"></td>
                            <template x-for="day in week.days">
                                <td x-text="day.dinner" :class="day.highlight ? 'highlight' : ''"></td>
                            </template>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </aside>
<script>
    function recentHistory() {
        return {
            weeks: [],
            init() {
                fetch('/FoodMenu/GetRecentMenuEntries?weeksBack=4')
                    .then(res => res.json())
                    .then(data => {
                        const grouped = {};
                        data.forEach(e => {
                            const dt = new Date(e.Date);
                            const weekNo = getISOWeek(dt);
                            const dayIdx = dt.getDay() === 0 ? 6 : dt.getDay() - 1;
                            const key = `W${weekNo}`;
                            if (!grouped[key]) grouped[key] = Array(7).fill().map(() => ({ dinner: '—', highlight: false }));
                            grouped[key][dayIdx] = { dinner: e.DinnerMealName?.trim() || '—', highlight: false };
                        });

                        this.weeks = Object.keys(grouped)
                            .sort((a,b) => b.localeCompare(a))
                            .map(weekKey => ({ weekNumber: parseInt(weekKey.replace('W','')), days: grouped[weekKey] }));

                        this.highlightFromCurrentWeek();
                    });

                function getISOWeek(date) {
                    const tmpDate = new Date(date.getTime());
                    tmpDate.setHours(0,0,0,0);
                    tmpDate.setDate(tmpDate.getDate() + 4 - (tmpDate.getDay()||7));
                    const yearStart = new Date(tmpDate.getFullYear(),0,1);
                    return Math.ceil((((tmpDate - yearStart) / 86400000) + 1)/7);
                }
            },

            highlightMeal(inputValue) {
                const val = inputValue?.trim().toLowerCase();
                this.weeks.forEach(week => {
                    week.days.forEach(day => {
                        day.highlight = val && day.dinner?.toLowerCase() === val;
                    });
                });
            },

            highlightFromCurrentWeek() {
                // hämta alla inputs som har något värde
                const values = Array.from(document.querySelectorAll(".meal-input"))
                                    .map(i => i.value?.trim().toLowerCase())
                                    .filter(v => v);

                this.weeks.forEach(week => {
                    week.days.forEach(day => {
                        day.highlight = values.includes(day.dinner?.toLowerCase());
                    });
                });
            }
        }

    }
        angular.module('app', [])
        .controller('WishListCtrl', ['$http', function($http){
            var vm = this;
            vm.WishList = [];

        vm.loadWishes = function(){
            $http.get('/api/MealWish/all')
                .then(function(res){
                    vm.WishList = res.data;
                }, function(err){
                    console.error(err);
                });
        };

            vm.archiveWish = function(id){
                $http.post('/api/MealWish/' + id + '/archive')
                    .then(function(){
                        vm.WishList = vm.WishList.filter(function(w){ return w.Id !== id; });
                    }, function(err){
                        console.error(err);
                    });
            };

            vm.importWish = function(id){
                $http.post('/api/MealWish/' + id + '/import')
                    .then(function(){
                        vm.WishList = vm.WishList.filter(function(w){ return w.Id !== id; });
                    }, function(err){
                        console.error(err);
                    });
            };
        }]);
</script>

</body>
</html>