// Read-only syntax-highlighted code viewer powered by `moonbitlang/editor`
// (`viewer/html` + `syntax.LineTokenizer`) bridged to `bobzhang/codemirror-lang`
// native MoonBit tokenizers so every Mission Control language (YAML, XML,
// Turtle, JSON-LD, Markdown, TOML, Shell, Mermaid, MoonBit) renders through the
// same Monaco `mtk` token pipeline and theme variables.

///|
/// Languages supported by the Mission Control code viewer and editor.
#derive(Eq, Debug)
pub(all) enum CodeLanguage {
  Mermaid
  Xml
  Yaml
  Turtle
  JsonLd
  Markdown
  Toml
  Shell
  MoonBit
}

///|
pub extend CodeLanguage with Eq::{equal, not_equal}

///|
pub extend CodeLanguage with @debug.Debug::{to_repr}

///|
/// Human-readable badge label for a code language.
pub fn CodeLanguage::label(self : CodeLanguage) -> String {
  match self {
    Mermaid => "Mermaid"
    Xml => "BPMN XML"
    Yaml => "YAML"
    Turtle => "Turtle"
    JsonLd => "JSON-LD"
    Markdown => "Markdown"
    Toml => "TOML"
    Shell => "Shell"
    MoonBit => "MoonBit"
  }
}

///|
/// CodeMirror mode name corresponding to this language.
fn CodeLanguage::cm_mode(self : CodeLanguage) -> String {
  match self {
    Mermaid => "mermaid"
    Xml => "xml"
    Yaml => "yaml"
    Turtle => "turtle"
    JsonLd => "application/ld+json"
    Markdown => "markdown"
    Toml => "toml"
    Shell => "shell"
    MoonBit => "text/x-moonbit"
  }
}

///|
/// Maps a Workflow Studio format into its syntax language.
pub fn CodeLanguage::of_studio_format(format : StudioFormat) -> CodeLanguage {
  match format {
    Mermaid => Mermaid
    BpmnXml => Xml
    ArtifactYaml => Yaml
  }
}

///|
/// Maps a CodeMirror token style string (potentially space-separated like
/// `"string property"` or `"header header-1"`) to a `moonbitlang/editor`
/// `HighlightTag`.
pub fn highlight_tag_of_cm_style(style : String?) -> @ed_syntax.HighlightTag {
  guard style is Some(raw) else { return Plain }
  for part in raw.split(" ") {
    match part {
      "keyword" | "strong" => return Keyword
      "comment" | "meta" | "hr" => return Comment
      "string" | "string-2" | "link" => return String
      "number" => return Number
      "atom" => return Constant
      "tag" | "header" => return Tag
      "attribute" | "property" => return Attribute
      "def" | "builtin" => return Function
      "type" | "variable-3" | "qualifier" => return Type
      "variable" | "variable-2" => return Variable
      "operator" => return Operator
      "bracket" | "punctuation" => return Punctuation
      "error" => return Invalid
      _ => continue
    }
  }
  Plain
}

///|
/// Converts a single line of CodeMirror spans into `moonbitlang/editor`
/// `LineToken` entries covering the whole line without gaps.
fn line_tokens_from_cm_spans(
  line : String,
  spans : Array[@cm_tok.Span],
) -> Array[@ed_syntax.LineToken] {
  let out : Array[@ed_syntax.LineToken] = []
  let len = line.length()
  let mut cursor = 0
  for span in spans {
    let start = if span.start < cursor {
      cursor
    } else if span.start > len {
      len
    } else {
      span.start
    }
    let end = if span.end < start {
      start
    } else if span.end > len {
      len
    } else {
      span.end
    }
    if start > cursor {
      @ed_syntax.push_token(out, cursor, start, Plain)
    }
    if end > start {
      @ed_syntax.push_token(
        out,
        start,
        end,
        highlight_tag_of_cm_style(span.style),
      )
      cursor = end
    }
  }
  if cursor < len {
    @ed_syntax.push_token(out, cursor, len, Plain)
  }
  out
}

