// The screen: the primary sidebar, the open project, the dialogs and the status
// bar. The theme is the one of the operating system (design UI-1).

///|
/// A path in two parts, for a place that is too small for it. The view shortens `head`
/// first, because the last names tell two projects apart.
// Only the tests compare the parts and write them as text.
#warnings("-unused_value")
#derive(Eq, Debug)
priv struct PathParts {
  head : String
  tail : String
}

///|
/// Splits a path before its last two names. A path with less than four parts is
/// complete in `tail`.
fn PathParts::of_path(path : String) -> PathParts {
  // Only a path of Windows starts with no `/`, and there `\` separates the names.
  let separator = if path.has_prefix("/") { "/" } else { "\\" }
  let names = path.split(separator).map(name => name.to_owned()).to_array()
  guard names.length() >= 4 else { { head: "", tail: path, } }
  let first = names.length() - 2
  {
    head: names[:first].join(separator),
    tail: separator + names[first:].join(separator),
  }
}

///|
/// The text of the status bar for the connection.
fn connection_text(connection : ConnectionState) -> String {
  match connection {
    Connecting => "Connecting…"
    Connected => "Connected"
    Reconnecting => "Reconnecting…"
    // The main area says what happened.
    Restarted | Stopped => "Not connected"
  }
}

///|
/// The text of the status bar for the kind of the view.
fn surface_text(surface : @app.Surface) -> String {
  match surface {
    Browser => "Browser"
    Desktop => "Desktop"
  }
}

///|
/// What a view says after it ended. The view shows `command` as code.
priv struct EndText {
  title : String
  before : String
  command : String
  after : String
}

///|
/// The text of a view that ended, or `None` for a view that is in use.
fn EndText::of_view(
  connection : ConnectionState,
  surface : @app.Surface,
  instance : @app.InstanceName,
) -> EndText? {
  let command = surface.open_command(instance)
  match connection {
    Restarted =>
      Some({
        title: "Session ended",
        before: "Mission Control restarted. Run ",
        command,
        after: " to open it again.",
      })
    Stopped =>
      Some({
        title: "Mission Control stopped.",
        before: "Run ",
        command,
        after: " to start it again.",
      })
    Connecting | Connected | Reconnecting => None
  }
}

///|
/// The colors of the UI over the ones of `rui`. Each color is for both themes, so the
/// page needs no script to follow the operating system.
let theme_tokens : String =
  #|color-scheme:light dark;
  #|--rui-radius:0.5rem;
  #|--rui-background:light-dark(oklch(1 0 0),oklch(0.2 0.006 260));
  #|--rui-foreground:light-dark(oklch(0.24 0.012 260),oklch(0.93 0.004 260));
  #|--rui-card:var(--rui-background);
  #|--rui-card-foreground:var(--rui-foreground);
  #|--rui-popover:light-dark(oklch(1 0 0),oklch(0.245 0.008 260));
  #|--rui-popover-foreground:var(--rui-foreground);
  #|--rui-primary:light-dark(oklch(0.48 0.13 255),oklch(0.76 0.1 250));
  #|--rui-primary-foreground:light-dark(oklch(1 0 0),oklch(0.2 0.03 255));
  #|--rui-secondary:light-dark(oklch(0.955 0.004 260),oklch(0.29 0.009 260));
  #|--rui-secondary-foreground:var(--rui-foreground);
  #|--rui-muted:light-dark(oklch(0.965 0.003 260),oklch(0.27 0.008 260));
  #|--rui-muted-foreground:light-dark(oklch(0.47 0.014 260),oklch(0.74 0.01 260));
  #|--rui-accent:light-dark(oklch(0.94 0.006 260),oklch(0.3 0.01 260));
  #|--rui-accent-foreground:var(--rui-foreground);
  #|--rui-destructive:light-dark(oklch(0.5 0.18 27),oklch(0.76 0.13 22));
  #|--rui-destructive-border:var(--rui-destructive);
  #|--rui-destructive-subtle:light-dark(oklch(0.5 0.18 27 / 0.08),oklch(0.76 0.13 22 / 0.14));
  #|--rui-destructive-surface:var(--rui-destructive-subtle);
  #|--rui-destructive-ring:light-dark(oklch(0.5 0.18 27 / 0.2),oklch(0.76 0.13 22 / 0.3));
  #|--rui-border:light-dark(oklch(0.9 0.005 260),oklch(0.32 0.009 260));
  #|--rui-input:light-dark(oklch(0.62 0.012 260),oklch(0.58 0.012 260));
  #|--rui-input-background:light-dark(oklch(1 0 0),oklch(0.2 0.006 260));
  #|--rui-outline-background:transparent;
  #|--rui-outline-border:light-dark(oklch(0.82 0.008 260),oklch(0.42 0.011 260));
  #|--rui-outline-hover-bg:var(--rui-accent);
  #|--rui-ghost-hover-bg:var(--rui-accent);
  #|--rui-ring:light-dark(oklch(0.52 0.15 255),oklch(0.74 0.12 250));
  #|--rui-sidebar:light-dark(oklch(0.972 0.003 260),oklch(0.17 0.006 260));
  #|--rui-sidebar-foreground:var(--rui-foreground);
  #|--rui-sidebar-primary:var(--rui-primary);
  #|--rui-sidebar-primary-foreground:var(--rui-primary-foreground);
  #|--rui-sidebar-accent:light-dark(oklch(0.925 0.007 260),oklch(0.275 0.01 260));
  #|--rui-sidebar-accent-foreground:var(--rui-foreground);
  #|--rui-sidebar-border:var(--rui-border);
  #|--rui-sidebar-ring:var(--rui-ring);
  #|--rui-sidebar-width:18rem;
  #|--rui-sidebar-width-mobile:20rem;
  #|--rui-font-sans:system-ui,-apple-system,"Segoe UI",Roboto,"Noto Sans",sans-serif;
  #|--mc-mono:ui-monospace,"Cascadia Code","SF Mono",Menlo,Consolas,monospace;
  #|--mc-good:light-dark(oklch(0.58 0.14 150),oklch(0.76 0.15 150));
  #|--mc-wait:light-dark(oklch(0.62 0.14 65),oklch(0.8 0.13 80))

