/**
 * Static catalog of Abracadabra page types and their metadata schemas.
 *
 * Kept in sync with `cou-sh/app/utils/docTypes.ts` and the plugin definitions
 * under `cou-sh/plugin-<name>/src/index.ts`. No UI dependencies — it
 * is a plain data description so agents (via MCP) and CLI tooling can discover
 * what fields apply to which renderer without having to read the dashboard
 * source code.
 *
 * Schema semantics (from page-type-guidelines.md):
 *
 * - `metaSchema` — fields that apply to DESCENDANTS (children, grandchildren,
 *   and beyond) of a page of this type. E.g. the calendar's schema describes
 *   what an *event* meta looks like, not the calendar itself.
 * - `defaultMetaFields` — fields inserted into the page doc's own metadata
 *   when first rendered; these are view config knobs (e.g. `calendarView`).
 */

export type MetaFieldType
  = | 'datetimerange'
    | 'daterange'
    | 'timerange'
    | 'datetime'
    | 'date'
    | 'time'
    | 'slider'
    | 'number'
    | 'toggle'
    | 'select'
    | 'multiselect'
    | 'colorPreset'
    | 'colorPicker'
    | 'location'
    | 'icon'
    | 'textarea'
    | 'url'
    | 'rating'
    | 'tags'
    | 'members'

export interface PageTypeMetaField {
  type: MetaFieldType
  label?: string
  /** single-value fields */
  key?: string
  /** location */
  latKey?: string
  lngKey?: string
  /** ranges */
  startKey?: string
  endKey?: string
  allDayKey?: string
  /** color preset */
  presets?: string[]
  /** icon / select / tags */
  options?: string[]
  /** slider / number */
  min?: number
  max?: number
  step?: number
  unit?: string
  /** toggle default */
  default?: boolean
}

export interface PageTypeInfo {
  key: string
  label: string
  icon: string
  description?: string
  /** true = core type (always available); false = requires plugin */
  core: boolean
  plugin?: string
  supportsChildren: boolean
  childLabel?: string
  grandchildLabel?: string
  /** -1 = unlimited depth */
  defaultDepth?: number
  /** Fields that apply to this doc's descendants (children, grandchildren, ...) */
  metaSchema?: PageTypeMetaField[]
  /** Fields written to this doc's own meta on first render (renderer config) */
  defaultMetaFields?: PageTypeMetaField[]
}

const GEO_COLOR_PRESETS = ['#3b82f6', '#f97316', '#22c55e', '#ef4444', '#a855f7']
const GEO_ICON_OPTIONS = [
  'map-pin', 'star', 'flag', 'home', 'building-2', 'coffee', 'utensils',
  'camera', 'heart', 'zap', 'triangle-alert', 'car', 'plane', 'anchor',
  'tree-pine', 'mountain', 'waves', 'shield', 'crosshair', 'circle-dot',
  'bookmark', 'gem', 'radio', 'compass',
]

export const GEO_TYPE_META_SCHEMAS: Record<string, PageTypeMetaField[]> = {
  marker: [
    { type: 'location', latKey: 'geoLat', lngKey: 'geoLng', label: 'Location' },
    { type: 'icon', key: 'icon', options: GEO_ICON_OPTIONS, label: 'Icon' },
    { type: 'colorPreset', key: 'color', presets: GEO_COLOR_PRESETS, label: 'Color' },
  ],
  line: [
    { type: 'colorPreset', key: 'color', presets: GEO_COLOR_PRESETS, label: 'Color' },
  ],
  measure: [],
}