///|
/// Pure line tokenizer for Mermaid workflow diagrams (`stateDiagram-v2`,
/// `flowchart`, `graph`, comments, arrows, quoted strings, and state labels).
/// Shared between `moonbitlang/editor` read-only views and the custom
/// CodeMirror `mermaid` mode.
pub fn tokenize_mermaid_line(line : String) -> Array[@cm_tok.Span] {
  let spans : Array[@cm_tok.Span] = []
  let len = line.length()
  let mut i = 0
  while i < len {
    let ch = line.code_unit_at(i)
    // Skip whitespace
    if ch == ' ' || ch == '\t' || ch == '\r' {
      let start = i
      while i < len &&
            (
              line.code_unit_at(i) == ' ' ||
              line.code_unit_at(i) == '\t' ||
              line.code_unit_at(i) == '\r'
            ) {
        i += 1
      }
      spans.push({ start, end: i, style: None, })
      continue
    }
    // Line comments: %% ...
    if ch == '%' && i + 1 < len && line.code_unit_at(i + 1) == '%' {
      spans.push({ start: i, end: len, style: Some("comment"), })
      break
    }
    // Quoted strings: "..."
    if ch == '"' {
      let start = i
      i += 1
      while i < len {
        let c = line.code_unit_at(i)
        if c == '\\' && i + 1 < len {
          i += 2
        } else if c == '"' {
          i += 1
          break
        } else {
          i += 1
        }
      }
      spans.push({ start, end: i, style: Some("string"), })
      continue
    }
    // Start/end state token: [*]
    if ch == '[' &&
      i + 2 < len &&
      line.code_unit_at(i + 1) == '*' &&
      line.code_unit_at(i + 2) == ']' {
      spans.push({ start: i, end: i + 3, style: Some("atom"), })
      i += 3
      continue
    }
    // Arrows and connectors: -->, -.->, ==>, ---, --
    if ch == '-' || ch == '=' {
      let start = i
      while i < len {
        let c = line.code_unit_at(i)
        if c == '-' || c == '=' || c == '.' || c == '>' || c == '<' {
          i += 1
        } else {
          break
        }
      }
      let seg = line[start:i]
      if seg.contains(">") || seg.contains("<") || i - start >= 2 {
        spans.push({ start, end: i, style: Some("operator"), })
      } else {
        spans.push({ start, end: i, style: Some("punctuation"), })
      }
      continue
    }
    // Punctuation & brackets
    if ch == ':' ||
      ch == ';' ||
      ch == ',' ||
      ch == '{' ||
      ch == '}' ||
      ch == '[' ||
      ch == ']' ||
      ch == '(' ||
      ch == ')' {
      spans.push({ start: i, end: i + 1, style: Some("punctuation"), })
      i += 1
      continue
    }
    // Identifiers & keywords
    if is_mermaid_ident_start(ch) {
      let start = i
      i += 1
      while i < len && is_mermaid_ident_part(line.code_unit_at(i)) {
        i += 1
      }
      let word = line[start:i]
      let style = match word {
        "stateDiagram"
        | "stateDiagram-v2"
        | "flowchart"
        | "graph"
        | "sequenceDiagram"
        | "classDiagram"
        | "erDiagram"
        | "subgraph"
        | "end"
        | "state"
        | "note"
        | "as"
        | "direction"
        | "classDef"
        | "class"
        | "style"
        | "click"
        | "LR"
        | "RL"
        | "TD"
        | "TB"
        | "BT" => Some("keyword")
        _ => Some("variable")
      }
      spans.push({ start, end: i, style, })
      continue
    }
    // Numbers
    if ch >= '0' && ch <= '9' {
      let start = i
      while i < len &&
            (
              (line.code_unit_at(i) >= '0' && line.code_unit_at(i) <= '9') ||
              line.code_unit_at(i) == '.'
            ) {
        i += 1
      }
      spans.push({ start, end: i, style: Some("number"), })
      continue
    }
    spans.push({ start: i, end: i + 1, style: None, })
    i += 1
  }
  spans
}

