// Full-page Settings overlay with Project Workflow Presets, interactive
// Workflow Creation Studio preview, and Appearance controls.

///|
let settings_back_id : String = "settings-back"

///|
fn settings_overlay(
  model : Model,
  tab : SettingsTab,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let has_project = model.open_project() is Some(_)
  let project_name = match model.open_project() {
    Some(project) => project.title.to_string()
    None => "No open project"
  }
  let ws = model.active_mockup()
  let rail_item = (target : SettingsTab, label : String, badge : String) => {
    let active = tab == target
    @html.button(
      class=if active { "mc-set-nav active" } else { "mc-set-nav" },
      attrs=if active {
        @html.Attrs::build().aria_current("page")
      } else {
        @html.Attrs::build()
      },
      on_click=emit(SettingsTabChosen(target)),
      [
        @html.span(label),
        if badge.is_empty() {
          @html.nothing
        } else {
          @html.span(
            style=["font-family:var(--mc-mono);font-size:0.625rem;opacity:0.75"],
            badge,
          )
        },
      ],
    )
  }
  let mounts_badge = match model.active_workspace_value() {
    None => "—"
    Some(active_ws) =>
      match model.sources_load(active_ws.id) {
        Ready(loaded) => {
          let n = loaded.sources.length()
          if n == 1 {
            "1 source"
          } else {
            "\{n} sources"
          }
        }
        Loading => "Loading…"
        Failed(_) => "Error"
        Idle => "—"
      }
  }
  let body = match tab {
    Workflow => settings_workflow_tab(project_name, has_project~, ws, emit)
    Studio => settings_studio_tab(project_name, has_project~, ws, emit)
    Appearance => settings_appearance_tab(model, emit)
    Mounts => settings_mounts_tab(model, emit)
    Adapters | Scorecards | Perspectives =>
      settings_summary_tab(tab, project_name, ws)
  }
  @html.div(
    class="mc-settings-page",
    attrs=@html.Attrs::build().role("region").aria_label("Settings"),
    [
      @html.nav(
        class="mc-settings-rail",
        attrs=@html.Attrs::build().aria_label("Settings sections"),
        [
          @rui.button(
            id=settings_back_id,
            variant=Outline,
            size=Sm,
            style=["justify-content:flex-start;margin-bottom:0.5rem"],
            on_click=emit(CloseSettings),
            "<- Back to Workspace",
          ),
          @html.span(class="mc-kicker", "Project · \{project_name}"),
          rail_item(Workflow, "SDLC Workflow", "Presets"),
          rail_item(Studio, "Workflow Studio", "diagrams"),
          rail_item(Adapters, "Intent & SDD", "OpenSpec"),
          rail_item(
            Scorecards,
            "Scorecards & Rego",
            ">=\{ws.min_scorecard().value()}",
          ),
          rail_item(Mounts, "Mounts & Workspaces", mounts_badge),
          @html.span(
            class="mc-kicker",
            style=["margin-top:0.75rem"],
            "Application",
          ),
          rail_item(
            Appearance,
            "Appearance & Theme",
            model.color_scheme.label(),
          ),
          rail_item(Perspectives, "Perspectives & Keys", "1 · 2 · 3 · 4"),
        ],
      ),
      @html.div(class="mc-settings-main", body),
    ],
  )
}

///|
fn no_project_settings_notice(has_project : Bool) -> @html.Html {
  if has_project {
    @html.nothing
  } else {
    @html.div(
      class="mc-surface-card",
      style=[
        "padding:0.75rem 1rem;font-size:0.8125rem;color:var(--mc-wait-fg);border-color:var(--mc-wait)",
      ],
      "Open a project to change project workflow settings.",
    )
  }
}

