import { EditorView, basicSetup } from 'codemirror'
import { render } from 'hono/jsx/dom'

import { shrimpTheme } from './theme'
import { shrimpDiagnostics } from './diagnostics'
import { persistencePlugin, getContent } from './persistence'
import { shrimpHighlighter } from './highlighter'

export const Editor = () => {
  return (
    <div
      ref={(el: Element) => {
        if (!el?.querySelector('.cm-editor')) createEditorView(el)
      }}
    />
  )
}

const createEditorView = (el: Element) => {
  new EditorView({
    parent: el,
    doc: getContent() || '# type some code\necho hello',
    extensions: [basicSetup, shrimpTheme, shrimpDiagnostics, persistencePlugin, shrimpHighlighter],
  })
}

// Mount when running in browser
if (typeof document !== 'undefined') {
  render(<Editor />, document.getElementById('root')!)
}
