// The command palette: one list of the actions, which a user searches and runs from the
// keyboard. It has its own list in a `dialog` of `rui`, and the selected action is in the
// model (design UI-2).

///|
/// A direction in the list of the palette.
#derive(Eq, Debug)
pub(all) enum Direction {
  Up
  Down
}

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

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

///|
/// The ID of the element of an action in the palette.
fn ActionId::element(self : ActionId) -> String {
  "palette-\{self.key()}"
}

///|
/// The actions that the text of the user finds, in the order of the list.
fn Model::results(self : Model, query : String) -> Array[Action] {
  actions(self)
  .iter()
  .filter(action => finds(query, action.title(), action.search_words()))
  .to_array()
}

///|
/// The first result for this text. It can be disabled: the user then sees why it does
/// not run.
fn Model::first_result(self : Model, query : String) -> ActionId? {
  self.results(query).get(0).map(Action::id)
}

///|
/// The model with the palette, if no other dialog is open.
fn Model::open_palette(self : Model) -> (Model, Array[Effect]) {
  self.open_dialog(Palette(query="", selected=self.first_result("")))
}

///|
/// The model with this selection in the open palette. The user must see it.
fn Model::select(
  self : Model,
  query : String,
  selected : ActionId?,
) -> (Model, Array[Effect]) {
  let effects : Array[Effect] = match selected {
    Some(id) => [ShowEntry(id)]
    None => []
  }
  ({ ..self, dialog: Palette(query~, selected~), }, effects)
}

///|
/// New text selects its first result.
fn Model::search(self : Model, query : String) -> (Model, Array[Effect]) {
  guard self.dialog is Palette(..) else { (self, []) }
  self.select(query, self.first_result(query))
}

///|
/// Selects the next result, or the one before. The list goes around.
fn Model::move_selection(
  self : Model,
  direction : Direction,
) -> (Model, Array[Effect]) {
  guard self.dialog is Palette(query~, selected=Some(selected)) else {
    (self, [])
  }
  let ids = self.results(query).map(Action::id)
  guard ids.search(selected) is Some(at) else { (self, []) }
  let next = match direction {
    Down => at + 1
    Up => at + ids.length() - 1
  }
  self.select(query, Some(ids[next % ids.length()]))
}

///|
/// Selects the result below the pointer. It is visible, so the list does not scroll.
fn Model::point_at(self : Model, id : ActionId) -> (Model, Array[Effect]) {
  guard self.dialog is Palette(query~, ..) else { (self, []) }
  guard self.results(query).any(action => action.id() == id) else { (self, []) }
  ({ ..self, dialog: Palette(query~, selected=Some(id)), }, [])
}

///|
/// Runs the selected action. `seen` has the actions of the page when the user pressed
/// Enter. If a change that is not from the user came after them, then the selection can
/// be one that the user did not see. Nothing runs, and the user presses Enter again.
///
/// The text and the arrow keys are from the user, so the page can be older than them.
fn Model::run_selection(
  self : Model,
  seen : ReadOnlyArray[Action],
) -> (Model, Array[Effect]) {
  guard self.dialog is Palette(selected=Some(selected), ..) else { (self, []) }
  let actions = actions(self)
  guard look_same(actions, seen) else { (self, []) }
  guard actions.iter().find_first(action => action.id() == selected)
    is Some(action) else {
    (self, [])
  }
  self.choose(action)
}

///|
/// Keeps the selection of the open palette when the user sees a change of its actions.
/// If the selected action is no result now, then the first result is selected.
fn Model::keep_selection(
  self : Model,
  before~ : Model,
) -> (Model, Array[Effect]) {
  guard before.dialog is Palette(..) &&
    self.dialog is Palette(query~, selected~) &&
    !look_same(actions(before), actions(self)) else {
    (self, [])
  }
  if self.results(query).any(action => Some(action.id()) == selected) {
    // The action can have a different place now.
    self.select(query, selected)
  } else {
    self.select(query, self.first_result(query))
  }
}

///|
/// The ID of the search field, which always has the focus in the palette.
let palette_field_id : String = "palette-field"

///|
/// The ID of the list of the palette.
let palette_list_id : String = "palette-list"

///|
/// The ID of the text that says why some actions are disabled.
let palette_note_id : String = "palette-note"

///|
/// The palette. Its element is always in the page, and it has content only while the
/// palette is open.
fn palette(model : Model, emit : @cmd.Emit[Msg], mac~ : Bool) -> @html.Html {
  @rui.dialog(
    id=PaletteElement.id(),
    closedby="any",
    show_close=false,
    on_close=@cmd.Emit(_ => emit(DialogClosed(PaletteElement))),
    attrs=@html.Attrs::build().aria_label("Command palette"),
    style=[
      "width:min(calc(100% - 2rem),36rem);max-width:none;margin:min(12dvh,6rem) auto auto;max-height:calc(100dvh - 2 * min(12dvh,6rem));padding:0",
    ],
    match model.dialog {
      Palette(query~, selected~) =>
        palette_content(query, selected, model, emit, mac~)
      _ => @html.nothing
    },
  )
}