///|
/// The rules that an inline style cannot have. `rui` has its styles inline and removes
/// the focus ring of its buttons, so a rule for one of them needs `!important`.
let page_styles : String =
  #|:root { color-scheme:light dark; background:light-dark(oklch(1 0 0),oklch(0.2 0.006 260)); }
  #|body { margin:0; }
  #|/* The page does not scroll, so it needs no space for a scrollbar behind the sheet. */
  #|html { scrollbar-gutter:auto !important; }
  #|.mc-page { height:100vh; height:100dvh; overflow:hidden; }
  #|.mc-page :focus-visible { outline:2px solid var(--rui-ring) !important; outline-offset:2px; }
  #|.mc-page .mc-row:focus-visible, .mc-page input:focus-visible { outline-offset:-1px; }
  #|.mc-page input::placeholder { color:var(--rui-muted-foreground); opacity:1; }
  #|/* The box around the field of the palette has the ring, and not the field in it. */
  #|.mc-palette-field:focus-within { outline:2px solid var(--rui-ring); outline-offset:-1px; }
  #|.mc-page .mc-palette-field input:focus-visible { outline:none !important; }
  #|.mc-palette-field { display:flex; flex:none; align-items:center; gap:0.5rem; height:2.25rem; margin:0.25rem 0.25rem 0; padding-inline:0.5rem; border:1px solid var(--rui-border); border-radius:var(--rui-radius); background:var(--rui-input-background); color:var(--rui-muted-foreground); }
  #|.mc-palette-field input { color:var(--rui-foreground); }
  #|.mc-palette-note { margin:0; padding:0.5rem 0.75rem 0.25rem; font-size:0.8125rem; line-height:1.25rem; color:var(--rui-muted-foreground); }
  #|.mc-palette-empty { margin:0; padding:1.5rem 0.75rem; font-size:0.875rem; line-height:1.25rem; text-align:center; color:var(--rui-muted-foreground); }
  #|.mc-palette-note:empty, .mc-palette-empty:empty { padding:0; }
  #|.mc-palette-list { min-height:0; max-height:min(24rem,55dvh); overflow:hidden auto; outline:none; }
  #|.mc-palette-group { padding:0.25rem; }
  #|.mc-palette-heading { padding:0.375rem 0.5rem; font-size:0.75rem; line-height:1rem; font-weight:500; color:var(--rui-muted-foreground); }
  #|.mc-palette-entry { display:flex; align-items:center; min-height:2rem; box-sizing:border-box; padding:0.375rem 0.5rem; border-radius:calc(var(--rui-radius) - 0.25rem); font-size:0.875rem; line-height:1.25rem; cursor:pointer; -webkit-user-select:none; user-select:none; scroll-margin-block:0.25rem; }
  #|/* The name of the group is visible with its first entry. */
  #|.mc-palette-heading + .mc-palette-entry { scroll-margin-block-start:2.25rem; }
  #|.mc-palette-entry[aria-selected="true"] { background:var(--rui-accent); color:var(--rui-accent-foreground); }
  #|.mc-palette-entry[aria-disabled="true"] { cursor:not-allowed; }
  #|.mc-palette-entry[aria-disabled="true"] > * { opacity:0.5; }
  #|/* A closed dialog has no content, so it must not fade out. */
  #|.mc-page dialog, .mc-page dialog::backdrop { transition:none !important; }
  #|/* The sheet has the focus when it opens, and its edge is no control. */
  #|.mc-page [data-slot="sidebar"]:focus-visible { outline:none !important; }
  #|/* The title gets the focus when its control is gone, and it is no control. */
  #|.mc-page h1:focus-visible { outline:none !important; }
  #|.mc-page button:not(:disabled) { cursor:pointer; }
  #|.mc-page button[aria-disabled="true"] { cursor:not-allowed; opacity:0.5; }
  #|.mc-cut { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:pre; }
  #|.mc-path { display:flex; min-width:0; font-family:var(--mc-mono); font-size:0.75rem; font-weight:400; line-height:1.125rem; color:var(--rui-muted-foreground); }
  #|.mc-path > :first-child { flex:0 99999 auto; }
  #|.mc-path > :last-child { flex:0 1 auto; }
  #|.mc-row { position:relative; }
  #|.mc-row[aria-current]::before { content:""; position:absolute; inset-block:0.5rem; inset-inline-start:0; width:2px; border-radius:1px; background:var(--rui-primary); }
  #|.mc-warning { color:var(--rui-destructive); }
  #|.mc-dot { width:0.5rem; height:0.5rem; flex:none; border-radius:50%; background:var(--rui-muted-foreground); }
  #|.mc-dot[data-state="good"] { background:var(--mc-good); }
  #|.mc-dot[data-state="wait"] { background:var(--mc-wait); animation:mc-wait 1.6s ease-in-out infinite; }
  #|@keyframes mc-wait { 50% { opacity:0.35; } }
  #|@media (prefers-reduced-motion:reduce) { .mc-page *, .mc-page *::before { animation:none !important; transition:none !important; } }
  #|.mc-top { display:none; }
  #|.mc-hidden-primary-sidebar { display:flex; }
  #|@media (max-width:47.99rem) {
  #|  .mc-page [data-slot="sidebar-shell"] { display:none; }
  #|  .mc-top { display:flex; }
  #|  .mc-hidden-primary-sidebar { display:none; }
  #|}

