// Draggable & keyboard-accessible splitters and collapsible drawer states for
// the primary left sidebar, the secondary left sidebar (Review / Knowledge
// outlines), and the right companion panel, persisted in `localStorage`.

///|
let sidebar_width_key : String = "mission-control-sidebar-width"

///|
let secondary_sidebar_key : String = "mission-control-secondary-sidebar"

///|
let secondary_sidebar_width_key : String = "mission-control-secondary-sidebar-width"

///|
let companion_panel_key : String = "mission-control-companion-panel"

///|
let default_sidebar_width : Int32 = 272

///|
let min_sidebar_width : Int32 = 200

///|
let max_sidebar_width : Int32 = 520

///|
let default_secondary_width : Int32 = 248

///|
let min_secondary_width : Int32 = 190

///|
let max_secondary_width : Int32 = 440

///|
const SidebarSplitterId : String = "mc-sidebar-splitter"

///|
const SecondarySplitterId : String = "mc-secondary-splitter"

///|
/// Pure non-negative decimal integer parser used for persisted pixel widths.
fn parse_positive_int(text : String) -> Int32? {
  let trimmed = text.trim(chars=" \t\r\n")
  if trimmed.is_empty() {
    return None
  }
  let mut acc = 0
  for ch in trimmed {
    if ch < '0' || ch > '9' {
      return None
    }
    let digit = ch.to_int() - '0'.to_int()
    if acc > 100000 {
      return Some(acc)
    }
    acc = acc * 10 + digit
  }
  Some(acc)
}

///|
fn clamp_int(value : Int32, low : Int32, high : Int32) -> Int32 {
  if value < low {
    low
  } else if value > high {
    high
  } else {
    value
  }
}

///|
/// Clamped pixel width of the desktop primary sidebar.
#derive(Eq, Debug)
pub struct SidebarWidth(Int32)

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

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

///|
pub fn SidebarWidth::default() -> SidebarWidth {
  SidebarWidth(default_sidebar_width)
}

///|
pub fn SidebarWidth::clamped(px : Int32) -> SidebarWidth {
  SidebarWidth(clamp_int(px, min_sidebar_width, max_sidebar_width))
}

///|
pub fn SidebarWidth::of_stored(text : String) -> SidebarWidth {
  match parse_positive_int(text) {
    Some(px) => SidebarWidth::clamped(px)
    None => SidebarWidth::default()
  }
}

///|
pub fn SidebarWidth::stored(self : SidebarWidth) -> String {
  self.0.to_string()
}

///|
pub fn SidebarWidth::pixels(self : SidebarWidth) -> Int32 {
  self.0
}

///|
pub fn SidebarWidth::step_by(
  self : SidebarWidth,
  delta : Int32,
) -> SidebarWidth {
  SidebarWidth::clamped(self.0 + delta)
}

///|
/// Open/collapsed state of the secondary left sidebar inside Review and
/// Knowledge perspectives.
#derive(Eq, Debug)
pub(all) enum SecondarySidebar {
  SecondaryShown
  SecondaryHidden
}

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

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

///|
pub fn SecondarySidebar::of_stored(text : String) -> SecondarySidebar {
  match text {
    "hidden" => SecondaryHidden
    _ => SecondaryShown
  }
}

///|
pub fn SecondarySidebar::stored(self : SecondarySidebar) -> String {
  match self {
    SecondaryShown => "shown"
    SecondaryHidden => "hidden"
  }
}

///|
pub fn SecondarySidebar::other(self : SecondarySidebar) -> SecondarySidebar {
  match self {
    SecondaryShown => SecondaryHidden
    SecondaryHidden => SecondaryShown
  }
}

///|
/// Clamped pixel width of the secondary left sidebar.
#derive(Eq, Debug)
pub struct SecondarySidebarWidth(Int32)

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

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

///|
pub fn SecondarySidebarWidth::default() -> SecondarySidebarWidth {
  SecondarySidebarWidth(default_secondary_width)
}

///|
pub fn SecondarySidebarWidth::clamped(px : Int32) -> SecondarySidebarWidth {
  SecondarySidebarWidth(clamp_int(px, min_secondary_width, max_secondary_width))
}

