// Pure domain types for the unified adaptive shell: activity perspectives,
// view modes, bounded numeric values, color schemes, appearance overrides,
// settings sections, and bounded immutable navigation history.

///|
/// An activity-tuned perspective over the open project.
#derive(Eq, Debug)
pub(all) enum Perspective {
  /// Full-width workflow board and state-machine/BPMN diagrams.
  Plan
  /// Grouped delivery pipeline list with slide-over gate inspector.
  Build
  /// Editorial reader with inline concept peek and sign-off.
  Review
  /// Data Dictionary (RDF/SKOS/SHACL) and Knowledge Base workbench.
  Knowledge
}

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

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

///|
/// Returns the display label of a perspective.
pub fn Perspective::label(self : Perspective) -> String {
  match self {
    Plan => "Plan"
    Build => "Build"
    Review => "Review"
    Knowledge => "Knowledge"
  }
}

///|
/// Active sub-view inside the Knowledge perspective.
#derive(Eq, Debug)
pub(all) enum KnowledgeView {
  Dictionary
  KnowledgeBase
}

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

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

///|
/// Returns the display label of a Knowledge sub-view.
pub fn KnowledgeView::label(self : KnowledgeView) -> String {
  match self {
    Dictionary => "Data Dictionary"
    KnowledgeBase => "Knowledge Base"
  }
}

///|
/// Display format for one Data Dictionary concept in Knowledge.
#derive(Eq, Debug)
pub(all) enum DictFormat {
  DictStructured
  DictTurtle
  DictJsonLd
}

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

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

///|
/// Returns the display label of a dictionary serialization format.
pub fn DictFormat::label(self : DictFormat) -> String {
  match self {
    DictStructured => "Structured"
    DictTurtle => "Turtle"
    DictJsonLd => "JSON-LD"
  }
}

///|
/// Whether a named graph is mounted read-only or writable in the workspace.
#derive(Eq, Debug)
pub(all) enum GraphAccess {
  ReadOnly
  LocalWritable
}

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

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

///|
/// Returns the display label of a graph access mode.
pub fn GraphAccess::label(self : GraphAccess) -> String {
  match self {
    ReadOnly => "Read-only"
    LocalWritable => "Local writable"
  }
}

///|
/// Concrete RDF named graph owning a dictionary concept.
#derive(Eq, Debug)
pub(all) enum NamedGraph {
  MountedPci
  LocalPayments
}

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

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

///|
/// Returns the short display label of a concrete named graph.
pub fn NamedGraph::label(self : NamedGraph) -> String {
  match self {
    MountedPci => "Mounted PCI (RO)"
    LocalPayments => "Local Payments"
  }
}

///|
/// Returns the full URN and description of a concrete named graph.
pub fn NamedGraph::uri_label(self : NamedGraph) -> String {
  match self {
    MountedPci => " · PCI Restricted"
    LocalPayments => " · Local Turtle"
  }
}

///|
/// Returns the access policy derived from a concrete named graph.
pub fn NamedGraph::access(self : NamedGraph) -> GraphAccess {
  match self {
    MountedPci => ReadOnly
    LocalPayments => LocalWritable
  }
}

///|
/// Named graph filter inside the Data Dictionary view.
#derive(Eq, Debug)
pub(all) enum NamedGraphFilter {
  AllGraphs
  Graph(NamedGraph)
}

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

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

///|
/// Returns the display label of a named graph filter chip.
pub fn NamedGraphFilter::label(self : NamedGraphFilter) -> String {
  match self {
    AllGraphs => "All Graphs"
    Graph(graph) => graph.label()
  }
}

///|
/// Reports whether this filter includes `graph`.
pub fn NamedGraphFilter::matches(
  self : NamedGraphFilter,
  graph : NamedGraph,
) -> Bool {
  match self {
    AllGraphs => true
    Graph(target) => target == graph
  }
}

///|
/// Concrete storage origin of a Knowledge Base document.
#derive(Eq, Debug)
pub(all) enum KbSource {
  LocalOkf
  MountedRo
}

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

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

