import { createRootRouteWithContext, Outlet } from '@tanstack/react-router'
import type { QueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import { Sidebar, MobileSidebar } from '@/components/layout/Sidebar'
import { TopBar } from '@/components/layout/TopBar'
import { UpdateBanner } from '@/components/version/UpdateBanner'
import { AppErrorBoundary } from '@/components/layout/AppErrorBoundary'

/**
 * Root layout (Stage 3.1 + 3.x mobile responsive):
 *
 *  ≥1024px (lg+):
 *   ┌─ Sidebar 220px ──┬─ main column (flex-1) ────┐
 *   │ logo             │ TopBar (sticky)           │
 *   │ nav rail         │ Outlet (route content)    │
 *   │ user profile     │                           │
 *   └──────────────────┴───────────────────────────┘
 *
 *  <1024px:
 *   ┌─ main column (flex-1) ────────────────────────┐
 *   │ TopBar [☰] (hamburger toggles MobileSidebar)  │
 *   │ Outlet                                        │
 *   └───────────────────────────────────────────────┘
 *   MobileSidebar — overlay Sheet (slide-in left, 260px).
 */
export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
  component: RootLayout,
  // Catch unhandled errors inside any route — show friendly UI instead of
  // TanStack default "Something went wrong! Hide Error" + raw stack trace.
  errorComponent: AppErrorBoundary,
})

function RootLayout() {
  const [mobileNavOpen, setMobileNavOpen] = useState(false)
  return (
    <div className="h-screen flex flex-col bg-bg text-ink overflow-hidden">
      <UpdateBanner />
      <div className="flex-1 flex min-h-0">
        <Sidebar />
        <MobileSidebar open={mobileNavOpen} onClose={() => setMobileNavOpen(false)} />
        <div className="flex-1 flex flex-col min-w-0">
          <TopBar onMenuClick={() => setMobileNavOpen(true)} />
          <main className="flex-1 overflow-y-auto overflow-x-clip px-4 sm:px-6 py-4 sm:py-6">
            <div className="max-w-7xl mx-auto w-full min-w-0">
              <Outlet />
            </div>
          </main>
        </div>
      </div>
    </div>
  )
}
