/**
 * YamlEditor React wrapper — Lane A imperative wrap over src/editors/yaml-editor.ts
 *
 * Import from the dedicated subpath to keep CodeMirror out of the main bundle:
 *   import { YamlEditor } from '@countermeasure-platform/web-components/react/editors/yaml-editor'
 *
 * API is hybrid controlled/uncontrolled:
 *   - `defaultValue` seeds the editor on mount (uncontrolled, common case)
 *   - `value` + `onChange` enable controlled mode
 */

import * as React from 'react'
import { cn } from '../primitives/utils'
import { YamlEditor as YamlEditorImpl } from '../../editors/yaml-editor'
import type { YamlEditorConfig } from '../../editors/types'

export interface YamlEditorProps extends Omit<
  YamlEditorConfig,
  'container' | 'value' | 'onChange'
> {
  /** Uncontrolled initial value. Ignored once `value` is provided. */
  defaultValue?: string
  /** Controlled value. When provided the editor reflects this string. */
  value?: string
  /** Fires on every user-initiated change. Required for controlled mode. */
  onChange?: (value: string) => void
  className?: string
}

function YamlEditor({ defaultValue, value, onChange, className, ...config }: YamlEditorProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const editorRef = React.useRef<YamlEditorImpl | null>(null)
  const isUpdatingFromProps = React.useRef(false)
  const onChangeRef = React.useRef(onChange)
  onChangeRef.current = onChange

  // Construct once on mount — SSR-safe
  React.useEffect(() => {
    if (typeof document === 'undefined' || !containerRef.current) return
    const initial = value ?? defaultValue ?? ''
    editorRef.current = new YamlEditorImpl({
      ...config,
      container: containerRef.current,
      value: initial,
      onChange: (next: string) => {
        if (isUpdatingFromProps.current) return
        onChangeRef.current?.(next)
      },
    })
    return () => {
      editorRef.current?.destroy()
      editorRef.current = null
    }
  }, [])

  // Sync controlled value into the editor without re-firing onChange
  React.useEffect(() => {
    const editor = editorRef.current
    if (!editor || value === undefined) return
    if (editor.getValue() === value) return
    isUpdatingFromProps.current = true
    editor.setValue(value)
    isUpdatingFromProps.current = false
  }, [value])

  return <div ref={containerRef} data-slot="yaml-editor" className={cn('w-full', className)} />
}

YamlEditor.displayName = 'YamlEditor'

export { YamlEditor }