///|
/// The UI. `surface` is the kind of this view, and `instance` gave its page.
/// `primary_sidebar` is the state that the browser kept. `mac` is true on macOS, which
/// has other shortcuts. The UI runs the connection.
pub fn app(
  connection : Connection,
  surface~ : @app.Surface,
  instance~ : @app.InstanceName,
  primary_sidebar~ : PrimarySidebar,
  mac~ : Bool,
) -> @rabbita.Val[@html.Html] {
  let client = connection.client
  // `rui` gives the command that closes the sheet only to the view of the sidebar.
  let close_sheet = Ref(@cmd.none)
  let (model, emit) = @rabbita.create_state_with_init(
    init=emit => {
      (
        Model::Model(
          surface~,
          instance~,
          primary_sidebar~,
          window=window_size(),
        ),
        run_connection(connection, emit),
      )
    },
    update=(model, msg, emit) => update(model, msg, emit, connection),
    subscriptions=(model, emit) => {
      let failed = error => emit(CallFailed(error))
      @sub.batch([
        // The shortcuts of a view that ended are the ones of the browser.
        if model.is_over() {
          @sub.batch([])
        } else {
          on_shortcuts(
            shortcut => {
              match model.shortcut_msg(shortcut) {
                // The sheet closes before a dialog opens over the page.
                Some(msg) => @cmd.batch([close_sheet.val, emit(msg)])
                None => @cmd.none
              }
            },
            mac~,
          )
        },
        @sub.on_resize(
          @cmd.Emit(_ => {
            let window = window_size()
            match window {
              // A wide window has no button for the sheet.
              Wide => @cmd.batch([close_sheet.val, emit(WindowResized(window))])
              Small => emit(WindowResized(window))
            }
          }),
        ),
        @sub.on_url_changed(
          @cmd.Emit(url => {
            let hash = match url.fragment {
              Some(fragment) => "#\{fragment}"
              None => ""
            }
            emit(HashChanged(project_of_hash(hash)))
          }),
        ),
        @proton_rabbita.subscribe(
          @app.projects_changed,
          projects => emit(ProjectsListed(ReadOnlyArray::from_array(projects))),
          failed,
          client~,
        ),
        @proton_rabbita.subscribe(
          @app.project_shown,
          shown => emit(ProjectShown(shown)),
          failed,
          client~,
        ),
        @proton_rabbita.subscribe(
          @app.app_stopping,
          _ => emit(AppStopping),
          failed,
          client~,
        ),
      ])
    },
  )
  @rui.sidebar_provider_with_input(
    input=model,
    style=["flex-direction:column;height:100%;min-height:0"],
    on_mobile_open_change=@cmd.Emit(open => {
      if open {
        @cmd.none
      } else {
        // `rui` gives the focus back after this command, if the button is there.
        @cmd.custom_cmd(scheduler => scheduler.add(keep_focus(main_title_id)))
      }
    }),
    (scope, model) => {
      close_sheet.val = @rui.sidebar_close_mobile(scope)
      screen(scope, model, emit, mac~)
    },
  ).view(screen => {
    @rui.theme(class="mc-page", style=[theme_tokens], [
      @html.style_tag(@html.text(page_styles)),
      screen,
    ])
  })
}