///|
/// Returns the display label of a concrete Knowledge Base source.
pub fn KbSource::label(self : KbSource) -> String {
  match self {
    LocalOkf => "Local OKF"
    MountedRo => "Mounted RO"
  }
}

///|
/// Source filter inside the Knowledge Base browser.
#derive(Eq, Debug)
pub(all) enum KbSourceFilter {
  AllKbSources
  Source(KbSource)
}

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

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

///|
/// Returns the display label of a Knowledge Base source filter chip.
pub fn KbSourceFilter::label(self : KbSourceFilter) -> String {
  match self {
    AllKbSources => "All Sources"
    Source(source) => source.label()
  }
}

///|
/// Reports whether this filter includes `source`.
pub fn KbSourceFilter::matches(
  self : KbSourceFilter,
  source : KbSource,
) -> Bool {
  match self {
    AllKbSources => true
    Source(target) => target == source
  }
}

///|
/// Reading mode for a Knowledge Base document.
#derive(Eq, Debug)
pub(all) enum KbReadMode {
  KbPreview
  KbSource
}

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

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

///|
/// Returns the display label of a Knowledge Base reading mode.
pub fn KbReadMode::label(self : KbReadMode) -> String {
  match self {
    KbPreview => "Preview"
    KbSource => "Source"
  }
}

///|
/// Error returned when a local concept sequence identifier is not positive.
#derive(Eq, Debug)
pub suberror LocalConceptIdError {
  NonPositive(Int32)
}

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

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

///|
/// A validated positive 1-based identifier for a user-authored local concept.
#derive(Eq, Debug)
pub struct LocalConceptId {
  priv value : Int32
}

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

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

///|
/// Constructs a `LocalConceptId` when `value >= 1`.
pub fn LocalConceptId::LocalConceptId(
  value : Int32,
) -> LocalConceptId raise LocalConceptIdError {
  if value < 1 {
    raise NonPositive(value)
  }
  { value, }
}

///|
/// Returns the positive integer sequence value of a local concept identifier.
pub fn LocalConceptId::value(self : LocalConceptId) -> Int32 {
  self.value
}

///|
/// Error returned when text is not a valid SKOS concept label.
#derive(Eq, Debug)
pub suberror ConceptLabelError {
  Empty
  TooLong(Int32)
  ContainsControlChar(String)
}

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

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

///|
/// A validated preferred label for a local SKOS concept (1..=60 printable chars).
#derive(Eq, Debug)
pub struct ConceptLabel {
  priv text : String
}

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

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

///|
/// Parses a trimmed SKOS concept label of 1 to 60 printable characters.
pub fn ConceptLabel::ConceptLabel(
  raw : String,
) -> ConceptLabel raise ConceptLabelError {
  let trimmed = raw.trim().to_owned()
  let count = trimmed.iter().count()
  if count < 1 {
    raise Empty
  }
  if has_control_char(trimmed) {
    raise ContainsControlChar(trimmed)
  }
  if count > 60 {
    raise TooLong(count)
  }
  { text: trimmed, }
}

///|
/// Returns the validated concept label text.
pub fn ConceptLabel::as_str(self : ConceptLabel) -> String {
  self.text
}

///|
/// Error returned when text is not a valid SKOS concept definition.
#derive(Eq, Debug)
pub suberror ConceptDefinitionError {
  Empty
  TooLong(Int32)
  ContainsControlChar(String)
}

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

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

///|
/// A validated definition for a local SKOS concept (1..=240 printable chars).
#derive(Eq, Debug)
pub struct ConceptDefinition {
  priv text : String
}

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

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

///|
/// Parses a trimmed SKOS concept definition of 1 to 240 printable characters.
pub fn ConceptDefinition::ConceptDefinition(
  raw : String,
) -> ConceptDefinition raise ConceptDefinitionError {
  let trimmed = raw.trim().to_owned()
  let count = trimmed.iter().count()
  if count < 1 {
    raise Empty
  }
  if has_control_char(trimmed) {
    raise ContainsControlChar(trimmed)
  }
  if count > 240 {
    raise TooLong(count)
  }
  { text: trimmed, }
}