///|
fn settings_workflow_tab(
  project_name : String,
  has_project~ : Bool,
  ws : MockupWorkspace,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let preset_cards = WorkflowPreset::all()
    .iter()
    .map(preset => {
      let selected = ws.preset() == preset
      @html.button(
        class=if selected { "mc-zen-card selected" } else { "mc-zen-card" },
        attrs=enabled_attrs(has_project).aria_pressed(selected.to_string()),
        on_click=emit(PresetChosen(preset)),
        [
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:center;gap:0.5rem;width:100%",
            ],
            [
              @html.strong(style=["font-size:0.8125rem"], preset.title()),
              @html.span(class="mc-pill-brand", preset.badge()),
            ],
          ),
          @html.div(
            style=[
              "font-size:0.75rem;color:var(--rui-muted-foreground);text-align:left;line-height:1.45",
            ],
            preset.summary(),
          ),
          @html.div(
            style=[
              "font-family:var(--mc-mono);font-size:0.625rem;color:var(--rui-muted-foreground)",
            ],
            preset.diagram_kind(),
          ),
        ],
      )
    })
    .to_array()
  let floor_buttons = [75, 85, 90]
    .iter()
    .map(score => {
      let locked = !has_project || score < ws.policy_floor().value()
      let active = ws.min_scorecard().value() == score
      @html.button(
        class=if active { "mc-seg-btn active" } else { "mc-seg-btn" },
        attrs=enabled_attrs(!locked).aria_pressed(active.to_string()),
        on_click=emit(MinScorecardChosen(Score::clamped(score))),
        "\{score}",
      )
    })
    .to_array()
  @html.div(
    style=[
      "display:flex;flex-direction:column;gap:1rem;max-width:76rem;width:100%",
    ],
    [
      no_project_settings_notice(has_project),
      @html.div(
        style=[
          "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.75rem",
        ],
        [
          @html.div([
            @html.h2(
              style=["margin:0;font-size:1.125rem;font-weight:700"],
              "SDLC Workflow & Canned Defaults — \{project_name}",
            ),
            @html.p(
              style=[text_style, "margin-top:0.25rem"],
              "Select a workflow preset or open Workflow Studio to edit stages and diagram source (local preview state).",
            ),
          ]),
          @rui.button(
            size=Sm,
            on_click=emit(SettingsTabChosen(Studio)),
            "Open Workflow Studio ->",
          ),
        ],
      ),
      @html.div(
        style=[
          "display:grid;grid-template-columns:repeat(auto-fit,minmax(17rem,1fr));gap:0.75rem",
        ],
        preset_cards,
      ),
      @html.div(class="mc-studio-split", style=["min-height:0;flex:0 0 auto"], [
        @html.div(
          class="mc-surface-card",
          style=[
            "padding:0.875rem 1rem;display:flex;flex-direction:column;gap:0.5rem",
          ],
          [
            @html.strong(
              style=["font-size:0.8125rem"],
              "Verify Gate Scorecard Floor",
            ),
            @html.p(
              style=[text_style, "font-size:0.75rem"],
              "Policy Root floor enforces Scorecard >= \{ws.policy_floor().value()} for this preview project.",
            ),
            @html.div(
              class="mc-seg",
              style=["align-self:flex-start"],
              floor_buttons,
            ),
          ],
        ),
        code_viewer(
          ws.config_yaml(),
          lang=Yaml,
          label="Effective project configuration YAML",
          copy_id="mc-copy-config-yaml",
        ),
      ]),
    ],
  )
}

