import "./index.css";
import "./App.css"
import { Route, Switch } from "react-router-dom";

import React, { useEffect, useState } from "react";
import { useAppDispatch, useAppSelector } from "./hooks/redux";
import cookies from "js-cookie";

import AOS from "aos";
import "aos/dist/aos.css";
import { Main } from "./components/main/main";
import { Header } from "./components/header/header";
import { Footer } from "./components/footer/footer";
import useQuery from "./hooks/useQuery";
import textRU from "./utils/textRU"
import textEN from "./utils/textEN";
import { languageSlice } from "./store/reducers/languageSlice";
import { fetchCards } from "./store/reducers/ActionCreator";



export type TObjct = {
  calendar: boolean;
  timePicker: boolean;
  form: boolean;
  confirm: boolean;
};




export const App: React.FC = () => {
  const [language, setLanguage] = useState<any>("");
  const [text, setText] = useState(textRU);
  const savedLanguage = localStorage.getItem('savedLang')


  const dispatch = useAppDispatch();
  const { handleChangeLanguage } = languageSlice.actions;
  const { cards, currentCard, error } = useAppSelector((state) => state.cardReducer);
  const { currentLang } = useAppSelector((state) => state.languageReducer);

  const query = useQuery()

  const langQuery = query.get('lang')

  const langArray = ['en', 'ru']

  const browserLanguage = window.navigator.language

  const handleBrowserLanguage = () => {
    return langArray.includes(browserLanguage)
  }

  const handleCookiesLanguage = () => {
    const language = cookies.get("i18next")
    return language
  }

  useEffect(() => {
    if (langArray.includes(langQuery as string)) {
      dispatch(handleChangeLanguage(langQuery as string));
      return
    }
    else if (handleCookiesLanguage()) {
      const languageCookies = handleCookiesLanguage()
      console.log(languageCookies)
      dispatch(handleChangeLanguage(languageCookies as string))
      return
    }
    let isSupported = handleBrowserLanguage()
    dispatch(handleChangeLanguage(isSupported ? browserLanguage : 'en'));
  }, [])


  useEffect(() => {
    if (currentLang) {
      dispatch(fetchCards(currentLang))
    }
  }, [currentLang])




  AOS.init({
    mirror: true,
  });
  return (
    <Switch>
      <Route path="/" exact>
        <div className='App'>
          <Header></Header>
          <Main cards={cards} locale={language} text={text}></Main>
          <Footer language={language} text={text.footer}></Footer>
        </div>
      </Route>

    </Switch>
  );
};

export default App;
