<!DOCTYPE html>
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor

@{
    bool isChef = HttpContextAccessor.HttpContext.User.IsInRole("Chef");
}

<html lang="sv" ng-app="mealGalleryApp">
<head>
  <meta charset="utf-8">
  <title>Måltider</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
  <link rel="stylesheet" href="/css/meal-gallery.css">
  <script src="https://kit.fontawesome.com/yourkit.js" crossorigin="anonymous"></script>
  <style>
    *, *::before, *::after { box-sizing: border-box; }
    body { overflow-x: hidden; }
  </style>
</head>
<body ng-controller="MealGalleryController">
  <div class="meal-gallery-container">
    <div class="meal-gallery-header">
      <h1>Recept</h1>
        <div class="search-container">
          <input type="text" ng-model="search" placeholder="Sök recept..." />
          <i class="fa-solid fa-magnifying-glass"></i>

          @if (isChef)
          {
              <label class="toggle-published">
                <input type="checkbox" ng-model="includeUnpublished" ng-change="reloadMeals()" />
                <span>Visa alla</span>
              </label>

              <a href="/meal/view?edit=true" class="btn-create-meal">+ Ny rätt</a>
          }
        </div>


    </div>

    <div class="meal-gallery-grid">
      <div class="meal-card"
           ng-repeat="meal in (meals | filter:search) | limitTo:visibleCount track by meal.Id">
        <img ng-src="{{ meal.ThumbnailData ? 'data:image/webp;base64,' + meal.ThumbnailData : '/images/fallback.jpg' }}"
             alt="{{ meal.Name }}">
        <div class="meal-card-content">
          <h3>{{ meal.Name }}</h3>
          <p ng-if="meal.Description">{{ meal.Description }}</p>
          <a class="btn-readmore" ng-href="/meal/view/{{ meal.Id }}">Läs mer</a>
        </div>
      </div>
    </div>
  </div>

  <script>
angular.module("mealGalleryApp", []).controller("MealGalleryController", function ($scope, $http) {
  $scope.meals = [];
  $scope.search = "";
  $scope.visibleCount = 12;
  $scope.includeUnpublished = false;

  $scope.reloadMeals = function () {
    const url = `/api/mealMenuApi/getPublishedMeals?includeUnpublished=${$scope.includeUnpublished}`;
    $http.get(url).then(res => {
      $scope.meals = res.data;
    });
  };

  $scope.reloadMeals();

  window.addEventListener('scroll', function () {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 150) {
      $scope.$applyAsync(() => {
        $scope.visibleCount += 8;
      });
    }
  });

  $scope.$watch('search', function (newVal) {
    $scope.visibleCount = newVal ? 9999 : 12;
  });
});

  </script>
</body>
</html>