///|
fn settings_studio_tab(
  project_name : String,
  has_project~ : Bool,
  ws : MockupWorkspace,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let stages = ws.stages()
  let sel_stage = ws.stage_spec(ws.studio_stage())
  let is_bpmn = ws.studio_diagram() == BpmnFlow
  let stage_chips = stages
    .iter()
    .map(st => {
      let active = st.id == sel_stage.id
      @html.button(
        class=if active { "mc-seg-btn active" } else { "mc-seg-btn" },
        attrs=enabled_attrs(has_project).aria_pressed(active.to_string()),
        on_click=emit(StudioStageChosen(st.id)),
        st.id.label(),
      )
    })
    .to_array()
  let extra_toggles = [
      ExtraArtifactInput::ThreatModel,
      DictionaryAudit,
      RunbookSignoff,
    ]
    .iter()
    .map(extra => {
      let active = ws.has_extra_input(sel_stage.id, extra)
      @html.button(
        class=if active { "mc-seg-btn active" } else { "mc-seg-btn" },
        attrs=enabled_attrs(has_project).aria_pressed(active.to_string()),
        on_click=emit(StudioExtraInputToggled(sel_stage.id, extra)),
        if active {
          "✓ \{extra.label()}"
        } else {
          "+ \{extra.label()}"
        },
      )
    })
    .to_array()
  let fmt_btn = (fmt : StudioFormat, label : String) => {
    let active = ws.studio_format() == fmt
    @html.button(
      class=if active { "mc-seg-btn active" } else { "mc-seg-btn" },
      attrs=enabled_attrs(has_project).aria_pressed(active.to_string()),
      on_click=emit(StudioFormatChosen(fmt)),
      label,
    )
  }
  @html.div(
    style=[
      "display:flex;flex-direction:column;gap:1rem;flex:1;min-height:100%;width:100%",
    ],
    [
      no_project_settings_notice(has_project),
      @html.div(
        style=[
          "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.75rem",
        ],
        [
          @html.div([
            @html.h2(
              style=["margin:0;font-size:1.125rem;font-weight:700"],
              "Workflow Studio — \{project_name}",
            ),
            @html.p(
              style=[text_style, "margin-top:0.25rem"],
              "Inspect and edit stage contracts, security gates, and Mermaid/BPMN/YAML source (moonrockz/diagrams.mbt preview).",
            ),
          ]),
          @html.div(
            style=["display:flex;align-items:center;gap:0.5rem;flex-wrap:wrap"],
            [
              match ws.studio_error() {
                Some(err) =>
                  @html.span(class="mc-pill-warn", "Invalid source · \{err}")
                None =>
                  @html.span(
                    class="mc-pill-good",
                    "Valid workflow · \{stages.length()} states · 0 errors",
                  )
              },
              @rui.button(
                variant=Outline,
                size=Sm,
                attrs=enabled_attrs(has_project).aria_pressed(
                  ws.has_security_gate().to_string(),
                ),
                on_click=emit(ToggleSecurityGate),
                if ws.has_security_gate() {
                  "Remove Security Gate"
                } else {
                  "+ Add Security Gate"
                },
              ),
              @html.div(
                class="mc-seg",
                attrs=@html.Attrs::build()
                  .role("group")
                  .aria_label("Studio diagram kind"),
                [
                  @html.button(
                    class=if !is_bpmn {
                      "mc-seg-btn active"
                    } else {
                      "mc-seg-btn"
                    },
                    attrs=enabled_attrs(has_project).aria_pressed(
                      (!is_bpmn).to_string(),
                    ),
                    on_click=emit(StudioDiagramChosen(MermaidState)),
                    "Mermaid",
                  ),
                  @html.button(
                    class=if is_bpmn {
                      "mc-seg-btn active"
                    } else {
                      "mc-seg-btn"
                    },
                    attrs=enabled_attrs(has_project).aria_pressed(
                      is_bpmn.to_string(),
                    ),
                    on_click=emit(StudioDiagramChosen(BpmnFlow)),
                    "BPMN 2.0",
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
      workflow_diagram_card(
        project_name,
        ws,
        is_bpmn~,
        mode=StudioMode(enabled=has_project),
        emit,
      ),
      @html.div(class="mc-studio-split", [
        @html.div(
          class="mc-surface-card",
          style=[
            "padding:0.875rem 1rem;display:flex;flex-direction:column;gap:0.75rem;min-width:0",
          ],
          [
            @html.div(
              style=[
                "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.5rem",
              ],
              [
                @html.strong("State Contract: \{sel_stage.id.label()}"),
                @html.div(class="mc-seg", stage_chips),
              ],
            ),
            @html.div(
              style=["display:flex;flex-direction:column;gap:0.375rem"],
              [
                @html.span(class="mc-kicker", "Required Input Artifacts"),
                @html.div(
                  style=["display:flex;flex-wrap:wrap;gap:0.375rem"],
                  sel_stage.inputs
                  .iter()
                  .map(x => @html.span(class="mc-chip-tag", x))
                  .to_array(),
                ),
                @html.div(
                  style=[
                    "display:flex;flex-wrap:wrap;gap:0.375rem;margin-top:0.25rem",
                  ],
                  extra_toggles,
                ),
              ],
            ),
            @html.div(
              style=["display:flex;flex-direction:column;gap:0.375rem"],
              [
                @html.span(class="mc-kicker", "Expected Output Artifacts"),
                @html.div(
                  style=["display:flex;flex-wrap:wrap;gap:0.375rem"],
                  sel_stage.outputs
                  .iter()
                  .map(x => @html.span(class="mc-chip-tag", x))
                  .to_array(),
                ),
              ],
            ),
          ],
        ),
        @html.div(
          class="mc-surface-card",
          style=[
            "display:flex;flex-direction:column;overflow:hidden;min-width:0",
          ],
          [
            @html.div(
              style=[
                "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.5rem;padding:0.5rem 0.75rem;border-bottom:1px solid var(--rui-border)",
              ],
              [
                @html.span(
                  style=["font-size:0.75rem;color:var(--rui-muted-foreground)"],
                  "Editable Diagram Source",
                ),
                @html.div(class="mc-seg", [
                  fmt_btn(Mermaid, "Mermaid"),
                  fmt_btn(BpmnXml, "BPMN XML"),
                  fmt_btn(ArtifactYaml, "Artifact YAML"),
                ]),
              ],
            ),
            studio_editor_host_view(editable=has_project),
          ],
        ),
      ]),
    ],
  )
}

///|

///|
extern "js" fn pick_brand_image_file(on_data : (String) -> Unit) -> Unit =
  #| (onData) => {
  #|   const input = document.createElement("input");
  #|   input.type = "file";
  #|   input.accept = "image/png,image/jpeg,image/webp,image/gif";
  #|   input.onchange = () => {
  #|     const file = input.files?.[0];
  #|     if (!file) return;
  #|     const reader = new FileReader();
  #|     reader.onload = () => {
  #|       if (typeof reader.result === "string") onData(reader.result);
  #|     };
  #|     reader.readAsDataURL(file);
  #|   };
  #|   input.click();
  #| }

///|
fn settings_appearance_tab(model : Model, emit : @cmd.Emit[Msg]) -> @html.Html {
  let scheme_btns = [ColorScheme::Moonrockz, Minimal, WarmEditorial]
    .iter()
    .map(scheme => {
      let active = model.color_scheme == scheme
      @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(ColorSchemeChosen(scheme)),
        scheme.label(),
      )
    })
    .to_array()
  let app_btns = [Appearance::System, Light, Dark]
    .iter()
    .map(appearance => {
      let active = model.appearance == appearance
      @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(AppearanceChosen(appearance)),
        appearance.label(),
      )
    })
    .to_array()
  let is_moonrockz = model.brand.mark is Moonrockz
  let is_monogram = model.brand.mark is Monogram(_)
  let is_emoji = model.brand.mark is Emoji(_)
  let is_custom_img = model.brand.mark is CustomImage(_)
  let upload_cmd = @cmd.custom_cmd(scheduler => {
    pick_brand_image_file(url => scheduler.add(emit(BrandImageSelected(url))))
  })
  let mark_detail = match model.brand.mark {
    Moonrockz => @html.nothing
    Monogram(mono) =>
      @html.div(
        style=[
          "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.75rem",
        ],
        [
          @html.span(
            style=["font-size:0.75rem;color:var(--rui-muted-foreground)"],
            "Monogram letters (1–3 characters)",
          ),
          @rui.input(
            value=mono.as_str(),
            placeholder="MC",
            attrs=@html.Attrs::build()
              .aria_label("Brand monogram")
              .spellcheck(false),
            style=[
              "width:6rem;font-family:var(--mc-mono);text-transform:uppercase",
            ],
            on_input=@cmd.Emit(text => emit(BrandMonogramChanged(text))),
          ),
        ],
      )
    Emoji(emoji) =>
      @html.div(
        style=[
          "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.75rem",
        ],
        [
          @html.span(
            style=["font-size:0.75rem;color:var(--rui-muted-foreground)"],
            "Emoji or short symbol",
          ),
          @rui.input(
            value=emoji.as_str(),
            placeholder="🚀",
            attrs=@html.Attrs::build().aria_label("Brand emoji"),
            style=["width:6rem"],
            on_input=@cmd.Emit(text => emit(BrandEmojiChanged(text))),
          ),
        ],
      )
    CustomImage(_) =>
      @html.div(
        style=[
          "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.75rem",
        ],
        [
          @html.span(
            style=["font-size:0.75rem;color:var(--rui-muted-foreground)"],
            "PNG, JPEG, WebP, or GIF image up to 96 KB.",
          ),
          @rui.button(
            variant=Outline,
            size=Sm,
            on_click=upload_cmd,
            "Choose another image…",
          ),
        ],
      )
  }
  let brand_error_node = match model.brand_error {
    Some(err) =>
      @html.p(
        class="mc-warning",
        style=["margin:0;font-size:0.75rem;font-weight:500"],
        err,
      )
    None => @html.nothing
  }
  @html.div(
    style=["display:flex;flex-direction:column;gap:1rem;max-width:44rem"],
    [
      @html.h2(
        style=["margin:0;font-size:1.125rem;font-weight:700"],
        "Appearance & Branding",
      ),
      @html.div(
        class="mc-surface-card",
        style=["padding:1rem;display:flex;flex-direction:column;gap:0.75rem"],
        [
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.75rem",
            ],
            [
              @html.div([
                @html.strong("Color Scheme"),
                @html.p(
                  style=[text_style, "font-size:0.75rem"],
                  "Kept in this browser for the next page.",
                ),
              ]),
              @html.div(class="mc-seg", scheme_btns),
            ],
          ),
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.75rem;padding-top:0.75rem;border-top:1px solid var(--rui-border)",
            ],
            [
              @html.div([
                @html.strong("Appearance"),
                @html.p(
                  style=[text_style, "font-size:0.75rem"],
                  "System follows the operating system light or dark setting.",
                ),
              ]),
              @html.div(class="mc-seg", app_btns),
            ],
          ),
        ],
      ),
      @html.div(
        class="mc-surface-card",
        style=["padding:1rem;display:flex;flex-direction:column;gap:0.875rem"],
        [
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.75rem",
            ],
            [
              @html.div(style=["display:flex;align-items:center;gap:0.5rem"], [
                brand_emblem(model.brand.mark),
                @html.div([
                  @html.strong("Brand Identity"),
                  @html.p(
                    style=[text_style, "font-size:0.75rem"],
                    "Personalize the sidebar emblem and title for this browser.",
                  ),
                ]),
              ]),
              if model.brand != BrandConfig::default() {
                @rui.button(
                  variant=Outline,
                  size=Sm,
                  on_click=emit(BrandReset),
                  "Reset to default",
                )
              } else {
                @html.nothing
              },
            ],
          ),
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.75rem;padding-top:0.75rem;border-top:1px solid var(--rui-border)",
            ],
            [
              @html.strong(style=["font-size:0.8125rem"], "Brand Mark"),
              @html.div(
                class="mc-seg",
                attrs=@html.Attrs::build()
                  .role("group")
                  .aria_label("Brand mark style"),
                [
                  @html.button(
                    class=if is_moonrockz {
                      "mc-seg-btn active"
                    } else {
                      "mc-seg-btn"
                    },
                    attrs=@html.Attrs::build().aria_pressed(
                      is_moonrockz.to_string(),
                    ),
                    on_click=emit(BrandMarkChosen(Moonrockz)),
                    "Moonrockz",
                  ),
                  @html.button(
                    class=if is_monogram {
                      "mc-seg-btn active"
                    } else {
                      "mc-seg-btn"
                    },
                    attrs=@html.Attrs::build().aria_pressed(
                      is_monogram.to_string(),
                    ),
                    on_click=emit(
                      BrandMarkChosen(Monogram(BrandMonogram::default())),
                    ),
                    "Monogram",
                  ),
                  @html.button(
                    class=if is_emoji {
                      "mc-seg-btn active"
                    } else {
                      "mc-seg-btn"
                    },
                    attrs=@html.Attrs::build().aria_pressed(
                      is_emoji.to_string(),
                    ),
                    on_click=emit(BrandMarkChosen(Emoji(BrandEmoji::default()))),
                    "Emoji",
                  ),
                  @html.button(
                    class=if is_custom_img {
                      "mc-seg-btn active"
                    } else {
                      "mc-seg-btn"
                    },
                    attrs=@html.Attrs::build().aria_pressed(
                      is_custom_img.to_string(),
                    ),
                    on_click=upload_cmd,
                    "Custom Image…",
                  ),
                ],
              ),
            ],
          ),
          mark_detail,
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.75rem;padding-top:0.75rem;border-top:1px solid var(--rui-border)",
            ],
            [
              @html.strong(style=["font-size:0.8125rem"], "Display Title"),
              @rui.input(
                value=model.brand.title.as_str(),
                placeholder="Mission Control",
                attrs=@html.Attrs::build().aria_label("Brand display title"),
                style=["width:14rem"],
                on_input=@cmd.Emit(text => emit(BrandTitleChanged(text))),
              ),
            ],
          ),
          brand_error_node,
        ],
      ),
    ],
  )
}