///|
fn window_size() -> WindowSize {
  if is_wide() {
    Wide
  } else {
    Small
  }
}

///|
/// The window has space for the primary sidebar. The limit is the one in `page_styles`.
extern "js" fn is_wide() -> Bool =
  #| () => matchMedia("(min-width:48rem)").matches

///|
/// Runs the connection until it ends. An error means that it cannot try at all.
fn run_connection(connection : Connection, emit : @cmd.Emit[Msg]) -> @cmd.Cmd {
  @cmd.custom_cmd(scheduler => {
    let send = msg => scheduler.add(emit(msg))
    @js_async.Promise::from_async(() => {
      (connection.run)(state => send(ConnectionChanged(state))) catch {
        error =>
          send(ConnectionFailed("Mission Control cannot connect: \{error}"))
      }
    })
    |> ignore
  })
}

///|
fn screen(
  scope : @rui.SidebarScope,
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  let body = match
    EndText::of_view(model.connection, model.surface, model.instance) {
    Some(text) => end_view(text)
    None =>
      @html.div(style=["display:flex;flex:1;min-width:0;min-height:0"], [
        match model.primary_sidebar {
          Shown => project_sidebar(scope, model, emit, mac~, mobile=false)
          Hidden => @html.nothing
        },
        project_sidebar(scope, model, emit, mac~, mobile=true),
        main_area(scope, model, emit, mac~),
      ])
  }
  @html.fragment([
    body,
    status_bar(model),
    // A dialog must be in the page before a command opens it.
    add_dialog(model, emit),
    stop_dialog(model, emit),
    palette(model, emit, mac~),
  ])
}

///|
/// The primary sidebar. `mobile` is the sheet with the same content, which a button opens
/// on a small screen.
fn project_sidebar(
  scope : @rui.SidebarScope,
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
  mobile~ : Bool,
) -> @html.Html {
  let close_sheet = if mobile {
    Some(@rui.sidebar_close_mobile(scope))
  } else {
    None
  }
  @rui.sidebar(
    scope,
    collapsible=SidebarFixed,
    mobile~,
    aria_label=if mobile { "Projects" } else { "Primary sidebar" },
    sidebar_parts(model, emit, mac~, close_sheet~),
  )
}

