export const APP_ROUTE_PREFIX = "/app";

export const WORKSPACE_SECTION_KEYS = [
  "dashboard",
  "elders",
  "beds",
  "health",
  "care",
  "emergency",
  "devices",
  "notices",
  "alerts",
  "family",
  "settings",
] as const;

export const RESERVED_WORKSPACE_SLUGS = new Set<string>(WORKSPACE_SECTION_KEYS);

function splitPath(pathname: string): string[] {
  const pathOnly = pathname.split(/[?#]/, 1)[0] ?? "";
  return pathOnly.split("/").filter(Boolean);
}

export function normalizeWorkspacePath(path: string): string {
  const trimmed = path.trim();
  if (!trimmed || trimmed === "/" || trimmed === APP_ROUTE_PREFIX) {
    return "/dashboard";
  }

  if (trimmed.startsWith(`${APP_ROUTE_PREFIX}/`) || trimmed === APP_ROUTE_PREFIX) {
    return getWorkspacePathFromPathname(trimmed);
  }

  const withLeadingSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
  return withLeadingSlash.replace(/\/{2,}/g, "/");
}

export function getWorkspacePathFromPathname(pathname: string): string {
  const segments = splitPath(pathname);
  if (segments[0] !== "app") {
    return "/dashboard";
  }

  const appSegments = segments.slice(1);
  if (appSegments.length === 0) {
    return "/dashboard";
  }

  const firstSegment = appSegments[0] ?? "";
  if (RESERVED_WORKSPACE_SLUGS.has(firstSegment)) {
    return `/${appSegments.join("/")}`;
  }

  const scopedSegments = appSegments.slice(1);
  return scopedSegments.length > 0 ? `/${scopedSegments.join("/")}` : "/dashboard";
}

export function getWorkspaceSlugFromPathname(pathname: string): string | undefined {
  const segments = splitPath(pathname);
  if (segments[0] !== "app") {
    return undefined;
  }

  const candidate = segments[1];
  if (!candidate || RESERVED_WORKSPACE_SLUGS.has(candidate)) {
    return undefined;
  }

  return candidate;
}

export function getWorkspaceHref(organizationSlug: string | undefined, path = "/dashboard"): string {
  const workspacePath = normalizeWorkspacePath(path);
  const slug = organizationSlug?.trim();

  if (!slug) {
    return `${APP_ROUTE_PREFIX}${workspacePath}`;
  }

  return `${APP_ROUTE_PREFIX}/${encodeURIComponent(slug)}${workspacePath}`;
}

export function isWorkspacePathActive(pathname: string, itemPath: string): boolean {
  const currentPath = getWorkspacePathFromPathname(pathname);
  const normalizedItemPath = normalizeWorkspacePath(itemPath);

  if (normalizedItemPath === "/dashboard") {
    return currentPath === "/dashboard";
  }

  return currentPath === normalizedItemPath || currentPath.startsWith(`${normalizedItemPath}/`);
}