///|
/// A combobox with its list. The focus stays in the search field, and
/// `aria-activedescendant` tells a screen reader which entry is selected.
fn palette_content(
  query : String,
  selected : ActionId?,
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  let actions = actions(model)
  let results = model.results(query)
  let note = if actions.iter().all(action => action.enabled(model)) {
    ""
  } else {
    "\{connection_text(model.connection)} The disabled commands need the server."
  }
  // A click in the palette does not take the focus from the search field. Only the
  // field itself uses the mouse for the cursor and the selection of text.
  let attrs = @html.Attrs::build().on_mousedown(event => {
    event.prevent_default()
    @cmd.none
  })
  @html.div(style=["padding:0.25rem"], attrs~, [
    palette_field(query, selected, actions, emit),
    // The status bar is behind the palette, so a screen reader does not read it.
    @html.p(
      id=palette_note_id,
      class="mc-palette-note",
      attrs=@html.Attrs::build().role("status"),
      note,
    ),
    @html.div(
      id=palette_list_id,
      class="mc-palette-list",
      attrs=@html.Attrs::build()
        .role("listbox")
        .aria_label("Projects and commands")
        // A list that scrolls is a stop of the Tab key in some browsers.
        .tabindex(-1),
      [Projects, Commands].map(group => {
        palette_group(
          group,
          results.filter(action => action.group() == group),
          selected,
          model,
          emit,
          mac~,
        )
      }),
    ),
    @html.p(
      class="mc-palette-empty",
      attrs=@html.Attrs::build().role("status"),
      if results.is_empty() {
        "No command found"
      } else {
        ""
      },
    ),
  ])
}

///|
/// The search field. `actions` are the ones that the page shows with it.
fn palette_field(
  query : String,
  selected : ActionId?,
  actions : ReadOnlyArray[Action],
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let attrs = @html.Attrs::build()
    .role("combobox")
    .aria_label("Find a project or a command")
    .aria_expanded("true")
    .aria_controls(palette_list_id)
    .aria_autocomplete("list")
    .aria_describedby(palette_note_id)
    .spellcheck(false)
    .autocapitalize("off")
    .on_mousedown(event => {
      event.stop_propagation()
      @cmd.none
    })
    .on_keydown(event => {
      guard palette_msg(event, actions) is Some(msg) else { @cmd.none }
      event.prevent_default()
      emit(msg)
    })
  if selected is Some(id) {
    attrs.aria_activedescendant(id.element()) |> ignore
  }
  @html.div(class="mc-palette-field", [
    icon("M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM16 16l4 4"),
    @rui.input(
      id=palette_field_id,
      value=query,
      placeholder="Find a project or a command",
      autofocus=true,
      auto_complete="off",
      on_input=@cmd.Emit(text => emit(PaletteTyped(text))),
      attrs~,
      style=[
        "height:100%;padding:0;border:0;background:transparent;box-shadow:none",
      ],
    ),
  ])
}

///|
/// The message for a key in the search field. Each other key is for the text, also the
/// ones of an input method.
fn palette_msg(
  event : @dom.KeyboardEvent,
  actions : ReadOnlyArray[Action],
) -> Msg? {
  guard !event.is_composing() &&
    !event.ctrl_key() &&
    !event.alt_key() &&
    !event.meta_key() &&
    !event.shift_key() else {
    None
  }
  match event.key() {
    "ArrowDown" => Some(PaletteMoved(Down))
    "ArrowUp" => Some(PaletteMoved(Up))
    // The key that opened the palette with its control can still be down.
    "Enter" if !event.repeat() => Some(PaletteEntered(seen=actions))
    _ => None
  }
}

///|
/// A group of the list with its name. A group with no result is not there.
fn palette_group(
  group : ActionGroup,
  results : Array[Action],
  selected : ActionId?,
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  guard !results.is_empty() else { @html.nothing }
  let (id, name) = match group {
    Projects => ("palette-projects", "Projects")
    Commands => ("palette-commands", "Commands")
  }
  let parts = {
    "heading": @html.div(
      id~,
      class="mc-palette-heading",
      attrs=@html.Attrs::build().role("presentation"),
      name,
    ),
  }
  for action in results {
    let is_selected = selected == Some(action.id())
    parts[action.id().key()] = palette_entry(
      action,
      is_selected~,
      model,
      emit,
      mac~,
    )
  }
  @html.div(
    class="mc-palette-group",
    attrs=@html.Attrs::build().role("group").aria_labelledby(id),
    parts,
  )
}

///|
fn palette_entry(
  action : Action,
  is_selected~ : Bool,
  model : Model,
  emit : @cmd.Emit[Msg],
  mac~ : Bool,
) -> @html.Html {
  let id = action.id()
  let attrs = action_attrs(action, model)
  if action is SetPrimarySidebar(_) {
    attrs.aria_keyshortcuts(ChangePrimarySidebar.aria(mac~)) |> ignore
  }
  @html.div(
    id=id.element(),
    class="mc-palette-entry",
    attrs=attrs
      .role("option")
      .aria_selected(is_selected.to_string())
      .on_mousemove(event => {
        // The browser also sends this event when the list moves below a pointer that
        // does not move.
        if is_selected ||
          (event.get_movement_x() == 0 && event.get_movement_y() == 0) {
          @cmd.none
        } else {
          emit(PalettePointed(id))
        }
      }),
    on_click=emit(ActionChosen(action)),
    match action {
      OpenProject(project) => project_lines(project)
      RemoveProject(project) =>
        // The open project can change while the palette is open.
        @html.span(
          style=["display:flex;flex-direction:column;gap:0.125rem;min-width:0"],
          [@html.span(action.title()), project_line(project)],
        )
      SetPrimarySidebar(_) =>
        @html.fragment([
          @html.span(action.title()),
          shortcut_hint(ChangePrimarySidebar, mac~),
        ])
      AddProject | StopApp => @html.span(action.title())
    },
  )
}

///|
/// The name of a project and its path in one line.
fn project_line(project : @app.Project) -> @html.Html {
  @html.span(style=["display:flex;gap:0.5rem;min-width:0"], [
    @html.span(
      class="mc-cut",
      style=[
        "flex:0 1 auto;max-width:60%;font-size:0.75rem;line-height:1.125rem;font-weight:500",
      ],
      project.name,
    ),
    short_path(project.path),
  ])
}