import { useEffect, useRef } from 'react'
import ProjectList from './components/Projects/ProjectList'
import MainCalendar from './components/Calendar/MainCalendar'
import FocusDrawer from './components/FocusView/FocusDrawer'
import ToastContainer from './components/UI/Toast'
import { fetchProjects } from './api/projects'
import useProjectStore from './store/useProjectStore'
import useUIStore from './store/useUIStore'

export default function App() {
  const { setProjects, setLoading } = useProjectStore()
  const { sidebarOpen, toggleSidebar } = useUIStore()
  const calApiRef    = useRef(null)
  const newProjectFn = useRef(null)

  useEffect(() => {
    setLoading(true)
    fetchProjects()
      .then(data => { setProjects(data); setLoading(false) })
      .catch(() => setLoading(false))
  }, [])

  // Global keyboard shortcuts
  useEffect(() => {
    const handler = (e) => {
      if (['INPUT','TEXTAREA','SELECT'].includes(e.target.tagName)) return
      if (e.key === 'n' || e.key === 'N') { e.preventDefault(); newProjectFn.current?.() }
      if (e.key === 'b' || e.key === 'B') toggleSidebar()
      if (e.key === 'ArrowLeft'  && calApiRef.current) calApiRef.current.prev()
      if (e.key === 'ArrowRight' && calApiRef.current) calApiRef.current.next()
      if ((e.key === 't' || e.key === 'T') && calApiRef.current) calApiRef.current.today()
    }
    document.addEventListener('keydown', handler)
    return () => document.removeEventListener('keydown', handler)
  }, [toggleSidebar])

  return (
    <div className="flex h-screen bg-surface overflow-hidden">
      {/* Sidebar */}
      <aside className={`flex-shrink-0 bg-surface-raised border-r border-surface-border flex flex-col h-full transition-[width] duration-300 overflow-hidden ${sidebarOpen ? 'w-72' : 'w-0'}`}>
        <ProjectList onRegisterNewProject={fn => { newProjectFn.current = fn }} />
      </aside>

      {/* Sidebar toggle tab */}
      <button onClick={toggleSidebar} title={`${sidebarOpen ? 'Collapse' : 'Expand'} sidebar  [B]`}
        className={`absolute top-4 z-30 bg-surface-elevated border border-surface-border hover:border-gold/50 text-text-muted hover:text-gold rounded-r-lg px-1 py-3 transition-all duration-300 text-xs ${sidebarOpen ? 'left-72' : 'left-0'}`}>
        {sidebarOpen ? '◀' : '▶'}
      </button>

      {/* Main content */}
      <main className="flex-1 overflow-hidden">
        <MainCalendar onCalendarReady={api => { calApiRef.current = api }} />
      </main>

      <FocusDrawer />
      <ToastContainer />
    </div>
  )
}
