// Imperative CodeMirror 5 editor host for editable code surfaces in Mission
// Control (currently Settings -> Workflow Studio diagram source).
//
// Keeps all foreign DOM and CodeMirror state isolated outside the pure Rabbita
// `Model`, matching the OpenSeek `ViewerHost` boundary pattern: Rabbita renders
// a stable empty host container, and `sync_studio_editor_cmd` attaches, updates,
// or releases the CodeMirror instance after each render.

///|
const StudioEditorHostId : String = "mc-studio-editor-host"

///|
/// Module-level imperative host state for the Workflow Studio CodeMirror
/// instance. Never stored in `Model`.
priv struct StudioEditorHost {
  mut modes_registered : Bool
  mut container : @cm_js.Node?
  mut editor : @cm_core.Editor?
  mut mode : String
  mut read_only : Bool
  mut syncing : Bool
}

///|
let studio_editor_host : StudioEditorHost = {
  modes_registered: false,
  container: None,
  editor: None,
  mode: "",
  read_only: false,
  syncing: false,
}

///|
/// Registers native MoonBit CodeMirror modes (`yaml`, `xml`, and custom
/// `mermaid`) once per browser realm.
fn ensure_cm_modes_registered() -> Unit {
  if studio_editor_host.modes_registered {
    return
  }
  studio_editor_host.modes_registered = true
  @cm_yaml.register()
  @cm_xml.register()
  register_mermaid_cm_mode()
}

///|
/// Registers the `mermaid` mode for CodeMirror using our shared
/// `tokenize_mermaid_line` scanner.
fn register_mermaid_cm_mode() -> Unit {
  @cm_mode.define_mode("mermaid", (_cfg, _spec) => {
    @cm_mode.Mode::stateless("mermaid", stream => {
      let line = stream.string
      let pos = stream.pos
      for span in tokenize_mermaid_line(line) {
        if span.end > pos {
          let target = if span.start > pos { span.start } else { span.end }
          let style = if span.start > pos { None } else { span.style }
          let steps = target - pos
          let mut n = 0
          while n < steps && !stream.eol() {
            ignore(stream.next())
            n += 1
          }
          return style
        }
      }
      stream.skip_to_end()
      None
    })
  })
}

///|
/// Releases any mounted Studio CodeMirror instance.
fn detach_studio_editor() -> Unit {
  studio_editor_host.container = None
  studio_editor_host.editor = None
  studio_editor_host.mode = ""
  studio_editor_host.read_only = false
  studio_editor_host.syncing = false
}

///|
/// Mounts or synchronizes the Workflow Studio CodeMirror instance against the
/// current `Model`. Safe to call in headless tests (no-ops when DOM is absent).
fn sync_studio_editor(model : Model, dispatch : (Msg) -> Unit) -> Unit {
  if !@cm_js.has_dom() {
    return
  }
  guard model.settings is Open(Studio) else {
    detach_studio_editor()
    return
  }
  guard @cm_js.document().get_element_by_id(StudioEditorHostId) is Some(host) else {
    detach_studio_editor()
    return
  }
  let has_project = model.open_project() is Some(_)
  let ws = model.active_mockup()
  let desired_source = ws.studio_source()
  let desired_mode = CodeLanguage::of_studio_format(ws.studio_format).cm_mode()
  let desired_read_only = !has_project
  ensure_cm_modes_registered()
  let already_mounted = match
    (studio_editor_host.container, studio_editor_host.editor) {
    (Some(prev), Some(_)) => prev == host
    _ => false
  }
  if !already_mounted {
    host.set_text_content("")
    let cm = @cm_core.Editor::create(host, config={
      "value": Json::string(desired_source),
      "mode": Json::string(desired_mode),
      "theme": Json::string("mc-theme"),
      "lineNumbers": Json::boolean(true),
      "lineWrapping": Json::boolean(true),
      "tabSize": Json::number(2.0),
      "indentUnit": Json::number(2.0),
      "readOnly": Json::boolean(desired_read_only),
      "inputStyle": Json::string("textarea"),
    })
    // Allow Escape to bubble to Mission Control's global Settings dismiss
    // shortcut instead of being swallowed by CodeMirror's singleSelection key.
    cm.set_extra_keys(Some(@cm_core.KeyMap::new({ "Esc": Disabled })))
    let input = cm.get_input_field()
    input.set_attribute("aria-label", "Workflow Studio diagram source")
    input.set_attribute("spellcheck", "false")
    ignore(
      cm.on("change", _ => {
        if !studio_editor_host.syncing {
          dispatch(StudioSourceEdited(cm.get_value()))
        }
      }),
    )
    studio_editor_host.container = Some(host)
    studio_editor_host.editor = Some(cm)
    studio_editor_host.mode = desired_mode
    studio_editor_host.read_only = desired_read_only
    ignore(@cm_js.request_animation_frame(() => cm.refresh()))
    return
  }
  guard studio_editor_host.editor is Some(cm) else { return }
  if studio_editor_host.mode != desired_mode {
    studio_editor_host.mode = desired_mode
    cm.set_option("mode", Json::string(desired_mode))
  }
  if studio_editor_host.read_only != desired_read_only {
    studio_editor_host.read_only = desired_read_only
    cm.set_option("readOnly", Json::boolean(desired_read_only))
  }
  if cm.get_value() != desired_source {
    studio_editor_host.syncing = true
    cm.set_value(desired_source)
    studio_editor_host.syncing = false
  }
}

///|
/// Post-render command that keeps the imperative Workflow Studio CodeMirror
/// editor in sync with `model`.
fn sync_studio_editor_cmd(model : Model, emit : @cmd.Emit[Msg]) -> @cmd.Cmd {
  @cmd.custom_cmd(
    scheduler => sync_studio_editor(model, msg => scheduler.add(emit(msg))),
    kind=@cmd.after_render,
  )
}

///|
/// Stable, never-diffed empty host container for the Workflow Studio
/// CodeMirror editor.
fn studio_editor_host_view(editable~ : Bool) -> @html.Html {
  @html.div(
    id=StudioEditorHostId,
    class=if editable { "mc-cm-host" } else { "mc-cm-host readonly" },
    attrs=@html.Attrs::build().data_set(
      "editable",
      if editable {
        "true"
      } else {
        "false"
      },
    ),
    @html.nothing,
  )
}