'use client';

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

export function Dialog({
  open,
  onClose,
  title,
  children,
  wide,
}: {
  open: boolean;
  onClose: () => void;
  title?: string;
  children: React.ReactNode;
  wide?: boolean;
}) {
  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]);

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-40 flex items-center justify-center p-4">
      <button
        type="button"
        aria-label="Close dialog"
        className="absolute inset-0 bg-overlay border-0 cursor-default"
        onClick={onClose}
      />
      <div
        role="dialog"
        aria-modal="true"
        className={cn(
          'relative z-10 bg-surface text-text border border-line rounded-xl p-6 shadow-card max-h-[92vh] overflow-auto',
          wide ? 'w-[min(680px,94vw)]' : 'w-[min(520px,94vw)]',
        )}
      >
        {title ? <h2 className="text-lg font-semibold m-0 mb-3">{title}</h2> : null}
        {children}
      </div>
    </div>
  );
}
