// Knowledge perspective: RDF/SKOS Data Dictionary workbench, live Prose Term
// Audit, and OKF Knowledge Base browser.

///|
/// Segmented switch between Data Dictionary and Knowledge Base in the project strip.
fn knowledge_view_switch(
  current : KnowledgeView,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let item = (view : KnowledgeView) => {
    let active = current == view
    @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(KnowledgeViewChosen(view)),
      view.label(),
    )
  }
  @html.div(
    class="mc-seg",
    attrs=@html.Attrs::build().role("group").aria_label("Knowledge view"),
    [item(Dictionary), item(KnowledgeBase)],
  )
}

///|
/// Top-level Knowledge perspective dispatching between Data Dictionary and Knowledge Base.
fn knowledge_perspective(
  model : Model,
  ws : MockupWorkspace,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  match model.knowledge_view {
    Dictionary =>
      match model.active_live_dictionary() {
        Some(dict) => live_dictionary_workbench(model, dict, emit)
        None => dictionary_workbench(model, ws, emit)
      }
    KnowledgeBase => kb_workbench(model, ws, emit)
  }
}

///|
fn concept_matches_filter(
  card : ConceptCard,
  graph : NamedGraphFilter,
  query : String,
) -> Bool {
  if !graph.matches(card.graph) {
    return false
  }
  let needle = lower_case(query.trim().to_owned())
  if needle.is_empty() {
    return true
  }
  lower_case(card.label.as_str()).contains(needle) ||
  lower_case(card.iri.as_str()).contains(needle) ||
  lower_case(card.definition.as_str()).contains(needle) ||
  card.alt_labels.iter().any(alt => lower_case(alt).contains(needle))
}

///|
fn kb_doc_matches_filter(
  doc : KbDocument,
  source : KbSourceFilter,
  query : String,
) -> Bool {
  if !source.matches(doc.source) {
    return false
  }
  let needle = lower_case(query.trim().to_owned())
  if needle.is_empty() {
    return true
  }
  lower_case(doc.title).contains(needle) ||
  lower_case(doc.path).contains(needle) ||
  lower_case(doc.summary).contains(needle)
}

///|
fn concept_relation_row(
  heading : String,
  ids : ReadOnlyArray[ConceptId],
  ws : MockupWorkspace,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  if ids.is_empty() {
    return @html.nothing
  }
  let buttons = ids
    .iter()
    .map(id => {
      let label = ws.concept(id).unwrap_or(default_concept_card()).label.as_str()
      @html.button(
        class="mc-chip-btn",
        on_click=emit(ConceptSelected(id)),
        label,
      )
    })
    .to_array()
  @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);min-width:5rem",
        ],
        heading,
      ),
      @html.fragment(buttons),
    ],
  )
}

