import { useEffect, useState } from 'react';

import { Paint } from '@/pages/Paint';
import { LoadScreen } from '@/components/LoadScreen';

import { gridFromAscii, gridFromAnsi } from '@/utils/grid';
import type { Grid } from '@/types/grid';

export const App: React.FC = () => {
    const [route, setRoute] = useState(window.location.hash || '#home');
    const [chosenArt, setChosenArt] = useState<null | string>(null);
    const [loadedGrid, setLoadedGrid] = useState<Grid | null>(null);

    useEffect(() => {
        const handleHashChange = () => {
            setRoute(window.location.hash || '#home');
        };
        window.addEventListener('hashchange', handleHashChange);
        return () => window.removeEventListener('hashchange', handleHashChange);
    }, []);

    const handleLoad = (grid: Grid) => {
        setLoadedGrid(grid);
        window.location.hash = '#paint';
    };

    const handleNew = () => {
        setChosenArt('');
        window.location.hash = '#paint';
    };

    const handlePaste = (ansiText: string) => {
        const importedGrid = gridFromAnsi(ansiText);
        setLoadedGrid(importedGrid);
        window.location.hash = '#paint';
    };

    const handleGoHome = () => {
        setLoadedGrid(null);
        setChosenArt(null);
        window.location.hash = '#home';
    };

    if (route === '#paint') {
        if (loadedGrid !== null) {
            return <Paint grid={loadedGrid} onGoHome={handleGoHome} />;
        }
        if (chosenArt !== null) {
            return <Paint grid={gridFromAscii(chosenArt)} onGoHome={handleGoHome} />;
        }
    }

    return <LoadScreen onLoad={handleLoad} onNew={handleNew} onPaste={handlePaste} />;
};
