// Unified adaptive shell top bar and the Plan, Build, Review, and Knowledge
// perspectives rendered over live `@app.Project` entries and isolated `MockupWorkspace` data.

///|
let perspective_panel_id : String = "mc-perspective-panel"

///|
fn Perspective::tab_id(self : Perspective) -> String {
  match self {
    Plan => "mc-tab-plan"
    Build => "mc-tab-build"
    Review => "mc-tab-review"
    Knowledge => "mc-tab-knowledge"
  }
}

///|
/// Computes the next perspective for WAI-ARIA tablist keyboard navigation.
fn Perspective::move_tab(self : Perspective, key : String) -> Perspective? {
  match key {
    "ArrowRight" =>
      Some(
        match self {
          Plan => Build
          Build => Review
          Review => Knowledge
          Knowledge => Plan
        },
      )
    "ArrowLeft" =>
      Some(
        match self {
          Plan => Knowledge
          Build => Plan
          Review => Build
          Knowledge => Review
        },
      )
    "Home" => Some(Plan)
    "End" => Some(Knowledge)
    _ => None
  }
}

///|
/// Deterministic DOM ID for the card, diagram chip, or pipeline row that opens
/// the floating gate inspector so focus returns cleanly when it closes.
fn workflow_item_trigger_id(
  perspective : Perspective,
  plan_view : PlanView,
  item_id : WorkflowItemId,
) -> String {
  let view_key = match perspective {
    Plan =>
      match plan_view {
        Board => "plan-board"
        StateMachine => "plan-state"
        Bpmn => "plan-bpmn"
      }
    Build => "build"
    Review => "review"
    Knowledge => "knowledge"
  }
  "mc-item-\{view_key}-\{item_id.key()}"
}

///|
fn grade_class(grade : Grade) -> String {
  match grade {
    A | B => "mc-grade mc-grade-good"
    C => "mc-grade mc-grade-warn"
    D | F => "mc-grade mc-grade-bad"
  }
}

///|
fn stage_accent(stage : StageId) -> String {
  match stage {
    Explore | Propose => "var(--mc-cobalt)"
    Implement => "var(--mc-brand)"
    SecurityGate | VerifyGate => "var(--mc-wait)"
    Archived => "var(--mc-good)"
  }
}

///|
/// The single invariant top bar of the adaptive shell.
fn shell_top_bar(
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  let back_btn = @rui.button(
    variant=Ghost,
    size=IconSm,
    title="\{NavigateBack.title()} (\{GoBack.text(mac~)})",
    attrs=action_attrs(NavigateBack, model)
      .aria_label(NavigateBack.title())
      .aria_keyshortcuts(GoBack.aria(mac~)),
    on_click=emit(ActionChosen(NavigateBack)),
    icon("M15 18l-6-6 6-6"),
  )
  let fwd_btn = @rui.button(
    variant=Ghost,
    size=IconSm,
    title="\{NavigateForward.title()} (\{GoForward.text(mac~)})",
    attrs=action_attrs(NavigateForward, model)
      .aria_label(NavigateForward.title())
      .aria_keyshortcuts(GoForward.aria(mac~)),
    on_click=emit(ActionChosen(NavigateForward)),
    icon("M9 18l6-6-6-6"),
  )
  let sidebar_toggle = match model.primary_sidebar {
    Shown => @html.nothing
    Hidden =>
      @html.span(
        class="mc-hidden-primary-sidebar",
        primary_sidebar_button(Shown, emit, mac~),
      )
  }
  let perspectives = if model.has_perspectives() {
    @html.div(
      class="mc-persp-switch",
      attrs=@html.Attrs::build()
        .role("tablist")
        .aria_label("Activity perspective"),
      [
        perspective_button(Plan, "1", model, emit, mac~),
        perspective_button(Build, "2", model, emit, mac~),
        perspective_button(Review, "3", model, emit, mac~),
        perspective_button(Knowledge, "4", model, emit, mac~),
      ],
    )
  } else {
    @html.nothing
  }
  let find_btn = match model.primary_sidebar {
    Shown => @html.nothing
    Hidden =>
      @rui.button(
        variant=Ghost,
        size=Sm,
        title="Find… (\{OpenPalette.text(mac~)})",
        attrs=@html.Attrs::build().aria_keyshortcuts(OpenPalette.aria(mac~)),
        on_click=emit(PaletteOpened),
        [
          icon("M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM16 16l4 4"),
          @html.span("Find…"),
        ],
      )
  }
  let appearance_glyph : Glyph = match model.appearance {
    System => Monitor
    Light => Sun
    Dark => Moon
  }
  let appearance_btn = @rui.button(
    variant=Ghost,
    size=IconSm,
    title="Appearance: \{model.appearance.label()} (click for \{model.appearance.next().label()})",
    attrs=@html.Attrs::build().aria_label(
      "Cycle appearance (current: \{model.appearance.label()})",
    ),
    on_click=emit(AppearanceCycled),
    glyph(appearance_glyph, size=Icon),
  )
  let settings_btn = @rui.button(
    variant=Ghost,
    size=Sm,
    title=OpenSettings.title(),
    attrs=action_attrs(OpenSettings, model).aria_label(OpenSettings.title()),
    on_click=emit(ActionChosen(OpenSettings)),
    [
      icon(
        "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09c-.66 0-1.25.4-1.51 1z",
      ),
      @html.span(class="mc-settings-label", "Settings"),
    ],
  )
  let crumb = match model.open_project() {
    Some(project) => {
      let ws = model.active_mockup()
      let (score_val, grade_str, grade_cls) = match model.active_live_sdlc() {
        Some(sdlc) if !sdlc.evaluations.is_empty() =>
          (
            sdlc.rollup_score,
            sdlc.rollup_grade,
            live_grade_class(sdlc.rollup_grade),
          )
        _ => {
          let sc = ws.rollup_score()
          let gr = sc.grade()
          (sc.value(), gr.label(), grade_class(gr))
        }
      }
      let title_text = project.title.to_string()
      let workspace_pill = match model.active_workspace_value() {
        Some(active_ws) => {
          let pill_glyph_class = match active_ws.position {
            OnLine(..) | Unborn(..) => "mc-tree-glyph mc-glyph-branch"
            Detached(..) => "mc-tree-glyph mc-glyph-warn"
            Unversioned => "mc-tree-glyph"
          }
          @html.span(
            class="mc-ws-pill",
            title="Active workspace: \{active_ws.name} — \{active_ws.path}",
            [
              @html.span(
                class=pill_glyph_class,
                position_glyph(active_ws.position, size=Sm),
              ),
              @html.span(class="mc-cut", workspace_primary_label(active_ws)),
            ],
          )
        }
        None => @html.nothing
      }
      @rui.button(
        variant=Ghost,
        size=Sm,
        title="Switch project or workspace (\{OpenPalette.text(mac~)})",
        attrs=@html.Attrs::build().aria_label(
          "Switch project or workspace \{title_text}",
        ),
        on_click=emit(PaletteOpened),
        style=[
          "display:flex;flex:0 1 auto;flex-shrink:1;align-items:center;gap:0.45rem;min-width:0;max-width:100%;overflow:hidden;padding-inline:0.45rem",
        ],
        [
          @html.span(
            class="mc-cut",
            style=[
              "flex:0 1 auto;min-width:0;font-size:0.8125rem;font-weight:600;color:var(--rui-foreground)",
            ],
            title_text,
          ),
          workspace_pill,
          if model.has_perspectives() {
            @html.span(
              class=grade_cls,
              title="Workspace rollup scorecard: Grade \{grade_str} (\{score_val}/100)",
              grade_str,
            )
          } else {
            @html.nothing
          },
        ],
      )
    }
    None => @html.nothing
  }
  @html.header(class="mc-shell-bar", [
    @html.div(class="mc-shell-bar-left", [
      sidebar_toggle, back_btn, fwd_btn, crumb,
    ]),
    @html.div(class="mc-shell-bar-persp", perspectives),
    @html.div(class="mc-shell-bar-right", [
      find_btn, appearance_btn, settings_btn,
    ]),
  ])
}