///|
pub fn SecondarySidebarWidth::of_stored(text : String) -> SecondarySidebarWidth {
  match parse_positive_int(text) {
    Some(px) => SecondarySidebarWidth::clamped(px)
    None => SecondarySidebarWidth::default()
  }
}

///|
pub fn SecondarySidebarWidth::stored(self : SecondarySidebarWidth) -> String {
  self.0.to_string()
}

///|
pub fn SecondarySidebarWidth::pixels(self : SecondarySidebarWidth) -> Int32 {
  self.0
}

///|
pub fn SecondarySidebarWidth::step_by(
  self : SecondarySidebarWidth,
  delta : Int32,
) -> SecondarySidebarWidth {
  SecondarySidebarWidth::clamped(self.0 + delta)
}

///|
/// Open/collapsed state of the right companion panel in Review and Knowledge.
#derive(Eq, Debug)
pub(all) enum CompanionPanel {
  CompanionShown
  CompanionHidden
}

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

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

///|
pub fn CompanionPanel::of_stored(text : String) -> CompanionPanel {
  match text {
    "hidden" => CompanionHidden
    _ => CompanionShown
  }
}

///|
pub fn CompanionPanel::stored(self : CompanionPanel) -> String {
  match self {
    CompanionShown => "shown"
    CompanionHidden => "hidden"
  }
}

///|
pub fn CompanionPanel::other(self : CompanionPanel) -> CompanionPanel {
  match self {
    CompanionShown => CompanionHidden
    CompanionHidden => CompanionShown
  }
}

///|
fn sidebar_splitter_key(event : @html.Keyboard, width : SidebarWidth) -> Msg? {
  let step = if event.shift_key() { 48 } else { 16 }
  match event.key() {
    "ArrowLeft" => Some(SidebarResized(width.step_by(-step)))
    "ArrowRight" => Some(SidebarResized(width.step_by(step)))
    "Home" => Some(SidebarResized(SidebarWidth::clamped(min_sidebar_width)))
    "End" => Some(SidebarResized(SidebarWidth::clamped(max_sidebar_width)))
    "Enter" | "0" => Some(SidebarResized(SidebarWidth::default()))
    _ => None
  }
}

///|
fn secondary_splitter_key(
  event : @html.Keyboard,
  width : SecondarySidebarWidth,
) -> Msg? {
  let step = if event.shift_key() { 48 } else { 16 }
  match event.key() {
    "ArrowLeft" => Some(SecondarySidebarResized(width.step_by(-step)))
    "ArrowRight" => Some(SecondarySidebarResized(width.step_by(step)))
    "Home" =>
      Some(
        SecondarySidebarResized(
          SecondarySidebarWidth::clamped(min_secondary_width),
        ),
      )
    "End" =>
      Some(
        SecondarySidebarResized(
          SecondarySidebarWidth::clamped(max_secondary_width),
        ),
      )
    "Enter" | "0" =>
      Some(SecondarySidebarResized(SecondarySidebarWidth::default()))
    _ => None
  }
}