///|
/// Returns the validated concept definition text.
pub fn ConceptDefinition::as_str(self : ConceptDefinition) -> String {
  self.text
}

///|
/// The view inside the Plan perspective.
#derive(Eq, Debug)
pub(all) enum PlanView {
  Board
  StateMachine
  Bpmn
}

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

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

///|
/// The reading mode of a document inside the Review perspective.
#derive(Eq, Debug)
pub(all) enum ReadMode {
  Structured
  Preview
  Source
}

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

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

///|
/// Identifier of a workflow item in the local preview workspace.
#derive(Eq, Debug)
pub(all) enum WorkflowItemId {
  ChgMask
  ChgRefund
  Int3ds
  IntBmad
  ChgVault
}

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

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

///|
/// Returns the stable machine key of a workflow item identifier.
pub fn WorkflowItemId::key(self : WorkflowItemId) -> String {
  match self {
    ChgMask => "chg-mask"
    ChgRefund => "chg-refund"
    Int3ds => "int-3ds"
    IntBmad => "int-bmad"
    ChgVault => "chg-vault"
  }
}

///|
/// Identifier of a document in the Review reading packet.
#derive(Eq, Debug)
pub(all) enum ReviewDocId {
  Proposal
  Design
  Spec
  Adr
  Kb
  Tasks
}

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

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

///|
/// Returns the stable machine key of a reading packet document identifier.
pub fn ReviewDocId::key(self : ReviewDocId) -> String {
  match self {
    Proposal => "proposal"
    Design => "design"
    Spec => "spec"
    Adr => "adr"
    Kb => "kb"
    Tasks => "tasks"
  }
}

///|
/// Letter grade derived from a bounded scorecard `Score`.
#derive(Eq, Debug)
pub(all) enum Grade {
  A
  B
  C
  D
  F
}

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

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

///|
/// Returns the single-letter display text of a grade.
pub fn Grade::label(self : Grade) -> String {
  match self {
    A => "A"
    B => "B"
    C => "C"
    D => "D"
    F => "F"
  }
}

///|
/// Error returned when a raw integer is outside the valid scorecard score range
/// of 0 through 100.
#derive(Eq, Debug)
pub suberror ScoreError {
  BelowZero(Int32)
  AboveMax(Int32)
}

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

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

///|
/// A bounded scorecard score between 0 and 100 inclusive.
#derive(Eq, Debug)
pub struct Score {
  priv value : Int32
}

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

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

///|
/// Constructs a `Score` when `value` is between 0 and 100 inclusive.
pub fn Score::Score(value : Int32) -> Score raise ScoreError {
  if value < 0 {
    raise BelowZero(value)
  }
  if value > 100 {
    raise AboveMax(value)
  }
  { value, }
}

///|
/// Returns a valid `Score` clamped into the 0..=100 range.
pub fn Score::clamped(value : Int32) -> Score {
  let bounded = if value < 0 { 0 } else if value > 100 { 100 } else { value }
  { value: bounded, }
}

///|
/// Returns the numeric score value between 0 and 100.
pub fn Score::value(self : Score) -> Int32 {
  self.value
}

///|
/// Computes the letter grade for this score.
pub fn Score::grade(self : Score) -> Grade {
  if self.value >= 90 {
    A
  } else if self.value >= 80 {
    B
  } else if self.value >= 70 {
    C
  } else if self.value >= 60 {
    D
  } else {
    F
  }
}

///|
/// Error returned when task progress counts violate `0 <= done <= total`.
#derive(Eq, Debug)
pub suberror TaskProgressError {
  NegativeDone(Int32)
  NegativeTotal(Int32)
  DoneExceedsTotal(Int32, Int32)
}

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

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

///|
/// Validated task completion progress where `0 <= done <= total`.
#derive(Eq, Debug)
pub struct TaskProgress {
  priv done : Int32
  priv total : Int32
}

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

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

