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))
  }, [])

  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 — arrow when open, mini logo when collapsed */}
      <button
        onClick={toggleSidebar}
        title={`${sidebarOpen ? 'Collapse' : 'Expand'} sidebar  [B]`}
        className={`absolute top-0 z-30 flex flex-col items-center justify-center
          border-r border-b border-surface-border bg-surface-raised
          hover:border-gold/40 transition-all duration-300
          ${sidebarOpen
            ? 'w-6 h-10 top-4 rounded-r-lg border-l-0 hover:bg-surface-elevated'
            : 'w-14 h-14 top-0 rounded-br-xl border-l-0 hover:bg-surface-elevated/80'
          }`}
        style={{ left: sidebarOpen ? 'calc(var(--sidebar-w, 18rem))' : 0 }}
      >
        {sidebarOpen ? (
          <span className="text-text-muted hover:text-gold text-xs leading-none">◀</span>
        ) : (
          <div className="flex flex-col items-center gap-0.5">
            <img
              src="/logo.png"
              alt="FabDash"
              className="w-8 h-8 object-contain rounded"
              onError={e => { e.target.style.display='none'; e.target.nextSibling.style.display='block' }}
            />
            {/* Fallback if logo not yet placed */}
            <span className="text-gold text-[10px] font-black tracking-widest hidden">FD</span>
            <span className="text-text-muted/50 text-[8px] mt-0.5">▶</span>
          </div>
        )}
      </button>

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

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