import React from 'react';
import {createRoot} from 'react-dom/client';
import Dashboard from './Dashboard';
import {Provider} from 'react-redux'
import {Provider as JotaiProvider} from "jotai";
import store from './data/store';
import {DashboardManager} from './DashboardManager';
import {atomsStore} from "./tree/atoms";
import {QueryClient, QueryClientProvider} from "@tanstack/react-query";
import './App.css';

// REGISTER ERROR OVERLAY
// @ts-ignore
if (import.meta.env.DEV) {
    window.onerror = (event, source, lineno, colno, err) => {
        // must be within function call because that's when the element is defined for sure.
        const ErrorOverlay = customElements.get('vite-error-overlay');
        // don't open outside vite environment
        if (!ErrorOverlay) {
            return;
        }
        if (!source?.match(/^https?:\/\/localhost(:\d+)?\//)) {
            return;
        }
        const overlay = new ErrorOverlay(err);
        document.body.appendChild(overlay);
    };
}

if (import.meta.env.DEV && import.meta.hot) {
    type HmrUpdate = { type?: string; path?: string };
    type HmrUpdatePayload = { type?: string; updates?: HmrUpdate[] };
    type HmrFullReloadPayload = { path?: string };
    type HmrErrorPayload = { err?: unknown };

    import.meta.hot.on('vite:beforeUpdate', (payload: HmrUpdatePayload) => {
        const changedPaths = payload.updates?.map((update) => `${update.type}:${update.path}`) ?? [];

        console.info('[dashboard-hmr]', 'beforeUpdate', {
            type: payload.type,
            changedPaths,
        });
    });

    import.meta.hot.on('vite:beforeFullReload', (payload: HmrFullReloadPayload) => {
        console.warn('[dashboard-hmr]', 'beforeFullReload', payload.path ?? '(unknown path)');
    });

    import.meta.hot.on('vite:error', (payload: HmrErrorPayload) => {
        console.error('[dashboard-hmr]', 'vite:error', payload.err);
    });
}

new DashboardManager(store);

const container = document.getElementById('coupons-plus');

if (container) {
    const root = createRoot(container);
    const queryClient = new QueryClient()

    root.render(
        <React.StrictMode>
            <Provider store={store}>
                <JotaiProvider store={atomsStore}>
                    <QueryClientProvider client={queryClient}>
                        <Dashboard/>
                    </QueryClientProvider>
                </JotaiProvider>
            </Provider>
        </React.StrictMode>
    );
}
