@model Aberwyn.Models.Meal
@using Microsoft.AspNetCore.Authorization
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor

@{
    ViewData["Title"] = Model.Name;
    bool isEditing = (bool)(ViewData["IsEditing"] ?? false);
    string imageSrc;
    if (Model.ImageData != null && Model.ImageData.Length > 0)
    {
        var base64 = Convert.ToBase64String(Model.ImageData);
        var mime = string.IsNullOrEmpty(Model.ImageMimeType) ? "image/jpeg" : Model.ImageMimeType;
        imageSrc = $"data:{mime};base64,{base64}";
    }
    else
    {
        imageSrc = "/images/placeholder-meal.jpg";
    }

    bool isChef = HttpContextAccessor.HttpContext.User.IsInRole("Chef");
    isEditing = isEditing && isChef;
}

<div class="meal-container">
    <div class="meal-header">
        <div class="meal-image-wrapper clickable" title="Bild på rätten">
            <img id="imagePreview" src="@imageSrc" alt="@Model.Name" class="meal-image" />
        </div>
        @if (isEditing)
        {
            <div style="margin-top: 0.5rem;">
                <button type="button" class="btn-outline" onclick="openImageModal()">Byt bild</button>
            </div>
        }

        <div class="meal-meta">
            <h1 class="meal-title">@Model.Name</h1>
            <p class="description">@Model.Description</p>
        </div>
    </div>

    @if (isEditing)
    {
        <form asp-action="SaveMeal" method="post" enctype="multipart/form-data">
            <input type="hidden" name="Id" value="@Model.Id" />
            <input type="file" id="ImageFile" name="ImageFile" accept="image/*" style="display: none;" />

            <div class="form-group">
                <label for="Name">Namn</label>
                <input type="text" name="Name" value="@Model.Name" class="form-control" required />
            </div>

            <div class="form-group">
                <label for="Description">Beskrivning</label>
                <textarea name="Description" class="form-control">@Model.Description</textarea>
            </div>

            <div class="form-group">
                <label for="ProteinType">Protein</label>
                <input type="text" name="ProteinType" value="@Model.ProteinType" class="form-control" />
            </div>

            <div class="form-group">
                <label for="CarbType">Kolhydrat</label>
                <input type="text" name="CarbType" value="@Model.CarbType" class="form-control" />
            </div>

            <div class="form-group">
                <label for="RecipeUrl">Receptlänk</label>
                <input type="url" name="RecipeUrl" value="@Model.RecipeUrl" class="form-control" />
            </div>

            <div id="recipe-section">
                <h2>Så här gör du</h2>
                <div class="form-group">
                    <label for="Instructions">Tillagningsinstruktioner</label>
                    <textarea id="Instructions" name="Instructions">@Html.Raw(Model.Instructions)</textarea>
                </div>
                <div class="form-group">
                    <label>Ingredienser</label>
                    <div id="ingredients-list">
                        @for (int i = 0; i < Model.Ingredients.Count; i++)
                        {
                            <div class="ingredient-row">
                                <input type="text" name="Ingredients[@i].Quantity" placeholder="Mängd" value="@Model.Ingredients[i].Quantity" class="form-control ingredient-qty" />
                                <input type="text" name="Ingredients[@i].Item" placeholder="Ingrediens" value="@Model.Ingredients[i].Item" class="form-control ingredient-item" />
                            </div>
                        }
                    </div>
                    <button type="button" class="btn-outline" onclick="addIngredientRow()">+ Lägg till ingrediens</button>
                </div>
            </div>

            <div class="buttons">
                <button type="submit" class="btn">Spara</button>
                <button type="submit" formaction="@Url.Action("DeleteMeal", new { id = Model.Id })" formmethod="post" onclick="return confirm('Vill du verkligen ta bort denna måltid?');" class="btn-outline">Ta bort</button>
                <a href="@Url.Action("View", new { id = Model.Id, edit = false })" class="btn-outline">Avbryt</a>
            </div>
        </form>
    }
    else
    {
        <div class="meal-details">
            @if (!string.IsNullOrEmpty(Model.ProteinType))
            {
                <p><span class="label">Protein:</span> @Model.ProteinType</p>
            }
            @if (!string.IsNullOrEmpty(Model.CarbType))
            {
                <p><span class="label">Kolhydrat:</span> @Model.CarbType</p>
            }
        </div>

        @if (!string.IsNullOrEmpty(Model.RecipeUrl))
        {
            <p><a href="@Model.RecipeUrl" class="recipe-link" target="_blank">Visa Recept</a></p>
        }

        <div class="buttons">
            @if (isChef)
            {
                <a class="btn-outline" href="@Url.Action("View", new { id = Model.Id, edit = true })">Redigera</a>
            }
            <button type="button" class="btn-outline" onclick="toggleRecipe()">Recept</button>
        </div>

        <div id="recipe-section" style="display:none; margin-top:1.5rem;">
            <h2>Så här gör du</h2>
            @if (!string.IsNullOrWhiteSpace(Model.Instructions))
            {
                <div class="instructions-content">
                    @Html.Raw(Model.Instructions)
                </div>
            }
            else
            {
                <p class="placeholder">Ingen instruktion har lagts till ännu.</p>
            }

            @if (Model.Ingredients != null && Model.Ingredients.Any())
            {
                <h3>Ingredienser</h3>
                <ul>
                    @foreach (var ing in Model.Ingredients)
                    {
                        <li>@ing.Quantity @ing.Item</li>
                    }
                </ul>
            }
        </div>
    }