///|
/// Shared pointer-capture drag + double-click reset binder for vertical
/// splitters. Updates `css_var` on `.mc-shell-root` at 60fps during drag and
/// commits the final clamped width on pointer release.
extern "js" fn bind_vertical_splitter(
  id : String,
  css_var : String,
  target_selector : String,
  min_w : Int32,
  max_w : Int32,
  default_w : Int32,
  on_commit : (Int32) -> Unit,
) -> Unit =
  #| (id, cssVar, targetSelector, minW, maxW, defaultW, onCommit) => {
  #|   if (typeof document === "undefined") return;
  #|   const el = document.getElementById(id);
  #|   if (!el || el.dataset.mcBound === "1") return;
  #|   el.dataset.mcBound = "1";
  #|   let dragging = false;
  #|   let startX = 0;
  #|   let startW = defaultW;
  #|   let lastW = defaultW;
  #|   const clamp = (raw) => {
  #|     const vpMax = Math.max(minW, Math.min(maxW, (window.innerWidth || 1200) - 320));
  #|     return Math.max(minW, Math.min(vpMax, Math.round(raw)));
  #|   };
  #|   const apply = (px) => {
  #|     const root = el.closest(".mc-shell-root");
  #|     if (root) root.style.setProperty(cssVar, px + "px");
  #|     el.setAttribute("aria-valuenow", String(px));
  #|     el.setAttribute("aria-valuetext", px + "px");
  #|   };
  #|   el.addEventListener("pointerdown", (e) => {
  #|     if (e.button !== 0) return;
  #|     e.preventDefault();
  #|     const root = el.closest(".mc-shell-root");
  #|     const pane = root && root.querySelector(targetSelector);
  #|     startW = pane ? pane.getBoundingClientRect().width : defaultW;
  #|     lastW = clamp(startW);
  #|     startX = e.clientX;
  #|     dragging = true;
  #|     if (root) root.setAttribute("data-resizing", "true");
  #|     el.setAttribute("data-dragging", "true");
  #|     try { el.setPointerCapture(e.pointerId); } catch {}
  #|   });
  #|   el.addEventListener("pointermove", (e) => {
  #|     if (!dragging) return;
  #|     const next = clamp(startW + (e.clientX - startX));
  #|     if (next !== lastW) {
  #|       lastW = next;
  #|       apply(next);
  #|     }
  #|   });
  #|   const finish = (e) => {
  #|     if (!dragging) return;
  #|     dragging = false;
  #|     const root = el.closest(".mc-shell-root");
  #|     if (root) root.removeAttribute("data-resizing");
  #|     el.removeAttribute("data-dragging");
  #|     try { el.releasePointerCapture(e.pointerId); } catch {}
  #|     onCommit(lastW);
  #|   };
  #|   el.addEventListener("pointerup", finish);
  #|   el.addEventListener("pointercancel", finish);
  #|   el.addEventListener("dblclick", (e) => {
  #|     e.preventDefault();
  #|     const next = clamp(defaultW);
  #|     apply(next);
  #|     onCommit(next);
  #|   });
  #| }

///|
/// Post-render command that ensures both primary and secondary left splitters
/// have their pointer drag & double-click handlers bound whenever present.
fn sync_sidebar_splitter_cmd(emit : @cmd.Emit[Msg]) -> @cmd.Cmd {
  @cmd.custom_cmd(
    scheduler => {
      bind_vertical_splitter(
        SidebarSplitterId,
        "--rui-sidebar-width",
        "[data-slot=\"sidebar-shell\"]",
        min_sidebar_width,
        max_sidebar_width,
        default_sidebar_width,
        px => scheduler.add(emit(SidebarResized(SidebarWidth::clamped(px)))),
      )
      bind_vertical_splitter(
        SecondarySplitterId,
        "--mc-secondary-width",
        ".mc-review-outline",
        min_secondary_width,
        max_secondary_width,
        default_secondary_width,
        px => {
          scheduler.add(
            emit(SecondarySidebarResized(SecondarySidebarWidth::clamped(px))),
          )
        },
      )
    },
    kind=@cmd.after_render,
  )
}

///|
/// Draggable & keyboard-accessible vertical splitter for the primary sidebar.
fn sidebar_splitter_view(
  width : SidebarWidth,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let px = width.pixels()
  @html.div(
    id=SidebarSplitterId,
    class="mc-sidebar-splitter",
    title="Drag to resize sidebar · Double-click to reset",
    attrs=@html.Attrs::build()
      .role("separator")
      .aria_orientation("vertical")
      .aria_label("Resize primary sidebar")
      .aria_valuemin(min_sidebar_width.to_string())
      .aria_valuemax(max_sidebar_width.to_string())
      .aria_valuenow(px.to_string())
      .aria_valuetext("\{px}px")
      .tabindex(0),
    on_keydown=@cmd.Emit(event => {
      match sidebar_splitter_key(event, width) {
        Some(msg) => emit(msg)
        None => @cmd.none
      }
    }),
    @html.nothing,
  )
}