///|
fn trust_tier_label(tier : @app.TrustTier) -> String {
  match tier {
    ProjectMount => "Project"
    LocalMount => "Local"
    UserMount => "User"
    SystemMount => "System"
  }
}

///|
fn source_problem_summary(problem : @app.SourceProblem) -> (String, String) {
  match problem {
    ConfigReadFailed(origin~, reason~) =>
      (origin.to_string(), "Cannot read configuration file: \{reason}")
    ConfigParseFailed(origin~, reason~) =>
      (origin.to_string(), "Cannot parse configuration file: \{reason}")
    ConfigTooLarge(origin~) =>
      (
        origin.to_string(),
        "Configuration file exceeds the 1 MiB read size limit.",
      )
    InvalidMountName(origin~, name~, ..) =>
      (origin.to_string(), "Invalid mount name '\{name}'.")
  }
}

///|
let mount_example_toml : String =
  #|[workspace.mounts.shared-glossary]
  #|kind = "folder"
  #|role = "dictionary"
  #|path = "shared/glossary"
  #|access = "read-only"

///|
fn settings_mounts_tab(model : Model, emit : @cmd.Emit[Msg]) -> @html.Html {
  let active_ws = model.active_workspace_value()
  let header = @html.div(
    style=[
      "display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:0.75rem",
    ],
    [
      @html.div([
        @html.h2(
          style=["margin:0;font-size:1.125rem;font-weight:700"],
          "Mounts & Workspaces",
        ),
        match active_ws {
          Some(ws) =>
            @html.p(
              style=[text_style, "margin-top:0.25rem"],
              "Live in-tree discovery and configured mounts for \{workspace_primary_label(ws)} (\{ws.path}).",
            )
          None =>
            @html.p(
              style=[text_style, "margin-top:0.25rem"],
              "Open a project with an active workspace to inspect discovered sources and configured mounts.",
            )
        },
      ]),
      match active_ws {
        Some(_) =>
          @rui.button(
            variant=Outline,
            size=Sm,
            on_click=emit(SettingsTabChosen(Mounts)),
            "Refresh",
          )
        None => @html.nothing
      },
    ],
  )
  let content : @html.Html = match active_ws {
    None =>
      @html.div(
        class="mc-surface-card",
        style=[
          "padding:1rem;display:flex;flex-direction:column;gap:0.5rem;font-size:0.8125rem",
        ],
        [
          @html.strong("No open workspace"),
          @html.p(
            style=[text_style, "margin:0"],
            "Open a project from the sidebar to inspect its in-tree OpenSpec, OKF, and dictionary folders together with configured mounts.",
          ),
        ],
      )
    Some(ws) =>
      match model.sources_load(ws.id) {
        Idle | Loading =>
          @html.div(
            class="mc-surface-card",
            style=[
              "padding:1rem;font-size:0.8125rem;color:var(--rui-muted-foreground)",
            ],
            "Loading workspace sources…",
          )
        Failed(msg) =>
          @html.div(
            class="mc-surface-card",
            style=[
              "padding:1rem;display:flex;flex-direction:column;gap:0.5rem;border-color:var(--mc-wait)",
            ],
            [
              @html.strong(
                class="mc-warning",
                "Could not load workspace sources",
              ),
              @html.p(style=[text_style, "margin:0"], msg),
              @html.div([
                @rui.button(
                  variant=Outline,
                  size=Sm,
                  on_click=emit(SettingsTabChosen(Mounts)),
                  "Try again",
                ),
              ]),
            ],
          )
        Ready(ws_sources) => {
          let in_tree_items : Array[@app.InTreeSource] = []
          let mount_items : Array[@app.MountedSource] = []
          for src in ws_sources.sources {
            match src {
              InTree(it) => in_tree_items.push(it)
              Mounted(m) => mount_items.push(m)
            }
          }
          let problems_section : @html.Html = if ws_sources.problems.is_empty() {
            @html.nothing
          } else {
            let problem_rows = ws_sources.problems
              .iter()
              .map(p => {
                let (origin, detail) = source_problem_summary(p)
                @html.div(
                  style=[
                    "display:flex;flex-direction:column;gap:0.2rem;padding:0.5rem 0.625rem;border-radius:0.45rem;background:var(--mc-wait-surface);border:1px solid var(--mc-wait)",
                  ],
                  [
                    @html.span(
                      class="mc-warning",
                      style=["font-size:0.75rem;font-weight:600"],
                      detail,
                    ),
                    @html.span(
                      style=[
                        "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--rui-muted-foreground)",
                      ],
                      origin,
                    ),
                  ],
                )
              })
              .to_array()
            @html.div(
              class="mc-surface-card",
              style=[
                "padding:0.875rem 1rem;display:flex;flex-direction:column;gap:0.625rem;border-color:var(--mc-wait)",
              ],
              [
                @html.div(
                  style=[
                    "display:flex;align-items:center;justify-content:space-between;gap:0.5rem",
                  ],
                  [
                    @html.strong(
                      style=["font-size:0.8125rem"],
                      "Configuration Problems",
                    ),
                    @html.span(
                      class="mc-pill-warn",
                      "\{ws_sources.problems.length()} problem(s)",
                    ),
                  ],
                ),
                @html.div(
                  style=["display:flex;flex-direction:column;gap:0.45rem"],
                  problem_rows,
                ),
              ],
            )
          }
          let in_tree_body : @html.Html = if in_tree_items.is_empty() {
            @html.p(
              style=[text_style, "margin:0;font-size:0.75rem"],
              "No recognized in-tree sources discovered (`openspec/`, OKF `index.md`, or `.mission-control/dictionary/`).",
            )
          } else {
            let rows = in_tree_items
              .iter()
              .map(src => {
                let (status_class, status_label) = match src.status {
                  Available => ("mc-pill-good", "Available")
                  EscapesWorkspace => ("mc-pill-warn", "Escapes workspace")
                  Unavailable(reason) =>
                    ("mc-pill-warn", "Unavailable: \{reason}")
                }
                @html.div(
                  style=[
                    "display:flex;flex-direction:column;gap:0.35rem;padding:0.625rem 0.75rem;border-radius:0.5rem;background:var(--rui-background);border:1px solid var(--rui-border)",
                  ],
                  [
                    @html.div(
                      style=[
                        "display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:0.5rem",
                      ],
                      [
                        @html.div(
                          style=[
                            "display:flex;align-items:center;gap:0.4rem;flex-wrap:wrap",
                          ],
                          [
                            @html.strong(
                              style=["font-size:0.8125rem"],
                              src.name.to_string(),
                            ),
                            @html.span(
                              class="mc-chip-tag",
                              src.role.wire_name(),
                            ),
                            @html.span(
                              class="mc-chip-tag",
                              src.adapter.to_string(),
                            ),
                            @html.span(
                              class="mc-chip-tag",
                              src.access.wire_name(),
                            ),
                          ],
                        ),
                        @html.span(class=status_class, status_label),
                      ],
                    ),
                    @html.span(
                      style=[
                        "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--rui-muted-foreground);word-break:break-all",
                      ],
                      src.path,
                    ),
                  ],
                )
              })
              .to_array()
            @html.div(
              style=["display:flex;flex-direction:column;gap:0.5rem"],
              rows,
            )
          }
          let mounts_body : @html.Html = if mount_items.is_empty() {
            @html.div(style=["display:flex;flex-direction:column;gap:0.5rem"], [
              @html.p(
                style=[text_style, "margin:0;font-size:0.75rem"],
                "No configured mounts for this workspace. Add a mount in `mission-control.toml` to attach shared knowledge bases or dictionaries:",
              ),
              code_viewer(
                mount_example_toml,
                lang=Toml,
                label="Example mission-control.toml mount configuration",
                copy_id="mc-copy-mount-toml",
                compact=true,
              ),
            ])
          } else {
            let rows = mount_items
              .iter()
              .map(m => {
                match m {
                  Resolved(r) => {
                    let (status_class, status_label) = match r.status {
                      Available => ("mc-pill-good", "Available")
                      Missing => ("mc-pill-warn", "Missing")
                      Unavailable(reason) =>
                        ("mc-pill-warn", "Unavailable: \{reason}")
                    }
                    @html.div(
                      style=[
                        "display:flex;flex-direction:column;gap:0.35rem;padding:0.625rem 0.75rem;border-radius:0.5rem;background:var(--rui-background);border:1px solid var(--rui-border)",
                      ],
                      [
                        @html.div(
                          style=[
                            "display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:0.5rem",
                          ],
                          [
                            @html.div(
                              style=[
                                "display:flex;align-items:center;gap:0.4rem;flex-wrap:wrap",
                              ],
                              [
                                @html.strong(
                                  style=["font-size:0.8125rem"],
                                  r.name.to_string(),
                                ),
                                @html.span(
                                  class="mc-pill-brand",
                                  trust_tier_label(r.trust),
                                ),
                                @html.span(
                                  class="mc-chip-tag",
                                  r.role.wire_name(),
                                ),
                                @html.span(
                                  class="mc-chip-tag",
                                  r.access.wire_name(),
                                ),
                              ],
                            ),
                            @html.span(class=status_class, status_label),
                          ],
                        ),
                        @html.span(
                          style=[
                            "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--rui-foreground);word-break:break-all",
                          ],
                          r.resolved_path,
                        ),
                        @html.span(
                          style=[
                            "font-family:var(--mc-mono);font-size:0.65rem;color:var(--rui-muted-foreground);word-break:break-all",
                          ],
                          "Origin: \{r.origin}",
                        ),
                      ],
                    )
                  }
                  Refused(r) => {
                    let reason_text = r.reason.summary()
                    @html.div(
                      style=[
                        "display:flex;flex-direction:column;gap:0.35rem;padding:0.625rem 0.75rem;border-radius:0.5rem;background:var(--mc-wait-surface);border:1px solid var(--mc-wait)",
                      ],
                      [
                        @html.div(
                          style=[
                            "display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:0.5rem",
                          ],
                          [
                            @html.div(
                              style=[
                                "display:flex;align-items:center;gap:0.4rem;flex-wrap:wrap",
                              ],
                              [
                                @html.strong(
                                  style=["font-size:0.8125rem"],
                                  r.name.to_string(),
                                ),
                                @html.span(
                                  class="mc-pill-brand",
                                  trust_tier_label(r.trust),
                                ),
                                match r.role {
                                  Some(role) =>
                                    @html.span(
                                      class="mc-chip-tag",
                                      role.wire_name(),
                                    )
                                  None => @html.nothing
                                },
                              ],
                            ),
                            @html.span(class="mc-pill-warn", "Refused"),
                          ],
                        ),
                        @html.span(
                          class="mc-warning",
                          style=["font-size:0.75rem;font-weight:600"],
                          "Refused: \{reason_text}",
                        ),
                        match r.target {
                          Some(target) =>
                            @html.span(
                              style=[
                                "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--rui-muted-foreground);word-break:break-all",
                              ],
                              "Target: \{target}",
                            )
                          None => @html.nothing
                        },
                        @html.span(
                          style=[
                            "font-family:var(--mc-mono);font-size:0.65rem;color:var(--rui-muted-foreground);word-break:break-all",
                          ],
                          "Origin: \{r.origin}",
                        ),
                      ],
                    )
                  }
                }
              })
              .to_array()
            @html.div(
              style=["display:flex;flex-direction:column;gap:0.5rem"],
              rows,
            )
          }
          @html.div(style=["display:flex;flex-direction:column;gap:0.875rem"], [
            problems_section,
            @html.div(
              class="mc-surface-card",
              style=[
                "padding:0.875rem 1rem;display:flex;flex-direction:column;gap:0.625rem",
              ],
              [
                @html.div(
                  style=[
                    "display:flex;align-items:center;justify-content:space-between;gap:0.5rem",
                  ],
                  [
                    @html.strong(
                      style=["font-size:0.8125rem"],
                      "In-Tree Sources",
                    ),
                    @html.span(class="mc-chip-tag", "\{in_tree_items.length()}"),
                  ],
                ),
                in_tree_body,
              ],
            ),
            @html.div(
              class="mc-surface-card",
              style=[
                "padding:0.875rem 1rem;display:flex;flex-direction:column;gap:0.625rem",
              ],
              [
                @html.div(
                  style=[
                    "display:flex;align-items:center;justify-content:space-between;gap:0.5rem",
                  ],
                  [
                    @html.strong(
                      style=["font-size:0.8125rem"],
                      "Configured Mounts",
                    ),
                    @html.span(class="mc-chip-tag", "\{mount_items.length()}"),
                  ],
                ),
                mounts_body,
              ],
            ),
          ])
        }
      }
  }
  @html.div(
    style=[
      "display:flex;flex-direction:column;gap:1rem;max-width:76rem;width:100%",
    ],
    [header, content],
  )
}

