import { useEffect, useRef, type ReactNode } from 'react'
import { useRouterState } from '@tanstack/react-router'
import { cn } from '@cfdm/ui/lib/utils'
import { DEBUG_BUILD_STAMP, debugAgentLog } from '@/lib/debug-agent-log'

interface PageShellProps {
  children: ReactNode
  className?: string
}

export function PageShell({ children, className }: PageShellProps) {
  const ref = useRef<HTMLDivElement>(null)
  const pathname = useRouterState({ select: (s) => s.location.pathname })

  useEffect(() => {
    const el = ref.current
    if (!el) return
    const main = el.closest('main')
    const mainWidth = main?.clientWidth ?? 0
    const shellWidth = el.clientWidth
    const child = el.firstElementChild as HTMLElement | null
    const childWidth = child?.clientWidth ?? 0
    const childMaxWidth = child ? getComputedStyle(child).maxWidth : 'none'
    debugAgentLog(
      'page-shell.tsx:mount',
      'page layout widths',
      {
        buildStamp: DEBUG_BUILD_STAMP,
        pathname,
        mainWidth,
        shellWidth,
        childWidth,
        childMaxWidth,
        shellClass: el.className,
        childClass: child?.className ?? null,
      },
      'A',
    )
  }, [pathname])

  return (
    <div ref={ref} className={cn('flex flex-col gap-4 md:gap-6', className)}>
      {children}
    </div>
  )
}
