import { useEffect, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { X } from '../../lib/icons'

interface Props {
  open: boolean
  onClose: () => void
  title: string
  body: string
  source?: string | null
}

const FONT_SIZES: Array<{ label: string; class: string }> = [
  { label: 'Aa', class: 'text-[15px] leading-[1.7]' },
  { label: 'Aa', class: 'text-[17px] leading-[1.7]' },
  { label: 'Aa', class: 'text-[19px] leading-[1.75]' },
  { label: 'Aa', class: 'text-[22px] leading-[1.8]' },
]

/**
 * Typography-tuned reader overlay for long Wikipedia / Cinemeta
 * synopses. Keyboard: Esc to close, +/- to bump font size.
 *
 * The overlay sits above everything else and traps focus implicitly by
 * being modal; we don't render an explicit focus trap because the
 * user can dismiss with Esc or click outside.
 */
export default function ReadingMode({ open, onClose, title, body, source }: Props) {
  const [fontIdx, setFontIdx] = useState(1)

  useEffect(() => {
    if (!open) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
      else if (e.key === '+' || e.key === '=') setFontIdx(i => Math.min(FONT_SIZES.length - 1, i + 1))
      else if (e.key === '-' || e.key === '_') setFontIdx(i => Math.max(0, i - 1))
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [open, onClose])

  // Split on blank lines into paragraphs so Wikipedia-style copy reads
  // properly, and on single newlines as soft breaks within a paragraph.
  const paragraphs = body
    .split(/\n{2,}/)
    .map(p => p.trim())
    .filter(p => p.length > 0)

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.2 }}
          className="fixed inset-0 z-[80] bg-void/95 backdrop-blur-sm overflow-y-auto"
          onClick={onClose}
        >
          <motion.article
            initial={{ y: 24, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={{ y: 24, opacity: 0 }}
            transition={{ duration: 0.32, ease: [0.16, 1, 0.3, 1] }}
            onClick={e => e.stopPropagation()}
            className="relative max-w-[68ch] mx-auto py-12 px-6 md:px-8"
          >
            <header className="sticky top-4 z-10 flex items-center justify-end gap-2 mb-4 -mr-2">
              <div className="inline-flex items-center bg-elevated/70 ring-1 ring-border rounded-md p-0.5 backdrop-blur">
                {FONT_SIZES.map((f, i) => (
                  <button
                    key={i}
                    onClick={() => setFontIdx(i)}
                    aria-label={`Font size ${i + 1}`}
                    className={`h-7 px-2 rounded text-text-3 hover:text-text-1 transition ${
                      fontIdx === i ? 'bg-accent/15 text-accent' : ''
                    }`}
                    style={{ fontSize: 10 + i * 2 }}
                  >
                    {f.label}
                  </button>
                ))}
              </div>
              <button
                onClick={onClose}
                aria-label="Close reader"
                className="w-8 h-8 grid place-items-center rounded-full bg-elevated/70 ring-1 ring-border text-text-3 hover:text-text-1 backdrop-blur transition focus-ring"
              >
                <X size={14} stroke={2} />
              </button>
            </header>

            <h1 className="font-display text-3xl md:text-4xl font-bold text-text-1 tracking-tight mb-6 leading-tight [text-wrap:balance]">
              {title}
            </h1>

            <div
              className={`space-y-5 text-text-1 ${FONT_SIZES[fontIdx].class} font-light tracking-[-0.005em] [text-wrap:pretty]`}
              style={{ fontFamily: 'Geist, system-ui, sans-serif' }}
            >
              {paragraphs.map((p, i) => (
                <p key={i}>{p}</p>
              ))}
            </div>

            {source && (
              <p className="mt-8 text-[11.5px] text-text-4 tracking-tight">
                Source: {source}
              </p>
            )}
          </motion.article>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
