import { useState, useCallback } from 'react';
import { Outlet } from '@tanstack/react-router';
import { AudioEngine } from './AudioEngine';
import { NavRail } from './NavRail';
import { TopBar } from './TopBar';
import { PlaybackBar } from './PlaybackBar';
import { NowPlayingPanel } from './NowPlayingPanel';
import { LyricsOverlay } from './LyricsOverlay';
import { Toaster } from './Toaster';
import { CommandPalette } from './CommandPalette';
import { KeyboardListener, useKeyboard } from '../hooks/useKeyboard';
import { Inspector, type InspectorMode } from './Inspector';

export default function AppShell() {
  const [queueOpen, setQueueOpen] = useState(false);
  const [lyricsOpen, setLyricsOpen] = useState(false);
  const [paletteOpen, setPaletteOpen] = useState(false);
  const [inspector, setInspector] = useState<{ mode: InspectorMode; id: string } | null>(null);

  const togglePalette = useCallback(() => setPaletteOpen((p) => !p), []);
  const closeInspector = useCallback(() => setInspector(null), []);

  // Ctrl+K — command palette (uses `code` so it works on any keyboard layout)
  useKeyboard({
    code: 'KeyK',
    ctrl: true,
    handler: () => setPaletteOpen((p) => !p),
  });

  // Alt+← / Alt+→ — back / forward (uses `code` for layout independence)
  useKeyboard({
    code: 'ArrowLeft',
    alt: true,
    handler: () => window.history.back(),
  });
  useKeyboard({
    code: 'ArrowRight',
    alt: true,
    handler: () => window.history.forward(),
  });

  // Esc — closes inspector, palette, etc.
  useKeyboard({
    code: 'Escape',
    handler: () => {
      if (inspector) closeInspector();
    },
  });

  return (
    <div className="flex flex-col h-screen bg-bg0 text-text overflow-hidden">
      <KeyboardListener />
      <TopBar onToggleCommandPalette={togglePalette} />
      <div className="relative flex flex-1 overflow-hidden">
        <NavRail />
        <main className="flex-1 overflow-y-auto p-4 pb-8">
          <Outlet />
        </main>
        {inspector && <Inspector mode={inspector.mode} id={inspector.id} onClose={closeInspector} />}
        {queueOpen && <NowPlayingPanel onClose={() => setQueueOpen(false)} />}
        {lyricsOpen && <LyricsOverlay onClose={() => setLyricsOpen(false)} />}
      </div>
      <PlaybackBar
        queueOpen={queueOpen}
        lyricsOpen={lyricsOpen}
        onToggleQueue={() => setQueueOpen((o) => !o)}
        onToggleLyrics={() => setLyricsOpen((o) => !o)}
      />
      <AudioEngine />
      <Toaster />
      <CommandPalette open={paletteOpen} onClose={() => setPaletteOpen(false)} />
    </div>
  );
}