///|
/// Constructs a `TaskProgress` when `0 <= done <= total`.
pub fn TaskProgress::TaskProgress(
  done : Int32,
  total : Int32,
) -> TaskProgress raise TaskProgressError {
  if done < 0 {
    raise NegativeDone(done)
  }
  if total < 0 {
    raise NegativeTotal(total)
  }
  if done > total {
    raise DoneExceedsTotal(done, total)
  }
  { done, total, }
}

///|
/// Returns the number of completed tasks.
pub fn TaskProgress::done(self : TaskProgress) -> Int32 {
  self.done
}

///|
/// Returns the total number of tasks.
pub fn TaskProgress::total(self : TaskProgress) -> Int32 {
  self.total
}

///|
/// Reports whether at least one task exists and all tasks are complete.
pub fn TaskProgress::is_complete(self : TaskProgress) -> Bool {
  self.total > 0 && self.done == self.total
}

///|
/// Returns a new `TaskProgress` with all tasks marked complete.
pub fn TaskProgress::complete_all(self : TaskProgress) -> TaskProgress {
  { done: self.total, total: self.total, }
}

///|
/// Error returned when a warning count is negative.
#derive(Eq, Debug)
pub suberror WarningCountError {
  Negative(Int32)
}

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

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

///|
/// A non-negative count of validation warnings.
#derive(Eq, Debug)
pub struct WarningCount {
  priv count : Int32
}

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

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

///|
/// Constructs a `WarningCount` when `count >= 0`.
pub fn WarningCount::WarningCount(
  count : Int32,
) -> WarningCount raise WarningCountError {
  if count < 0 {
    raise Negative(count)
  }
  { count, }
}

///|
/// Returns a zero warning count.
pub fn WarningCount::zero() -> WarningCount {
  { count: 0, }
}

///|
/// Returns the numeric warning count.
pub fn WarningCount::count(self : WarningCount) -> Int32 {
  self.count
}

///|
/// Reports whether there are zero warnings.
pub fn WarningCount::is_zero(self : WarningCount) -> Bool {
  self.count == 0
}

///|
/// Error returned when a reading packet step number is not positive.
#derive(Eq, Debug)
pub suberror StepNumberError {
  NonPositive(Int32)
}

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

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

///|
/// A positive 1-based step number in a reading packet.
#derive(Eq, Debug)
pub struct StepNumber {
  priv value : Int32
}

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

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

///|
/// Constructs a `StepNumber` when `value >= 1`.
pub fn StepNumber::StepNumber(
  value : Int32,
) -> StepNumber raise StepNumberError {
  if value < 1 {
    raise NonPositive(value)
  }
  { value, }
}

///|
/// Returns the positive step number value.
pub fn StepNumber::value(self : StepNumber) -> Int32 {
  self.value
}

///|
/// Error returned when text is not a valid RDF concept IRI.
#derive(Eq, Debug)
pub suberror ConceptIriError {
  Empty
  ContainsWhitespace(String)
  MissingScheme(String)
}

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

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

///|
/// A validated RDF concept IRI with a supported URI scheme and no whitespace.
#derive(Eq, Debug)
pub struct ConceptIri {
  priv value : String
}

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

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

///|
/// Parses a concept IRI, rejecting empty text, whitespace, and missing schemes.
pub fn ConceptIri::ConceptIri(
  text : String,
) -> ConceptIri raise ConceptIriError {
  if text.is_empty() {
    raise Empty
  }
  for ch in text {
    if ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' {
      raise ContainsWhitespace(text)
    }
  }
  let has_scheme = text.has_prefix("https://") ||
    text.has_prefix("http://") ||
    text.has_prefix("urn:")
  if !has_scheme {
    raise MissingScheme(text)
  }
  let rest = if text.has_prefix("https://") {
    text[8:]
  } else if text.has_prefix("http://") {
    text[7:]
  } else {
    text[4:]
  }
  if rest.is_empty() {
    raise MissingScheme(text)
  }
  { value: text, }
}

///|
/// Returns the validated IRI text.
pub fn ConceptIri::as_str(self : ConceptIri) -> String {
  self.value
}

