// MNote 资源打开运行时外置模块。
// 当前先承接 SIDEBAR_TREE_JS 中的低风险纯辅助函数。
// 本文件以 type="module" 加载，执行时机可能晚于 inline script。
// SIDEBAR_TREE_JS 会在运行时优先委托到 window.__mnoteResourceOpenRuntime。
// 模块尚未加载或加载失败时，inline script 保留原实现兜底。

function localFilePathFromAssetId(assetId) {
  var value = String(assetId || '').trim();
  return value.indexOf('local-file:') === 0
    ? value.slice('local-file:'.length)
    : value.indexOf('local:asset:') === 0
      ? value.slice('local:asset:'.length)
      : '';
}

function buildLocalFileOpenUrl(relativePath, download) {
  var rootUri = currentRootUri();
  if (!rootUri || !relativePath) return '';
  var url = new URL('/api/local-folder/files/open', window.location.origin);
  url.searchParams.set('rootUri', rootUri);
  url.searchParams.set('path', relativePath);
  if (download) url.searchParams.set('download', 'true');
  return url.toString();
}

function buildPdfPreviewOpenUrl(fileUrl, fileName) {
  var rawUrl = String(fileUrl || '').trim();
  if (!rawUrl) return '';
  var url = new URL('/pdf-preview', window.location.origin);
  url.searchParams.set('fileUrl', rawUrl);
  if (fileName) url.searchParams.set('fileName', fileName);
  return url.toString();
}

function shouldUseOfficePreview(fileType, mode) {
  var normalizedMode = String(mode || 'view').trim().toLowerCase();
  if (normalizedMode === 'edit') return false;
  var ext = String(fileType || '').trim().toLowerCase();
  return ['docx', 'xlsx', 'xls', 'csv', 'pptx'].indexOf(ext) >= 0;
}

function buildOfficePreviewOpenUrl(input) {
  var target = new URL('/office-preview', window.location.origin);
  var workspacePath = input && input.workspacePath && typeof input.workspacePath === 'object' ? input.workspacePath : {};
  var fileUrl = String(input.fileUrl || '').trim();
  if (fileUrl) {
    try {
      fileUrl = new URL(fileUrl, window.location.origin).toString();
    } catch (_error) {}
  }
  target.searchParams.set('fileUrl', fileUrl);
  target.searchParams.set('fileName', input.fileName || '未命名资源');
  target.searchParams.set('fileType', input.fileType || 'docx');
  if (input.assetId) target.searchParams.set('assetId', input.assetId);
  if (input.documentId) target.searchParams.set('documentId', input.documentId);
  if (input.userId) target.searchParams.set('userId', input.userId);
  var workspaceId = String(input.workspaceId || workspacePath.workspaceId || '').trim();
  var sourceKind = String(input.sourceKind || workspacePath.sourceKind || currentSourceKind() || '').trim();
  var rootUri = String(input.rootUri || workspacePath.rootUri || currentRootUri() || '').trim();
  if (workspaceId) target.searchParams.set('workspaceId', workspaceId);
  if (sourceKind) target.searchParams.set('sourceKind', sourceKind);
  if (rootUri) target.searchParams.set('rootUri', rootUri);
  return target.toString();
}

function buildOnlyOfficeOpenPath(input) {
  if (shouldUseOfficePreview(input.fileType, input.mode)) {
    return buildOfficePreviewOpenUrl(input);
  }
  var params = new URLSearchParams();
  params.set('fileUrl', input.fileUrl || '');
  params.set('fileName', input.fileName || '未命名资源');
  params.set('fileType', input.fileType || 'docx');
  if (input.assetId) params.set('assetId', input.assetId);
  if (input.documentId) params.set('documentId', input.documentId);
  if (input.userId) params.set('userId', input.userId);
  params.set('mode', input.mode || 'view');
  if (input.documentId && input.assetId) {
    return '/office/' + encodeURIComponent(input.documentId) + '/' + encodeURIComponent(input.assetId) + '?' + params.toString();
  }
  return '/onlyoffice?' + params.toString();
}

function currentRootUri() {
  var params = new URLSearchParams(window.location.search);
  var fromUrl = (params.get('rootUri') || '').trim();
  if (fromUrl) return fromUrl;
  return document.body instanceof HTMLElement
    ? (document.body.getAttribute('data-mnote-root-uri') || '').trim()
    : '';
}

function currentSourceKind() {
  var params = new URLSearchParams(window.location.search);
  var fromUrl = (params.get('sourceKind') || '').trim();
  if (fromUrl) return fromUrl;
  return document.body instanceof HTMLElement
    ? (document.body.getAttribute('data-mnote-source-kind') || '').trim()
    : '';
}

window.__mnoteResourceOpenRuntime = {
  localFilePathFromAssetId: localFilePathFromAssetId,
  buildLocalFileOpenUrl: buildLocalFileOpenUrl,
  buildPdfPreviewOpenUrl: buildPdfPreviewOpenUrl,
  buildOfficePreviewOpenUrl: buildOfficePreviewOpenUrl,
  buildOnlyOfficeOpenPath: buildOnlyOfficeOpenPath
};
