import { useEffect } from 'react';
import { EditorPage } from '@/pages/EditorPage';
import { HomePage } from '@/pages/HomePage';
import { OnboardingPage } from '@/pages/OnboardingPage';
import { ProfilePage } from '@/pages/ProfilePage';
import { SettingsPage } from '@/pages/SettingsPage';
import { SignInPage } from '@/pages/SignInPage';
import { SystemUpdatePage } from '@/pages/SystemUpdatePage';
import { useVeect } from '@/store/veect';
import type { Screen } from '@/types';

const PAGES: Record<Screen, () => JSX.Element> = {
  signin: SignInPage,
  home: HomePage,
  onboarding: OnboardingPage,
  editor: EditorPage,
  settings: SettingsPage,
  profile: ProfilePage,
  sysupdate: SystemUpdatePage,
};

export default function App() {
  const screen = useVeect((s) => s.screen);
  const undo = useVeect((s) => s.undo);
  const redo = useVeect((s) => s.redo);
  const select = useVeect((s) => s.select);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      const typing = ['INPUT', 'TEXTAREA'].includes((e.target as HTMLElement).tagName);
      if (e.key === 'Escape') return select(null);
      if (typing) return;
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') {
        e.preventDefault();
        (e.shiftKey ? redo : undo)();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [redo, select, undo]);

  const Page = PAGES[screen];
  return (
    <div className="fixed inset-0 flex flex-col overflow-hidden bg-bg text-ink">
      <Page />
    </div>
  );
}
