/**
 * Layout for a single recollection: shared menubar (with optional custom content from active page) and outlet.
 */

import React, { useEffect } from 'react'
import { Link, Outlet, useParams } from 'react-router-dom'
import { usePlatform } from '@/app/kosmos/KosmosContext'
import { RecollectionMenubarProvider } from './RecollectionMenubarContext'
import { RecollectionMenubar } from './RecollectionMenubar'

export function RecollectionLayout() {
  const { recollectionId } = useParams<{ recollectionId: string }>()
  const { recollections, recordRecollectionAccess } = usePlatform()

  useEffect(() => {
    if (recollectionId) recordRecollectionAccess(recollectionId)
  }, [recollectionId, recordRecollectionAccess])

  const recollection = recollectionId ? recollections.find((p) => p.id === recollectionId) : null

  if (!recollectionId) return null
  if (!recollection) {
    return (
      <div className="flex flex-1 flex-col items-center justify-center gap-4 p-8">
        <p className="text-sm text-muted-foreground">Recollection not found.</p>
        <Link to="/recollections" className="text-sm text-primary hover:underline">
          Back to recollections
        </Link>
      </div>
    )
  }

  return (
    <RecollectionMenubarProvider>
      <div className="flex min-h-0 flex-1 flex-col">
        <RecollectionMenubar />
        <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
          <Outlet />
        </div>
      </div>
    </RecollectionMenubarProvider>
  )
}
