/**
 * DiffViewer React wrapper — Lane A imperative wrap over src/editors/diff-viewer.ts
 *
 * Import from the dedicated subpath to keep CodeMirror out of the main bundle:
 *   import { DiffViewer } from '@countermeasure-platform/web-components/react/editors/diff-viewer'
 *
 * DiffViewer is always read-only — it shows the diff between `original` and
 * `modified` side-by-side. There is no `onChange` callback because neither pane
 * is editable. Pass new strings to re-render the diff.
 */

import * as React from 'react'
import { cn } from '../primitives/utils'
import { DiffViewer as DiffViewerImpl } from '../../editors/diff-viewer'
import type { DiffViewerConfig } from '../../editors/types'

export interface DiffViewerProps extends Omit<DiffViewerConfig, 'container'> {
  className?: string
}

function DiffViewer({ original, modified, className, ...config }: DiffViewerProps) {
  const containerRef = React.useRef<HTMLDivElement>(null)
  const viewerRef = React.useRef<DiffViewerImpl | null>(null)

  // Construct once on mount — SSR-safe
  React.useEffect(() => {
    if (typeof document === 'undefined' || !containerRef.current) return
    viewerRef.current = new DiffViewerImpl({
      ...config,
      container: containerRef.current,
      original,
      modified,
    })
    return () => {
      viewerRef.current?.destroy()
      viewerRef.current = null
    }
  }, [])

  // Re-render whenever original or modified changes
  React.useEffect(() => {
    if (!viewerRef.current) return
    viewerRef.current.setContent(original, modified)
  }, [original, modified])

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

DiffViewer.displayName = 'DiffViewer'

export { DiffViewer }
