'use client'

/**
 * Right-side drawer built on Radix Dialog — focus-trapped, escape-closable,
 * token-only styling. Shared by the Forms schema / entry-detail drawers.
 */
import * as Dialog from '@radix-ui/react-dialog'
import { X } from 'lucide-react'
import type { ReactNode } from 'react'
import { btnGhostIcon } from './primitives.js'

export function Drawer({
  open,
  onOpenChange,
  title,
  description,
  headerExtra,
  footer,
  children,
  width = 'max-w-xl',
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  title: ReactNode
  description?: ReactNode
  /** Optional content rendered between the header text and the close button. */
  headerExtra?: ReactNode
  footer?: ReactNode
  children: ReactNode
  width?: string
}) {
  return (
    <Dialog.Root open={open} onOpenChange={onOpenChange}>
      <Dialog.Portal>
        <Dialog.Overlay className="bg-foreground/40 motion-safe:animate-in motion-safe:fade-in fixed inset-0 z-50" />
        <Dialog.Content
          {...(description ? {} : { 'aria-describedby': undefined })}
          className={`bg-card text-foreground fixed inset-y-0 right-0 z-50 flex w-full ${width} motion-safe:animate-in motion-safe:slide-in-from-right flex-col shadow-xl outline-none`}
        >
          <header className="border-border flex items-start justify-between gap-3 border-b px-5 py-4">
            <div className="min-w-0">
              <Dialog.Title className="text-foreground truncate text-lg font-medium">
                {title}
              </Dialog.Title>
              {description && (
                <Dialog.Description className="text-muted-foreground mt-0.5 truncate text-sm">
                  {description}
                </Dialog.Description>
              )}
            </div>
            <div className="flex shrink-0 items-center gap-1">
              {headerExtra}
              <Dialog.Close asChild>
                <button className={btnGhostIcon} aria-label="Close" data-shortcut="close">
                  <X size={20} aria-hidden />
                </button>
              </Dialog.Close>
            </div>
          </header>
          <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">{children}</div>
          {footer && (
            <footer className="border-border bg-card flex items-center justify-end gap-2 border-t px-5 py-4">
              {footer}
            </footer>
          )}
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  )
}
