@model Aberwyn.Models.UserProfileViewModel
@{
    ViewData["Title"] = "Min profil";
}

<h2>Min profil</h2>

<form method="post" asp-action="SaveProfile">
    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" />
    </div>
    <div>
        <label asp-for="Email"></label>
        <input asp-for="Email" readonly />
    </div>

    <h3>Pushnotiser</h3>
    <div>
        <input asp-for="NotifyPizza" type="checkbox" />
        <label asp-for="NotifyPizza">Ny pizzabeställning</label>
    </div>
    <div>
        <input asp-for="NotifyMenu" type="checkbox" />
        <label asp-for="NotifyMenu">Meny ändrad</label>
    </div>
    <div>
        <input asp-for="NotifyBudget" type="checkbox" />
        <label asp-for="NotifyBudget">Budget uppdaterad</label>
    </div>

    <button type="submit">Spara</button>

    <div style="margin-top: 1em;">
        <div id="notificationStatus" style="font-weight: bold;"></div>
        <button type="button" id="enableNotificationsBtn">Aktivera notiser</button>
        <button type="button" id="disableNotificationsBtn">Stäng av notiser</button>
    </div>
</form>

@section Scripts {
<script>
    async function updateNotificationStatus() {
        const el = document.getElementById("notificationStatus");

        if (!("Notification" in window)) {
            el.textContent = "⛔️ Pushnotiser stöds inte i denna webbläsare.";
            el.style.color = "gray";
            return;
        }

        const status = Notification.permission;
        const reg = await navigator.serviceWorker.ready;
        const existing = await reg.pushManager.getSubscription();

        switch (status) {
            case "granted":
                el.textContent = existing ? "✅ Pushnotiser är aktiverade." : "🟡 Tillåtet men ingen prenumeration aktiv.";
                el.style.color = existing ? "green" : "orange";
                break;
            case "denied":
                el.textContent = "❌ Pushnotiser är blockerade.";
                el.style.color = "red";
                break;
            case "default":
                el.textContent = "❔ Pushnotiser har inte begärts ännu.";
                el.style.color = "orange";
                break;
        }
    }

    document.addEventListener("DOMContentLoaded", updateNotificationStatus);

    document.getElementById("enableNotificationsBtn").addEventListener("click", async () => {
        if (!("Notification" in window)) {
            alert("Notiser stöds inte i denna webbläsare.");
            return;
        }

        const permission = await Notification.requestPermission();
        if (permission !== "granted") {
            alert("Du måste tillåta notiser.");
            updateNotificationStatus();
            return;
        }

        const reg = await navigator.serviceWorker.ready;
        const existing = await reg.pushManager.getSubscription();
        if (existing) {
            alert("🔔 Du är redan prenumererad på notiser.");
            updateNotificationStatus();
            return;
        }

        const vapidPublicKey = await fetch('/api/push/vapid-public-key').then(r => r.text());
        const sub = await reg.pushManager.subscribe({
            userVisibleOnly: true,
            applicationServerKey: urlBase64ToUint8Array(vapidPublicKey.trim())
        });

        await fetch("/api/push/subscribe-user", {
            method: "POST",
            body: JSON.stringify(sub),
            headers: { "Content-Type": "application/json" }
        });

        alert("✅ Du är nu prenumererad!");
        updateNotificationStatus();
    });

    document.getElementById("disableNotificationsBtn").addEventListener("click", async () => {
        const reg = await navigator.serviceWorker.ready;
        const sub = await reg.pushManager.getSubscription();
        if (!sub) {
            alert("ℹ️ Ingen prenumeration att ta bort.");
            return;
        }

        await sub.unsubscribe();
        await fetch("/api/push/unsubscribe", {
            method: "POST",
            body: JSON.stringify({ endpoint: sub.endpoint }),
            headers: { "Content-Type": "application/json" }
        });

        alert("🚫 Prenumeration avslutad.");
        updateNotificationStatus();
    });

    function urlBase64ToUint8Array(base64String) {
        const padding = '='.repeat((4 - base64String.length % 4) % 4);
        const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
        const raw = atob(base64);
        return new Uint8Array([...raw].map(char => char.charCodeAt(0)));
    }
</script>
}