///|
fn is_mermaid_ident_start(ch : UInt16) -> Bool {
  (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_'
}

///|
fn is_mermaid_ident_part(ch : UInt16) -> Bool {
  is_mermaid_ident_start(ch) || (ch >= '0' && ch <= '9') || ch == '-'
}

///|
/// Internal stateful driver for `bobzhang/codemirror-lang` tokenizers when
/// bridged into `moonbitlang/editor/syntax::LineTokenizer`.
priv enum CmLangDriver {
  MermaidDriver
  YamlDriver(@cm_yaml.State)
  XmlDriver(@cm_xml.State)
  TurtleDriver(@lang_turtle.State)
  JsonLdDriver(@lang_js.State)
  MarkdownDriver(@lang_md.State)
  TomlDriver(@lang_toml.State)
  ShellDriver(@lang_shell.State)
}

///|
priv struct CmLineTokenizer {
  driver : CmLangDriver
}

///|
fn CmLineTokenizer::for_language(lang : CodeLanguage) -> CmLineTokenizer {
  let driver = match lang {
    Mermaid => MermaidDriver
    Yaml => YamlDriver(@cm_yaml.State::new())
    Xml => XmlDriver(@cm_xml.State::new())
    Turtle => TurtleDriver(@lang_turtle.State::new())
    JsonLd => JsonLdDriver(@lang_js.State::new(dialect=JsonLd))
    Markdown => MarkdownDriver(@lang_md.State::new())
    Toml => TomlDriver(@lang_toml.State::new())
    Shell => ShellDriver(@lang_shell.State::new())
    MoonBit => MermaidDriver
  }
  { driver, }
}

///|
impl @ed_syntax.LineTokenizer for CmLineTokenizer with fn initial_state(_self) {
  @ed_syntax.TokenizerState()
}

///|
impl @ed_syntax.LineTokenizer for CmLineTokenizer with fn tokenize_line(
  self,
  line_view,
  state,
) {
  let line = line_view.to_owned()
  let spans = match self.driver {
    MermaidDriver => tokenize_mermaid_line(line)
    YamlDriver(st) => st.tokenize_line(line)
    XmlDriver(st) => st.tokenize_line(line)
    TurtleDriver(st) => st.tokenize_line(line)
    JsonLdDriver(st) => st.tokenize_line(line)
    MarkdownDriver(st) => st.tokenize_line(line)
    TomlDriver(st) => st.tokenize_line(line)
    ShellDriver(st) => st.tokenize_line(line)
  }
  (line_tokens_from_cm_spans(line, spans), state)
}

///|
/// Renders `source` as line-numbered, syntax-highlighted `moonbitlang/editor`
/// HTML using the production `mtk` token classes.
pub fn highlighted_numbered_source(
  source : String,
  lang : CodeLanguage,
) -> @html.Html {
  match lang {
    MoonBit => @ed_html.moonbit_numbered_source(source)
    _ => {
      let tok : &@ed_syntax.LineTokenizer = CmLineTokenizer::for_language(lang)
      @ed_html.numbered_source(source, tokenizer=tok)
    }
  }
}

///|
/// Copies text to the clipboard and briefly flashes the triggering button's
/// label to `"Copied"`.
extern "js" fn copy_code_text(text : String, btn_id : String) -> Unit =
  #| (text, btnId) => {
  #|   const flash = () => {
  #|     const el = document.getElementById(btnId);
  #|     if (!el) return;
  #|     const prev = el.dataset.prevLabel || el.textContent || "Copy";
  #|     el.dataset.prevLabel = prev;
  #|     el.textContent = "Copied";
  #|     clearTimeout(el._mcCopyTimer);
  #|     el._mcCopyTimer = setTimeout(() => { el.textContent = prev; }, 1400);
  #|   };
  #|   if (navigator.clipboard && navigator.clipboard.writeText) {
  #|     navigator.clipboard.writeText(text).then(flash).catch(() => {});
  #|   }
  #| }

///|
/// Full Monaco-styled read-only code viewer with header bar (language badge,
/// line count, Copy action) and `moonbitlang/editor` line-numbered highlighting.
fn code_viewer(
  source : String,
  lang~ : CodeLanguage,
  label~ : String,
  copy_id~ : String,
  compact~ : Bool = false,
  fill~ : Bool = false,
) -> @html.Html {
  let line_count = source.split("\n").count()
  let line_word = if line_count == 1 { "1 line" } else { "\{line_count} lines" }
  let body = @html.div(
    class=if compact {
      "mc-code-viewer-body compact"
    } else {
      "mc-code-viewer-body"
    },
    attrs=@html.Attrs::build().aria_label(label).tabindex(0),
    [highlighted_numbered_source(source, lang)],
  )
  let root_class = if fill {
    "mc-code-viewer fill"
  } else if compact {
    "mc-code-viewer compact"
  } else {
    "mc-code-viewer"
  }
  @html.div(class=root_class, [
    @html.div(class="mc-code-viewer-bar", [
      @html.div(
        style=["display:flex;align-items:center;gap:0.5rem;min-width:0"],
        [
          @html.span(class="mc-code-lang-pill", lang.label()),
          @html.span(class="mc-code-meta", line_word),
        ],
      ),
      @html.button(
        id=copy_id,
        class="mc-code-copy-btn",
        type_="button",
        attrs=@html.Attrs::build().aria_label("Copy \{lang.label()} snippet"),
        on_click=@cmd.custom_cmd(_ => copy_code_text(source, copy_id)),
        "Copy",
      ),
    ]),
    body,
  ])
}