///|
fn perspective_button(
  perspective : Perspective,
  key : String,
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  let action = SetPerspective(perspective)
  let active = model.perspective == perspective
  @html.button(
    id=perspective.tab_id(),
    class=if active { "mc-persp-btn active" } else { "mc-persp-btn" },
    attrs=action_attrs(action, model)
      .role("tab")
      .aria_selected(active.to_string())
      .aria_controls(perspective_panel_id)
      .tabindex(if active { 0 } else { -1 })
      .aria_label(action.title())
      .aria_keyshortcuts(SwitchPerspective(perspective).aria(mac~))
      .on_keydown(event => {
        guard !event.is_composing() &&
          !event.ctrl_key() &&
          !event.alt_key() &&
          !event.meta_key() &&
          !event.shift_key() else {
          @cmd.none
        }
        match perspective.move_tab(event.key()) {
          Some(next) => {
            event.prevent_default()
            emit(PerspectiveTabMoved(next))
          }
          None => @cmd.none
        }
      }),
    on_click=emit(ActionChosen(action)),
    [
      @html.span(perspective.label()),
      @html.span(
        class="mc-persp-key",
        attrs=@html.Attrs::build().aria_hidden("true"),
        key,
      ),
    ],
  )
}

///|
/// Plain-English description of why a repository store is unavailable.
fn unavailable_reason_label(reason : @app.UnavailableReason) -> String {
  match reason {
    StoreMissing => "The repository store was not found on disk."
    BackendNotKnown(backend) =>
      "This build does not know the workspace backend '\{backend}'."
    ToolMissing => "The required VCS tool is not installed or not on PATH."
    TimedOut => "Inspecting the repository timed out."
    Failed(message) => message
  }
}

///|
/// Guided state shown when a repository project has zero attached workspaces (`Empty`).
fn empty_workspace_view(
  project : @app.Project,
  model : Model,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let remove = RemoveProject(project)
  let command_hint = if project.backend == @app.BackendId::git() {
    "git worktree add ../\{project.name}-worktree "
  } else {
    "Attach a checkout to this repository."
  }
  @html.div(
    style=[
      "flex:1;min-height:0;overflow:auto;padding:2rem 1.5rem;display:flex;justify-content:center;align-items:flex-start",
    ],
    [
      @html.div(
        class="mc-surface-card",
        style=[
          "max-width:36rem;width:100%;padding:1.5rem;display:flex;flex-direction:column;gap:0.875rem",
        ],
        [
          main_title(project.title.to_string()),
          @html.p(
            style=[text_style, "font-family:var(--mc-mono);font-size:0.75rem"],
            project.path,
          ),
          @html.p(
            style=[text_style],
            "This repository has no attached workspaces yet. Add an existing checkout folder or create a new Git worktree to open Plan, Build, Review, and Knowledge perspectives.",
          ),
          code_viewer(
            command_hint,
            lang=Shell,
            label="Git worktree creation command",
            copy_id="mc-copy-worktree-cmd",
            compact=true,
          ),
          @html.div(style=["display:flex;gap:0.5rem;flex-wrap:wrap"], [
            @rui.button(
              size=Sm,
              attrs=action_attrs(AddProject, model),
              on_click=emit(ActionChosen(AddProject)),
              AddProject.title(),
            ),
            @rui.button(
              variant=Outline,
              size=Sm,
              attrs=action_attrs(remove, model),
              on_click=emit(ActionChosen(remove)),
              remove.title(),
            ),
          ]),
        ],
      ),
    ],
  )
}

///|
/// Guided state shown when a repository store is unavailable (`Unavailable`).
fn unavailable_workspace_view(
  project : @app.Project,
  reason : @app.UnavailableReason,
  remembered : ReadOnlyArray[@app.RememberedWorkspace],
  model : Model,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let remove = RemoveProject(project)
  let remembered_list = if remembered.is_empty() {
    @html.nothing
  } else {
    @html.div(style=["display:flex;flex-direction:column;gap:0.375rem"], [
      @html.span(class="mc-kicker", "Remembered workspaces"),
      @html.fragment(
        remembered
        .iter()
        .map(ws => {
          @html.div(
            style=[
              "display:flex;flex-direction:column;gap:0.125rem;padding:0.5rem 0.625rem;border:1px solid var(--rui-border);border-radius:0.45rem",
            ],
            [
              @html.strong(style=["font-size:0.8125rem"], ws.name.to_string()),
              @html.span(
                style=[
                  "font-family:var(--mc-mono);font-size:0.75rem;color:var(--rui-muted-foreground)",
                ],
                ws.path,
              ),
            ],
          )
        })
        .to_array(),
      ),
    ])
  }
  @html.div(
    style=[
      "flex:1;min-height:0;overflow:auto;padding:2rem 1.5rem;display:flex;justify-content:center;align-items:flex-start",
    ],
    [
      @html.div(
        class="mc-surface-card",
        style=[
          "max-width:36rem;width:100%;padding:1.5rem;display:flex;flex-direction:column;gap:0.875rem",
        ],
        [
          main_title(project.title.to_string()),
          @html.p(
            class="mc-warning",
            style=["margin:0;font-size:0.875rem;font-weight:600"],
            "Workspaces unavailable",
          ),
          @html.p(style=[text_style], unavailable_reason_label(reason)),
          @html.p(
            style=[text_style, "font-family:var(--mc-mono);font-size:0.75rem"],
            project.path,
          ),
          remembered_list,
          @html.div(style=["display:flex;gap:0.5rem;flex-wrap:wrap"], [
            @rui.button(
              variant=Outline,
              size=Sm,
              attrs=action_attrs(remove, model),
              on_click=emit(ActionChosen(remove)),
              remove.title(),
            ),
          ]),
        ],
      ),
    ],
  )
}