///|
fn settings_summary_tab(
  tab : SettingsTab,
  project_name : String,
  ws : MockupWorkspace,
) -> @html.Html {
  let heading = match tab {
    Adapters => "Intent & SDD Adapter"
    Scorecards => "Scorecards & Rego"
    Perspectives => "Perspectives & Keyboard Shortcuts"
    Workflow | Studio | Mounts | Appearance => "Settings"
  }
  @html.div(
    style=["display:flex;flex-direction:column;gap:0.875rem;max-width:46rem"],
    [
      @html.h2(style=["margin:0;font-size:1.125rem;font-weight:700"], heading),
      @html.div(
        class="mc-surface-card",
        style=[
          "padding:1rem;display:flex;flex-direction:column;gap:0.5rem;font-size:0.8125rem",
        ],
        [
          @html.div("Project: \{project_name}"),
          @html.div("Active workflow preset: \{ws.preset().title()} (preview)"),
          @html.div("Verify Gate floor: Score >= \{ws.min_scorecard().value()}"),
          @html.div(
            "Shortcuts: 1 Plan · 2 Build · 3 Review · 4 Knowledge · Alt+Left/Right History · Ctrl/Cmd+K Palette · Ctrl/Cmd+B Sidebar · Esc Close overlay",
          ),
        ],
      ),
    ],
  )
}