export const PAGE_TYPES: Record<string, PageTypeInfo> = {
  doc: {
    key: 'doc',
    label: 'Document',
    icon: 'file-text',
    description: 'Rich text document with real-time collaboration',
    core: true,
    supportsChildren: true,
  },
  prose: {
    key: 'prose',
    label: 'Prose',
    icon: 'pen-tool',
    description: 'Long-form prose with serif typography and a narrow readable measure',
    core: true,
    supportsChildren: true,
    childLabel: 'Item',
    defaultDepth: -1,
  },
  kanban: {
    key: 'kanban',
    label: 'Kanban',
    icon: 'kanban',
    description: 'Drag-and-drop task board with columns and cards',
    core: true,
    supportsChildren: true,
    childLabel: 'Column',
    grandchildLabel: 'Card',
    defaultMetaFields: [
      { type: 'select', key: 'kanbanColumnWidth', options: ['narrow', 'default', 'wide'], label: 'Column Width' },
    ],
  },
  gallery: {
    key: 'gallery',
    label: 'Gallery',
    icon: 'images',
    description: 'Visual grid of items with rich content',
    core: true,
    supportsChildren: true,
    childLabel: 'Item',
    metaSchema: [
      { type: 'location', latKey: 'geoLat', lngKey: 'geoLng', label: 'Location' },
      { type: 'datetime', key: 'datetimeStart', label: 'Date' },
      { type: 'tags', key: 'tags', label: 'Tags' },
      { type: 'rating', key: 'rating', max: 5, label: 'Rating' },
      { type: 'icon', key: 'icon', label: 'Icon' },
      { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#ec4899', '#f97316', '#22c55e', '#3b82f6', '#a855f7'], label: 'Color' },
    ],
    defaultMetaFields: [
      { type: 'number', key: 'galleryColumns', min: 1, max: 6, step: 1, label: 'Columns' },
      { type: 'select', key: 'galleryAspect', options: ['square', '4:3', '3:2', '16:9', 'free'], label: 'Aspect Ratio' },
      { type: 'select', key: 'galleryCardStyle', options: ['default', 'compact', 'detailed'], label: 'Card Style' },
      { type: 'toggle', key: 'galleryShowLabels', label: 'Show Labels' },
      { type: 'select', key: 'gallerySortBy', options: ['manual', 'date', 'name', 'rating'], label: 'Sort' },
    ],
  },
  table: {
    key: 'table',
    label: 'Table',
    icon: 'table',
    description: 'Collaborative spreadsheet with custom fields',
    core: true,
    supportsChildren: true,
    childLabel: 'Column',
    grandchildLabel: 'Row',
    defaultMetaFields: [
      { type: 'select', key: 'tableMode', options: ['hierarchy', 'flat'], label: 'Mode' },
      { type: 'select', key: 'tableSortDir', options: ['asc', 'desc'], label: 'Sort Direction' },
    ],
  },
  outline: {
    key: 'outline',
    label: 'Outline',
    icon: 'list-tree',
    description: 'Hierarchical outline with keyboard navigation',
    core: true,
    supportsChildren: true,
    childLabel: 'Item',
    defaultDepth: -1,
  },
  checklist: {
    key: 'checklist',
    label: 'Checklist',
    icon: 'check-square',
    description: 'Collaborative checklist with sub-tasks, drag-and-drop, and due dates',
    core: true,
    supportsChildren: true,
    childLabel: 'Task',
    defaultDepth: -1,
    metaSchema: [
      { type: 'toggle', key: 'checked', label: 'Done' },
      { type: 'select', key: 'priority', options: ['none', 'low', 'medium', 'high'], label: 'Priority' },
      { type: 'date', key: 'dateEnd', label: 'Due date' },
    ],
    defaultMetaFields: [
      { type: 'select', key: 'checklistFilter', options: ['all', 'active', 'completed'], label: 'Filter' },
      { type: 'select', key: 'checklistSort', options: ['manual', 'priority', 'due'], label: 'Sort' },
    ],
  },
  graph: {
    key: 'graph',
    label: 'Graph',
    icon: 'git-fork',
    description: 'Force-directed knowledge graph — full document tree as nodes & edges',
    core: true,
    supportsChildren: true,
    childLabel: 'Node',
    defaultMetaFields: [
      { type: 'toggle', key: 'showRefEdges', label: 'Show Ref Edges', default: true },
    ],
  },
  timeline: {
    key: 'timeline',
    label: 'Timeline',
    icon: 'gantt-chart',
    description: 'Gantt-style project timeline with epics and tasks',
    core: true,
    supportsChildren: true,
    childLabel: 'Epic',
    grandchildLabel: 'Task',
    metaSchema: [
      { type: 'daterange', startKey: 'dateStart', endKey: 'dateEnd' },
      { type: 'slider', key: 'taskProgress', min: 0, max: 100, label: 'Progress' },
      { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#818cf8', '#f97316', '#22c55e', '#3b82f6', '#a855f7'], label: 'Color' },
    ],
  },
  calendar: {
    key: 'calendar',
    label: 'Calendar',
    icon: 'calendar',
    description: 'Event calendar with month, week, and day views',
    core: true,
    supportsChildren: true,
    childLabel: 'Event',
    metaSchema: [
      { type: 'datetimerange', startKey: 'datetimeStart', endKey: 'datetimeEnd', allDayKey: 'allDay' },
      { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#ec4899', '#f97316', '#22c55e', '#3b82f6', '#a855f7'], label: 'Color' },
      { type: 'icon', key: 'icon', label: 'Icon' },
    ],
    defaultMetaFields: [
      { type: 'select', key: 'calendarWeekStart', options: ['sun', 'mon'], label: 'Week Starts' },
      { type: 'select', key: 'calendarView', options: ['month', 'week', 'day'], label: 'Default View' },
      { type: 'toggle', key: 'calendarShowWeekNumbers', label: 'Show Week Numbers' },
    ],
  },
  map: {
    key: 'map',
    label: 'Map',
    icon: 'map',
    description: 'Collaborative world map with shared markers',
    core: true,
    supportsChildren: true,
    childLabel: 'Location',
    defaultMetaFields: [
      { type: 'toggle', key: 'mapShowLabels', label: 'Show Labels', default: true },
    ],
  },
  dashboard: {
    key: 'dashboard',
    label: 'Dashboard',
    icon: 'layout-dashboard',
    description: 'Arrange documents as draggable icons with optional widget views',
    core: true,
    supportsChildren: true,
    childLabel: 'Item',
  },
  call: {
    key: 'call',
    label: 'Call',
    icon: 'phone',
    description: 'Video call room with live audio and screen sharing',
    core: true,
    supportsChildren: false,
  },
  chart: {
    key: 'chart',
    label: 'Chart',
    icon: 'bar-chart-3',
    description: 'Charts — manual data points or aggregation over document trees',
    core: true,
    supportsChildren: true,
    childLabel: 'Data Point',
    grandchildLabel: 'Data Point',
    metaSchema: [
      { type: 'number', key: 'number', step: 0.01, label: 'Value' },
      { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#ec4899', '#f97316', '#22c55e', '#3b82f6', '#a855f7', '#14b8a6', '#eab308'], label: 'Color' },
      { type: 'tags', key: 'tags', label: 'Tags' },
    ],
    defaultMetaFields: [
      { type: 'select', key: 'chartType', options: ['bar', 'stacked bar', 'line', 'donut', 'treemap'], label: 'Chart Type' },
      { type: 'select', key: 'chartMetric', options: ['value', 'type', 'tag', 'status', 'priority', 'activity', 'completion'], label: 'Metric' },
      { type: 'select', key: 'chartColorScheme', options: ['default', 'warm', 'cool', 'mono'], label: 'Colors' },
      { type: 'number', key: 'chartLimit', min: 3, max: 30, step: 1, label: 'Max Items' },
      { type: 'toggle', key: 'chartShowLegend', label: 'Show Legend', default: true },
      { type: 'toggle', key: 'chartShowValues', label: 'Show Values' },
    ],
  },
  sheets: {
    key: 'sheets',
    label: 'Sheets',
    icon: 'grid-3x3',
    description: 'Spreadsheet — cells, formulas, and formatting in a collaborative grid',
    core: true,
    supportsChildren: true,
    childLabel: 'Column',
    grandchildLabel: 'Cell',
    defaultMetaFields: [
      { type: 'number', key: 'sheetsDefaultColWidth', min: 40, max: 500, step: 10, label: 'Column Width' },
      { type: 'number', key: 'sheetsDefaultRowHeight', min: 20, max: 100, step: 2, label: 'Row Height' },
      { type: 'toggle', key: 'sheetsShowGridlines', label: 'Gridlines' },
    ],
  },
  slides: {
    key: 'slides',
    label: 'Slides',
    icon: 'presentation',
    description: 'Presentation slides with two-axis navigation',
    core: true,
    supportsChildren: true,
    childLabel: 'Slide',
    grandchildLabel: 'Sub-slide',
    metaSchema: [
      { type: 'select', key: 'slidesTransition', options: ['none', 'fade', 'slide'], label: 'Transition' },
      { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#ec4899', '#f97316', '#22c55e', '#3b82f6', '#a855f7'], label: 'Accent' },
    ],
    defaultMetaFields: [
      { type: 'select', key: 'slidesTheme', options: ['dark', 'light'], label: 'Theme' },
    ],
  },
  overview: {
    key: 'overview',
    label: 'Overview',
    icon: 'radar',
    description: 'Space home — activity, people, stats, and health at a glance',
    core: true,
    supportsChildren: true,
    childLabel: 'Page',
  },

  // Plugin-contributed types — require the named plugin to be enabled server-side.

  spatial: {
    key: 'spatial',
    label: 'Spatial',
    icon: 'box',
    description: '3D scene with collaborative objects and real-time presence',
    core: false,
    plugin: 'spatial',
    supportsChildren: true,
    childLabel: 'Object',
    grandchildLabel: 'Part',
    defaultDepth: -1,
    metaSchema: [
      { type: 'select', key: 'spShape', options: ['box', 'sphere', 'cylinder', 'cone', 'plane', 'torus', 'glb'], label: 'Shape' },
      { type: 'colorPreset', key: 'color', presets: ['#6366f1', '#ef4444', '#22c55e', '#3b82f6', '#f97316', '#a855f7', '#ec4899', '#14b8a6'], label: 'Color' },
      { type: 'slider', key: 'spOpacity', min: 0, max: 100, label: 'Opacity' },
      { type: 'number', key: 'spX', step: 0.1, label: 'X' },
      { type: 'number', key: 'spY', step: 0.1, label: 'Y' },
      { type: 'number', key: 'spZ', step: 0.1, label: 'Z' },
      { type: 'number', key: 'spRX', min: -180, max: 180, step: 1, label: 'Rot X' },
      { type: 'number', key: 'spRY', min: -180, max: 180, step: 1, label: 'Rot Y' },
      { type: 'number', key: 'spRZ', min: -180, max: 180, step: 1, label: 'Rot Z' },
      { type: 'number', key: 'spSX', min: 0.01, max: 100, step: 0.1, label: 'Scale X' },
      { type: 'number', key: 'spSY', min: 0.01, max: 100, step: 0.1, label: 'Scale Y' },
      { type: 'number', key: 'spSZ', min: 0.01, max: 100, step: 0.1, label: 'Scale Z' },
    ],
    defaultMetaFields: [
      { type: 'toggle', key: 'spatialGridVisible', label: 'Show Grid', default: true },
    ],
  },
  media: {
    key: 'media',
    label: 'Media',
    icon: 'disc-3',
    description: 'Media player with synced listening and playlists',
    core: false,
    plugin: 'media',
    supportsChildren: true,
    childLabel: 'Track',
    defaultDepth: -1,
    metaSchema: [
      { type: 'tags', key: 'tags', label: 'Tags' },
    ],
    defaultMetaFields: [
      { type: 'select', key: 'mediaRepeat', options: ['off', 'all', 'one'], label: 'Repeat' },
      { type: 'toggle', key: 'mediaShuffle', label: 'Shuffle' },
    ],
  },
  coder: {
    key: 'coder',
    label: 'Coder',
    icon: 'code-2',
    description: 'Collaborative multi-file coding environment',
    core: false,
    plugin: 'coder',
    supportsChildren: true,
    childLabel: 'File',
    defaultDepth: -1,
    metaSchema: [
      { type: 'select', key: 'fileType', options: ['vue', 'ts', 'js', 'css', 'json', 'folder'], label: 'Type' },
      { type: 'toggle', key: 'entry', label: 'Entry Point' },
    ],
  },
}

export const TYPE_ALIASES: Record<string, string> = {
  desktop: 'dashboard',
}

export function resolvePageType(key: string | undefined): PageTypeInfo | undefined {
  if (!key) return undefined
  const resolved = TYPE_ALIASES[key] ?? key
  return PAGE_TYPES[resolved]
}
