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

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

global.Socket = new Socket()

global.currentNetwork = ""
global.currentApp = ""

async function openNetworkAndApp() {
    // console.log("currentApp: ", currentApp, "currentnet: ", currentNetwork, "nfrompath: ", networkFromPath(), "afrompath", appFromPath())
    
    if(global.currentNetwork !== networkFromPath()) {
        global.currentNetwork = networkFromPath()
        const event = new CustomEvent('networkchange', {
            detail: { name: currentNetwork }
        });
        window.dispatchEvent(event)
    }

    if(!global.currentNetwork.data) {
        let appData = await fetch("/api/orgdata/" + global.profile.networks[0].id, {method: "GET"})
        let json = await appData.json()
        global.currentNetwork.data = json
    }

    console.log("current: ", global.currentApp, "afrompath: ", appFromPath())
    if(global.currentApp !== appFromPath()) {
        global.currentApp = appFromPath()
        const event = new CustomEvent('appchange', {
            detail: { name: global.currentApp }
        });
        window.dispatchEvent(event)
    }

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

window.addEventListener("navigate", openNetworkAndApp)

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

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

window.appFromPath = 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
}

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("getProfile: ", profile);
        global.profile = profile
    } catch (err) {
        console.error(err);
    }
}

function getInitialNetworkPath() {
    let path = ""
    let defaultNetwork = global.profile.networks[0]

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

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

    return path
}

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

    Home()
})