'use client'

/**
 * Dialog - 專業級彈窗組件
 * ========================
 * Nothing.tech 設計語言，支援 ApprovalCard 詳情顯示
 *
 * Phase 19: 使用 Z_INDEX.DIALOG (70)
 * @see lib/constants/z-index.ts
 */

import { useEffect, useCallback } from 'react'
import { cn } from '@/lib/utils'
import { X } from 'lucide-react'
import { Z_INDEX } from '@/lib/constants/z-index'

interface DialogProps {
  open: boolean
  onClose: () => void
  children: React.ReactNode
  title?: string
  className?: string
}

export function Dialog({ open, onClose, children, title, className }: DialogProps) {
  // ESC 關閉
  const handleKeyDown = useCallback((e: KeyboardEvent) => {
    if (e.key === 'Escape') onClose()
  }, [onClose])

  useEffect(() => {
    if (open) {
      document.addEventListener('keydown', handleKeyDown)
      document.body.style.overflow = 'hidden'
    }
    return () => {
      document.removeEventListener('keydown', handleKeyDown)
      document.body.style.overflow = ''
    }
  }, [open, handleKeyDown])

  if (!open) return null

  return (
    <div
      className="fixed inset-0 flex items-center justify-center"
      style={{ zIndex: Z_INDEX.DIALOG }}
    >
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Dialog Panel */}
      <div
        className={cn(
          'relative z-10 w-full max-w-lg max-h-[85vh] overflow-y-auto',
          'bg-white rounded-2xl shadow-2xl',
          'animate-in fade-in zoom-in-95 duration-200',
          className
        )}
      >
        {/* Header */}
        {title && (
          <div className="sticky top-0 z-10 flex items-center justify-between px-6 py-4 bg-white border-b border-nothing-gray-100">
            <h2 className="font-heading text-lg font-bold text-nothing-gray-900">
              {title}
            </h2>
            <button
              onClick={onClose}
              className="p-2 rounded-lg hover:bg-nothing-gray-100 transition-colors"
            >
              <X className="w-5 h-5 text-nothing-gray-500" />
            </button>
          </div>
        )}

        {/* Content */}
        <div className={cn(!title && 'pt-6')}>
          {children}
        </div>
      </div>
    </div>
  )
}