///|
/// A selectable color scheme for the UI.
#derive(Eq, Debug)
pub(all) enum ColorScheme {
  Moonrockz
  Minimal
  WarmEditorial
}

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

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

///|
/// The browser storage key for the selected color scheme.
let color_scheme_key : String = "mission-control-color-scheme"

///|
/// Parses a color scheme from browser storage text. Unknown text defaults to
/// `Moonrockz`.
pub fn ColorScheme::of_stored(text : String) -> ColorScheme {
  match text {
    "minimal" => Minimal
    "warm-editorial" => WarmEditorial
    _ => Moonrockz
  }
}

///|
/// Returns the canonical text written to browser storage and `data-scheme`.
pub fn ColorScheme::stored(self : ColorScheme) -> String {
  match self {
    Moonrockz => "moonrockz"
    Minimal => "minimal"
    WarmEditorial => "warm-editorial"
  }
}

///|
/// Returns the display label of a color scheme.
pub fn ColorScheme::label(self : ColorScheme) -> String {
  match self {
    Moonrockz => "Moonrockz"
    Minimal => "Minimal"
    WarmEditorial => "Warm Editorial"
  }
}

///|
/// Light or dark preference, or follow the operating system.
#derive(Eq, Debug)
pub(all) enum Appearance {
  System
  Light
  Dark
}

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

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

///|
/// The browser storage key for the selected appearance override.
let appearance_key : String = "mission-control-appearance"

///|
/// Parses an appearance preference from browser storage text. Unknown text
/// defaults to `System`.
pub fn Appearance::of_stored(text : String) -> Appearance {
  match text {
    "light" => Light
    "dark" => Dark
    _ => System
  }
}

///|
/// Returns the canonical text written to browser storage and `data-appearance`.
pub fn Appearance::stored(self : Appearance) -> String {
  match self {
    System => "system"
    Light => "light"
    Dark => "dark"
  }
}

///|
/// Returns the display label of an appearance mode.
pub fn Appearance::label(self : Appearance) -> String {
  match self {
    System => "System"
    Light => "Light"
    Dark => "Dark"
  }
}

///|
/// Cycles appearance in order: `System -> Light -> Dark -> System`.
pub fn Appearance::next(self : Appearance) -> Appearance {
  match self {
    System => Light
    Light => Dark
    Dark => System
  }
}

///|
/// The browser storage key for custom brand identity.
let brand_key : String = "mission-control-brand"

///|
let brand_title_max : Int32 = 40

///|
let brand_image_max : Int32 = 131_072

///|
fn has_control_char(text : String) -> Bool {
  text.iter().any(c => c < ' ' || c == '\u{7f}')
}

///|
/// A validated display title for the Mission Control header (1..=40 printable chars).
#derive(Eq, Debug)
pub struct BrandTitle {
  priv text : String
}

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

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

///|
pub fn BrandTitle::default() -> BrandTitle {
  { text: "Mission Control", }
}

///|
/// Parses a trimmed single-line brand title, returning `None` when empty,
/// longer than 40 characters, or containing control characters.
pub fn BrandTitle::parse(raw : String) -> BrandTitle? {
  let trimmed = raw.trim().to_owned()
  let count = trimmed.iter().count()
  if count < 1 || count > brand_title_max || has_control_char(trimmed) {
    None
  } else {
    Some({ text: trimmed, })
  }
}

///|
pub fn BrandTitle::as_str(self : BrandTitle) -> String {
  self.text
}

///|
/// A validated 1..=3 character uppercase ASCII alphanumeric monogram badge.
#derive(Eq, Debug)
pub struct BrandMonogram {
  priv text : String
}

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

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

///|
pub fn BrandMonogram::default() -> BrandMonogram {
  { text: "MC", }
}

///|
/// Parses 1..=3 ASCII letters or digits, normalizing lowercase letters to uppercase.
pub fn BrandMonogram::parse(raw : String) -> BrandMonogram? {
  let trimmed = raw.trim().to_owned()
  let buf = StringBuilder()
  let mut count : Int32 = 0
  for ch in trimmed {
    let upper = if ch >= 'a' && ch <= 'z' {
      Int32::unsafe_to_char(ch.to_int() - 32)
    } else if (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') {
      ch
    } else {
      return None
    }
    count += 1
    if count > 3 {
      return None
    }
    buf.write_char(upper)
  }
  if count < 1 {
    None
  } else {
    Some({ text: buf.to_string(), })
  }
}