///|
/// The adaptive shell canvas for an open live `@app.Project`.
fn shell_project_view(
  project : @app.Project,
  model : Model,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  match model.open_workspaces() {
    Some(Ready(Empty)) => return empty_workspace_view(project, model, emit)
    Some(Ready(Unavailable(reason~, remembered~))) =>
      return unavailable_workspace_view(
        project, reason, remembered, model, emit,
      )
    Some(Failed(message)) =>
      return unavailable_workspace_view(
        project,
        Failed(message),
        [],
        model,
        emit,
      )
    None | Some(Loading) | Some(Ready(Populated(_))) => ()
  }
  let ws = model.active_mockup()
  let active_ws = model.active_workspace_value()
  let display_path = match active_ws {
    Some(live) => live.path
    None => project.path
  }
  let effective_folder = match active_ws {
    Some(live) => live.folder
    None => project.folder
  }
  let remove = RemoveProject(project)
  let missing = match effective_folder {
    Missing =>
      @html.p(
        class="mc-warning",
        style=["margin:0;font-size:0.8125rem;line-height:1.25rem"],
        [
          @html.span(style=["font-weight:600"], folder_not_found),
          @html.span(
            ". Put the folder back at this path, or remove the project from the list.",
          ),
        ],
      )
    Present => @html.nothing
  }
  let project_strip = @html.div(class="mc-project-strip", [
    @html.div(
      style=[
        "display:flex;flex-direction:column;gap:0.125rem;min-width:0;flex:1",
      ],
      [
        @html.div(
          style=["display:flex;align-items:center;gap:0.5rem;flex-wrap:wrap"],
          [
            main_title(project.title.to_string()),
            match active_ws {
              Some(live) => {
                let pill_glyph_class = match live.position {
                  OnLine(..) | Unborn(..) => "mc-tree-glyph mc-glyph-branch"
                  Detached(..) => "mc-tree-glyph mc-glyph-warn"
                  Unversioned => "mc-tree-glyph"
                }
                @html.span(
                  class="mc-ws-pill",
                  title="Active workspace: \{live.name} — \{live.path}",
                  [
                    @html.span(
                      class=pill_glyph_class,
                      position_glyph(live.position, size=Sm),
                    ),
                    @html.span(class="mc-cut", workspace_primary_label(live)),
                  ],
                )
              }
              None => @html.nothing
            },
            @html.span(
              class=grade_class(ws.rollup_grade()),
              title="Preview workspace rollup scorecard",
              "Grade \{ws.rollup_grade().label()} · \{ws.rollup_score().value()}",
            ),
            @html.span(class="mc-pill-brand", ws.preset().title()),
            @html.span(
              class="mc-pill-warn",
              "Floor >= \{ws.min_scorecard().value()}",
            ),
          ],
        ),
        match project.caption {
          Some(caption) =>
            @html.p(
              style=[text_style, "font-size:0.8125rem"],
              caption.to_string(),
            )
          None => @html.nothing
        },
        @html.p(
          style=[
            text_style, "font-family:var(--mc-mono);font-size:0.75rem;overflow-wrap:anywhere;white-space:pre-wrap",
          ],
          display_path,
        ),
        missing,
      ],
    ),
    @html.div(
      style=[
        "display:flex;align-items:center;gap:0.5rem;flex-wrap:wrap;flex:none",
      ],
      Map([
        (
          "view-toggle",
          match model.perspective {
            Plan => plan_view_switch(model.plan_view, emit)
            Build =>
              @html.span(
                style=["font-size:0.75rem;color:var(--rui-muted-foreground)"],
                "Click any row to inspect gates",
              )
            Review => read_mode_switch(model.read_mode, emit)
            Knowledge => knowledge_view_switch(model.knowledge_view, emit)
          },
        ),
        (
          remove.id().key(),
          @rui.button(
            variant=Outline,
            size=Sm,
            attrs=action_attrs(remove, model),
            on_click=emit(ActionChosen(remove)),
            remove.title(),
          ),
        ),
      ]),
    ),
  ])
  let live_intent = model.active_live_intent()
  let body = match (model.perspective, live_intent) {
    (Plan, Some(intent)) =>
      live_plan_perspective(project, ws, intent, model, model.plan_view, emit)
    (Plan, None) => plan_perspective(project, ws, model.plan_view, emit)
    (Build, Some(intent)) => live_build_perspective(ws, intent, model, emit)
    (Build, None) => build_perspective(ws, emit)
    (Review, Some(intent)) =>
      live_review_perspective(model, intent, model.read_mode, emit)
    (Review, None) =>
      review_perspective(model, ws, model.review_doc, model.read_mode, emit)
    (Knowledge, _) => knowledge_perspective(model, ws, emit)
  }
  let inspector = if ws.inspector_open() &&
    model.perspective != Review &&
    model.perspective != Knowledge {
    floating_inspector(ws, emit)
  } else {
    @html.nothing
  }
  @html.div(
    style=[
      "display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:hidden",
    ],
    [
      project_strip,
      @html.div(
        id=perspective_panel_id,
        class="mc-perspective-stage",
        attrs=@html.Attrs::build()
          .role("tabpanel")
          .aria_labelledby(model.perspective.tab_id()),
        [body, inspector],
      ),
    ],
  )
}

///|
fn plan_view_switch(current : PlanView, emit : @cmd.Emit[Msg]) -> @html.Html {
  let item = (view : PlanView, label : String) => {
    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(PlanViewChosen(view)),
      label,
    )
  }
  @html.div(
    class="mc-seg",
    attrs=@html.Attrs::build().role("group").aria_label("Plan view"),
    [
      item(Board, "Board"),
      item(StateMachine, "State Machine"),
      item(Bpmn, "BPMN 2.0"),
    ],
  )
}

///|
fn read_mode_switch(current : ReadMode, emit : @cmd.Emit[Msg]) -> @html.Html {
  let item = (mode : ReadMode, label : String) => {
    let active = current == 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(ReadModeChosen(mode)),
      label,
    )
  }
  @html.div(
    class="mc-seg",
    attrs=@html.Attrs::build().role("group").aria_label("Reading mode"),
    [
      item(Structured, "Structured"),
      item(Preview, "Preview"),
      item(Source, "Source"),
    ],
  )
}

///|
/// Plan perspective: workflow stage board and full-width State Machine or BPMN
/// preview.
fn plan_perspective(
  project : @app.Project,
  ws : MockupWorkspace,
  view : PlanView,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let content = match view {
    Board => {
      let cols = ws
        .stages()
        .iter()
        .map(stage => {
          let cards = ws.items().filter(item => item.stage == stage.id)
          let out_hint = match stage.outputs.get(0) {
            Some(first) => "Out: \{first}"
            None => ""
          }
          @html.div(
            class="mc-zen-col",
            style=["--col-accent:\{stage_accent(stage.id)}"],
            [
              @html.div(
                style=[
                  "display:flex;justify-content:space-between;align-items:center;gap:0.375rem",
                ],
                [
                  @html.span(style=["font-size:0.8125rem;font-weight:650"], [
                    @html.text(stage.id.label()),
                    @html.span(
                      style=[
                        "margin-inline-start:0.375rem;color:var(--rui-muted-foreground);font-weight:500",
                      ],
                      "\{cards.length()}",
                    ),
                  ]),
                  if stage.id.is_gate() {
                    @html.span(class="mc-pill-warn", "Gate")
                  } else {
                    @html.nothing
                  },
                ],
              ),
              @html.div(
                style=["font-size:0.6875rem;color:var(--rui-muted-foreground)"],
                out_hint,
              ),
              @html.div(
                style=["display:flex;flex-direction:column;gap:0.5rem"],
                cards.iter().map(card => zen_card(card, ws, emit)).to_array(),
              ),
            ],
          )
        })
        .to_array()
      @html.div(class="mc-zen-board", cols)
    }
    StateMachine =>
      workflow_diagram_card(
        project.name,
        ws,
        is_bpmn=false,
        mode=PlanMode,
        emit,
      )
    Bpmn =>
      workflow_diagram_card(project.name, ws, is_bpmn=true, mode=PlanMode, emit)
  }
  @html.div(
    style=[
      "flex:1;min-height:0;overflow:auto;padding:1rem 1.25rem 1.5rem;display:flex;flex-direction:column;gap:1rem",
    ],
    content,
  )
}

