'use client'

/**
 * Right-side drawer built on Radix Dialog — focus-trapped, escape-closable,
 * token-only styling. Shared by the SEO editor / fix / copilot drawers.
 */
import * as Dialog from '@radix-ui/react-dialog'
import { adminPortalContainer } from '../../lib/portal-container.js'
import { X } from 'lucide-react'
import type { ReactNode } from 'react'
import { btnGhostIcon } from './primitives.js'

export function Drawer({
  open,
  onOpenChange,
  title,
  description,
  footer,
  children,
  width = 'max-w-xl',
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  title: string
  description?: string
  footer?: ReactNode
  children: ReactNode
  width?: string
}) {
  return (
    <Dialog.Root open={open} onOpenChange={onOpenChange}>
      <Dialog.Portal container={adminPortalContainer()}>
        <Dialog.Overlay className="bg-foreground/40 motion-safe:animate-in motion-safe:fade-in fixed inset-0 z-50" />
        <Dialog.Content
          // Radix auto-associates `aria-describedby` with the Dialog.Description
          // when one is present; when it isn't, explicitly clear the attribute so
          // Radix doesn't emit its "Missing Description" console warning.
          {...(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 text-lg font-medium">{title}</Dialog.Title>
              {description && (
                <Dialog.Description className="text-muted-foreground mt-0.5 text-sm">
                  {description}
                </Dialog.Description>
              )}
            </div>
            <Dialog.Close asChild>
              <button className={btnGhostIcon} aria-label="Close">
                <X size={20} aria-hidden />
              </button>
            </Dialog.Close>
          </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>
  )
}