///|
/// The parts of the primary sidebar. `close_sheet` is there only in the sheet.
fn sidebar_parts(
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
  close_sheet~ : @cmd.Cmd?,
) -> Array[@html.Html] {
  // The sheet closes before the message, because a dialog opens over the page.
  let leave = (msg : Msg) => {
    match close_sheet {
      Some(close) => @cmd.batch([close, emit(msg)])
      None => emit(msg)
    }
  }
  let act = (action : Action) => {
    // The sheet stays for an action that does nothing.
    if action.enabled(model) {
      leave(ActionChosen(action))
    } else {
      emit(ActionChosen(action))
    }
  }
  [
    @rui.sidebar_header(
      style=["flex-direction:row;align-items:center;padding:0.75rem 1rem"],
      [
        @html.span(
          style=["font-size:0.875rem;font-weight:600;flex:1"],
          "Mission Control",
        ),
        match close_sheet {
          Some(close) =>
            @rui.button(
              variant=Ghost,
              size=IconSm,
              attrs=@html.Attrs::build().aria_label("Close the project list"),
              on_click=close,
              icon("M6 6l12 12M18 6L6 18"),
            )
          None => primary_sidebar_button(Hidden, emit, mac~)
        },
      ],
    ),
    @html.div(
      style=["flex:none;padding:0 0.75rem 0.25rem"],
      palette_button(leave(PaletteOpened), mac~),
    ),
    @rui.sidebar_content(
      @rui.sidebar_group([
        @rui.sidebar_group_label("Projects"),
        @rui.sidebar_group_action(
          title=AddProject.title(),
          aria_label=AddProject.title(),
          attrs=action_attrs(AddProject, model),
          style=["width:1.5rem;height:1.5rem;top:0.75rem"],
          on_click=act(AddProject),
          icon("M12 5v14M5 12h14"),
        ),
        @rui.sidebar_group_content(
          @rui.sidebar_menu(style=["gap:0.125rem"], project_rows(model, act)),
        ),
      ]),
    ),
    @rui.sidebar_footer(
      @rui.button(
        variant=Ghost,
        size=Sm,
        attrs=action_attrs(StopApp, model),
        style=["justify-content:flex-start"],
        on_click=act(StopApp),
        [icon("M12 4v8M7.5 6.8a7 7 0 1 0 9 0"), @html.text(StopApp.title())],
      ),
    ),
  ]
}

///|
/// The control that gives the primary sidebar this state.
fn primary_sidebar_button(
  state : PrimarySidebar,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  let action = SetPrimarySidebar(state)
  @rui.button(
    variant=Ghost,
    size=IconSm,
    id=state.other().control_id(),
    title="\{action.title()} (\{ChangePrimarySidebar.text(mac~)})",
    attrs=@html.Attrs::build()
      .aria_label(action.title())
      .aria_keyshortcuts(ChangePrimarySidebar.aria(mac~)),
    on_click=emit(ActionChosen(action)),
    // A panel with a left part.
    icon(
      "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM9 3v18",
    ),
  )
}

///|
/// The bar over the main area while the primary sidebar is hidden. The bar has its own
/// space, so its control covers no text. A small window does not show it.
fn hidden_primary_sidebar_bar(
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  match model.primary_sidebar {
    Shown => @html.nothing
    Hidden =>
      @html.div(
        class="mc-hidden-primary-sidebar",
        style=["flex:none;padding:0.5rem 1rem 0"],
        primary_sidebar_button(Shown, emit, mac~),
      )
  }
}

///|
/// The control that opens the command palette.
fn palette_button(on_click : @cmd.Cmd, mac~ : Bool) -> @html.Html {
  @rui.button(
    variant=Outline,
    style=[
      "width:100%;justify-content:flex-start;font-weight:400;--rui-button-base-fg:var(--rui-muted-foreground)",
    ],
    attrs=@html.Attrs::build()
      .aria_haspopup("dialog")
      .aria_keyshortcuts(OpenPalette.aria(mac~)),
    on_click~,
    [
      icon("M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM16 16l4 4"),
      @html.span("Find…"),
      shortcut_hint(OpenPalette, mac~),
    ],
  )
}

///|
/// The rows of the projects, with the keys of their actions.
fn project_rows(
  model : Model,
  act : (Action) -> @cmd.Cmd,
) -> Map[String, @html.Html] {
  let rows : Map[String, @html.Html] = Map([])
  for project in model.projects.unwrap_or([]) {
    let open = OpenProject(project)
    rows[open.id().key()] = project_row(
      project,
      is_open=model.open == Some(project.id),
      on_click=act(open),
    )
  }
  rows
}

///|
fn project_row(
  project : @app.Project,
  is_open~ : Bool,
  on_click~ : @cmd.Cmd,
) -> @html.Html {
  let attrs = @html.Attrs::build()
  if is_open {
    attrs.aria_current("true") |> ignore
  }
  @rui.sidebar_menu_item(
    @rui.sidebar_menu_button(
      is_active=is_open,
      class="mc-row",
      title=project.path,
      attrs~,
      on_click~,
      style=[
        "flex-direction:column;align-items:stretch;justify-content:center;gap:0.125rem;height:auto;padding-block:0.375rem;padding-inline:0.625rem",
      ],
      project_lines(project),
    ),
  )
}

