'use client';

import React, { useEffect } from 'react';
import { X, LucideIcon } from 'lucide-react';

interface ModalProps {
  isOpen?: boolean; // Helpful if migrating to controlled state later
  onClose: () => void;
  title: React.ReactNode;
  icon?: LucideIcon;
  iconClassName?: string;
  children: React.ReactNode;
  maxWidthClassName?: string; // Defaults to max-w-md, can override to max-w-xl etc.
}

export function Modal({
  onClose,
  title,
  icon: Icon,
  iconClassName = "text-primary",
  children,
  maxWidthClassName = "max-w-md"
}: ModalProps) {
  
  // UX Win: Close modal on Escape key press automatically
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', handleEscape);
    return () => window.removeEventListener('keydown', handleEscape);
  }, [onClose]);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm p-4 animate-in fade-in duration-200">
      {/* Click outside to close wrapper */}
      <div className="fixed inset-0" onClick={onClose} />

      <div className={`w-full ${maxWidthClassName} border border-border/40 bg-surface shadow-lg rounded-xl overflow-hidden flex flex-col z-10 animate-in zoom-in-95 duration-150 select-none`}>
        
        {/* MODAL HEADER AXIS */}
        <div className="flex h-12 items-center justify-between border-b border-border/20 px-4 shrink-0 bg-muted/5">
          <div className="flex items-center gap-1.5">
            {Icon && <Icon className={`h-3.5 w-3.5 ${iconClassName}`} />}
            <h3 className="text-xs font-bold tracking-tight text-foreground">
              {title}
            </h3>
          </div>
          <button 
            type="button"
            onClick={onClose}
            className="p-1 rounded-md text-muted-foreground/60 hover:text-foreground hover:bg-muted transition-colors cursor-pointer"
          >
            <X className="h-3.5 w-3.5" />
          </button>
        </div>

        {/* MODAL BODY CONTROLLER */}
        <div className="overflow-y-auto max-h-[calc(100vh-8rem)]">
          {children}
        </div>
      </div>
    </div>
  );
}