import { jsx as _jsx } from "react/jsx-runtime";
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useInput } from 'ink';
import { DbProvider } from '../db/dbContext.js';
import { useEffect, useRef } from 'react';
import { Spinner } from '@inkjs/ui';
import { useMappingChainById } from '../queries/chainById.js';
import { createWagmiConfig } from '../createWagmiConfig.js';
import { WagmiProvider } from 'wagmi';
import { startServer } from '../server/startServer.js';
export const queryClient = new QueryClient();
const AppInner = ({ children }) => {
    const { data: chainById, isLoading: isChainByIdLoading } = useMappingChainById();
    if (isChainByIdLoading || !chainById) {
        return _jsx(Spinner, { label: "Loading chain config from Superchain registry..." });
    }
    const wagmiConfig = createWagmiConfig(chainById);
    return (_jsx(WagmiProvider, { config: wagmiConfig, children: _jsx(DbProvider, { children: children }) }));
};
export default function App({ Component, commandProps }) {
    const serverRef = useRef();
    useInput((input, key) => {
        if (input === 'c' && key.ctrl) {
            process.exit(0);
        }
    });
    useEffect(() => {
        startServer()
            .then(s => {
            serverRef.current = s;
        })
            .catch(err => {
            console.error('Failed to start server:', err);
            process.exit(1);
        });
        return () => {
            if (serverRef.current) {
                serverRef.current.close(err => {
                    if (err) {
                        console.error('Error while closing server:', err);
                    }
                });
            }
        };
    }, []);
    return (_jsx(QueryClientProvider, { client: queryClient, children: _jsx(AppInner, { children: _jsx(Component, { ...commandProps }) }) }));
}
