/**
 * Mémoire de navigation de l'onglet (sessionStorage) : sert à revenir « à la
 * page d'où l'on vient » sans empiler de nouvelles entrées d'historique, et à
 * sortir du wizard d'un seul geste malgré une entrée d'historique par étape.
 *
 * sessionStorage est propre à l'onglet et survit au rechargement, comme la pile
 * d'historique du navigateur qu'il décrit. Toute lecture/écriture est protégée :
 * stockage indisponible = comportement de repli (navigation simple).
 */

const TRAIL_KEY = 'nav:trail';
const TRAIL_MAX = 30;

function read<T>(key: string, fallback: T): T {
  try {
    const raw = window.sessionStorage.getItem(key);
    return raw ? (JSON.parse(raw) as T) : fallback;
  } catch {
    return fallback;
  }
}

function write(key: string, value: unknown): void {
  try {
    window.sessionStorage.setItem(key, JSON.stringify(value));
  } catch {
    // Stockage indisponible (navigation privée…) : on s'en passe.
  }
}

/** `/installation` (brouillon) ou `/installation/{id}` : pages du wizard. */
export function isWizardPath(path: string): boolean {
  return /^\/installation(\/\d+)?$/.test(path);
}

/** Enregistre la page affichée (pathname seul), sans doublon consécutif. */
export function recordPath(path: string): void {
  const trail = read<string[]>(TRAIL_KEY, []);
  if (trail[trail.length - 1] === path) return;
  trail.push(path);
  write(TRAIL_KEY, trail.slice(-TRAIL_MAX));
}

/** Page affichée juste avant la page courante, ou null. */
export function previousPath(): string | null {
  const trail = read<string[]>(TRAIL_KEY, []);
  return trail.length >= 2 ? trail[trail.length - 2] : null;
}

/**
 * Dernière page hors wizard avant d'y entrer (la page d'origine), ou null si
 * le wizard a été ouvert directement (nouvel onglet, lien).
 */
export function wizardOriginPath(): string | null {
  const trail = read<string[]>(TRAIL_KEY, []);
  let i = trail.length - 1;
  while (i >= 0 && isWizardPath(trail[i])) i--;
  const origin = i >= 0 ? trail[i] : null;
  return origin && origin !== '/login' ? origin : null;
}

/**
 * Chaque entrée d'historique du wizard porte sa position (`entry`) : 0 pour la
 * première, +1 à chaque passage à l'étape suivante. Elle survit au
 * rechargement (history.state) et permet de revenir d'une étape ou de sortir du
 * wizard d'un seul coup.
 */
interface WizardHistoryState {
  wizard?: { id: number; entry: number };
}

export function wizardUrl(installationId: number, step: number): string {
  return `/installation/${installationId}?step=${step + 1}`;
}

/** Position de l'entrée courante dans le wizard de cette installation (0 par défaut). */
export function currentWizardEntry(installationId: number): number {
  const wizard = (window.history.state as WizardHistoryState | null)?.wizard;
  return wizard && wizard.id === installationId ? wizard.entry : 0;
}

/** Remplace l'entrée courante (sans en ajouter) par l'URL de l'étape `step`. */
export function replaceWizardStep(installationId: number, step: number, entry?: number): void {
  const state = { wizard: { id: installationId, entry: entry ?? currentWizardEntry(installationId) } };
  window.history.replaceState(state, '', wizardUrl(installationId, step));
}

/** Ajoute une entrée d'historique pour l'étape `step` (retour = étape précédente). */
export function pushWizardStep(installationId: number, step: number): void {
  const state = { wizard: { id: installationId, entry: currentWizardEntry(installationId) + 1 } };
  window.history.pushState(state, '', wizardUrl(installationId, step));
}

/**
 * Sort du wizard en revenant sur la page d'origine (toutes les entrées
 * d'étapes sont dépilées : « retour » ne rouvre pas le wizard), puis va sur
 * `destination` si elle diffère. Sans page d'origine connue (wizard ouvert
 * directement), remplace simplement l'URL par la destination.
 */
export function leaveWizard(
  installationId: number | null,
  destination: string | null,
  replace: (path: string) => void,
): void {
  const fallback = destination ?? '/installation-requests';
  // Brouillon jamais enregistré : une seule entrée (`/installation`).
  const entries = installationId == null ? 1 : currentWizardEntry(installationId) + 1;
  const canRewind = wizardOriginPath() !== null && window.history.length > entries;
  if (!canRewind) {
    replace(fallback);
    return;
  }
  if (destination) {
    const onArrive = () => {
      window.removeEventListener('popstate', onArrive);
      if (window.location.pathname !== destination) replace(destination);
    };
    window.addEventListener('popstate', onArrive);
  }
  window.history.go(-entries);
}

/**
 * Retour vers `path` (ex. la liste depuis un détail) : si l'on vient de cette
 * page, on y revient dans l'historique (pas d'entrée en plus, donc pas de
 * boucle détail ↔ liste) ; sinon on remplace la page courante.
 */
export function goBackTo(path: string, router: { back: () => void; replace: (p: string) => void }): void {
  if (previousPath() === path) router.back();
  else router.replace(path);
}

/**
 * Met à jour la requête de l'URL courante sans ajouter d'entrée d'historique,
 * en conservant nos données d'entrée (ex. position dans le wizard).
 *
 * On ne repasse PAS `window.history.state` tel quel : il contient le marqueur
 * interne de Next (`__NA`), et Next ignore alors l'appel — useSearchParams ne
 * verrait pas la nouvelle URL. Next recopie lui-même ses champs internes.
 */
export function replaceQuery(update: (params: URLSearchParams) => void): void {
  const params = new URLSearchParams(window.location.search);
  update(params);
  const qs = params.toString();
  window.history.replaceState(customHistoryState(), '', `${window.location.pathname}${qs ? `?${qs}` : ''}`);
}

/** Nos champs de history.state, sans les champs internes de Next. */
function customHistoryState(): Record<string, unknown> {
  const state = (window.history.state ?? {}) as Record<string, unknown>;
  const custom: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(state)) {
    if (key !== '__NA' && key !== '_N' && key !== '__PRIVATE_NEXTJS_INTERNALS_TREE') custom[key] = value;
  }
  return custom;
}

/** Position de défilement mémorisée d'une page (clé = URL). */
export function readScroll(key: string): number {
  return read<number>(`scroll:${key}`, 0);
}

export function saveScroll(key: string, top: number): void {
  write(`scroll:${key}`, Math.round(top));
}