///|
pub fn BrandMonogram::as_str(self : BrandMonogram) -> String {
  self.text
}

///|
/// A validated concise emoji or symbol brand mark (1..=8 non-control chars).
#derive(Eq, Debug)
pub struct BrandEmoji {
  priv text : String
}

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

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

///|
pub fn BrandEmoji::default() -> BrandEmoji {
  { text: "🚀", }
}

///|
pub fn BrandEmoji::parse(raw : String) -> BrandEmoji? {
  let trimmed = raw.trim().to_owned()
  let count = trimmed.iter().count()
  if count < 1 || count > 8 || has_control_char(trimmed) {
    None
  } else {
    Some({ text: trimmed, })
  }
}

///|
pub fn BrandEmoji::as_str(self : BrandEmoji) -> String {
  self.text
}

///|
/// A validated raster `data:image/*;base64,...` URI allowed under the server's
/// `img-src data:` CSP and capped at 128 KB.
#derive(Eq, Debug)
pub struct BrandImageUrl {
  priv url : String
}

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

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

///|
pub fn BrandImageUrl::parse(raw : String) -> BrandImageUrl? {
  let trimmed = raw.trim().to_owned()
  if trimmed.length() > brand_image_max || has_control_char(trimmed) {
    return None
  }
  let prefixes = [
    "data:image/png;base64,", "data:image/jpeg;base64,", "data:image/webp;base64,",
    "data:image/gif;base64,",
  ]
  for prefix in prefixes {
    if trimmed.has_prefix(prefix) {
      let payload = trimmed[prefix.length():]
      if payload.length() > 0 &&
        payload
        .iter()
        .all(ch => {
          (ch >= 'A' && ch <= 'Z') ||
          (ch >= 'a' && ch <= 'z') ||
          (ch >= '0' && ch <= '9') ||
          ch == '+' ||
          ch == '/' ||
          ch == '='
        }) {
        return Some({ url: trimmed, })
      }
      return None
    }
  }
  None
}

///|
pub fn BrandImageUrl::as_str(self : BrandImageUrl) -> String {
  self.url
}

///|
/// Closed set of configurable brand marks shown in the sidebar header and mobile bar.
#derive(Eq, Debug)
pub(all) enum BrandMark {
  Moonrockz
  Monogram(BrandMonogram)
  Emoji(BrandEmoji)
  CustomImage(BrandImageUrl)
}

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

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

///|
/// Complete persisted brand identity for this browser's Mission Control instance.
#derive(Eq, Debug)
pub struct BrandConfig {
  mark : BrandMark
  title : BrandTitle
}

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

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

///|
pub fn BrandConfig::default() -> BrandConfig {
  { mark: Moonrockz, title: BrandTitle::default(), }
}

///|
/// Encodes brand identity into a newline-delimited string for `localStorage`.
/// Every field is validated to contain no control characters or newlines.
pub fn BrandConfig::stored(self : BrandConfig) -> String {
  let title = self.title.as_str()
  match self.mark {
    Moonrockz => "v1\n\{title}\nmoonrockz"
    Monogram(mono) => "v1\n\{title}\nmonogram\n\{mono.as_str()}"
    Emoji(emoji) => "v1\n\{title}\nemoji\n\{emoji.as_str()}"
    CustomImage(img) => "v1\n\{title}\nimage\n\{img.as_str()}"
  }
}