///|
/// Draggable & keyboard-accessible vertical splitter for the secondary left
/// sidebar inside Review and Knowledge perspectives.
fn secondary_splitter_view(
  width : SecondarySidebarWidth,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  let px = width.pixels()
  @html.div(
    id=SecondarySplitterId,
    class="mc-sidebar-splitter mc-secondary-splitter",
    title="Drag to resize navigation panel · Double-click to reset",
    attrs=@html.Attrs::build()
      .role("separator")
      .aria_orientation("vertical")
      .aria_label("Resize secondary sidebar")
      .aria_valuemin(min_secondary_width.to_string())
      .aria_valuemax(max_secondary_width.to_string())
      .aria_valuenow(px.to_string())
      .aria_valuetext("\{px}px")
      .tabindex(0),
    on_keydown=@cmd.Emit(event => {
      match secondary_splitter_key(event, width) {
        Some(msg) => emit(msg)
        None => @cmd.none
      }
    }),
    @html.nothing,
  )
}

///|
/// Renders the collapsible, resizable secondary left sidebar (or its collapsed
/// vertical rail strip) for Review and Knowledge perspectives.
fn secondary_sidebar_shell(
  model : Model,
  title~ : String,
  count~ : String,
  emit : @cmd.Emit[Msg],
  header_extras : Array[@html.Html],
  body : Array[@html.Html],
) -> @html.Html {
  match model.secondary_sidebar {
    SecondaryHidden =>
      @html.div(class="mc-pane-rail left", [
        @html.button(
          class="mc-pane-rail-btn",
          type_="button",
          title="Expand \{title} sidebar",
          attrs=@html.Attrs::build()
            .aria_label("Expand \{title} sidebar")
            .aria_expanded("false"),
          on_click=emit(SecondarySidebarToggled),
          [icon("M9 6l6 6-6 6"), @html.span(class="mc-pane-rail-label", title)],
        ),
      ])
    SecondaryShown => {
      let header_children : Array[@html.Html] = [
        @html.div(class="mc-pane-head-row", [
          @html.div(
            style=[
              "display:flex;align-items:baseline;gap:0.45rem;min-width:0;flex:1",
            ],
            [
              @html.span(class="mc-pane-title", title),
              @html.span(class="mc-pane-count", count),
            ],
          ),
          @html.button(
            class="mc-pane-toggle-btn",
            type_="button",
            title="Collapse \{title} sidebar",
            attrs=@html.Attrs::build()
              .aria_label("Collapse \{title} sidebar")
              .aria_expanded("true"),
            on_click=emit(SecondarySidebarToggled),
            icon("M15 6l-6 6 6 6"),
          ),
        ]),
      ]
      for extra in header_extras {
        header_children.push(extra)
      }
      let aside_children : Array[@html.Html] = [
        @html.div(class="mc-pane-header", header_children),
      ]
      for child in body {
        aside_children.push(child)
      }
      @html.fragment([
        @html.aside(class="mc-review-outline", aside_children),
        secondary_splitter_view(model.secondary_sidebar_width, emit),
      ])
    }
  }
}

///|
/// Renders the collapsible right companion panel (or its collapsed vertical
/// rail strip) for Review and Knowledge perspectives.
fn companion_panel_shell(
  model : Model,
  title~ : String,
  emit : @cmd.Emit[Msg],
  content : Array[@html.Html],
) -> @html.Html {
  match model.companion_panel {
    CompanionHidden =>
      @html.div(class="mc-pane-rail right", [
        @html.button(
          class="mc-pane-rail-btn",
          type_="button",
          title="Expand \{title} panel",
          attrs=@html.Attrs::build()
            .aria_label("Expand \{title} panel")
            .aria_expanded("false"),
          on_click=emit(CompanionPanelToggled),
          [
            icon("M15 6l-6 6 6 6"),
            @html.span(class="mc-pane-rail-label", title),
          ],
        ),
      ])
    CompanionShown => @html.aside(class="mc-review-companion", content)
  }
}

///|
/// Subtle collapse button placed inside an expanded right companion header.
fn companion_collapse_button(
  title~ : String,
  emit : @cmd.Emit[Msg],
) -> @html.Html {
  @html.button(
    class="mc-pane-toggle-btn",
    type_="button",
    title="Collapse \{title} panel",
    attrs=@html.Attrs::build()
      .aria_label("Collapse \{title} panel")
      .aria_expanded("true"),
    on_click=emit(CompanionPanelToggled),
    icon("M9 6l6 6-6 6"),
  )
}