///|
/// The name of a project over its path, for a list. Two projects can have the same
/// name.
fn project_lines(project : @app.Project) -> @html.Html {
  @html.span(
    style=["display:flex;flex-direction:column;gap:0.125rem;min-width:0"],
    [
      @html.span(style=["display:flex;gap:0.5rem;min-width:0"], [
        @html.span(
          class="mc-cut",
          style=["flex:0 1 auto;font-weight:500"],
          project.name,
        ),
        match project.parent {
          Some(parent) =>
            @html.span(
              class="mc-cut",
              style=["flex:0 4 auto;color:var(--rui-muted-foreground)"],
              parent,
            )
          None => @html.nothing
        },
      ]),
      short_path(project.path),
      match project.folder {
        Missing =>
          @html.span(
            class="mc-warning",
            style=["font-size:0.75rem;line-height:1.125rem;font-weight:400"],
            folder_not_found,
          )
        Present => @html.nothing
      },
    ],
  )
}

///|
let folder_not_found : String = "Folder not found"

///|
/// A path in one line. A long path loses characters before its last two names.
fn short_path(path : String) -> @html.Html {
  let { head, tail, } = PathParts::of_path(path)
  @html.span(class="mc-path", [
    @html.span(class="mc-cut", head),
    @html.span(class="mc-cut", tail),
  ])
}

///|
fn main_area(
  scope : @rui.SidebarScope,
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  @html.main_(
    style=[
      "display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:auto",
    ],
    [
      @html.div(
        class="mc-top",
        style=[
          "align-items:center;gap:0.5rem;padding:0.5rem 0.75rem;border-bottom:1px solid var(--rui-border)",
        ],
        [
          @rui.sidebar_trigger(
            scope,
            mobile=true,
            aria_label="Show the project list",
            icon("M4 7h16M4 12h16M4 17h16"),
          ),
          @html.span(
            style=["font-size:0.875rem;font-weight:600"],
            "Mission Control",
          ),
        ],
      ),
      hidden_primary_sidebar_bar(model, emit, mac~),
      match model.notice {
        Some(text) => notice(text, emit)
        None => @html.nothing
      },
      main_content(model, emit),
    ],
  )
}

///|
/// A failure that has no other place.
fn notice(text : String, emit : @cmd.Emit[Msg]) -> @html.Html {
  @html.div(
    style=[
      "display:flex;align-items:flex-start;gap:0.5rem;margin:1rem 1.5rem 0;padding:0.5rem 0.5rem 0.5rem 0.75rem;border:1px solid var(--rui-destructive-border);border-radius:var(--rui-radius);background:var(--rui-destructive-subtle);font-size:0.875rem;line-height:1.25rem",
    ],
    attrs=@html.Attrs::build().role("alert"),
    [
      @html.span(
        style=[
          "flex:1;min-width:0;padding-block:0.25rem;overflow-wrap:anywhere",
        ],
        text,
      ),
      @rui.button(
        variant=Ghost,
        size=IconSm,
        attrs=@html.Attrs::build().aria_label("Close the message"),
        on_click=emit(NoticeDismissed),
        icon("M6 6l12 12M18 6L6 18"),
      ),
    ],
  )
}

///|
fn main_content(model : Model, emit : @cmd.Emit[Msg]) -> @html.Html {
  match (model.open_project(), model.projects) {
    (Some(project), _) => project_view(project, model, emit)
    (None, None) =>
      message_view(
        if model.connection is Connected {
          "Reading the projects…"
        } else {
          connection_text(model.connection)
        },
        "",
        @html.nothing,
      )
    (None, Some(projects)) =>
      if projects.is_empty() {
        message_view(
          "Add a project to start",
          "A project is a folder on this computer.",
          @rui.button(
            attrs=action_attrs(AddProject, model),
            on_click=emit(ActionChosen(AddProject)),
            [icon("M12 5v14M5 12h14"), @html.text(AddProject.title())],
          ),
        )
      } else if model.open is Some(_) {
        message_view(
          "This project is not in the list", "Select a different project from the list.",
          @html.nothing,
        )
      } else {
        message_view("Select a project", "", @html.nothing)
      }
  }
}

///|
/// A message in the center of the main area, with one action.
fn message_view(
  title : String,
  text : String,
  action : @html.Html,
) -> @html.Html {
  @html.div(
    style=[
      "display:flex;flex:1;flex-direction:column;align-items:center;justify-content:center;gap:0.5rem;padding:2rem 1.5rem;text-align:center",
    ],
    [
      main_title(title),
      if text.is_empty() {
        @html.nothing
      } else {
        @html.p(style=[text_style, "max-width:26rem"], text)
      },
      @html.div(style=["margin-top:0.5rem"], action),
    ],
  )
}

///|
let title_style : String = "margin:0;font-size:1.125rem;line-height:1.625rem;font-weight:600;overflow-wrap:anywhere"

