@using System.Globalization
@model Aberwyn.Models.WeeklyMenuViewModel
@{
    ViewData["Title"] = "Veckomeny";
    var days = new[] { "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag" };
}
<head>
    <link rel="stylesheet" href="~/css/Veckomeny.css" asp-append-version="true" />
</head>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.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>

<div class="weekly-menu-wrapper"
     x-data="{
        highlightNew(event) {
          const input = event.target;
          const val = input.value?.trim().toLowerCase();
          input.classList.remove('new-entry', 'existing-entry');

          if (!val) return;

          const isKnown = window.knownMeals.some(name => name.toLowerCase() === val);
          input.classList.add(isKnown ? 'existing-entry' : 'new-entry');
        }
     }">
  <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="highlightNew($event)" />
                  <button type="button" class="delete-btn" title="Rensa middag" onclick="this.previousElementSibling.value='';">
                    <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="highlightNew($event)" />
                  <button type="button" class="delete-btn" title="Rensa frukost" onclick="this.previousElementSibling.value='';">
                    <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="highlightNew($event)" />
                  <button type="button" class="delete-btn" title="Rensa lunch" onclick="this.previousElementSibling.value='';">
                    <i class="fa-solid fa-xmark"></i>
                  </button>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
        }
        </tbody>
      </table>

      <div class="add-meal-wrapper">
        <button type="submit" class="save-menu-btn">Spara veckomeny</button>
      </div>

      <aside class="recent-history">
        <h2>Översikt senaste 4 veckor</h2>
        @{
          var lastWeeks = Enumerable.Range(1, 4)
            .Select(i => DateTime.Now.AddDays(-7 * i))
            .Select(dt => new { Year = dt.Year, Week = ISOWeek.GetWeekOfYear(dt) })
            .Distinct().ToList();
        }
        <table>
          <thead>
            <tr>
              <th>Vecka</th>
              @foreach (var d in days) {
                <th>@d</th>
              }
            </tr>
          </thead>
          <tbody>
            @foreach (var w in lastWeeks) {
              <tr>
                <td>@w.Week</td>
                @for (int idx = 1; idx <= 7; idx++) {
                  var entry = Model.RecentEntries?.FirstOrDefault(e =>
                    e.Date.Year == w.Year &&
                    ISOWeek.GetWeekOfYear(e.Date) == w.Week &&
                    ((int)e.Date.DayOfWeek == (idx % 7)));
                  <td>@(entry?.DinnerMealName ?? "—")</td>
                }
              </tr>
            }
          </tbody>
        </table>
      </aside>

      <datalist id="meals-list">
        @foreach (var m in ViewBag.AvailableMeals as List<Aberwyn.Models.Meal>) {
          <option value="@m.Name" />
        }
      </datalist>
    </form>
  </section>
</div>
