/** Default Kaleidoscope Dashboard path (Kindergarten). */
export const DEFAULT_KALEIDOSCOPE_HREF = "/grade/kg";

/** Paths that mean Spark / site home — never valid as "Back to Kaleidoscope". */
const SPARK_DASHBOARD_HREFS = new Set(["", "/", "/signin", "/home"]);

/**
 * Strip admin + preview prefixes so we can derive /grade/:id from the current URL.
 * Uses the browser pathname (includes /secure-access) when provided.
 */
export function publicPathFromLocationPathname(pathname: string): string {
  let path = pathname.trim() || "/";
  if (path.startsWith("/secure-access")) {
    path = path.slice("/secure-access".length) || "/";
  }
  if (path === "/preview" || path.startsWith("/preview/")) {
    path = path.replace(/^\/preview\/?/, "/") || "/";
  }
  path = path.replace(/\/+$/, "") || "/";
  return path.startsWith("/") ? path : `/${path}`;
}

/**
 * Derive Kaleidoscope Dashboard href from a curriculum (or grade) public path.
 * `/grade/kg/curriculum` → `/grade/kg`
 */
export function kaleidoscopeHrefFromPublicPath(publicPath: string): string {
  const match = publicPath.match(/^\/grade\/([^/]+)/i);
  if (match?.[1]) {
    return `/grade/${match[1]}`;
  }
  return DEFAULT_KALEIDOSCOPE_HREF;
}

function normalizeHref(raw: string): string {
  const trimmed = raw.trim();
  if (!trimmed) return "";
  return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
}

/**
 * Resolve the Curriculum Hero "Back to Kaleidoscope" target.
 * - Honors a configured backHref when it is not the Spark Dashboard (`/`).
 * - Otherwise derives `/grade/:grade` from the current page path.
 */
export function resolveCurriculumHeroBackHref(
  configuredHref: unknown,
  locationPathname: string
): string {
  const configured = typeof configuredHref === "string" ? normalizeHref(configuredHref) : "";
  if (configured && !SPARK_DASHBOARD_HREFS.has(configured.toLowerCase())) {
    return configured;
  }
  return kaleidoscopeHrefFromPublicPath(publicPathFromLocationPathname(locationPathname));
}

export type CurriculumHeroBackNav = {
  /** Path to navigate to (may include /preview prefix). */
  href: string;
  /**
   * When false, use a plain <a href> so navigation leaves the admin shell
   * (/secure-access) instead of being caught by the admin router.
   */
  useRouterLink: boolean;
};

/**
 * Build preview/published/admin-safe navigation for the Kaleidoscope back link.
 */
export function resolveCurriculumHeroBackNav(
  configuredHref: unknown,
  locationPathname: string
): CurriculumHeroBackNav {
  const kaleidoscopeHref = resolveCurriculumHeroBackHref(configuredHref, locationPathname);
  const browserPath = locationPathname.trim() || "/";

  // Admin Page Editor / component preview: React Router basename is /secure-access.
  // A <Link to="/grade/kg"> becomes /secure-access/grade/kg → catch-all → admin dashboard.
  if (browserPath.startsWith("/secure-access")) {
    return { href: kaleidoscopeHref, useRouterLink: false };
  }

  // Public preview mode: keep the user inside /preview/*
  if (browserPath === "/preview" || browserPath.startsWith("/preview/")) {
    if (kaleidoscopeHref === "/") {
      return { href: "/preview", useRouterLink: true };
    }
    return { href: `/preview${kaleidoscopeHref}`, useRouterLink: true };
  }

  return { href: kaleidoscopeHref, useRouterLink: true };
}
