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
}

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

    const updateSelect = (item: string) => {
        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 = () => {
        const titleKey = "ministream.title"
        var title = localStorage.getItem(titleKey)
        const setTitle = (title: string) => {
            const el = document.querySelector('title')
            if (el) {
                el.textContent = title
            }
        }
        if (title) {
            setTitle(title)
        }
        api.siteInfo().then((info) => {
            if (info.siteName != 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");
if (rootElement) {
    const root = createRoot(rootElement);
    const api = new MinistreamApiClient()
    root.render(<App api={api} />)
}