import { createRoot } from '@wordpress/element';
import domReady from '@wordpress/dom-ready';
import { RouterProvider, createRouter, createHashHistory } from '@tanstack/react-router'

import { QueryClient } from '@tanstack/react-query';
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'

/**
 * Styles
 */

import './style.css'

/**
 * Query Client
 */

const queryClient = new QueryClient()

const persister = createAsyncStoragePersister({
    storage: window.localStorage,
})

/**
 * Router
 */

import { routeTree } from '@/routeTree.gen'
import usePluginSelectedStore from './stores/pluginSelectedStore';

const router = createRouter({
    routeTree,
    history: createHashHistory(),
})

router.subscribe('onBeforeLoad', (env) => {
    const currentPlugin = usePluginSelectedStore.getState().plugin

    if(currentPlugin) {
        usePluginSelectedStore.getState().setPlugin(null)
    }
})
declare module '@tanstack/react-router' {
    interface Register {
        router: typeof router
    }
}

const App = () => {
    return (
        <PersistQueryClientProvider client={queryClient} persistOptions={{ persister }}>
            <RouterProvider router={router} />
        </PersistQueryClientProvider>
    )
}

domReady(() => {
    const container = document.getElementById('ploogins');

    if (container) {
        const root = createRoot(container);
        root.render(
            <App />
        );
    }
});