///|
/// Three-pane RDF/SKOS Data Dictionary workbench: graph & concept explorer,
/// Structured/Turtle/JSON-LD inspector, and live Prose Term Audit companion.
fn dictionary_workbench(
  model : Model,
  ws : MockupWorkspace,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let all_concepts = ws.all_concepts()
  let filtered = all_concepts.filter(c => {
    concept_matches_filter(c, model.dict_graph, model.dict_query)
  })
  let concept = ws
    .concept(ws.active_concept())
    .unwrap_or(default_concept_card())
  let lookup = (id : ConceptId) => ws.concept(id)

  let graph_chips = [
      NamedGraphFilter::AllGraphs,
      Graph(MountedPci),
      Graph(LocalPayments),
    ]
    .iter()
    .map(filter => {
      let active = model.dict_graph == filter
      @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(DictGraphChosen(filter)),
        filter.label(),
      )
    })
    .to_array()

  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(card => {
      let active = card.id == concept.id
      @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(ConceptSelected(card.id)),
        [
          @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"],
                    card.label.as_str(),
                  ),
                  @html.span(
                    class=if card.is_deprecated() {
                      "mc-pill-warn"
                    } else {
                      "mc-pill-good"
                    },
                    if card.is_deprecated() {
                      "Deprecated"
                    } else {
                      "Active"
                    },
                  ),
                ],
              ),
              @html.span(
                class="mc-cut",
                style=[
                  "font-family:var(--mc-mono);font-size:0.625rem;color:var(--rui-muted-foreground)",
                ],
                "\{card.graph.label()} · \{card.access().label()}",
              ),
            ],
          ),
        ],
      )
    })
    .to_array()
  }

  let format_switch = {
    let item = (fmt : DictFormat) => {
      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(),
      )
    }
    @html.div(
      class="mc-seg",
      attrs=@html.Attrs::build()
        .role("group")
        .aria_label("Concept serialization format"),
      [item(DictStructured), item(DictTurtle), item(DictJsonLd)],
    )
  }

  let has_relations = !concept.broader.is_empty() ||
    !concept.narrower.is_empty() ||
    !concept.related.is_empty()

  let inspector_body = match model.dict_format {
    DictStructured =>
      @html.div(style=["display:flex;flex-direction:column;gap:0.875rem"], [
        @html.div(
          class="mc-surface-card",
          style=[
            "padding:0.875rem 1rem;display:flex;flex-direction:column;gap:0.5rem",
          ],
          [
            @html.span(class="mc-kicker", "SKOS Definition"),
            @html.p(
              style=[
                "margin:0;font-size:0.875rem;line-height:1.65;color:var(--rui-foreground)",
              ],
              concept.definition.as_str(),
            ),
            if concept.alt_labels.is_empty() {
              @html.nothing
            } else {
              @html.div(
                style=[
                  "display:flex;align-items:center;gap:0.375rem;flex-wrap:wrap;padding-top:0.375rem;border-top:1px solid var(--rui-border)",
                ],
                [
                  @html.span(
                    style=[
                      "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--rui-muted-foreground)",
                    ],
                    "skos:altLabel",
                  ),
                  @html.fragment(
                    concept.alt_labels
                    .iter()
                    .map(alt => @html.span(class="mc-pill-brand", alt))
                    .to_array(),
                  ),
                ],
              )
            },
          ],
        ),
        if has_relations {
          @html.div(
            class="mc-surface-card",
            style=[
              "padding:0.875rem 1rem;display:flex;flex-direction:column;gap:0.5rem",
            ],
            [
              @html.span(class="mc-kicker", "SKOS Taxonomy & Relations"),
              concept_relation_row("skos:broader", concept.broader, ws, emit),
              concept_relation_row("skos:narrower", concept.narrower, ws, emit),
              concept_relation_row("skos:related", concept.related, ws, emit),
            ],
          )
        } else {
          @html.nothing
        },
        @html.div(
          class="mc-surface-card",
          style=[
            "padding:0.875rem 1rem;display:flex;flex-direction:column;gap:0.375rem",
          ],
          [
            @html.span(class="mc-kicker", "SHACL & Policy Constraint"),
            @html.p(
              style=[
                "margin:0;font-size:0.8125rem;line-height:1.55;color:var(--rui-foreground)",
              ],
              concept.shacl,
            ),
          ],
        ),
        @html.div(
          class="mc-surface-card",
          style=[
            "padding:0.875rem 1rem;display:flex;flex-direction:column;gap:0.5rem",
          ],
          [
            @html.span(class="mc-kicker", "Cross-Document Backlinks"),
            if concept.backlinks.is_empty() {
              @html.p(
                style=[
                  "margin:0;font-size:0.75rem;color:var(--rui-muted-foreground)",
                ],
                "No linked Review documents yet.",
              )
            } else {
              @html.div(
                style=["display:flex;flex-direction:column;gap:0.375rem"],
                concept.backlinks
                .iter()
                .map(bl => {
                  @html.button(
                    class="mc-out-item",
                    on_click=emit(OpenBacklinkInReview(bl.item, bl.doc)),
                    [
                      @html.span(
                        class="mc-cut",
                        style=[
                          "flex:1;text-align:left;font-size:0.75rem;font-weight:500",
                        ],
                        bl.label,
                      ),
                      @html.span(
                        style=[
                          "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--mc-cobalt)",
                        ],
                        "Review ->",
                      ),
                    ],
                  )
                })
                .to_array(),
              )
            },
          ],
        ),
      ])
    DictTurtle =>
      code_viewer(
        concept.to_turtle(lookup),
        lang=Turtle,
        label="Concept Turtle source",
        copy_id="mc-copy-concept-turtle",
        fill=true,
      )
    DictJsonLd =>
      code_viewer(
        concept.to_json_ld(lookup),
        lang=JsonLd,
        label="Concept JSON-LD source",
        copy_id="mc-copy-concept-jsonld",
        fill=true,
      )
  }

  let audits = ws.term_audits()
  let open_audits = audits.iter().filter(a => !a.status.is_resolved()).count()
  let audit_cards = audits
    .iter()
    .map(audit => {
      let (kind_label, kind_class, target, action_label) = match audit.kind {
        DeprecatedSynonym(target~) => {
          let target_label = ws
          .concept(target)
          .unwrap_or(default_concept_card()).label.as_str()
          ("Deprecated", "mc-pill-warn", target, "Normalize -> \{target_label}")
        }
        UnlinkedMention(target~) => {
          let target_label = ws
          .concept(target)
          .unwrap_or(default_concept_card()).label.as_str()
          (
            "Unlinked",
            "mc-pill-brand",
            target,
            "Accept link -> \{target_label}",
          )
        }
      }
      @html.div(
        class="mc-surface-card",
        style=[
          "padding:0.625rem 0.75rem;display:flex;flex-direction:column;gap:0.375rem",
        ],
        [
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:center;gap:0.375rem",
            ],
            [
              @html.strong(style=["font-size:0.75rem"], "\"\{audit.mention}\""),
              @html.span(
                class=if audit.status.is_resolved() {
                  "mc-pill-good"
                } else {
                  kind_class
                },
                if audit.status.is_resolved() {
                  "Resolved"
                } else {
                  kind_label
                },
              ),
            ],
          ),
          @html.button(
            class="mc-dict-term",
            style=[
              "align-self:flex-start;font-family:var(--mc-mono);font-size:0.625rem;text-align:left",
            ],
            on_click=emit(OpenBacklinkInReview(audit.item, audit.doc)),
            audit.location,
          ),
          if audit.status.is_resolved() {
            @html.span(
              style=[
                "font-size:0.6875rem;font-weight:600;color:var(--mc-good-fg)",
              ],
              "✓ Resolved in workspace",
            )
          } else {
            @html.div(
              style=[
                "display:flex;flex-wrap:wrap;gap:0.375rem;align-items:center",
              ],
              [
                @rui.button(
                  variant=match audit.kind {
                    DeprecatedSynonym(..) => Default
                    UnlinkedMention(..) => Outline
                  },
                  size=Sm,
                  on_click=emit(TermAuditResolved(audit.id)),
                  action_label,
                ),
                @html.button(
                  class="mc-chip-btn",
                  on_click=emit(ConceptSelected(target)),
                  "Inspect",
                ),
              ],
            )
          },
        ],
      )
    })
    .to_array()

  @html.div(class="mc-review-grid", [
    secondary_sidebar_shell(
      model,
      title="Data dictionary",
      count="\{filtered.length()}/\{all_concepts.length()}",
      emit,
      [
        @html.div(
          style=["display:flex;flex-wrap:wrap;gap:0.25rem"],
          attrs=@html.Attrs::build()
            .role("group")
            .aria_label("Named graph filter"),
          graph_chips,
        ),
        @rui.input(
          value=model.dict_query,
          placeholder="Filter concepts, IRI, synonym…",
          attrs=@html.Attrs::build().aria_label("Filter dictionary concepts"),
          on_input=@cmd.Emit(text => emit(DictQueryChanged(text))),
        ),
      ],
      [
        @html.div(
          style=[
            "flex:1;overflow:auto;padding:0.5rem;display:flex;flex-direction:column;gap:0.25rem",
          ],
          concept_rows,
        ),
        @html.div(
          style=[
            "padding:0.75rem;border-top:1px solid var(--rui-border);display:flex;flex-direction:column;gap:0.375rem",
          ],
          [
            @html.span(class="mc-pane-title", "Add local concept"),
            @rui.input(
              value=model.dict_draft_label,
              placeholder="Concept label…",
              attrs=@html.Attrs::build().aria_label("New concept label"),
              on_input=@cmd.Emit(text => emit(DictDraftLabelChanged(text))),
            ),
            @rui.input(
              value=model.dict_draft_def,
              placeholder="Short SKOS definition…",
              attrs=@html.Attrs::build().aria_label("New concept definition"),
              on_input=@cmd.Emit(text => emit(DictDraftDefChanged(text))),
            ),
            match model.dict_draft_error {
              Some(err) =>
                @html.p(
                  class="mc-warning",
                  style=["margin:0;font-size:0.6875rem;font-weight:500"],
                  err,
                )
              None => @html.nothing
            },
            @rui.button(
              size=Sm,
              on_click=emit(DictConceptSubmitted),
              "+ Add local concept",
            ),
          ],
        ),
      ],
    ),
    @html.div(
      class=if model.dict_format is (DictTurtle | DictJsonLd) {
        "mc-review-canvas code-mode"
      } else {
        "mc-review-canvas"
      },
      @html.article(
        style=if model.dict_format is (DictTurtle | DictJsonLd) {
          [
            "width:100%;flex:1;min-height:100%;display:flex;flex-direction:column;gap:0.875rem",
          ]
        } else {
          [
            "max-width:44rem;margin:0 auto;display:flex;flex-direction:column;gap:1rem",
          ]
        },
        [
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:flex-start;gap:0.75rem;flex-wrap:wrap;padding-bottom:0.75rem;border-bottom:1px solid var(--rui-border)",
            ],
            [
              @html.div(
                style=[
                  "display:flex;flex-direction:column;gap:0.25rem;min-width:0;flex:1",
                ],
                [
                  @html.div(
                    style=[
                      "display:flex;align-items:center;gap:0.375rem;flex-wrap:wrap",
                    ],
                    [
                      @html.h2(
                        style=["margin:0;font-size:1.25rem;font-weight:700"],
                        concept.label.as_str(),
                      ),
                      @html.span(
                        class=if concept.is_deprecated() {
                          "mc-pill-warn"
                        } else {
                          "mc-pill-good"
                        },
                        if concept.is_deprecated() {
                          "Deprecated"
                        } else {
                          "Active"
                        },
                      ),
                      @html.span(
                        class="mc-pill-brand",
                        concept.access().label(),
                      ),
                    ],
                  ),
                  @html.span(
                    style=[
                      "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--mc-cobalt);overflow-wrap:anywhere",
                    ],
                    "<\{concept.iri.as_str()}>",
                  ),
                  @html.span(
                    style=[
                      "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--rui-muted-foreground)",
                    ],
                    "Graph: \{concept.graph_display()}",
                  ),
                ],
              ),
              format_switch,
            ],
          ),
          inspector_body,
        ],
      ),
    ),
    companion_panel_shell(model, title="Prose term audit", emit, [
      @html.div(
        style=[
          "padding:0.75rem;border-bottom:1px solid var(--rui-border);display:flex;justify-content:space-between;align-items:center;gap:0.5rem",
        ],
        [
          @html.div(
            style=["display:flex;align-items:center;gap:0.45rem;min-width:0"],
            [
              @html.span(class="mc-pane-title", "Prose term audit"),
              @html.span(
                class=if open_audits == 0 {
                  "mc-pill-good"
                } else {
                  "mc-pill-warn"
                },
                if open_audits == 0 {
                  "All clean"
                } else {
                  "\{open_audits} open"
                },
              ),
            ],
          ),
          companion_collapse_button(title="Prose term audit", emit),
        ],
      ),
      @html.div(
        style=[
          "flex:1;overflow:auto;padding:0.75rem;display:flex;flex-direction:column;gap:0.625rem",
        ],
        audit_cards,
      ),
    ]),
  ])
}

