var MNOTE_SIDEBAR_TREE_MODE_KEY = 'mnote.sidebar.tree.mode';
var MNOTE_SIDEBAR_WIDTH_STORAGE_KEY = 'mnote.workspace.sidebarWidth.v1';
var MNOTE_SIDEBAR_MIN_WIDTH = 220;
var MNOTE_SIDEBAR_MAX_WIDTH = 520;
var MNOTE_SIDEBAR_DEFAULT_WIDTH = 248;

function normalizeSidebarTreeModeForShell(mode) {
  return mode === 'filetree' ? 'filetree' : 'page';
}

function readStoredSidebarTreeMode() {
  var params = new URLSearchParams(window.location.search);
  var fromUrl = normalizeSidebarTreeModeForShell(params.get('treeView') || params.get('sidebarTree'));
  if (params.has('treeView') || params.has('sidebarTree')) return fromUrl;
  try {
    var stored = window.sessionStorage ? window.sessionStorage.getItem(MNOTE_SIDEBAR_TREE_MODE_KEY) : '';
    return normalizeSidebarTreeModeForShell(stored);
  } catch (_) {
    return 'page';
  }
}

function persistSidebarTreeMode(mode) {
  var normalized = normalizeSidebarTreeModeForShell(mode);
  document.documentElement.setAttribute('data-mnote-sidebar-tree-mode', normalized);
  try {
    if (window.sessionStorage) window.sessionStorage.setItem(MNOTE_SIDEBAR_TREE_MODE_KEY, normalized);
  } catch (_) {}
  return normalized;
}

function activeSidebarTreeMode() {
  var active = document.querySelector('[data-mnote-sidebar-tree-tab][aria-selected="true"]');
  if (active instanceof HTMLElement) {
    return normalizeSidebarTreeModeForShell(active.getAttribute('data-mnote-sidebar-tree-tab'));
  }
  return readStoredSidebarTreeMode();
}

function toggleWorkspaceSidebar(trigger) {
  var shell = document.querySelector('.mnote-shell, .wolai-workspace-shell');
  if (!(shell instanceof HTMLElement)) return;
  var collapsed = shell.getAttribute('data-mnote-sidebar-collapsed') === 'true';
  var next = !collapsed;
  shell.setAttribute('data-mnote-sidebar-collapsed', String(next));
  document.documentElement.setAttribute('data-mnote-sidebar-collapsed', String(next));
  document.documentElement.setAttribute('data-mnote-sidebar-toggle-applied', 'true');
  if (trigger instanceof HTMLElement) {
    trigger.setAttribute('aria-pressed', String(next));
    trigger.setAttribute('title', next ? '展开侧栏' : '切换侧栏');
  }
}

function clampSidebarWidth(value) {
  var width = Number(value);
  if (!Number.isFinite(width)) return MNOTE_SIDEBAR_DEFAULT_WIDTH;
  return Math.max(MNOTE_SIDEBAR_MIN_WIDTH, Math.min(MNOTE_SIDEBAR_MAX_WIDTH, width));
}

function installWorkspaceSidebarResizer() {
  var shell = document.querySelector('.mnote-shell, .wolai-workspace-shell');
  var sidebar = document.querySelector('[data-testid="wolai-sidebar"]');
  var resizer = document.querySelector('[data-mnote-sidebar-resizer="true"]');
  if (!(shell instanceof HTMLElement) || !(sidebar instanceof HTMLElement) || !(resizer instanceof HTMLElement)) return;
  if (resizer.getAttribute('data-mnote-sidebar-resizer-bound') === 'true') return;
  resizer.setAttribute('data-mnote-sidebar-resizer-bound', 'true');

  function applyWidth(value) {
    var width = clampSidebarWidth(value);
    shell.style.setProperty('--mnote-sidebar-width', width + 'px');
    document.documentElement.setAttribute('data-mnote-sidebar-width', String(width));
    return width;
  }

  try {
    var stored = Number(window.localStorage.getItem(MNOTE_SIDEBAR_WIDTH_STORAGE_KEY) || '');
    if (stored) applyWidth(stored);
  } catch (_) {}

  resizer.addEventListener('wheel', function(event) {
    event.preventDefault();
    event.stopPropagation();
  }, { passive: false });
  resizer.addEventListener('pointerdown', function(event) {
    if (event.button !== 0) return;
    event.preventDefault();
    var startX = event.clientX;
    var startWidth = sidebar.getBoundingClientRect().width || clampSidebarWidth(0);
    resizer.setPointerCapture(event.pointerId);
    document.documentElement.setAttribute('data-mnote-sidebar-resizing', 'true');
    function onMove(moveEvent) {
      applyWidth(startWidth + moveEvent.clientX - startX);
    }
    function onEnd(endEvent) {
      resizer.removeEventListener('pointermove', onMove);
      resizer.removeEventListener('pointerup', onEnd);
      resizer.removeEventListener('pointercancel', onEnd);
      try { resizer.releasePointerCapture(endEvent.pointerId); } catch (_) {}
      document.documentElement.removeAttribute('data-mnote-sidebar-resizing');
      try {
        window.localStorage.setItem(MNOTE_SIDEBAR_WIDTH_STORAGE_KEY, String(Math.round(sidebar.getBoundingClientRect().width)));
      } catch (_) {}
    }
    resizer.addEventListener('pointermove', onMove);
    resizer.addEventListener('pointerup', onEnd);
    resizer.addEventListener('pointercancel', onEnd);
  });
}

function applySidebarTreeTab(mode, shell) {
  mode = persistSidebarTreeMode(mode);
  shell = shell || document.querySelector('[data-testid="wolai-sidebar-page-tree-shell"]');
  if (!shell) return;
  var tabs = shell.querySelectorAll('[data-mnote-sidebar-tree-tab]');
  for (var i = 0; i < tabs.length; i++) {
    var isActive = tabs[i].getAttribute('data-mnote-sidebar-tree-tab') === mode;
    tabs[i].setAttribute('aria-selected', isActive ? 'true' : 'false');
    tabs[i].classList.toggle('wolai-sidebar-tab-active', isActive);
    tabs[i].classList.toggle('wolai-sidebar-tab-muted', !isActive);
  }
  var panels = shell.querySelectorAll('[data-mnote-sidebar-tree-panel]');
  for (var j = 0; j < panels.length; j++) {
    var isCurrentPanel = panels[j].getAttribute('data-mnote-sidebar-tree-panel') === mode;
    panels[j].hidden = !isCurrentPanel;
  }
}

function switchSidebarTreeTab(trigger) {
  var mode = trigger ? trigger.getAttribute('data-mnote-sidebar-tree-tab') : 'page';
  applySidebarTreeTab(mode, trigger ? trigger.closest('[data-testid="wolai-sidebar-page-tree-shell"]') : null);
}

function restoreSidebarTreeTab() {
  applySidebarTreeTab(readStoredSidebarTreeMode(), null);
}

if (!window.__mnoteSidebarShellRuntime) {
  window.__mnoteSidebarShellRuntime = {
    activeSidebarTreeMode: activeSidebarTreeMode,
    applySidebarTreeTab: applySidebarTreeTab,
    installWorkspaceSidebarResizer: installWorkspaceSidebarResizer,
    persistSidebarTreeMode: persistSidebarTreeMode,
    readStoredSidebarTreeMode: readStoredSidebarTreeMode,
    restoreSidebarTreeTab: restoreSidebarTreeTab,
    switchSidebarTreeTab: switchSidebarTreeTab,
    toggleWorkspaceSidebar: toggleWorkspaceSidebar
  };
}
