/**
 * Platform: main layout with sidebar and header. Renders child routes (projects list or canvas) via Outlet.
 */

import React, { useEffect, useState } from 'react'
import { Outlet, useParams } from 'react-router-dom'
import { SidebarProvider } from '@/components/ui/sidebar'
import { PlatformProvider, usePlatform } from './platformContext'
import { AppSidebar } from './AppSidebar'

function PlatformLayoutInner() {
  const { projectId } = useParams<{ projectId: string }>()
  const { recordProjectAccess } = usePlatform()
  const [sidebarOpen, setSidebarOpen] = useState(true)

  useEffect(() => {
    if (projectId) setSidebarOpen(false)
    else setSidebarOpen(true)
  }, [projectId])

  useEffect(() => {
    if (projectId) recordProjectAccess(projectId)
  }, [projectId, recordProjectAccess])

  return (
    <SidebarProvider open={sidebarOpen} onOpenChange={setSidebarOpen}>
      <AppSidebar />
      <div className="relative flex min-h-0 w-full flex-1 flex-col bg-background">
        <div className="flex min-h-0 flex-1 flex-col">
          <Outlet />
        </div>
      </div>
    </SidebarProvider>
  )
}

export function PlatformPage() {
  return (
    <PlatformProvider>
      <PlatformLayoutInner />
    </PlatformProvider>
  )
}
