'use client'

import * as React from 'react'
import { X } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'

interface ArticleContent {
  title: string
  eyebrow?: string
  content: React.ReactNode
}

interface ContentModalProps {
  open: boolean
  onClose: () => void
  article: ArticleContent | null
}

export function ContentModal({ open, onClose, article }: ContentModalProps) {
  React.useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden'
    } else {
      document.body.style.overflow = ''
    }
    return () => { document.body.style.overflow = '' }
  }, [open])

  React.useEffect(() => {
    const onEsc = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    if (open) window.addEventListener('keydown', onEsc)
    return () => window.removeEventListener('keydown', onEsc)
  }, [open, onClose])

  if (!article) return null

  return (
    <AnimatePresence>
      {open && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[200] bg-black/60 backdrop-blur-sm"
            onClick={onClose}
          />
          <motion.div
            initial={{ opacity: 0, y: 40 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 40 }}
            transition={{ type: 'spring', damping: 28, stiffness: 300 }}
            className="fixed inset-x-4 top-[10vh] bottom-[10vh] z-[210] mx-auto flex max-w-3xl flex-col overflow-hidden rounded-3xl border border-border bg-card shadow-2xl"
          >
            {/* Header */}
            <div className="flex items-start justify-between border-b px-6 py-5">
              <div>
                {article.eyebrow && (
                  <span className="text-[11px] font-bold uppercase tracking-[0.18em] text-[#0d5d50] dark:text-[#8fb9ad]">
                    {article.eyebrow}
                  </span>
                )}
                <h2 className="mt-2 text-2xl font-semibold tracking-[-0.03em]">
                  {article.title}
                </h2>
              </div>
              <button
                onClick={onClose}
                className="grid h-10 w-10 flex-shrink-0 place-items-center rounded-full border border-border transition hover:bg-muted"
                aria-label="Close"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            {/* Body */}
            <div className="flex-1 overflow-y-auto px-6 py-6">
              {article.content}
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  )
}
