'use client'

import { Modal } from '../../components/ui/Modal.js'
import { getSectionTypesForScope, type SectionScope, type SectionTypeId } from './section-types.js'
import { sectionIconFor } from './section-icons.js'

interface AddSectionModalProps {
  open: boolean
  onClose: () => void
  onAdd: (type: SectionTypeId) => void
  /** Which editor surface this gallery serves. Defaults to the page editor. */
  scope?: SectionScope
}

/**
 * Predefined section gallery. Only types that have a working renderer +
 * inspector are listed (the registry is the source of truth), so every
 * card here actually inserts a usable section.
 *
 * (Saved-section / template insertion is a separate flow — deferred until
 * the saved-section storage model is reconciled with the flat section
 * model; see the page-editor changeset.)
 */
export function AddSectionModal({ open, onClose, onAdd, scope = 'page' }: AddSectionModalProps) {
  const types = getSectionTypesForScope(scope)
  return (
    <Modal open={open} onClose={onClose} title="Add a section">
      <p className="text-muted-foreground mb-4 text-sm">
        Choose a section type. It will be added to the bottom and selected for editing.
      </p>
      <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
        {types.map((type) => {
          const Icon = sectionIconFor(type.id)
          return (
            <button
              key={type.id}
              type="button"
              onClick={() => onAdd(type.id)}
              className="border-border hover:border-primary hover:bg-accent/50 focus-visible:ring-ring flex items-start gap-3 rounded-lg border p-3 text-left transition-colors focus-visible:ring-2 focus-visible:outline-none"
            >
              <span className="bg-muted text-foreground flex h-9 w-9 shrink-0 items-center justify-center rounded-md">
                <Icon className="h-5 w-5" aria-hidden />
              </span>
              <span className="min-w-0">
                <span className="text-foreground block text-sm font-medium">{type.name}</span>
                <span className="text-muted-foreground mt-0.5 block text-xs leading-snug">
                  {type.description}
                </span>
              </span>
            </button>
          )
        })}
      </div>
    </Modal>
  )
}
