@using Newtonsoft.Json
@using Newtonsoft.Json.Serialization
@{
    ViewData["Title"] = "Beställ pizza";
    var pizzas = ViewBag.Pizzas as List<Meal>;
    var previousOrder = ViewBag.PreviousOrder as PizzaOrder;
    var lastId = Context.Session.GetInt32("LastPizzaOrderId");
    var isCurrentOrder = previousOrder?.Id == lastId;
var forceShow = TempData["ForceShowForm"]?.ToString() == "true";
var justOrdered = TempData["Success"]?.ToString()?.Contains("beställd") == true;
var showForm = previousOrder == null || (forceShow && !justOrdered);

}

<link rel="stylesheet" href="~/css/pizza.css" />

<div class="pizza-container">
    @if (!(ViewBag.RestaurantIsOpen as bool? ?? true))
    {
        <div class="alert alert-warning text-center mt-5">
            🛑 <strong>Restaurangen är stängd just nu.</strong><br />
            Kom tillbaka senare för att lägga din beställning.
        </div>
        return;
    }

    @if (TempData["Success"] != null)
    {
        <div class="alert alert-success text-center mb-4">
            🍕 @TempData["Success"]
        </div>
    }

    @if (previousOrder != null)
    {
        var ingredienser = string.IsNullOrEmpty(previousOrder.IngredientsJson)
            ? new List<string>()
            : System.Text.Json.JsonSerializer.Deserialize<List<string>>(previousOrder.IngredientsJson);

        <div class="alert alert-info mb-4">
            <strong>🍕 Du har redan beställt:</strong><br />
            <strong>@previousOrder.PizzaName</strong>
            @if (ingredienser.Count > 0)
            {
                <span>(med @string.Join(", ", ingredienser))</span>
            }
            <div class="mt-2">
                <span class="badge bg-secondary">Status: @previousOrder.Status</span>
            </div>
            <form method="get" asp-action="EditPizzaOrder" asp-route-id="@previousOrder.Id" class="d-inline mt-2">
                <button class="btn btn-sm btn-outline-primary me-2">✏️ Uppdatera min beställning</button>
            </form>
            <form method="post" asp-action="ClearPizzaSession" class="d-inline">
                <button class="btn btn-sm btn-outline-secondary">➕ Beställ ny pizza</button>
            </form>
        </div>
    }

    @if (showForm)
    {
        <!-- Steg 1: Namn -->
        <div id="step1" class="pizza-step active">
            <h2>Hej! Vad heter du? 😊</h2>
            <input type="text" id="customerName" placeholder="Ditt namn" class="form-control" />
            <button onclick="goToStep(2)" class="btn btn-primary mt-3">Fortsätt</button>
        </div>

        <!-- Steg 2: Välj pizza -->
        <div id="step2" class="pizza-step">
            <h2>🍕 Välj en pizza</h2>
            <div class="pizza-list">
                @foreach (var pizza in pizzas)
                {
                    <div class="pizza-card" onclick="selectPizza(@pizza.Id)">
                        <h3>@pizza.Name</h3>
                        <p>@string.Join(", ", pizza.Ingredients?.Select(i => i.Item) ?? new List<string>())</p>
                    </div>
                }
                <div class="pizza-card custom" onclick="selectPizza(null)">
                    <h3>🧑‍🍳 Skapa egen pizza</h3>
                    <p>Lägg till dina egna ingredienser</p>
                </div>
            </div>
        </div>

        <!-- Steg 3: Redigera ingredienser -->
        <div id="step3" class="pizza-step">
            <h2 id="editTitle">Redigera pizza</h2>
            <ul id="ingredientList" class="list-group mb-3"></ul>
            <div class="input-group mb-3">
                <input type="text" id="newIngredient" class="form-control" placeholder="Lägg till ingrediens" />
                <button type="button" class="btn btn-outline-secondary" onclick="addIngredient()">➕</button>
            </div>
            <button class="btn btn-secondary" onclick="goToStep(2)">⬅ Tillbaka</button>
            <button class="btn btn-primary" onclick="goToStep(4)">Fortsätt</button>
        </div>

        <!-- Steg 4: Summering -->
        <div id="step4" class="pizza-step">
            <h2>Bekräfta din beställning</h2>
            <p>Din pizza:</p>
            <p><strong id="summaryPizza"></strong></p>
            <ul id="summaryIngredients" class="list-group mb-3"></ul>

            <form method="post">
                <input type="hidden" name="customerName" id="formName" />
                <input type="hidden" name="pizzaName" id="formPizza" />
                <input type="hidden" name="ingredients" id="formIngredients" />
                <button type="submit" class="btn btn-success">✅ Skicka beställning</button>
            </form>
        </div>
    }