///|
fn zen_card(
  card : WorkflowItem,
  ws : MockupWorkspace,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let eval = ws.evaluate_gates(card)
  let ready = eval.target is Some(_) && eval.all_passed()
  let clean_count = card.artifacts.iter().filter(a => a.status == Clean).count()
  let selected = card.id == ws.selected_item() && ws.inspector_open()
  let status_text = match eval.target {
    None => "Synced & archived"
    Some(next) =>
      if ready {
        "Ready -> \{next.label()}"
      } else {
        "\{eval.open_count()} gates open"
      }
  }
  let status_color = if card.stage == Archived {
    "var(--rui-muted-foreground)"
  } else if ready {
    "var(--mc-good-fg)"
  } else {
    "var(--mc-wait-fg)"
  }
  let kind_label = match card.kind {
    Change => "CHANGE"
    Intent => "INTENT"
  }
  let kind_color = match card.kind {
    Change => "var(--mc-cobalt)"
    Intent => "var(--mc-brand-fg)"
  }
  let segments = card.artifacts
    .iter()
    .map(art => {
      let cls = match art.status {
        Clean => "mc-seg-ok"
        Warning => "mc-seg-warn"
        Missing => "mc-seg-miss"
      }
      @html.span(class=cls, title="\{art.kind.label()}", @html.nothing)
    })
    .to_array()
  @html.button(
    id=workflow_item_trigger_id(Plan, Board, card.id),
    class=if selected { "mc-zen-card selected" } else { "mc-zen-card" },
    attrs=@html.Attrs::build().aria_expanded(selected.to_string()),
    on_click=emit(ItemSelected(card.id)),
    [
      @html.div(
        style=[
          "display:flex;justify-content:space-between;align-items:center;gap:0.375rem;width:100%",
        ],
        [
          @html.span(
            style=[
              "font-size:0.625rem;font-weight:700;letter-spacing:0.05em;color:\{kind_color}",
            ],
            "• \{kind_label}",
          ),
          @html.span(
            class=grade_class(card.grade()),
            "\{card.grade().label()} · \{card.score.value()}",
          ),
        ],
      ),
      @html.div(
        style=[
          "font-size:0.8125rem;font-weight:650;line-height:1.3;text-align:left",
        ],
        card.title,
      ),
      @html.div(
        style=[
          "font-size:0.6875rem;color:var(--rui-muted-foreground);text-align:left",
        ],
        card.intent,
      ),
      @html.div(class="mc-seg-bar", segments),
      @html.div(
        style=[
          "display:flex;justify-content:space-between;font-size:0.6875rem;color:var(--rui-muted-foreground);width:100%",
        ],
        [
          @html.span(
            "\{clean_count}/\{card.artifacts.length()} artifacts clean",
          ),
          if card.progress.total() > 0 {
            @html.span("\{card.progress.done()}/\{card.progress.total()} tasks")
          } else {
            @html.nothing
          },
        ],
      ),
      @html.div(
        style=[
          "display:flex;justify-content:space-between;align-items:center;padding-top:0.375rem;border-top:1px solid var(--rui-border);font-size:0.6875rem;width:100%",
        ],
        [
          @html.span(
            style=["font-weight:600;color:\{status_color}"],
            status_text,
          ),
          @html.span(
            style=["color:var(--rui-muted-foreground);font-size:0.625rem"],
            card.adapter.label(),
          ),
        ],
      ),
    ],
  )
}

///|
/// Controls whether `workflow_diagram_card` selects workflow items (Plan)
/// or stage contracts (Workflow Studio).
priv enum DiagramCardMode {
  PlanMode
  StudioMode(enabled~ : Bool)
}