///|
/// Three-pane OKF Knowledge Base browser: source filter & doc list,
/// Preview/Source reader with clickable dictionary terms, and Link Neighborhood.
fn kb_workbench(
  model : Model,
  ws : MockupWorkspace,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let all_docs = kb_documents()
  let filtered = all_docs.filter(doc => {
    kb_doc_matches_filter(doc, model.kb_source, model.kb_query)
  })
  let doc = kb_document(model.kb_doc)

  let source_chips = [
      KbSourceFilter::AllKbSources,
      Source(LocalOkf),
      Source(MountedRo),
    ]
    .iter()
    .map(src => {
      let active = model.kb_source == src
      @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(KbSourceChosen(src)),
        src.label(),
      )
    })
    .to_array()

  let doc_rows = if filtered.is_empty() {
    [
      @html.p(
        style=[
          "margin:0;padding:0.75rem;font-size:0.75rem;color:var(--rui-muted-foreground)",
        ],
        "No Knowledge Base documents match the active filter.",
      ),
    ]
  } else {
    filtered
    .iter()
    .map(d => {
      let active = d.id == doc.id
      @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(KbDocChosen(d.id)),
        [
          @html.span(
            style=[
              "display:flex;flex-direction:column;gap:0.1875rem;min-width:0;flex:1;text-align:left",
            ],
            [
              @html.span(
                class="mc-cut",
                style=["font-size:0.75rem;font-weight:600"],
                d.title,
              ),
              @html.span(
                class="mc-cut",
                style=[
                  "font-family:var(--mc-mono);font-size:0.625rem;color:var(--rui-muted-foreground)",
                ],
                "\{d.kind.label()} · \{d.trust_tier}",
              ),
            ],
          ),
        ],
      )
    })
    .to_array()
  }

  let read_toggle = {
    let item = (mode : KbReadMode) => {
      let active = model.kb_read_mode == mode
      @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(KbReadModeChosen(mode)),
        mode.label(),
      )
    }
    @html.div(
      class="mc-seg",
      attrs=@html.Attrs::build()
        .role("group")
        .aria_label("Knowledge base reading mode"),
      [item(KbPreview), item(KbSource)],
    )
  }

  let doc_body = match model.kb_read_mode {
    KbPreview =>
      @html.div(style=["display:flex;flex-direction:column;gap:1rem"], [
        @html.p(
          style=[
            "margin:0;font-size:0.875rem;font-style:italic;color:var(--rui-muted-foreground)",
          ],
          doc.summary,
        ),
        @html.fragment(
          doc.paragraphs
          .iter()
          .map(spans => {
            @html.p(
              style=[
                "margin:0;font-size:0.9375rem;line-height:1.8;color:var(--rui-foreground)",
              ],
              render_prose_spans_with(spans, concept => {
                emit(OpenConceptInDictionary(concept))
              }),
            )
          })
          .to_array(),
        ),
      ])
    KbSource =>
      code_viewer(
        doc.source_lines.iter().join("\n"),
        lang=Markdown,
        label="Line-numbered knowledge base source",
        copy_id="mc-copy-kb-source",
        fill=true,
      )
  }

  let incoming = all_docs.filter(other => {
    other.id != doc.id && other.links.contains(doc.id)
  })

  @html.div(class="mc-review-grid", [
    secondary_sidebar_shell(
      model,
      title="Knowledge base",
      count="\{filtered.length()}/\{all_docs.length()}",
      emit,
      [
        @html.div(
          style=["display:flex;flex-wrap:wrap;gap:0.25rem"],
          attrs=@html.Attrs::build()
            .role("group")
            .aria_label("Knowledge base source filter"),
          source_chips,
        ),
        @rui.input(
          value=model.kb_query,
          placeholder="Search knowledge base…",
          attrs=@html.Attrs::build().aria_label("Search knowledge base"),
          on_input=@cmd.Emit(text => emit(KbQueryChanged(text))),
        ),
      ],
      [
        @html.div(
          style=[
            "flex:1;overflow:auto;padding:0.5rem;display:flex;flex-direction:column;gap:0.25rem",
          ],
          doc_rows,
        ),
      ],
    ),
    @html.div(
      class=if model.kb_read_mode is KbSource {
        "mc-review-canvas code-mode"
      } else {
        "mc-review-canvas"
      },
      @html.article(
        style=if model.kb_read_mode is KbSource {
          [
            "width:100%;flex:1;min-height:100%;display:flex;flex-direction:column;gap:0.875rem",
          ]
        } else {
          [
            "max-width:44rem;margin:0 auto;display:flex;flex-direction:column;gap:1rem",
          ]
        },
        [
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:flex-start;gap:0.75rem;flex-wrap:wrap;padding-bottom:0.75rem;border-bottom:1px solid var(--rui-border)",
            ],
            [
              @html.div(
                style=[
                  "display:flex;flex-direction:column;gap:0.25rem;min-width:0;flex:1",
                ],
                [
                  @html.span(
                    style=[
                      "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--rui-muted-foreground)",
                    ],
                    doc.path,
                  ),
                  @html.div(
                    style=[
                      "display:flex;align-items:center;gap:0.375rem;flex-wrap:wrap",
                    ],
                    [
                      @html.h2(
                        style=["margin:0;font-size:1.25rem;font-weight:700"],
                        doc.title,
                      ),
                      @html.span(class="mc-pill-brand", doc.kind.label()),
                      @html.span(class="mc-pill-good", doc.trust_tier),
                    ],
                  ),
                ],
              ),
              read_toggle,
            ],
          ),
          doc_body,
        ],
      ),
    ),
    companion_panel_shell(model, title="Link neighborhood", emit, [
      @html.div(
        style=[
          "padding:0.75rem;border-bottom:1px solid var(--rui-border);display:flex;justify-content:space-between;align-items:center;gap:0.5rem",
        ],
        [
          @html.span(class="mc-pane-title", "Link neighborhood"),
          companion_collapse_button(title="Link neighborhood", emit),
        ],
      ),
      @html.div(
        style=[
          "flex:1;overflow:auto;padding:0.75rem;display:flex;flex-direction:column;gap:0.875rem",
        ],
        [
          @html.div(style=["display:flex;flex-direction:column;gap:0.375rem"], [
            @html.span(class="mc-kicker", "Linked Documents"),
            if doc.links.is_empty() {
              @html.span(
                style=["font-size:0.75rem;color:var(--rui-muted-foreground)"],
                "None",
              )
            } else {
              @html.fragment(
                doc.links
                .iter()
                .map(target_id => {
                  let target = kb_document(target_id)
                  @html.button(
                    class="mc-out-item",
                    on_click=emit(KbDocChosen(target.id)),
                    [
                      @html.span(
                        class="mc-cut",
                        style=["font-size:0.75rem;font-weight:500"],
                        target.title,
                      ),
                    ],
                  )
                })
                .to_array(),
              )
            },
          ]),
          @html.div(style=["display:flex;flex-direction:column;gap:0.375rem"], [
            @html.span(class="mc-kicker", "Incoming Backlinks"),
            if incoming.is_empty() {
              @html.span(
                style=["font-size:0.75rem;color:var(--rui-muted-foreground)"],
                "None",
              )
            } else {
              @html.fragment(
                incoming
                .iter()
                .map(other => {
                  @html.button(
                    class="mc-out-item",
                    on_click=emit(KbDocChosen(other.id)),
                    [
                      @html.span(
                        class="mc-cut",
                        style=["font-size:0.75rem;font-weight:500"],
                        other.title,
                      ),
                    ],
                  )
                })
                .to_array(),
              )
            },
          ]),
          @html.div(style=["display:flex;flex-direction:column;gap:0.375rem"], [
            @html.span(class="mc-kicker", "Dictionary Terms"),
            @html.div(
              style=["display:flex;flex-wrap:wrap;gap:0.375rem"],
              doc.concepts
              .iter()
              .map(cid => {
                let card = ws.concept(cid).unwrap_or(default_concept_card())
                @html.button(
                  class="mc-chip-btn",
                  on_click=emit(OpenConceptInDictionary(cid)),
                  card.label.as_str(),
                )
              })
              .to_array(),
            ),
          ]),
        ],
      ),
    ]),
  ])
}