///|
/// Parses stored brand identity text, falling back to defaults on unknown,
/// malformed, or untrusted data.
pub fn BrandConfig::of_stored(text : String) -> BrandConfig {
  let lines = text.split("\n").map(part => part.to_owned()).to_array()
  guard lines.length() >= 3 && lines[0] == "v1" else { BrandConfig::default() }
  let title = BrandTitle::parse(lines[1]).unwrap_or(BrandTitle::default())
  let mark : BrandMark = match lines[2] {
    "moonrockz" => Moonrockz
    "monogram" =>
      match lines.get(3).bind(BrandMonogram::parse) {
        Some(mono) => Monogram(mono)
        None => Moonrockz
      }
    "emoji" =>
      match lines.get(3).bind(BrandEmoji::parse) {
        Some(emoji) => Emoji(emoji)
        None => Moonrockz
      }
    "image" =>
      match lines.get(3).bind(BrandImageUrl::parse) {
        Some(img) => CustomImage(img)
        None => Moonrockz
      }
    _ => Moonrockz
  }
  { mark, title, }
}

///|
/// A section of the full-page Settings overlay.
#derive(Eq, Debug)
pub(all) enum SettingsTab {
  Workflow
  Studio
  Adapters
  Scorecards
  Mounts
  Appearance
  Perspectives
}

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

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

///|
/// Whether the full-page Settings overlay is open and which section it shows.
#derive(Eq, Debug)
pub(all) enum SettingsSurface {
  Closed
  Open(SettingsTab)
}

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

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

///|
/// A single visited shell location recorded in `NavHistory`.
/// Stores `Route` rather than paired optional IDs so `(None, Some(workspace))`
/// is unrepresentable.
#derive(Eq, Debug)
pub struct NavTarget {
  route : Route
  perspective : Perspective
  plan_view : PlanView
  review_doc : ReviewDocId
  knowledge_view : KnowledgeView
}

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

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

///|
/// Constructs a `NavTarget` for a visited shell location.
pub fn NavTarget::NavTarget(
  route~ : Route,
  perspective~ : Perspective,
  plan_view~ : PlanView,
  review_doc~ : ReviewDocId,
  knowledge_view~ : KnowledgeView = Dictionary,
) -> NavTarget {
  { route, perspective, plan_view, review_doc, knowledge_view, }
}

///|
/// The project ID referenced by this navigation target, if any.
pub fn NavTarget::project(self : NavTarget) -> @app.ProjectId? {
  self.route.project()
}

///|
/// The workspace ID referenced by this navigation target, if any.
pub fn NavTarget::workspace(self : NavTarget) -> @app.WorkspaceId? {
  self.route.workspace()
}

///|
/// The maximum number of entries kept in the back stack of `NavHistory`.
let nav_history_limit : Int32 = 64

///|
/// Immutable Back and Forward navigation history with private stacks.
#derive(Eq, Debug)
pub struct NavHistory {
  priv back : ReadOnlyArray[NavTarget]
  priv current : NavTarget
  priv forward : ReadOnlyArray[NavTarget]
}

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

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

///|
/// Creates a fresh navigation history starting at `initial`.
pub fn NavHistory::NavHistory(initial : NavTarget) -> NavHistory {
  { back: [], current: initial, forward: [], }
}

///|
/// Returns the current navigation target.
pub fn NavHistory::current(self : NavHistory) -> NavTarget {
  self.current
}

///|
/// Reports whether at least one back entry exists.
pub fn NavHistory::can_go_back(self : NavHistory) -> Bool {
  !self.back.is_empty()
}

///|
/// Reports whether at least one forward entry exists.
pub fn NavHistory::can_go_forward(self : NavHistory) -> Bool {
  !self.forward.is_empty()
}

///|
/// Returns the number of entries in the back stack.
pub fn NavHistory::back_len(self : NavHistory) -> Int32 {
  self.back.length()
}

///|
/// Returns the number of entries in the forward stack.
pub fn NavHistory::forward_len(self : NavHistory) -> Int32 {
  self.forward.length()
}

///|
/// Pushes a new target, clears forward history, and caps the back stack.
/// Pushing the current target leaves the history unchanged.
pub fn NavHistory::push(self : NavHistory, target : NavTarget) -> NavHistory {
  guard target != self.current else { self }
  let combined : Array[NavTarget] = [..self.back, self.current]
  let trimmed = if combined.length() > nav_history_limit {
    combined[combined.length() - nav_history_limit:].to_owned()
  } else {
    combined
  }
  { back: ReadOnlyArray::from_array(trimmed), current: target, forward: [], }
}

