'use client';

import { useEffect, useRef } from 'react';

interface ModalProps {
  open: boolean;
  onClose: () => void;
  title: string;
  children: React.ReactNode;
  wide?: boolean;
}

export default function Modal({ open, onClose, title, children, wide }: ModalProps) {
  const overlayRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (e.key === 'Escape') {
        onClose();
        return;
      }
      if (e.key === 'Enter' && e.ctrlKey) {
        const root = overlayRef.current;
        const btn =
          root?.querySelector<HTMLButtonElement>('button[type="submit"]:not([disabled])') ??
          root?.querySelector<HTMLButtonElement>('.btn-primary:not([disabled])');
        btn?.click();
      }
    }
    if (open) document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      ref={overlayRef}
      className="fixed inset-0 z-50 flex items-center justify-center bg-[#0E0F12]/50 p-4"
      onClick={(e) => { if (e.target === overlayRef.current) onClose(); }}
    >
      <div className={`bg-[#FAF7F2] rounded-2xl shadow-2xl w-full max-h-[90vh] flex flex-col border border-[#EAE4D9] ${wide ? 'max-w-3xl' : 'max-w-lg'}`}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-[#EAE4D9]">
          <h2 className="text-base font-semibold text-[#0E0F12] tracking-tight">{title}</h2>
          <button
            onClick={onClose}
            className="text-[#0E0F12]/30 hover:text-[#0E0F12] transition-colors text-xl leading-none"
          >
            ×
          </button>
        </div>
        <div className="overflow-y-auto px-6 py-5 flex-1">{children}</div>
      </div>
    </div>
  );
}
