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

let Global = class {
    Socket = new Socket()
    profile = null
    currentNetwork = ""
    currentApp = ""
    util = util

    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
        window.navigateTo(newPath)
        const event = new CustomEvent('appchange', {
            detail: { name: appName }
        });
        window.dispatchEvent(event)
    }

    async fetchAppData() {
        let personalSpace = this.currentNetwork === this.profile
        let appData = await fetch(`/api/${personalSpace ? "my" : "org"}data/` + this.currentNetwork.id, {method: "GET"})
        let json = await appData.json()
        return json
    }

    async handleStripeOnboarding() {
        const params = new URLSearchParams(window.location.search);
        const code = params.get("code");
        const { returnTo, networkId } = JSON.parse(atob(params.get("state")));

        if (code) {
            console.log("success!: ", code)
            await fetch("/api/stripe/onboarded", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ code, networkId })
            });
           
            window.location.href = returnTo

        } else {
            throw new Error("Stripe code is not present!")
        }
    }

    onNavigate = async () => {
        console.log("onnavigate", this.getFirstPathSegment())
        if(this.getFirstPathSegment() === "stripe") {
            this.handleStripeOnboarding()
        }

        let selectedNetwork = this.networkFromPath()
        let selectedApp = this.appFromPath()

        if(!selectedNetwork) {
            if(this.profile.networks.length > 0) {
                let path = `/${this.getDefaultNetworkName()}/${this.getDefaultAppName()}`
                history.replaceState({}, '', path)
            }
        } else if(!selectedApp) {
            if(this.currentNetwork === window.profile) {
                history.replaceState({}, '', `${window.location.pathname}/${window.profile.apps[0]}`)
            } else {
                history.replaceState({}, '', `${window.location.pathname}/${this.getDefaultAppName()}`)
            }
        }

        selectedNetwork = this.networkFromPath()
        selectedApp = this.appFromPath()

        let networkChanged = this.currentNetwork !== selectedNetwork
        let appChanged = this.currentApp !== selectedApp
        if(networkChanged) {
            this.currentNetwork = selectedNetwork
            this.currentApp = selectedApp
            const event = new CustomEvent('networkchange', {
                detail: { name: this.currentNetwork }
            });
            window.dispatchEvent(event)
        }

        if(!this.currentNetwork.data) {
            this.currentNetwork.data = await this.fetchAppData()
        }

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

        document.title = (this.currentNetwork === this.profile) ? "Forum" : `${this.currentNetwork.abbreviation} | Forum`
    }

    setCurrentNetworkAndApp() {
        this.currentNetwork = this.networkFromPath()

    }

    getDefaultNetworkName() {
        let defaultNetwork = this.profile.networks[0]
        return defaultNetwork.abbreviation
    }

    getDefaultAppName() {
        let defaultNetwork = this.profile.networks[0]
        return defaultNetwork.apps[0].toLowerCase()
    }

    getFirstPathSegment() {
        return window.location.pathname.split('/').filter(Boolean)[0] || '';
    }

    networkFromPath = function () {
        const firstSegment = this.getFirstPathSegment()
        if(firstSegment === "my") {
            return this.profile
        } else {
            let networks = this.profile.networks
            for(let i = 0; i < networks.length; i++) {
                let network = networks[i]
                if(network.abbreviation === firstSegment) {
                    return network
                }
            }
        }
    }

    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 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);
            this.profile = profile
        } catch (err) {
            console.error(err);
        }
    }

    constructor() {
        window.addEventListener("navigate", this.onNavigate)

        this.getProfile().then(async () => {

            await this.onNavigate()

            Home()
            
        })
    }
}

window.global = new Global()