</div>

<div id="imageModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.6); z-index:1000;">
    <div style="background:white; margin:5% auto; padding:2rem; max-width:400px; border-radius:8px; text-align:center; position:relative;">
        <h3>Klistra in eller dra in bild</h3>
        <div id="dropZone" style="border:2px dashed #aaa; padding:2rem; cursor:pointer;">
            <p>Släpp bild här eller klistra in (Ctrl+V)</p>
        </div>
        <input type="file" id="modalImageInput" accept="image/*" style="display:none;" />
        <button type="button" onclick="document.getElementById('modalImageInput').click()">Välj bild från enhet</button>
        <button onclick="closeImageModal()" style="margin-top:1rem;">Stäng</button>
    </div>
</div>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/ui/trumbowyg.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/trumbowyg.min.js"></script>

<script>
    function toggleRecipe() {
        const section = document.getElementById('recipe-section');
        if (!section) return;

        if (section.style.display === 'none' || section.style.display === '') {
            section.style.display = 'block';
        } else {
            section.style.display = 'none';
        }
    }
    function openImageModal() {
        document.getElementById('imageModal').style.display = 'block';
    }
    function closeImageModal() {
        document.getElementById('imageModal').style.display = 'none';
    }
    function handleImage(file) {
        const reader = new FileReader();
        reader.onload = e => {
            document.getElementById("imagePreview").src = e.target.result;
            const dt = new DataTransfer();
            dt.items.add(file);
            document.getElementById("ImageFile").files = dt.files;
        };
        reader.readAsDataURL(file);
    }
    document.getElementById('dropZone').addEventListener('dragover', e => {
        e.preventDefault();
        e.currentTarget.style.borderColor = '#6a0dad';
    });
    document.getElementById('dropZone').addEventListener('dragleave', e => {
        e.currentTarget.style.borderColor = '#aaa';
    });
    document.getElementById('dropZone').addEventListener('drop', e => {
        e.preventDefault();
        const file = e.dataTransfer.files[0];
        if (file && file.type.startsWith('image/')) {
            handleImage(file);
            closeImageModal();
        }
    });
    document.getElementById('modalImageInput').addEventListener('change', e => {
        const file = e.target.files[0];
        if (file && file.type.startsWith('image/')) {
            handleImage(file);
            closeImageModal();
        }
    });
        $(document).ready(function () {
        if ($('#Instructions').length > 0) {
            $('#Instructions').trumbowyg({
                autogrow: true,
                btns: [['strong', 'em'], ['unorderedList', 'orderedList'], ['link'], ['removeformat']]
            });
        }
    });
      if ('serviceWorker' in navigator && 'PushManager' in window) {
    navigator.serviceWorker.register('/service-worker.js')
      .then(function (registration) {
        console.log('Service Worker registered', registration);
        return registration.pushManager.getSubscription()
          .then(async function (subscription) {
            if (subscription) {
              console.log('Already subscribed to push notifications.');
              return subscription;
            }
            const response = await fetch('/api/push/vapid-public-key');
            const vapidPublicKey = await response.text();
            const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);

            return registration.pushManager.subscribe({
              userVisibleOnly: true,
              applicationServerKey: convertedVapidKey
            });
          });
      }).then(function (subscription) {
        return fetch('/api/push/subscribe', {
          method: 'POST',
          body: JSON.stringify(subscription),
          headers: {
            'Content-Type': 'application/json'
          }
        });
      });
  }

