import './style.css';
import { FALLBACK_STARGAZERS_COUNT, getRepoStargazersCount } from './github-utils.js';
import { Header } from './components/Header.jsx';
import { Home } from './pages/Home/index.jsx';
import { LocationProvider, Router, Route, hydrate, prerender as ssr, useLocation } from 'preact-iso';
import { NotFound } from './pages/_404.jsx';
import Footer from './components/Footer.js';
import GetStarted from './pages/GetStarted/get-started.js';
import SupportUs from './pages/SupportUs/SupportUs.js';
import { createContext } from 'preact';
import { useLayoutEffect, useState } from 'preact/hooks';
import { default as i18next, changeLanguage } from 'i18next';
import { extractLocaleFromUrl, LOCALES, mapLocale } from './i18n';
import HttpApi from 'i18next-http-backend';
import { initReactI18next } from "react-i18next";
import { Suspense } from 'preact/compat';

export const LocaleContext = createContext('en');

export function App(props: {repoStargazersCount: number}) {
	return (
        <LocationProvider>
                <LocaleProvider>
                    <Suspense fallback={<div class="loading-screen">Loading...</div>}>
                        <Header repoStargazersCount={props.repoStargazersCount} />
                        <main>
                            <Router>
                                <Route path="/" component={Home} />
                                <Route path="/get-started" component={GetStarted} />
                                <Route path="/support-us" component={SupportUs} />

                                <Route path="/:locale:/" component={Home} />
                                <Route path="/:locale:/get-started" component={GetStarted} />
                                <Route path="/:locale:/support-us" component={SupportUs} />

                                <Route default component={NotFound} />
                            </Router>
                        </main>
                        <Footer />
                    </Suspense>
                </LocaleProvider>
            </LocationProvider>
	);
}

export function LocaleProvider({ children }) {
  const { path } = useLocation();
  const localeId = mapLocale(extractLocaleFromUrl(path) || navigator.language);
  const [ loaded, setLoaded ] = useState(false);

  useLayoutEffect(() => {
      i18next
        .use(HttpApi)
        .use(initReactI18next);
      i18next.init({
        lng: localeId,
        fallbackLng: "en",
        backend: {
            loadPath: "/translations/{{lng}}/{{ns}}.json",
        },
        returnEmptyString: false
    }).then(() => setLoaded(true))
}, []);

  useLayoutEffect(() => {
    if (!loaded) return;
    changeLanguage(localeId);
    const correspondingLocale = LOCALES.find(l => l.id === localeId);
    document.documentElement.lang = localeId;
    document.documentElement.dir = correspondingLocale?.rtl ? "rtl" : "ltr";
  }, [ loaded, localeId ]);

  return (
    <LocaleContext.Provider value={localeId}>
      {children}
    </LocaleContext.Provider>
  );
}

if (typeof window !== 'undefined') {
	hydrate(<App repoStargazersCount={FALLBACK_STARGAZERS_COUNT} />, document.getElementById('app')!);
}

export async function prerender(data) {
	// Fetch the stargazer count of the Trilium's GitHub repo on prerender to pass
	// it to the App component for SSR.
	// This ensures the GitHub API is not called on every page load in the client.
	const stargazersCount = await getRepoStargazersCount();

	return await ssr(<App repoStargazersCount={stargazersCount} {...data} />);
}

