'use client';

import * as React from 'react';
import { cn } from '@/lib/cn';
import { Button } from './Button';

export function Drawer({
  open,
  onClose,
  title,
  children,
}: {
  open: boolean;
  onClose: () => void;
  title?: string;
  children: React.ReactNode;
}) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  return (
    <>
      <button
        type="button"
        aria-label="Close drawer"
        className={cn(
          'fixed inset-0 z-[29] bg-overlay border-0 transition-opacity',
          open ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none',
        )}
        onClick={onClose}
      />
      <aside
        aria-label={title || 'Details'}
        className={cn(
          'fixed top-0 right-0 h-full w-[min(560px,100vw)] z-30 bg-bg border-l border-line overflow-auto p-[26px]',
          'transition-transform duration-200',
          open ? 'translate-x-0' : 'translate-x-full',
        )}
      >
        <div className="flex items-start gap-3 mb-4">
          {title ? <h2 className="text-lg font-semibold m-0 flex-1">{title}</h2> : <div className="flex-1" />}
          <Button variant="ghost" size="sm" onClick={onClose} aria-label="Close">
            ✕
          </Button>
        </div>
        {children}
      </aside>
    </>
  );
}
