import { h, render } from 'preact'
import { useState } from 'preact/hooks'
import { BrowserRouter, Route, Switch } from 'react-router-dom'

import Main from './app'
import SeriesPage from './src/pages/SeriesPage'
import { useEventApi, useEventCalendar } from './src/hooks/data'
import { useTimeout } from './src/hooks/timerHooks'
import LoaderLayout from './src/pages/LoaderLayout'
import FourOhFour from './src/pages/404'
import Series from './src/pages/Series'

const App = () => {
  const { data: calData, calLoading } = useEventCalendar()
  const { data: seriesDataArray, loading: eventsLoading } = useEventApi()
  const [minLoadTimePassed, setMinTimeUp] = useState(false)

  useTimeout(() => {
    setMinTimeUp(true)
  }, 1500)


  const seriesData = Object.values(seriesDataArray)

  return calLoading || eventsLoading || !minLoadTimePassed ? (
    <LoaderLayout />
  ) : (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Main} />
        <Route exact path="/series" component={Series} />
        {seriesData.length ? seriesData.map(series => (
          <Route exact path={`/series/${series.slug}`}>
            <SeriesPage data={series} />
          </Route>)) : null}
        <Route path="*">
          <FourOhFour />
        </Route>
      </Switch>
    </BrowserRouter>
  )
}


const appEl = document.getElementById('app')

render(<App />, appEl)