///|
/// Interactive pure SVG State Machine / BPMN preview (previewing moonrockz/diagrams.mbt).
fn workflow_diagram_card(
  project_name : String,
  ws : MockupWorkspace,
  is_bpmn~ : Bool,
  mode~ : DiagramCardMode,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let stages = ws.stages()
  let active_item = ws.selected()
  let active_stage_id = match mode {
    PlanMode =>
      match active_item {
        Some(item) => item.stage
        None => Explore
      }
    StudioMode(..) => ws.studio_stage()
  }
  let count = stages.length()
  let step_x = if count > 1 { 820 / count } else { 200 }
  let svg_children : Array[@svg.Svg] = []
  if is_bpmn {
    svg_children.push(
      @svg.rect(
        x=12,
        y=12,
        width=936,
        height=216,
        rx=10,
        fill="none",
        stroke="var(--rui-border)",
        attrs=@svg.Attrs::build().stroke_dasharray("5 4"),
      ),
    )
    svg_children.push(
      @svg.svg_text(
        x=24,
        y=30,
        text="LANE: \{project_name} · \{ws.preset().id()}",
        fill="var(--rui-muted-foreground)",
        attrs=@svg.Attrs::build().font_size("10"),
      ),
    )
  }
  svg_children.push(
    @svg.circle(
      cx=28,
      cy=120,
      r=if is_bpmn { 9 } else { 7 },
      fill=if is_bpmn { "var(--rui-card)" } else { "var(--mc-brand)" },
      stroke=if is_bpmn { "var(--mc-good)" } else { "none" },
      stroke_width=2,
    ),
  )
  for idx = 0; idx < count; idx = idx + 1 {
    let stage = stages[idx]
    let cx = 96 + idx * step_x
    let items_in = ws.items().iter().filter(i => i.stage == stage.id).count()
    let has_active = active_stage_id == stage.id
    let stroke = if has_active {
      "var(--mc-brand)"
    } else {
      stage_accent(stage.id)
    }
    let fill = if has_active {
      "var(--mc-brand-surface)"
    } else {
      "var(--rui-background)"
    }
    if idx == 0 {
      svg_children.push(
        @svg.line(
          x1=37,
          y1=120,
          x2=cx - 56,
          y2=120,
          stroke="var(--mc-cobalt)",
          stroke_width=2,
        ),
      )
    }
    if idx < count - 1 {
      let next_cx = 96 + (idx + 1) * step_x
      let start_x = cx + (if is_bpmn && stage.id.is_gate() { 40 } else { 54 })
      let end_x = next_cx -
        (if is_bpmn && stages[idx + 1].id.is_gate() { 42 } else { 56 })
      svg_children.push(
        @svg.line(
          x1=start_x,
          y1=120,
          x2=end_x,
          y2=120,
          stroke="var(--mc-cobalt)",
          stroke_width=2,
        ),
      )
    }
    if stage.id.is_gate() && idx > 0 {
      let prev_cx = 96 + (idx - 1) * step_x
      svg_children.push(
        @svg.path(
          d="M \{cx} 156 C \{cx} 202, \{prev_cx} 202, \{prev_cx} 156",
          fill="none",
          stroke="var(--mc-wait)",
          stroke_width=2,
          attrs=@svg.Attrs::build().stroke_dasharray("4 3"),
        ),
      )
      svg_children.push(
        @svg.svg_text(
          x=(cx + prev_cx) / 2,
          y=204,
          text="gate_failed (Score < \{ws.min_scorecard().value()})",
          fill="var(--mc-wait-fg)",
          attrs=@svg.Attrs::build().font_size("10").text_anchor("middle"),
        ),
      )
    }
    if is_bpmn && stage.id.is_gate() {
      svg_children.push(
        @svg.polygon(
          points=[(cx, 84), (cx + 42, 120), (cx, 156), (cx - 42, 120)],
          fill~,
          stroke~,
          stroke_width=if has_active { 3 } else { 2 },
        ),
      )
      svg_children.push(
        @svg.svg_text(
          x=cx,
          y=116,
          text="×",
          fill="var(--mc-wait-fg)",
          attrs=@svg.Attrs::build()
            .font_size("13")
            .font_weight("700")
            .text_anchor("middle"),
        ),
      )
      svg_children.push(
        @svg.svg_text(
          x=cx,
          y=132,
          text="\{stage.id.label()} (\{items_in})",
          fill="var(--rui-foreground)",
          attrs=@svg.Attrs::build().font_size("10").text_anchor("middle"),
        ),
      )
    } else {
      svg_children.push(
        @svg.rect(
          x=cx - 54,
          y=88,
          width=108,
          height=64,
          rx=if is_bpmn { 6 } else { 12 },
          fill~,
          stroke~,
          stroke_width=if has_active { 3 } else { 2 },
        ),
      )
      svg_children.push(
        @svg.svg_text(
          x=cx,
          y=114,
          text=stage.id.label(),
          fill="var(--rui-foreground)",
          attrs=@svg.Attrs::build()
            .font_size("11")
            .font_weight("700")
            .text_anchor("middle"),
        ),
      )
      svg_children.push(
        @svg.svg_text(
          x=cx,
          y=132,
          text="\{items_in} item(s) · \{stage.outputs.length()} out",
          fill="var(--rui-muted-foreground)",
          attrs=@svg.Attrs::build().font_size("10").text_anchor("middle"),
        ),
      )
    }
  }
  let stage_buttons = stages
    .iter()
    .map(stage => {
      let count_in = ws.items().iter().filter(i => i.stage == stage.id).count()
      match mode {
        PlanMode =>
          match ws.items().iter().find_first(i => i.stage == stage.id) {
            Some(item) => {
              let diagram_view : PlanView = if is_bpmn {
                Bpmn
              } else {
                StateMachine
              }
              let is_selected = item.id == ws.selected_item() &&
                ws.inspector_open()
              @html.button(
                id=workflow_item_trigger_id(Plan, diagram_view, item.id),
                class="mc-chip-btn",
                attrs=@html.Attrs::build().aria_expanded(
                  is_selected.to_string(),
                ),
                on_click=emit(ItemSelected(item.id)),
                "\{stage.id.label()} (\{count_in})",
              )
            }
            None =>
              @html.span(
                class="mc-chip-tag",
                style=["opacity:0.65"],
                "\{stage.id.label()} (0)",
              )
          }
        StudioMode(enabled~) => {
          let is_selected = ws.studio_stage() == stage.id
          @html.button(
            class=if is_selected { "mc-chip-btn active" } else { "mc-chip-btn" },
            attrs=enabled_attrs(enabled).aria_pressed(is_selected.to_string()),
            on_click=if enabled {
              emit(StudioStageChosen(stage.id))
            } else {
              @cmd.none
            },
            "\{stage.id.label()} (\{count_in})",
          )
        }
      }
    })
    .to_array()
  let active_stage = ws.stage_spec(active_stage_id)
  let active_label = match mode {
    PlanMode =>
      match active_item {
        Some(item) => "Active: \{item.title} (\{item.stage.label()})"
        None => "Active: none"
      }
    StudioMode(..) => "Editing stage: \{ws.studio_stage().label()}"
  }
  @html.div(style=["display:flex;flex-direction:column;gap:0.875rem"], [
    @html.div(class="mc-surface-card", [
      @html.div(
        style=[
          "display:flex;justify-content:space-between;align-items:center;padding:0.625rem 0.875rem;border-bottom:1px solid var(--rui-border);font-size:0.75rem;flex-wrap:wrap;gap:0.5rem",
        ],
        [
          @html.div(style=["display:flex;align-items:center;gap:0.5rem"], [
            @html.strong("moonrockz/diagrams.mbt preview"),
            @html.span(
              style=["color:var(--rui-muted-foreground)"],
              if is_bpmn {
                "moonrockz/bpmn + diagrams-svg"
              } else {
                "diagrams-mermaid + diagrams-svg"
              },
            ),
          ]),
          @html.span(
            style=["color:var(--mc-brand-fg);font-weight:600"],
            active_label,
          ),
        ],
      ),
      @svg.svg(
        view_box="0 0 960 236",
        style=["width:100%;height:15rem;display:block"],
        svg_children,
      ),
      @html.div(
        style=[
          "display:flex;flex-wrap:wrap;gap:0.375rem;padding:0.625rem 0.875rem;border-top:1px solid var(--rui-border)",
        ],
        stage_buttons,
      ),
    ]),
    @html.div(
      style=[
        "display:grid;grid-template-columns:repeat(auto-fit,minmax(16rem,1fr));gap:0.75rem",
      ],
      [
        @html.div(
          class="mc-surface-card",
          style=[
            "padding:0.875rem 1rem;display:flex;flex-direction:column;gap:0.375rem",
          ],
          [
            @html.span(
              class="mc-kicker",
              "State Contract: \{active_stage.id.label()} — Required Inputs",
            ),
            @html.fragment(
              active_stage.inputs
              .iter()
              .map(inp => @html.div(style=["font-size:0.8125rem"], "• \{inp}"))
              .to_array(),
            ),
          ],
        ),
        @html.div(
          class="mc-surface-card",
          style=[
            "padding:0.875rem 1rem;display:flex;flex-direction:column;gap:0.375rem",
          ],
          [
            @html.span(
              class="mc-kicker",
              "State Contract: \{active_stage.id.label()} — Expected Outputs",
            ),
            @html.fragment(
              active_stage.outputs
              .iter()
              .map(out => @html.div(style=["font-size:0.8125rem"], "• \{out}"))
              .to_array(),
            ),
          ],
        ),
      ],
    ),
  ])
}

///|
/// Build perspective: grouped delivery pipeline list.
fn build_perspective(ws : MockupWorkspace, emit : @cmd.Emit[Msg]) -> @html.Html {
  let in_flight = ws.items().iter().filter(i => i.stage != Archived).count()
  let groups = ws
    .stages()
    .iter()
    .map(stage => {
      let stage_items = ws.items().filter(i => i.stage == stage.id)
      let outs = stage.outputs.iter().to_array().join(", ")
      @html.div(style=["display:flex;flex-direction:column;gap:0.375rem"], [
        @html.div(
          style=[
            "display:flex;justify-content:space-between;align-items:center;gap:0.5rem;padding:0.125rem 0.25rem;font-size:0.75rem",
          ],
          [
            @html.div(style=["display:flex;align-items:center;gap:0.5rem"], [
              @html.span(
                style=[
                  "width:0.5rem;height:0.5rem;border-radius:50%;background:\{stage_accent(stage.id)};display:inline-block",
                ],
                @html.nothing,
              ),
              @html.strong(stage.id.label()),
              @html.span(
                style=["color:var(--rui-muted-foreground)"],
                "\{stage_items.length()}",
              ),
            ]),
            @html.span(
              style=["font-size:0.6875rem;color:var(--rui-muted-foreground)"],
              "out: \{outs}",
            ),
          ],
        ),
        @html.div(
          style=["display:flex;flex-direction:column;gap:0.375rem"],
          stage_items
          .iter()
          .map(item => {
            let eval = ws.evaluate_gates(item)
            let ready = eval.target is Some(_) && eval.all_passed()
            let clean = item.artifacts
              .iter()
              .filter(a => a.status == Clean)
              .count()
            let selected = item.id == ws.selected_item() && ws.inspector_open()
            let kind = match item.kind {
              Change => "CHG"
              Intent => "INT"
            }
            let status_text = match eval.target {
              None => "Archived"
              Some(next) =>
                if ready {
                  "Ready -> \{next.label()}"
                } else {
                  "\{eval.open_count()} gates open"
                }
            }
            let status_color = if item.stage == Archived {
              "var(--rui-muted-foreground)"
            } else if ready {
              "var(--mc-good-fg)"
            } else {
              "var(--mc-wait-fg)"
            }
            @html.button(
              id=workflow_item_trigger_id(Build, Board, item.id),
              class=if selected {
                "mc-pipe-row selected"
              } else {
                "mc-pipe-row"
              },
              attrs=@html.Attrs::build().aria_expanded(selected.to_string()),
              on_click=emit(ItemSelected(item.id)),
              [
                @html.span(
                  style=[
                    "width:0.45rem;height:0.45rem;border-radius:50%;background:\{if ready || item.stage == Archived { "var(--mc-good)" } else { "var(--mc-wait)" }}",
                  ],
                  @html.nothing,
                ),
                @html.span(
                  style=[
                    "font-family:var(--mc-mono);font-size:0.625rem;color:var(--rui-muted-foreground)",
                  ],
                  kind,
                ),
                @html.span(
                  class="mc-cut mc-pipe-title",
                  style=["font-weight:600;font-size:0.8125rem;text-align:left"],
                  item.title,
                ),
                @html.span(
                  class="mc-cut mc-pipe-intent",
                  style=[
                    "font-size:0.75rem;color:var(--rui-muted-foreground);text-align:left",
                  ],
                  item.intent,
                ),
                @html.span(
                  class="mc-pipe-meta",
                  style=[
                    "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--rui-muted-foreground)",
                  ],
                  "\{clean}/\{item.artifacts.length()} art",
                ),
                @html.span(
                  class=grade_class(item.grade()),
                  item.grade().label(),
                ),
                @html.span(
                  class="mc-pipe-status",
                  style=[
                    "font-size:0.75rem;font-weight:600;text-align:right;color:\{status_color}",
                  ],
                  status_text,
                ),
              ],
            )
          })
          .to_array(),
        ),
      ])
    })
    .to_array()
  @html.div(
    style=[
      "flex:1;min-height:0;overflow:auto;padding:1rem 1.5rem 2rem;display:flex;flex-direction:column;gap:1rem",
    ],
    [
      @html.div(
        style=[
          "display:flex;justify-content:space-between;align-items:center;font-size:0.75rem;color:var(--rui-muted-foreground);flex-wrap:wrap;gap:0.5rem",
        ],
        [
          @html.span(
            "\{in_flight} in flight · \{ws.items().length() - in_flight} archived · Verify floor: Score >= \{ws.min_scorecard().value()}",
          ),
          @rui.button(
            variant=Outline,
            size=Sm,
            on_click=emit(ActionChosen(SetPerspective(Review))),
            "Open Reading Packet ->",
          ),
        ],
      ),
      @html.fragment(groups),
    ],
  )
}

