// Categorized example gallery, shown as a modal. Groups examples by their
// catalog category and lets the user load one (which populates the editor and
// runs it).
import { useEffect } from 'react'
import { CATEGORY_ORDER, type Category } from './catalog.ts'
import type { Example } from './index.ts'

export interface ExamplesModalProps {
  examples: Example[]
  onPick: (id: string) => void
  onClose: () => void
}

export default function ExamplesModal({ examples, onPick, onClose }: ExamplesModalProps) {
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [onClose])

  const byCategory = new Map<Category, Example[]>()
  for (const ex of examples) {
    const list = byCategory.get(ex.category) ?? []
    list.push(ex)
    byCategory.set(ex.category, list)
  }

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <h2>Examples</h2>
          <span className="count">{examples.length} sequences from pulseq&apos;s demoSeq</span>
          <div style={{ flex: 1 }} />
          <button onClick={onClose}>Close ✕</button>
        </div>
        <div className="modal-body">
          {CATEGORY_ORDER.filter((c) => byCategory.has(c)).map((category) => (
            <section key={category}>
              <h3>{category}</h3>
              <div className="example-grid">
                {byCategory.get(category)!.map((ex) => (
                  <button key={ex.id} className="example-card" onClick={() => onPick(ex.id)}>
                    <div className="ex-top">
                      <b>{ex.name}</b>
                      <span className="ex-time">{ex.approx}</span>
                    </div>
                    <span className="ex-desc">{ex.description}</span>
                  </button>
                ))}
              </div>
            </section>
          ))}
        </div>
      </div>
    </div>
  )
}
