// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.

if ('serviceWorker' in navigator) {
    window.addEventListener('load', function () {
        navigator.serviceWorker.register('/service-worker.js')
            .then(function (registration) {
                //console.log('✅ Service Worker registrerad med scope:', registration.scope);
                //subscribeToPush().catch(console.error);
            })
            .catch(function (error) {
                console.log('❌ Service Worker-registrering misslyckades:', error);
            });
    });
}
document.addEventListener("DOMContentLoaded", () => {
    const dropdowns = document.querySelectorAll(".dropdown");
    const globalContainer = document.getElementById("global-dropdown-container");

    dropdowns.forEach((dropdown, index) => {
        const toggle = dropdown.querySelector(".dropdown-toggle");
        const menu = dropdown.querySelector(".dropdown-menu");

        if (!toggle || !menu) return;

        let originalParent = dropdown;

        toggle.addEventListener("click", e => {
            e.preventDefault();
            e.stopPropagation();

            const isOpen = dropdown.classList.contains("open");

            // Stäng andra
            document.querySelectorAll(".dropdown.open").forEach(d => {
                d.classList.remove("open");
                const m = d.querySelector(".dropdown-menu");
                if (m && d !== dropdown) {
                    d.appendChild(m);
                    resetStyles(m);
                }
            });

            dropdown.classList.toggle("open", !isOpen);

            if (!isOpen && window.innerWidth <= 768) {
                const rect = toggle.getBoundingClientRect();
                const scrollTop = window.scrollY || document.documentElement.scrollTop;
                const scrollLeft = window.scrollX || document.documentElement.scrollLeft;

                let top = rect.bottom + scrollTop - 20;
                let left = rect.left + scrollLeft;
                const vw = window.innerWidth;
                const mw = menu.offsetWidth;

                if (left + mw > vw) {
                    left = vw - mw - 10;
                }
                if (left < 10) left = 10;

                // Flytta till global container
                globalContainer.appendChild(menu);

                Object.assign(menu.style, {
                    position: "fixed",
                    top: `${top}px`,
                    left: `${left}px`,
                    zIndex: "99999",
                    display: "flex"
                });
            } else {
                // Återställ till original
                originalParent.appendChild(menu);
                resetStyles(menu);
            }
        });
    });

    document.addEventListener("click", () => {
        document.querySelectorAll(".dropdown.open").forEach(d => {
            d.classList.remove("open");
            const m = d.querySelector(".dropdown-menu");
            if (m) {
                d.appendChild(m);
                resetStyles(m);
            }
        });

        // Töm extra container
        if (globalContainer) globalContainer.innerHTML = '';
    });

    function resetStyles(menu) {
        Object.assign(menu.style, {
            position: "",
            top: "",
            left: "",
            zIndex: "",
            display: ""
        });
    }
});



async function subscribeToPush() {
    const registration = await navigator.serviceWorker.ready;
    const publicVapidKey = await fetch('/api/push/vapid-public-key')
    .then(r => r.text())
    .then(key => {
        return key;
    });

    const subscription = await registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
    });

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

    //console.log('✅ Push-prenumeration skickad');
}

async function enablePush() {
    const permission = await Notification.requestPermission();
    const existingSub = await registration.pushManager.getSubscription();
    if (existingSub) {
        alert("🔔 Du är redan prenumererad på notiser.");
        return;
    }

    if (permission !== "granted") {
        alert("Du måste tillåta notiser för att få push.");
        return;
    }

    const registration = await navigator.serviceWorker.ready;
    const publicVapidKey = await fetch('/api/push/vapid-public-key').then(r => r.text());

    const subscription = await registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(publicVapidKey.trim()) // 👈 .trim() viktigt
    });


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

    alert("✅ Push-notiser aktiverade!");
}




// utility för att konvertera nyckeln
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)));
}
