import { createRoot } from "react-dom/client";
import { Menu } from "./menu";
import { createContext, useEffect, useState } from "react";
import { MediaContainer } from "./media";
import { MinistreamApiClient } from "./api";
import React from "react";

interface AppProps {
    api: MinistreamApiClient
}

const titleKey = "ministream.title"

function setTitleFromLocalstorage() {
    var title = localStorage.getItem(titleKey)
    if (title) {
        setTitle(title)
    }
}

function setTitle(title: string) {
    const el = document.querySelector('title')
    if (el) {
        el.textContent = title
    }
}

export function App({ api }: AppProps) {
    const [streamList, setStreamList] = useState<string[]>([])
    const [selectedStream, setSelectedStream] = useState<string | null>(null)

    const updateSelect = (item: string | null) => {
        setSelectedStream(item)
    }

    const updateStreamList = () => {
        api.listStreams().then((list) => {
            setStreamList(list)
            if (list.length != streamList.length) {
                setStreamList(list)
            }

            if (!list.every((_, idx) => {
                return list[idx] === streamList[idx]
            })) {
                setStreamList(list)
            }
        })
    }

    const updateTitle = () => {
            api.siteInfo().then((info) => {
            if (info.siteName != document.title) {
                setTitle(info.siteName)
                localStorage.setItem(titleKey, info.siteName)
            }
        })
        return
    }

    setInterval(() => {
        updateStreamList()
    }, 10000)

    useEffect(() => {
        updateStreamList()
    }, [])

    useEffect(() => {
        updateTitle()
    }, [])

    return (
        <>
            <Menu
                items={streamList}
                selectedItem={selectedStream}
                selectCallback={updateSelect}
            />
            <MediaContainer selectedStream={selectedStream} api={api} />
        </>
    )
}

const rootElement = document.getElementById("app");
setTitleFromLocalstorage()
if (rootElement) {
    const root = createRoot(rootElement)
    const api = new MinistreamApiClient()
    root.render(<App api={api} />)
}