import 'dayjs/locale/ru'; // load on demand

import { useEffect } from 'react';

import dayjs from 'dayjs';
import {
    Page,
    Preloader,
} from 'konsta/react';
import { observer } from 'mobx-react';

import {
    rpc,
    rpcClient,
} from '../../api/request';
import { ROUTER } from '../../router/router';
import store from '../../stores/store';

dayjs.locale("ru");


const LoadingPage = () => {


    const init = async () => {


        let mode = await rpc.mode();
        if (mode.result == "widget") {

            rpcClient.setToken(() => {

                //Берем параметр token из URL
                const searchParams = new URLSearchParams(window.location.search);
                const token = searchParams.get("token");
                return token ?? null;


            });

            const searchParams = new URLSearchParams(window.location.search);
            const channel = searchParams.get("channel");

            store.loadUser().then(() => {

                if (channel) {
                    store.setIsFixedChannel(true);


                    ROUTER().ChannelPage.move({
                        channelID: channel,
                    });

                    return;

                } else {

                    ROUTER().MainPage.move({});

                    store.setIsFixedChannel(false);
                }

            });



        } else {

            rpcClient.setUnauthorizedHandler(() => {
                localStorage.removeItem("token");
                window.location.reload();
            });

            rpcClient.setToken(() => {


                return localStorage.getItem("token") ?? null;

            });

            rpcClient.setUnauthorizedHandler(() => {
                localStorage.removeItem("token");
                window.location.reload();
            });

            store.setMode(mode.result ?? "full");


            if (localStorage.getItem("token")) {
                store.loadUser().then(() => {
                    ROUTER().MainPage.move({});
                });
            } else {
                ROUTER().LoginPage.move({});
            }



        }


    }

    useEffect(() => {


        init();

    }, []);


    return (
        <Page className="ios:bg-white ios:dark:bg-stone-900 overflow-hidden flex items-center justify-center">




            <Preloader />




        </Page>


    );
};

export default observer(LoadingPage);
