import { useId } from 'react';
import { X } from 'lucide-react';
import { useLanguage } from '../contexts/LanguageContext';
import useDialogA11y from '../hooks/useDialogA11y';

export default function Modal({ title, children, onClose, maxWidth = 'max-w-lg' }) {
  const { t } = useLanguage();
  const titleId = useId();
  const dialogRef = useDialogA11y(true, onClose);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div
        className="fixed inset-0 bg-black/60 backdrop-blur-xs"
        onClick={onClose}
        aria-hidden="true"
      />
      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        tabIndex={-1}
        className={`relative bg-th-card rounded-2xl border border-th-border shadow-2xl w-full ${maxWidth} max-h-[calc(100vh-2rem)] flex flex-col focus:outline-hidden`}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-th-border rounded-t-2xl shrink-0">
          <h2 id={titleId} className="text-lg font-semibold text-th-text">{title}</h2>
          <button
            type="button"
            onClick={onClose}
            aria-label={t('common.close')}
            className="p-2 rounded-lg hover:bg-th-hover text-th-text-s transition-colors"
          >
            <X size={20} />
          </button>
        </div>
        {/* Body — scrolls inside the card instead of overflowing the viewport */}
        <div className="p-6 overflow-y-auto min-h-0">
          {children}
        </div>
      </div>
    </div>
  );
}