</div>

@section Scripts {
<script>
    @if (ViewBag.PreviousOrder is PizzaOrder p)
    {
        <text>
        window.addEventListener("DOMContentLoaded", () => {
    const forceEdit = @((TempData["ForceShowForm"]?.ToString() == "true").ToString().ToLower());
    const customerField = document.getElementById("customerName");
    if (customerField) customerField.value = "@p.CustomerName";
    const selected = allMeals.find(m => m.name === "@p.PizzaName") || { name: "Egen pizza", ingredients: [] };
    if (forceEdit && selected) {
        selectedPizza = selected;
        selectedIngredients = @Html.Raw(p.IngredientsJson ?? "[]");
        document.getElementById("editTitle").innerText = `Redigera: ${selected.name}`;
        renderIngredientList();
        selectedName = "@p.CustomerName";
        goToStep(3);
    }
});
        </text>
    }

    const allMeals = @Html.Raw(JsonConvert.SerializeObject(
        pizzas,
        new JsonSerializerSettings {
            NullValueHandling = NullValueHandling.Ignore,
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        }));

    let selectedPizza = null;
    let selectedIngredients = [];
    let selectedName = "";

    function goToStep(step) {
        if (step === 2) {
            const nameInput = document.getElementById("customerName").value.trim();
            if (!nameInput) {
                alert("Skriv ditt namn!");
                return;
            }
            selectedName = nameInput;
        }

        if (step === 4) {
            const pizzaName = selectedPizza?.name ?? "Egen pizza";
            const originalIngredients = selectedPizza?.ingredients?.map(i => i.item) ?? [];
            const current = selectedIngredients;

            const removed = [];
            const added = [];

            let details = [];
            if (removed.length > 0) details.push("utan " + removed.join(", "));
            if (added.length > 0) details.push("extra " + added.join(", "));

            const fullName = details.length > 0
                ? `${pizzaName} (${details.join(", ")})`
                : pizzaName;

            document.getElementById("summaryPizza").innerText = fullName;
            document.getElementById("formName").value = selectedName;
            document.getElementById("formPizza").value = fullName;
            document.getElementById("formIngredients").value = JSON.stringify(selectedIngredients);
            const list = document.getElementById("summaryIngredients");
            list.innerHTML = '';
            selectedIngredients.forEach(ing => {
                const li = document.createElement("li");
                li.className = "list-group-item";
                li.innerText = ing;
                list.appendChild(li);
            });
        }

        document.querySelectorAll(".pizza-step").forEach(s => s.classList.remove("active"));
        document.getElementById(`step${step}`)?.classList.add("active");
    }

    function selectPizza(pizzaId) {
        pizzaId = parseInt(pizzaId);
        selectedPizza = allMeals.find(m => m.id === pizzaId);
        if (!selectedPizza) {
            selectedPizza = { name: "Egen pizza", ingredients: [] };
        }
        selectedIngredients = [...(selectedPizza.ingredients?.map(i => i.item) ?? [])];
        document.getElementById("editTitle").innerText = `Redigera: ${selectedPizza.name}`;
        renderIngredientList();
        goToStep(3);
    }

    function renderIngredientList() {
        const list = document.getElementById("ingredientList");
        list.innerHTML = '';
        selectedIngredients.forEach((ing, i) => {
            const li = document.createElement("li");
            li.className = "list-group-item d-flex justify-content-between";
            li.innerHTML = `${ing} <button class="btn btn-sm btn-danger" onclick="removeIngredient(${i})">🗑</button>`;
            list.appendChild(li);
        });
    }

    function addIngredient() {
        const input = document.getElementById("newIngredient");
        const value = input.value.trim();
        if (value) {
            selectedIngredients.push(value);
            input.value = '';
            renderIngredientList();
        }
    }

    function removeIngredient(index) {
        selectedIngredients.splice(index, 1);
        renderIngredientList();
    }

    document.getElementById("customerName")?.addEventListener("keydown", function (e) {
        if (e.key === "Enter") goToStep(2);
    });
</script>
}