///|
/// Replaces the current target without adding a back-stack entry.
pub fn NavHistory::replace_current(
  self : NavHistory,
  target : NavTarget,
) -> NavHistory {
  dedupe_history(self.back, target, self.forward)
}

///|
/// Moves one step backward and returns the updated history and new target, or
/// `None` when the back stack is empty.
pub fn NavHistory::go_back(self : NavHistory) -> (NavHistory, NavTarget)? {
  let len = self.back.length()
  guard len > 0 else { None }
  let target = self.back[len - 1]
  let rest = self.back[:len - 1].to_owned()
  let next_forward : Array[NavTarget] = [self.current, ..self.forward]
  let next = {
    back: ReadOnlyArray::from_array(rest),
    current: target,
    forward: ReadOnlyArray::from_array(next_forward),
  }
  Some((next, target))
}

///|
/// Moves one step forward and returns the updated history and new target, or
/// `None` when the forward stack is empty.
pub fn NavHistory::go_forward(self : NavHistory) -> (NavHistory, NavTarget)? {
  guard !self.forward.is_empty() else { None }
  let target = self.forward[0]
  let rest = self.forward[1:].to_owned()
  let next_back : Array[NavTarget] = [..self.back, self.current]
  let trimmed = if next_back.length() > nav_history_limit {
    next_back[next_back.length() - nav_history_limit:].to_owned()
  } else {
    next_back
  }
  let next = {
    back: ReadOnlyArray::from_array(trimmed),
    current: target,
    forward: ReadOnlyArray::from_array(rest),
  }
  Some((next, target))
}

///|
/// Removes adjacent duplicate targets and drops any edge entry equal to
/// `current`.
fn dedupe_history(
  back : ReadOnlyArray[NavTarget],
  current : NavTarget,
  forward : ReadOnlyArray[NavTarget],
) -> NavHistory {
  let clean_back : Array[NavTarget] = []
  for item in back {
    match clean_back.last() {
      Some(prev) if prev == item => ()
      _ => clean_back.push(item)
    }
  }
  while clean_back.last() == Some(current) {
    ignore(clean_back.pop())
  }
  let clean_forward : Array[NavTarget] = []
  for item in forward {
    if clean_forward.is_empty() && item == current {
      continue
    }
    match clean_forward.last() {
      Some(prev) if prev == item => ()
      _ => clean_forward.push(item)
    }
  }
  {
    back: ReadOnlyArray::from_array(clean_back),
    current,
    forward: ReadOnlyArray::from_array(clean_forward),
  }
}

///|
/// Removes every history entry that references `removed`, clears `current` if
/// it matches, and removes consecutive duplicates.
pub fn NavHistory::prune_project(
  self : NavHistory,
  removed : @app.ProjectId,
) -> NavHistory {
  let keep = (t : NavTarget) => t.route.project() != Some(removed)
  let back = self.back.filter(keep)
  let forward = self.forward.filter(keep)
  let current = if self.current.route.project() == Some(removed) {
    { ..self.current, route: NoRoute, }
  } else {
    self.current
  }
  dedupe_history(back, current, forward)
}

///|
/// Keeps only history entries whose project ID is absent or present in
/// `projects`, clearing `current` if its project was deleted and deduplicating
/// adjacent entries.
pub fn NavHistory::retain_projects(
  self : NavHistory,
  projects : ReadOnlyArray[@app.Project],
) -> NavHistory {
  let keep_id = (id : @app.ProjectId?) => {
    match id {
      None => true
      Some(pid) => projects.iter().any(p => p.id == pid)
    }
  }
  let back = self.back.filter(t => keep_id(t.route.project()))
  let forward = self.forward.filter(t => keep_id(t.route.project()))
  let current = if keep_id(self.current.route.project()) {
    self.current
  } else {
    { ..self.current, route: NoRoute, }
  }
  dedupe_history(back, current, forward)
}