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 { useInstallPrompt } from '../hooks/useInstallPrompt';
import { PlaybackSyncProvider } from './PlaybackSyncProvider';

export default function AppShell() {
  const [queueOpen, setQueueOpen] = useState(false);
  const [navigationOpen, setNavigationOpen] = useState(false);
  const [lyricsOpen, setLyricsOpen] = useState(false);
  const [paletteOpen, setPaletteOpen] = useState(false);

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

  useInstallPrompt();

  // 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(),
  });

  useKeyboard({
    code: 'Escape',
    handler: () => {
      if (navigationOpen) setNavigationOpen(false);
      else if (queueOpen) setQueueOpen(false);
      else if (lyricsOpen) setLyricsOpen(false);
    },
  });

  return (
    <PlaybackSyncProvider>
    <div className="flex h-screen h-[100dvh] flex-col overflow-hidden bg-bg0 text-text">
      <KeyboardListener />
      <TopBar
        onToggleCommandPalette={togglePalette}
        onToggleNavigation={() => setNavigationOpen((open) => !open)}
        navigationOpen={navigationOpen}
      />
      <div className="relative flex flex-1 overflow-hidden">
        <NavRail open={navigationOpen} onClose={() => setNavigationOpen(false)} />
        <main className="min-w-0 flex-1 overflow-y-auto p-3 pb-6 sm:p-4 sm:pb-8">
          <Outlet />
        </main>
        {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>
    </PlaybackSyncProvider>
  );
}
