// MNote debug /tree shell state parsing and normalization helpers.

export function parseTreeShellState(stateElement) {
  try {
    return JSON.parse(stateElement?.textContent || "{}");
  } catch {
    return {};
  }
}

export function normalizeTreeShellText(value, fallback = "") {
  if (typeof value !== "string") return fallback;
  const trimmed = value.trim();
  return trimmed || fallback;
}

export function normalizeTreeShellStringArray(value) {
  return Array.isArray(value)
    ? value
        .map((item) => (typeof item === "string" ? item.trim() : ""))
        .filter(Boolean)
    : [];
}

export function normalizeTreeShellNumber(value, fallback = Number.MAX_SAFE_INTEGER) {
  return Number.isFinite(value) ? Number(value) : fallback;
}

export function resolveTreeShellMode(state) {
  const rawMode = typeof state?.mode === "string" ? state.mode.trim() : "";
  if (rawMode === "picker") return "picker";
  if (rawMode === "filetree") return "filetree";
  return "page";
}

export function resolveTreeShellTargetOrigin(documentRef) {
  try {
    if (!documentRef?.referrer) return "*";
    return new URL(documentRef.referrer).origin || "*";
  } catch {
    return "*";
  }
}

export function parseTreeShellStateFromHtml(html) {
  const doc = new DOMParser().parseFromString(html, "text/html");
  const nextStateElement = doc.getElementById("tree-shell-state");
  if (!nextStateElement) return null;
  try {
    return JSON.parse(nextStateElement.textContent || "{}");
  } catch {
    return null;
  }
}