</script>

<style>
    .dragging {
        outline: 2px dashed #6a0dad;
    }
    .meal-image-wrapper {
        position: relative;
    }
    .meal-container {
        max-width: 900px;
        margin: 2rem auto;
        background: #fff;
        padding: 2rem;
        border-radius: 16px;
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
        font-family: 'Segoe UI', sans-serif;
    }
    .meal-header {
        display: flex;
        flex-direction: row;
        gap: 1.5rem;
        align-items: center;
    }
    .meal-meta {
        flex: 1;
    }
    .meal-title {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 1rem;
        color: #333;
    }
    .meal-image {
        width: 250px;
        height: 250px;
        object-fit: cover;
        border-radius: 12px;
        border: 1px solid #ccc;
    }
    .description {
        font-size: 1.1rem;
        color: #555;
        margin-top: 0.5rem;
        margin-bottom: 1.5rem;
    }
    .meal-details p {
        font-size: 1rem;
        color: #333;
        margin: 0.3rem 0;
    }
    .label {
        font-weight: bold;
        color: #6a0dad;
    }
    .form-group {
        margin-bottom: 1rem;
    }
    .form-group label {
        font-weight: 600;
        margin-bottom: 0.3rem;
        display: block;
    }
    .form-control {
        width: 100%;
        padding: 0.5rem;
        border: 1px solid #ccc;
        border-radius: 6px;
        font-size: 1rem;
    }
    .buttons {
        margin-top: 1.5rem;
    }
    .btn,
    .btn-outline {
        background-color: #6a0dad;
        color: white;
        border: none;
        padding: 0.6rem 1.4rem;
        border-radius: 6px;
        margin: 0.4rem;
        cursor: pointer;
        font-size: 1rem;
        text-decoration: none;
    }
    .btn-outline {
        background-color: transparent;
        border: 2px solid #6a0dad;
        color: #6a0dad;
    }
    .recipe-link {
        color: #6a0dad;
        text-decoration: underline;
        font-weight: 500;
    }
    .placeholder {
        color: #999;
        font-style: italic;
    }
    .ingredient-row {
    display: flex;
    gap: 0.5rem;
    margin-bottom: 0.5rem;
    }

    .ingredient-qty {
        flex: 1 0 30%;
    }

    .ingredient-item {
        flex: 2 0 60%;
    }

    @@media (max-width: 768px) {
    .meal-container {
        padding: 1rem;
    }

    .meal-header {
        flex-direction: column;
        align-items: center;
        text-align: center;
    }

    .meal-meta {
        width: 100%;
    }

    .meal-title {
        font-size: 2rem;
    }

    .meal-image {
        width: 100%;
        max-width: 300px;
        height: auto;
    }

    .form-control {
        font-size: 1rem;
    }

    .ingredient-row {
        flex-direction: column;
    }

    .ingredient-qty,
    .ingredient-item {
        flex: 1 0 auto;
        width: 100%;
    }

    .btn,
    .btn-outline {
        width: 100%;
        margin: 0.25rem 0;
    }

    .buttons {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }
}

</style>