///|
/// The title of the main area. It gets the focus when the control that had it is gone.
fn main_title(text : String) -> @html.Html {
  @html.h1(
    id=main_title_id,
    style=[title_style],
    attrs=@html.Attrs::build().tabindex(-1),
    text,
  )
}

///|
let text_style : String = "margin:0;color:var(--rui-muted-foreground);font-size:0.875rem;line-height:1.375rem;text-wrap:pretty"

///|
fn project_view(
  project : @app.Project,
  model : Model,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let remove = RemoveProject(project)
  let missing = match project.folder {
    Missing =>
      @html.p(
        class="mc-warning",
        style=["margin:0;font-size:0.875rem;line-height:1.375rem"],
        [
          @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
  }
  @html.div(
    style=[
      "display:flex;flex-direction:column;gap:0.75rem;max-width:48rem;padding:1.5rem",
    ],
    [
      main_title(project.name),
      @html.p(
        style=[
          text_style, "font-family:var(--mc-mono);font-size:0.8125rem;overflow-wrap:anywhere;white-space:pre-wrap",
        ],
        project.path,
      ),
      missing,
      @html.div(
        style=[
          "display:flex;flex-wrap:wrap;align-items:center;gap:0.5rem 0.75rem;margin-top:0.5rem",
        ],
        Map([
          (
            remove.id().key(),
            @rui.button(
              variant=Outline,
              size=Sm,
              attrs=action_attrs(remove, model),
              on_click=emit(ActionChosen(remove)),
              remove.title(),
            ),
          ),
          (
            "note",
            @html.span(
              style=[text_style, "font-size:0.8125rem"],
              "The files in the folder do not change.",
            ),
          ),
        ]),
      ),
    ],
  )
}

///|
/// The only thing of a view that ended.
fn end_view(text : EndText) -> @html.Html {
  @html.main_(
    style=["display:flex;flex:1;min-height:0;overflow:auto"],
    @html.div(
      style=[
        "display:flex;flex-direction:column;align-items:center;gap:0.5rem;margin:auto;padding:2rem 1.5rem;text-align:center",
      ],
      attrs=@html.Attrs::build().role("alert"),
      [
        main_title(text.title),
        @html.p(style=[text_style, "max-width:30rem"], [
          @html.text(text.before),
          @html.code(
            style=[
              "padding:0.125rem 0.375rem;border-radius:0.25rem;background:var(--rui-muted);color:var(--rui-foreground);font-family:var(--mc-mono);font-size:0.8125rem;white-space:nowrap",
            ],
            text.command,
          ),
          @html.text(text.after),
        ]),
      ],
    ),
  )
}

///|
fn status_bar(model : Model) -> @html.Html {
  let state = match model.connection {
    Connected => "good"
    Connecting | Reconnecting => "wait"
    Restarted | Stopped => "end"
  }
  let instance = match model.other_instance() {
    Some(name) =>
      @html.span(
        class="mc-cut",
        style=["font-weight:600;color:var(--rui-foreground)"],
        title="The name of this instance",
        name,
      )
    None => @html.nothing
  }
  let version = match model.info {
    Some(info) => @html.span(info.version.to_string())
    None => @html.nothing
  }
  @html.footer(
    style=[
      "display:flex;flex:none;align-items:center;gap:1rem;min-width:0;height:1.75rem;padding-inline:0.75rem;border-top:1px solid var(--rui-border);background:var(--rui-sidebar);color:var(--rui-muted-foreground);font-size:0.75rem;white-space:nowrap",
    ],
    [
      @html.span(
        style=["display:flex;align-items:center;gap:0.5rem"],
        attrs=@html.Attrs::build().role("status").aria_live("polite"),
        [
          @html.span(
            class="mc-dot",
            attrs=@html.Attrs::build()
              .aria_hidden("true")
              .data_set("state", state),
            @html.nothing,
          ),
          @html.span(connection_text(model.connection)),
        ],
      ),
      instance,
      @html.span(style=["flex:1"], @html.nothing),
      @html.span(surface_text(model.surface)),
      version,
    ],
  )
}

///|
/// The content is in the page only while the dialog is open. Then a new dialog has a
/// new input, and no text of the last one.
fn add_dialog(model : Model, emit : @cmd.Emit[Msg]) -> @html.Html {
  @rui.dialog(
    id=AddElement.id(),
    // A click outside must not lose the text.
    closedby="closerequest",
    on_close=@cmd.Emit(_ => emit(DialogClosed(AddElement))),
    attrs=@html.Attrs::build().aria_labelledby("add-title"),
    style=["width:min(calc(100% - 2rem),30rem)"],
    match model.dialog {
      AddDialog(path~, state~) => add_form(path, state, model, emit)
      _ => @html.nothing
    },
  )
}

///|
fn add_form(
  path : String,
  state : AddState,
  model : Model,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let (note_id, note) = match state {
    Refused(text) =>
      (
        "add-path-error",
        @rui.field_error(
          id="add-path-error",
          style=["overflow-wrap:anywhere"],
          text,
        ),
      )
    Typing | Browsing | Sending =>
      (
        "add-path-help",
        @rui.field_description(
          id="add-path-help",
          "Type the complete path of a folder on this computer.",
        ),
      )
  }
  let possible = AddProject.enabled(model)
  let refused = state is Refused(_)
  // The path does not change while the folder dialog is open or the server has it.
  let busy = state is (Browsing | Sending)
  // A browser cannot give the path of a folder to a page.
  let browse = match model.surface {
    Desktop =>
      @rui.button(
        variant=Outline,
        attrs=enabled_attrs(!busy),
        on_click=emit(BrowseChosen),
        "Browse…",
      )
    Browser => @html.nothing
  }
  @html.form(on_submit=emit(AddSubmitted), [
    @rui.dialog_header(@rui.dialog_title(id="add-title", "Add a project")),
    @rui.field(invalid=refused, [
      @rui.field_label(for_=add_path_id, "Folder path"),
      @html.div(style=["display:flex;gap:0.5rem"], [
        @rui.input(
          id=add_path_id,
          value=path,
          read_only=busy,
          required=true,
          invalid=refused,
          autofocus=true,
          auto_complete="off",
          on_input=@cmd.Emit(text => emit(PathTyped(text))),
          attrs=@html.Attrs::build()
            .aria_describedby(note_id)
            .spellcheck(false)
            .autocapitalize("off"),
          style=["flex:1;min-width:0;font-family:var(--mc-mono)"],
        ),
        browse,
      ]),
      note,
    ]),
    @rui.dialog_footer([
      @rui.button(variant=Outline, on_click=emit(CloseDialog), "Cancel"),
      @rui.button(
        type_="submit",
        attrs=enabled_attrs(possible && !busy),
        // The dialog is over the status bar, so the button has the state.
        if !possible {
          connection_text(model.connection)
        } else if state is Sending {
          "Adding…"
        } else {
          "Add project"
        },
      ),
    ]),
  ])
}

///|
/// The attributes of a button that the user can use now, or not. The button keeps the
/// focus, which the attribute `disabled` takes away. `step` ignores its message.
fn enabled_attrs(enabled : Bool) -> @html.Attrs {
  let attrs = @html.Attrs::build()
  if enabled {
    attrs
  } else {
    attrs.aria_disabled("true")
  }
}

///|
/// The attributes of the button for an action.
fn action_attrs(action : Action, model : Model) -> @html.Attrs {
  enabled_attrs(action.enabled(model))
}

///|
fn stop_dialog(model : Model, emit : @cmd.Emit[Msg]) -> @html.Html {
  let content = if model.dialog is ConfirmStop {
    @html.fragment([
      @rui.alert_dialog_header([
        @rui.alert_dialog_title(id="stop-title", "Stop Mission Control?"),
        @rui.alert_dialog_description(
          id="stop-text",
          "This stops Mission Control for each browser page and desktop window. Your projects stay in the list.",
        ),
      ]),
      @rui.alert_dialog_footer([
        @rui.button(
          variant=Outline,
          autofocus=true,
          on_click=emit(CloseDialog),
          "Cancel",
        ),
        @rui.button(
          variant=Destructive,
          attrs=action_attrs(StopApp, model),
          on_click=emit(StopConfirmed),
          "Stop Mission Control",
        ),
      ]),
    ])
  } else {
    @html.nothing
  }
  @rui.alert_dialog(
    id=StopElement.id(),
    on_close=@cmd.Emit(_ => emit(DialogClosed(StopElement))),
    attrs=@html.Attrs::build()
      .aria_labelledby("stop-title")
      .aria_describedby("stop-text"),
    content,
  )
}

///|
/// An icon of 24 by 24 units, as one line. The text near it, or the label of its
/// button, has the meaning.
fn icon(line : String) -> @html.Html {
  @html.span(
    style=["display:contents"],
    attrs=@html.Attrs::build().aria_hidden("true"),
    @svg.svg(
      width=16,
      height=16,
      view_box="0 0 24 24",
      attrs=@svg.Attrs::build().stroke_linecap("round").stroke_linejoin("round"),
      [@svg.path(d=line, fill="none", stroke="currentColor", stroke_width=2)],
    ),
  )
}