// SPDX-FileCopyrightText: 2026 Stan Grams <sjg@haxx.space>
//
// SPDX-License-Identifier: GPL-2.0-or-later

export const TAB_ORDER = [
  "main", "bookmarks", "digital-modes", "map", "statistics", "recorder", "settings", "about",
] as const;

export type TabName = typeof TAB_ORDER[number];

export const TAB_PATHS: Readonly<Record<TabName, string>> = {
  main: "/",
  bookmarks: "/bookmarks",
  "digital-modes": "/digital-modes",
  map: "/map",
  statistics: "/statistics",
  recorder: "/recorder",
  settings: "/settings",
  about: "/about",
};

export function normalizeTabPath(pathname: string): string {
  const raw = pathname.length > 0 ? pathname : "/";
  return raw === "/" ? "/" : raw.replace(/\/+$/, "") || "/";
}

export function tabFromPath(pathname: string): TabName {
  const normalized = normalizeTabPath(pathname);
  const match = Object.entries(TAB_PATHS).find(([, path]) => path === normalized);
  return match ? match[0] as TabName : "main";
}

export function updateTabHistory(name: TabName, replace = false): void {
  const targetPath = TAB_PATHS[name];
  if (normalizeTabPath(window.location.pathname) === targetPath) return;
  const nextUrl = `${targetPath}${window.location.search}${window.location.hash}`;
  if (replace) window.history.replaceState({}, "", nextUrl);
  else window.history.pushState({}, "", nextUrl);
}
