import Socket from "./ws/Socket.js"
import "./Home.js"

import util from "./util.js"
window.util = util

window.Socket = new Socket()

window.currentNetwork = ""
window.currentApp = ""

window.addEventListener("navigate", () => {
    if(window.currentNetwork !== selectedNetwork()) {
        window.currentNetwork = selectedNetwork()
        const event = new CustomEvent('networkchanged', {
            detail: { name: currentNetwork }
        });
        window.dispatchEvent(event)
    }

    if(window.currentApp !== selectedApp()) {
        window.currentApp = selectedApp()
        const event = new CustomEvent('appchange', {
            detail: { name: window.currentApp }
        });
        window.dispatchEvent(event)
    }

    if(window.currentNetwork) { // 2 navigates fire on load: 1 initial, and one after the org redirect
        document.title = `${window.currentNetwork.abbreviation} | Parchment`
    }
})

window.selectedNetwork = function () {
    const pathname = window.location.pathname;
    const firstSegment = pathname.split('/').filter(Boolean)[0] || '';
    let networks = window.profile?.networks
    for(let i = 0; i < networks.length; i++) {
        let network = networks[i]
        if(network.abbreviation === firstSegment) {
            return network
        }
    }
}

window.selectedApp = function() {
    const pathname = window.location.pathname;
    const segments = pathname.split('/').filter(Boolean);
    const secondSegment = segments[1] || "";
    const capitalized = secondSegment.charAt(0).toUpperCase() + secondSegment.slice(1);
    return capitalized
}

window.openApp = function(appName) {
    const appUrl = appName.charAt(0).toLowerCase() + appName.slice(1);
    let parts = window.location.pathname.split('/').filter(Boolean);
    let newPath = "/" + parts[0] + "/" + appUrl
    console.log(newPath)
    window.navigateTo(newPath)
    // window.history.replaceState({}, '', newPath);
    const event = new CustomEvent('appchange', {
        detail: { name: appName }
    });
    window.dispatchEvent(event)
}

async function getProfile() {
    try {
        const res = await fetch("/profile", {
            method: "GET",
            credentials: "include",
            headers: {
                "Content-Type": "application/json"
            }
        });

        if (!res.ok) throw new Error("Failed to fetch profile");

        const profile = await res.json();
        console.log(profile);
        window.profile = profile
    } catch (err) {
        console.error(err);
    }
}

async function setCurrentNetwork() {
    let path = ""
    let defaultNetwork = window.profile.networks[0]

    if(!selectedNetwork()) {
        path += (defaultNetwork.abbreviation + "/")
    }

    if(!selectedApp()) {
        let defaultApp = defaultNetwork.apps[0]
        path += defaultApp.toLowerCase()
    }

    let appData = await fetch("/app/comaldata", {method: "GET"})
    let json = await appData.json()
    window.comalData = json

    return path
}

getProfile().then(async () => {
    
    if(window.profile.networks.length > 0) {
        let path = await setCurrentNetwork()
        window.navigateTo(path)
    }

    Home()
})