// Live RDF/SKOS Data Dictionary workbench & Prose Term Audit view.

///|
fn live_concept_matches(
  concept : @app.WireDictionaryConcept,
  graph_filter : String?,
  query : String,
) -> Bool {
  match graph_filter {
    Some(gid) if concept.graph_id != gid => return false
    _ => ()
  }
  let needle = lower_case(query.trim().to_owned())
  if needle.is_empty() {
    return true
  }
  lower_case(concept.pref_label).contains(needle) ||
  lower_case(concept.iri).contains(needle) ||
  lower_case(concept.definition).contains(needle) ||
  concept.alt_labels.iter().any(alt => lower_case(alt).contains(needle))
}

///|
/// Three-pane live RDF/SKOS Data Dictionary workbench backed by server RPCs.
fn live_dictionary_workbench(
  model : Model,
  dict : @app.WorkspaceDictionary,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let filtered = dict.concepts
    .iter()
    .filter(c => {
      live_concept_matches(c, model.selected_live_dict_graph, model.dict_query)
    })
    .collect()
  let active_concept : @app.WireDictionaryConcept? = match
    model.selected_live_concept {
    Some(iri) =>
      match dict.concepts.iter().find_first(c => c.iri == iri) {
        Some(found) => Some(found)
        None => filtered.get(0)
      }
    None => filtered.get(0)
  }

  let graph_chips : Array[@html.Html] = [
    @html.button(
      class=if model.selected_live_dict_graph is None {
        "mc-chip-btn active"
      } else {
        "mc-chip-btn"
      },
      attrs=@html.Attrs::build().aria_pressed(
        (model.selected_live_dict_graph is None).to_string(),
      ),
      on_click=emit(LiveDictGraphSelected(None)),
      "All Graphs",
    ),
  ]
  for g in dict.graphs {
    let active = model.selected_live_dict_graph == Some(g.id)
    let access_badge = match g.access {
      ReadWrite => "RW"
      ReadOnly => "RO"
    }
    graph_chips.push(
      @html.button(
        class=if active { "mc-chip-btn active" } else { "mc-chip-btn" },
        attrs=@html.Attrs::build().aria_pressed(active.to_string()),
        on_click=emit(LiveDictGraphSelected(Some(g.id))),
        "\{g.name} (\{access_badge})",
      ),
    )
  }

  let concept_rows = if filtered.is_empty() {
    [
      @html.p(
        style=[
          "margin:0;padding:0.75rem;font-size:0.75rem;color:var(--rui-muted-foreground)",
        ],
        "No concepts match the active filter.",
      ),
    ]
  } else {
    filtered
    .iter()
    .map(c => {
      let active = active_concept.map(a => a.iri == c.iri).unwrap_or(false)
      @html.button(
        class=if active { "mc-out-item active" } else { "mc-out-item" },
        attrs=if active {
          @html.Attrs::build().aria_current("true")
        } else {
          @html.Attrs::build()
        },
        on_click=emit(LiveConceptSelected(c.iri)),
        [
          @html.span(
            style=[
              "display:flex;flex-direction:column;gap:0.1875rem;min-width:0;flex:1;text-align:left",
            ],
            [
              @html.div(
                style=[
                  "display:flex;justify-content:space-between;align-items:center;gap:0.375rem",
                ],
                [
                  @html.span(
                    class="mc-cut",
                    style=["font-size:0.75rem;font-weight:600"],
                    c.pref_label,
                  ),
                  @html.span(
                    class=if c.deprecated {
                      "mc-pill-warn"
                    } else {
                      "mc-pill-good"
                    },
                    if c.deprecated {
                      "Deprecated"
                    } else {
                      "Active"
                    },
                  ),
                ],
              ),
              @html.span(
                class="mc-cut",
                style=[
                  "font-size:0.625rem;font-family:var(--mc-mono);color:var(--rui-muted-foreground)",
                ],
                c.graph_name,
              ),
            ],
          ),
        ],
      )
    })
    .to_array()
  }

  let format_switch = @html.div(
    class="mc-seg",
    attrs=@html.Attrs::build().role("group").aria_label("Dictionary format"),
    [DictStructured, DictTurtle, DictJsonLd]
    .iter()
    .map(fmt => {
      let active = model.dict_format == fmt
      @html.button(
        class=if active { "mc-seg-btn active" } else { "mc-seg-btn" },
        attrs=@html.Attrs::build().aria_pressed(active.to_string()),
        on_click=emit(DictFormatChosen(fmt)),
        fmt.label(),
      )
    })
    .to_array(),
  )

  let detail_canvas : @html.Html = match active_concept {
    None =>
      @html.div(
        style=[
          "padding:1.5rem;color:var(--rui-muted-foreground);font-size:0.875rem",
        ],
        "Select a concept or add a new local concept to .mission-control/dictionary/local.ttl.",
      )
    Some(c) => {
      let body : @html.Html = match model.dict_format {
        DictTurtle =>
          code_viewer(
            c.turtle,
            lang=Turtle,
            label="Concept Turtle source",
            copy_id="mc-copy-live-dict-ttl",
            fill=true,
          )
        DictJsonLd =>
          code_viewer(
            c.jsonld,
            lang=CodeLanguage::JsonLd,
            label="Concept JSON-LD source",
            copy_id="mc-copy-live-dict-jsonld",
            fill=true,
          )
        DictStructured =>
          @html.div(style=["display:flex;flex-direction:column;gap:0.875rem"], [
            @html.p(
              style=[
                "margin:0;font-size:0.9375rem;line-height:1.7;color:var(--rui-foreground)",
              ],
              if c.definition.is_empty() {
                "No skos:definition recorded for this concept."
              } else {
                c.definition
              },
            ),
            if !c.alt_labels.is_empty() {
              @html.div(
                style=[
                  "display:flex;align-items:center;gap:0.375rem;flex-wrap:wrap;font-size:0.75rem",
                ],
                [
                  @html.span(
                    style=[
                      "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--rui-muted-foreground)",
                    ],
                    "skos:altLabel",
                  ),
                  @html.fragment(
                    c.alt_labels
                    .iter()
                    .map(alt => @html.span(class="mc-pill-warn", alt))
                    .to_array(),
                  ),
                ],
              )
            } else {
              @html.nothing
            },
            if !c.constraints.is_empty() {
              @html.div(
                class="mc-surface-card",
                style=[
                  "padding:0.75rem 0.875rem;display:flex;flex-direction:column;gap:0.35rem",
                ],
                [
                  @html.span(class="mc-kicker", "SHACL Constraints"),
                  @html.fragment(
                    c.constraints
                    .iter()
                    .map(rule => {
                      @html.div(
                        style=[
                          "font-family:var(--mc-mono);font-size:0.75rem;color:var(--rui-foreground)",
                        ],
                        "• \{rule}",
                      )
                    })
                    .to_array(),
                  ),
                ],
              )
            } else {
              @html.nothing
            },
          ])
      }
      @html.div(
        style=[
          "display:flex;flex-direction:column;gap:0.875rem;flex:1;min-height:0",
        ],
        [
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:center;gap:0.5rem;flex-wrap:wrap",
            ],
            [
              @html.div(
                style=["display:flex;align-items:center;gap:0.375rem"],
                [
                  @html.span(class="mc-pill-good", "Live RDF"),
                  @html.span(
                    class=match c.access {
                      ReadWrite => "mc-pill-good"
                      ReadOnly => "mc-pill-warn"
                    },
                    match c.access {
                      ReadWrite => "\{c.graph_name} · RW"
                      ReadOnly => "\{c.graph_name} · RO"
                    },
                  ),
                ],
              ),
              format_switch,
            ],
          ),
          @html.h2(
            style=[
              "margin:0;font-size:1.35rem;font-weight:700;letter-spacing:-0.02em",
            ],
            c.pref_label,
          ),
          @html.div(
            style=[
              "font-family:var(--mc-mono);font-size:0.75rem;color:var(--rui-muted-foreground);overflow-wrap:anywhere",
            ],
            c.iri,
          ),
          body,
        ],
      )
    }
  }

  let add_form = @html.div(
    style=[
      "margin-top:0.5rem;padding-top:0.75rem;border-top:1px solid var(--rui-border);display:flex;flex-direction:column;gap:0.375rem",
    ],
    [
      @html.span(class="mc-kicker", "Add Local Concept (.ttl)"),
      @html.input(
        input_type=Text,
        value=model.dict_draft_label,
        placeholder="Concept label (skos:prefLabel)",
        attrs=@html.Attrs::build().aria_label("New concept label"),
        on_input=v => emit(DictDraftLabelChanged(v)),
        style=[
          "width:100%;box-sizing:border-box;padding:0.35rem 0.5rem;border:1px solid var(--rui-border);border-radius:0.375rem;background:var(--rui-background);color:var(--rui-foreground);font-size:0.75rem",
        ],
      ),
      @html.input(
        input_type=Text,
        value=model.dict_draft_def,
        placeholder="Definition (skos:definition)",
        attrs=@html.Attrs::build().aria_label("New concept definition"),
        on_input=v => emit(DictDraftDefChanged(v)),
        style=[
          "width:100%;box-sizing:border-box;padding:0.35rem 0.5rem;border:1px solid var(--rui-border);border-radius:0.375rem;background:var(--rui-background);color:var(--rui-foreground);font-size:0.75rem",
        ],
      ),
      match model.dict_draft_error {
        Some(err) =>
          @html.div(style=["font-size:0.7rem;color:var(--mc-bad-fg)"], err)
        None => @html.nothing
      },
      @rui.button(
        size=Sm,
        on_click=emit(DictConceptSubmitted),
        "+ Add local concept",
      ),
    ],
  )

  let audit_cards = if dict.findings.is_empty() {
    [
      @html.p(
        style=["margin:0;font-size:0.75rem;color:var(--rui-muted-foreground)"],
        "No Prose Term Audit findings across active OpenSpec documents.",
      ),
    ]
  } else {
    dict.findings
    .iter()
    .map(f => {
      @html.div(
        class="mc-surface-card",
        style=[
          "padding:0.625rem 0.75rem;display:flex;flex-direction:column;gap:0.35rem;font-size:0.75rem",
        ],
        [
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:center;gap:0.375rem",
            ],
            [@html.strong(f.term), @html.span(class="mc-pill-warn", f.kind)],
          ),
          @html.div(
            style=["color:var(--rui-muted-foreground)"],
            "Prefer: \{f.suggested_label}",
          ),
          @html.div(
            style=[
              "font-family:var(--mc-mono);font-size:0.65rem;color:var(--rui-muted-foreground);overflow-wrap:anywhere",
            ],
            f.document_path,
          ),
          @html.div(
            style=["font-size:0.7rem;color:var(--rui-foreground)"],
            f.excerpt,
          ),
        ],
      )
    })
    .to_array()
  }

  let secondary_shown = model.secondary_sidebar is SecondaryShown
  let companion_shown = model.companion_panel is CompanionShown
  let grid_class = match (secondary_shown, companion_shown) {
    (true, true) => "mc-review-grid"
    (false, true) => "mc-review-grid secondary-collapsed"
    (true, false) => "mc-review-grid companion-collapsed"
    (false, false) => "mc-review-grid secondary-collapsed companion-collapsed"
  }
  let code_mode = model.dict_format is (DictTurtle | DictJsonLd)

  @html.div(
    class=grid_class,
    style=["--mc-secondary-w:\{model.secondary_sidebar_width.pixels()}px"],
    [
      if secondary_shown {
        @html.aside(
          class="mc-review-outline",
          attrs=@html.Attrs::build().aria_label("Data dictionary"),
          [
            @html.div(
              style=[
                "display:flex;justify-content:space-between;align-items:center;gap:0.375rem",
              ],
              [
                @html.span(class="mc-kicker", "Data Dictionary"),
                @rui.button(
                  variant=Ghost,
                  size=IconSm,
                  title="Collapse Data dictionary sidebar",
                  attrs=@html.Attrs::build().aria_label(
                    "Collapse Data dictionary sidebar",
                  ),
                  on_click=emit(SecondarySidebarToggled),
                  icon("M15 18l-6-6 6-6"),
                ),
              ],
            ),
            @html.div(
              style=["display:flex;flex-wrap:wrap;gap:0.25rem"],
              graph_chips,
            ),
            @html.input(
              input_type=Search,
              value=model.dict_query,
              placeholder="Filter concepts…",
              attrs=@html.Attrs::build().aria_label(
                "Filter dictionary concepts",
              ),
              on_input=v => emit(DictQueryChanged(v)),
              style=[
                "width:100%;box-sizing:border-box;padding:0.35rem 0.5rem;border:1px solid var(--rui-border);border-radius:0.375rem;background:var(--rui-background);color:var(--rui-foreground);font-size:0.75rem",
              ],
            ),
            @html.div(
              style=[
                "display:flex;flex-direction:column;gap:0.25rem;flex:1;overflow:auto",
              ],
              concept_rows,
            ),
            add_form,
          ],
        )
      } else {
        @html.nothing
      },
      if secondary_shown {
        secondary_splitter_view(model.secondary_sidebar_width, emit)
      } else {
        @html.nothing
      },
      @html.div(
        class=if code_mode {
          "mc-review-canvas code-mode"
        } else {
          "mc-review-canvas"
        },
        [detail_canvas],
      ),
      if companion_shown {
        @html.aside(
          class="mc-review-companion",
          attrs=@html.Attrs::build().aria_label("Prose term audit"),
          [
            @html.div(
              style=[
                "display:flex;justify-content:space-between;align-items:center;gap:0.5rem",
              ],
              [
                @html.span(class="mc-kicker", "Prose Term Audit"),
                @rui.button(
                  variant=Ghost,
                  size=IconSm,
                  title="Collapse Prose term audit panel",
                  attrs=@html.Attrs::build().aria_label(
                    "Collapse Prose term audit panel",
                  ),
                  on_click=emit(CompanionPanelToggled),
                  icon("M9 18l6-6-6-6"),
                ),
              ],
            ),
            @html.div(
              style=["display:flex;flex-direction:column;gap:0.5rem"],
              audit_cards,
            ),
          ],
        )
      } else {
        @html.nothing
      },
    ],
  )
}