///|
/// Renders shared prose spans with inline clickable dictionary terms.
fn render_prose_spans_with(
  spans : ReadOnlyArray[ProseSpan],
  on_term : (ConceptId) -> @cmd.Cmd,
) -> Array[@html.Html] {
  spans
  .iter()
  .map(span => {
    match span {
      Plain(text) => @html.text(text)
      Keyword(kw) => @html.span(class="mc-ears-kw", kw)
      Term(concept, label, deprecated~) =>
        @html.button(
          class=if deprecated {
            "mc-dict-term deprecated"
          } else {
            "mc-dict-term"
          },
          on_click=on_term(concept),
          label,
        )
    }
  })
  .to_array()
}

///|
/// Renders shared prose spans in Review, selecting terms in Concept Peek.
fn render_prose_spans(
  spans : ReadOnlyArray[ProseSpan],
  emit : @cmd.Emit[Msg],
) -> Array[@html.Html] {
  render_prose_spans_with(spans, concept => emit(ConceptSelected(concept)))
}

///|
/// Review perspective: reading packet outline, 68ch document reader, and
/// Reading Companion.
fn review_perspective(
  model : Model,
  ws : MockupWorkspace,
  active_doc_id : ReviewDocId,
  read_mode : ReadMode,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  guard ws.selected() is Some(active_item) else { @html.nothing }
  let docs = ws.docs()
  let doc = match ws.doc(active_doc_id) {
    Some(found) => found
    None =>
      match docs.get(0) {
        Some(first) => first
        None => return @html.nothing
      }
  }
  let fixed = active_item.warnings.is_zero()
  let read_count = docs.iter().filter(d => d.read).count()
  let concept = ws
    .concept(ws.active_concept())
    .unwrap_or(default_concept_card())
  let content = doc_content(doc.id, active_item)
  let eval = ws.evaluate_gates(active_item)
  let can_approve = eval.target is Some(_) && eval.all_passed()
  let can_send_back = ws.stage_spec(active_item.stage).back is Some(_)
  let outline_rows = docs
    .iter()
    .map(d => {
      let sc = d.score
      let gr = sc.grade()
      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(ReviewDocChosen(d.id)),
        [
          @html.span(
            class=if d.read { "mc-out-num read" } else { "mc-out-num" },
            if d.read {
              "✓"
            } else {
              "\{d.step.value()}"
            },
          ),
          @html.span(
            style=[
              "display:flex;flex-direction:column;gap:0.125rem;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(
                style=["font-size:0.625rem;color:var(--rui-muted-foreground)"],
                "\{d.kind.label()} · \{gr.label()} (\{sc.value()})",
              ),
            ],
          ),
        ],
      )
    })
    .to_array()

  let doc_body = match read_mode {
    Source =>
      code_viewer(
        content.source_lines.iter().join("\n"),
        lang=Markdown,
        label="Line-numbered document source",
        copy_id="mc-copy-review-source",
        fill=true,
      )
    Preview =>
      @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)",
          ],
          content.summary,
        ),
        @html.fragment(
          content.preview_paragraphs
          .iter()
          .map(spans => {
            @html.p(
              style=[
                "margin:0;font-size:0.9375rem;line-height:1.8;color:var(--rui-foreground)",
              ],
              render_prose_spans(spans, emit),
            )
          })
          .to_array(),
        ),
      ])
    Structured =>
      match doc.id {
        Spec =>
          @html.div(style=["display:flex;flex-direction:column;gap:0.875rem"], [
            @html.p(
              style=[
                "margin:0;font-size:0.875rem;line-height:1.7;color:var(--rui-foreground)",
              ],
              "This document belongs to \{active_item.title} (\{active_item.intent}). Select any underlined Data Dictionary term to inspect its RDF definition in the Reading Companion.",
            ),
            @html.fragment(
              content.clauses
              .iter()
              .map(clause => {
                let block_class = match (clause.finding, clause.change) {
                  (DeprecatedTermOpen, _) => "mc-delta-block warn"
                  (_, Added) => "mc-delta-block added"
                  (_, Modified(..)) => "mc-delta-block"
                }
                let heading_color = match (clause.finding, clause.change) {
                  (DeprecatedTermOpen, _) => "var(--mc-wait-fg)"
                  (_, Added) => "var(--mc-good-fg)"
                  (_, Modified(..)) => "var(--mc-cobalt)"
                }
                let body_node = match clause.change {
                  Modified(previous~) =>
                    @html.fragment([
                      @html.div(class="mc-diff-old", previous),
                      @html.div(
                        class="mc-diff-new",
                        render_prose_spans(clause.spans, emit),
                      ),
                    ])
                  Added =>
                    @html.p(
                      style=["margin:0;font-size:0.875rem;line-height:1.65"],
                      render_prose_spans(clause.spans, emit),
                    )
                }
                @html.div(class=block_class, [
                  @html.div(
                    style=[
                      "display:flex;justify-content:space-between;font-family:var(--mc-mono);font-size:0.6875rem",
                    ],
                    [
                      @html.strong(
                        style=["color:\{heading_color}"],
                        "\{clause.change.label()} · \{clause.id}",
                      ),
                      @html.span(
                        style=["color:var(--rui-muted-foreground)"],
                        clause.ears_kind.label(),
                      ),
                    ],
                  ),
                  body_node,
                  match clause.finding {
                    DeprecatedTermResolved =>
                      @html.div(
                        style=[
                          "font-size:0.75rem;font-weight:600;color:var(--mc-good-fg)",
                        ],
                        "✓ Normalized & Rego passing — live state updated across Plan and Build.",
                      )
                    DeprecatedTermOpen =>
                      @html.div(
                        style=["font-size:0.75rem;color:var(--mc-wait-fg)"],
                        "! \{active_item.warnings.count()} findings blocking Verify Gate — normalize CC# in the Reading Companion.",
                      )
                    NoFinding => @html.nothing
                  },
                ])
              })
              .to_array(),
            ),
          ])
        Proposal | Design | Adr | Kb | Tasks =>
          @html.div(style=["display:flex;flex-direction:column;gap:0.875rem"], [
            @html.div(
              class="mc-surface-card",
              style=[
                "padding:0.75rem 1rem;display:flex;justify-content:space-between;align-items:center;gap:0.5rem;flex-wrap:wrap;font-size:0.75rem",
              ],
              [
                @html.strong("\{doc.kind.label()} · \{active_item.title}"),
                @html.span(
                  class=grade_class(doc.score.grade()),
                  "Grade \{doc.score.grade().label()} · \{doc.score.value()}",
                ),
              ],
            ),
            @html.p(
              style=[
                "margin:0;font-size:0.875rem;line-height:1.7;color:var(--rui-muted-foreground)",
              ],
              content.summary,
            ),
            @html.fragment(
              content.preview_paragraphs
              .iter()
              .mapi((idx, spans) => {
                @html.div(class="mc-delta-block added", [
                  @html.span(
                    style=[
                      "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--mc-cobalt)",
                    ],
                    "SECTION \{idx + 1}",
                  ),
                  @html.p(
                    style=[
                      "margin:0;font-size:0.875rem;line-height:1.65;color:var(--rui-foreground)",
                    ],
                    render_prose_spans(spans, emit),
                  ),
                ])
              })
              .to_array(),
            ),
          ])
      }
  }

  let companion_body = match ws.review_tab() {
    ConceptPeek =>
      @html.div(style=["display:flex;flex-direction:column;gap:0.625rem"], [
        @html.span(class="mc-kicker", "RDF Data Dictionary Peek"),
        @html.div(
          class="mc-surface-card",
          style=[
            "padding:0.75rem;display:flex;flex-direction:column;gap:0.375rem",
          ],
          [
            @html.div(
              style=[
                "display:flex;justify-content:space-between;align-items:center;gap:0.5rem",
              ],
              [
                @html.strong(
                  style=["font-size:0.8125rem"],
                  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(
              style=[
                "font-family:var(--mc-mono);font-size:0.625rem;color:var(--mc-cobalt);overflow-wrap:anywhere",
              ],
              "<\{concept.iri.as_str()}>",
            ),
            @html.p(
              style=[
                "margin:0;font-size:0.75rem;line-height:1.5;color:var(--rui-foreground)",
              ],
              concept.definition.as_str(),
            ),
            @html.div(
              style=["font-size:0.6875rem;color:var(--rui-muted-foreground)"],
              "Graph: \{concept.graph_display()}",
            ),
            @html.div(
              style=["font-size:0.6875rem;color:var(--rui-muted-foreground)"],
              "SHACL: \{concept.shacl}",
            ),
            if concept.is_deprecated() && !fixed {
              @rui.button(
                size=Sm,
                on_click=emit(NormalizeDeprecatedTerm),
                "Normalize CC# -> Credit Card Number",
              )
            } else {
              @html.nothing
            },
            @rui.button(
              variant=Outline,
              size=Sm,
              on_click=emit(OpenConceptInDictionary(concept.id)),
              "Open in Dictionary",
            ),
          ],
        ),
      ])
    ScoreReview =>
      @html.div(style=["display:flex;flex-direction:column;gap:0.625rem"], [
        @html.span(class="mc-kicker", "Packet Scorecard & Gates"),
        @html.div(
          style=[
            "display:flex;justify-content:space-between;align-items:center",
          ],
          [
            @html.strong("Scorecard"),
            @html.span(
              class=grade_class(active_item.grade()),
              "Grade \{active_item.grade().label()} · \{active_item.score.value()}/100",
            ),
          ],
        ),
        @html.div(
          style=["display:flex;flex-direction:column;gap:0.375rem"],
          eval.checks
          .iter()
          .map(check => {
            @html.div(
              class=if check.passed {
                "mc-gate-row pass"
              } else {
                "mc-gate-row fail"
              },
              [
                @html.strong(
                  style=[
                    "color:\{if check.passed { "var(--mc-good-fg)" } else { "var(--mc-wait-fg)" }}",
                  ],
                  if check.passed {
                    "✓"
                  } else {
                    "!"
                  },
                ),
                @html.span(check.label),
              ],
            )
          })
          .to_array(),
        ),
      ])
  }

  let decision_text = match ws.review_decision().banner() {
    Some(text) => text
    None =>
      if can_approve {
        "Ready to Approve"
      } else if eval.target is None {
        "Terminal Stage"
      } else {
        "Blocked"
      }
  }

  @html.div(class="mc-review-grid", [
    secondary_sidebar_shell(
      model,
      title="Reading packet",
      count="\{read_count}/\{docs.length()} read",
      emit,
      [@html.strong(style=["font-size:0.8125rem"], active_item.title)],
      [
        @html.div(
          style=[
            "flex:1;overflow:auto;padding:0.5rem;display:flex;flex-direction:column;gap:0.25rem",
          ],
          outline_rows,
        ),
      ],
    ),
    @html.div(
      class=if read_mode is Source {
        "mc-review-canvas code-mode"
      } else {
        "mc-review-canvas"
      },
      @html.article(
        style=if read_mode is Source {
          [
            "width:100%;flex:1;min-height:100%;display:flex;flex-direction:column;gap:0.875rem",
          ]
        } else {
          [
            "max-width:42rem;margin:0 auto;display:flex;flex-direction:column;gap:1rem",
          ]
        },
        [
          @html.div(
            style=[
              "display:flex;justify-content:space-between;align-items:center;gap:0.5rem;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"],
                [
                  @html.span(
                    style=[
                      "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--rui-muted-foreground)",
                    ],
                    "Step \{doc.step.value()} of \{docs.length()} · \{doc.file}",
                  ),
                  @html.h2(
                    style=["margin:0;font-size:1.25rem;font-weight:700"],
                    doc.title,
                  ),
                ],
              ),
              @rui.button(
                variant=Outline,
                size=Sm,
                attrs=@html.Attrs::build().aria_pressed(doc.read.to_string()),
                on_click=emit(ToggleDocRead(doc.id)),
                if doc.read {
                  "✓ Marked as Read"
                } else {
                  "Mark as Read"
                },
              ),
            ],
          ),
          if ws.review_tab() == ConceptPeek {
            @html.div(
              class="mc-surface-card mc-mobile-peek",
              style=["padding:0.75rem"],
              [
                @html.div(
                  style=[
                    "display:flex;justify-content:space-between;align-items:center;gap:0.5rem",
                  ],
                  [
                    @html.span(
                      class="mc-kicker",
                      "Concept Peek · \{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.p(
                  style=[
                    "margin:0;font-size:0.75rem;line-height:1.5;color:var(--rui-foreground)",
                  ],
                  concept.definition.as_str(),
                ),
                @html.span(
                  style=[
                    "font-family:var(--mc-mono);font-size:0.6875rem;color:var(--rui-muted-foreground)",
                  ],
                  "\{concept.graph_display()} · \{concept.shacl}",
                ),
                @rui.button(
                  variant=Outline,
                  size=Sm,
                  on_click=emit(OpenConceptInDictionary(concept.id)),
                  "Open in Dictionary",
                ),
              ],
            )
          } else {
            @html.nothing
          },
          doc_body,
        ],
      ),
    ),
    companion_panel_shell(model, title="Reading companion", emit, [
      @html.div(
        style=[
          "display:flex;align-items:center;border-bottom:1px solid var(--rui-border);padding:0.375rem 0.5rem 0;gap:0.25rem",
        ],
        [
          @html.div(
            style=["display:flex;flex:1;gap:0.25rem;min-width:0"],
            attrs=@html.Attrs::build()
              .role("tablist")
              .aria_label("Reading companion"),
            [
              @html.button(
                class=if ws.review_tab() == ConceptPeek {
                  "mc-tab-btn active"
                } else {
                  "mc-tab-btn"
                },
                attrs=@html.Attrs::build()
                  .role("tab")
                  .aria_selected((ws.review_tab() == ConceptPeek).to_string()),
                on_click=emit(ReviewTabChosen(ConceptPeek)),
                "Concept Peek",
              ),
              @html.button(
                class=if ws.review_tab() == ScoreReview {
                  "mc-tab-btn active"
                } else {
                  "mc-tab-btn"
                },
                attrs=@html.Attrs::build()
                  .role("tab")
                  .aria_selected((ws.review_tab() == ScoreReview).to_string()),
                on_click=emit(ReviewTabChosen(ScoreReview)),
                "Score & Review",
              ),
            ],
          ),
          companion_collapse_button(title="Reading companion", emit),
        ],
      ),
      @html.div(style=["flex:1;overflow:auto;padding:0.75rem"], companion_body),
      @html.div(
        style=[
          "padding:0.75rem;border-top:1px solid var(--rui-border);display:flex;flex-direction:column;gap:0.5rem",
        ],
        [
          @html.div(
            style=[
              "display:flex;justify-content:space-between;font-size:0.6875rem",
            ],
            [
              @html.span(
                style=["color:var(--rui-muted-foreground)"],
                "Verify Gate (\{active_item.score.value()}/\{ws.min_scorecard().value()})",
              ),
              @html.strong(
                style=[
                  "color:\{if can_approve { "var(--mc-good-fg)" } else { "var(--mc-wait-fg)" }}",
                ],
                decision_text,
              ),
            ],
          ),
          @html.div(style=["display:flex;gap:0.375rem"], [
            @rui.button(
              size=Sm,
              attrs=enabled_attrs(can_approve),
              style=["flex:1"],
              on_click=emit(ReviewApproved),
              "Approve ->",
            ),
            @rui.button(
              variant=Outline,
              size=Sm,
              attrs=enabled_attrs(can_send_back),
              style=["flex:1"],
              on_click=emit(ReviewRequestedChanges),
              "Request Changes",
            ),
          ]),
        ],
      ),
    ]),
  ])
}

///|
/// On-demand floating Gate Inspector sheet shown in Plan and Build perspectives.
fn floating_inspector(
  ws : MockupWorkspace,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  guard ws.selected() is Some(item) else { @html.nothing }
  let stage = ws.stage_spec(item.stage)
  let eval = ws.evaluate_gates(item)
  let all_passed = eval.all_passed()
  @html.aside(
    class="mc-float-sheet",
    attrs=@html.Attrs::build().aria_label("Transition gate inspector"),
    [
      @html.div(
        style=[
          "padding:0.75rem 0.875rem;border-bottom:1px solid var(--rui-border);display:flex;justify-content:space-between;align-items:flex-start;gap:0.5rem",
        ],
        [
          @html.div(style=["display:flex;flex-direction:column;gap:0.25rem"], [
            @html.div(style=["display:flex;align-items:center;gap:0.375rem"], [
              @html.span(
                class=grade_class(item.grade()),
                "Grade \{item.grade().label()} · \{item.score.value()}",
              ),
              @html.span(
                style=["font-size:0.6875rem;color:var(--rui-muted-foreground)"],
                stage.id.label(),
              ),
            ]),
            @html.strong(style=["font-size:0.875rem"], item.title),
          ]),
          @rui.button(
            variant=Ghost,
            size=IconSm,
            attrs=@html.Attrs::build().aria_label("Close gate inspector"),
            on_click=emit(CloseInspector),
            icon("M6 6l12 12M18 6L6 18"),
          ),
        ],
      ),
      @html.div(
        style=[
          "flex:1;overflow:auto;padding:0.75rem 0.875rem;display:flex;flex-direction:column;gap:0.75rem",
        ],
        [
          @html.div(
            class="mc-surface-card",
            style=[
              "padding:0.625rem 0.75rem;font-size:0.75rem;display:flex;flex-direction:column;gap:0.25rem",
            ],
            [
              @html.div(
                "Required In: \{stage.inputs.iter().to_array().join(" · ")}",
              ),
              @html.div(
                "Expected Out: \{stage.outputs.iter().to_array().join(" · ")}",
              ),
            ],
          ),
          @html.div(style=["display:flex;flex-direction:column;gap:0.375rem"], [
            @html.span(
              class="mc-kicker",
              match eval.target {
                Some(next) => "Transition Gates -> \{next.label()}"
                None => "Terminal State"
              },
            ),
            @html.fragment(
              eval.checks
              .iter()
              .map(check => {
                @html.div(
                  class=if check.passed {
                    "mc-gate-row pass"
                  } else {
                    "mc-gate-row fail"
                  },
                  [
                    @html.strong(
                      style=[
                        "color:\{if check.passed { "var(--mc-good-fg)" } else { "var(--mc-wait-fg)" }}",
                      ],
                      if check.passed {
                        "✓"
                      } else {
                        "!"
                      },
                    ),
                    @html.div(
                      style=["display:flex;flex-direction:column;gap:0.125rem"],
                      [
                        @html.span(check.label),
                        @html.span(
                          style=[
                            "font-size:0.625rem;color:var(--rui-muted-foreground)",
                          ],
                          check.source.label(),
                        ),
                      ],
                    ),
                  ],
                )
              })
              .to_array(),
            ),
          ]),
        ],
      ),
      @html.div(
        style=[
          "padding:0.75rem 0.875rem;border-top:1px solid var(--rui-border);display:flex;flex-direction:column;gap:0.5rem",
        ],
        [
          @rui.button(
            variant=Outline,
            size=Sm,
            on_click=emit(ActionChosen(SetPerspective(Review))),
            "Open Reading & Review Packet ->",
          ),
          if !all_passed && eval.target is Some(_) {
            @rui.button(
              variant=Outline,
              size=Sm,
              on_click=emit(ResolveOpenGates(item.id)),
              "Simulate Resolving Open Gates",
            )
          } else {
            @html.nothing
          },
          @html.div(style=["display:flex;gap:0.5rem"], [
            match stage.back {
              Some(prev) =>
                @rui.button(
                  variant=Outline,
                  size=Sm,
                  style=["flex:1"],
                  on_click=emit(SendBackWorkflowItem(item.id)),
                  "<- \{prev.label()}",
                )
              None => @html.nothing
            },
            match eval.target {
              Some(next) =>
                @rui.button(
                  size=Sm,
                  style=["flex:1.4"],
                  attrs=enabled_attrs(all_passed),
                  on_click=emit(AdvanceWorkflowItem(item.id)),
                  "Advance -> \{next.label()}",
                )
              None => @html.nothing
            },
          ]),
        ],
      ),
    ],
  )
}