'use client';

export const CHUNK_RELOAD_SESSION_KEY = 'rm_chunk_reload_attempted_at';
const CHUNK_RELOAD_QUERY_PARAM = '__rm_chunk_reload';
const CHUNK_RELOAD_COOLDOWN_MS = 60_000;

export function isChunkLoadFailure(details: string | null | undefined): boolean {
  const normalized = String(details || '').toLowerCase();
  return (
    normalized.includes('failed to load chunk') ||
    normalized.includes('loading chunk') ||
    normalized.includes('chunkloaderror') ||
    normalized.includes('/_next/static/chunks/')
  );
}

export function clearChunkReloadQueryParam(): void {
  if (typeof window === 'undefined') return;
  const url = new URL(window.location.href);
  if (!url.searchParams.has(CHUNK_RELOAD_QUERY_PARAM)) return;
  url.searchParams.delete(CHUNK_RELOAD_QUERY_PARAM);
  window.history.replaceState({}, '', url.toString());
}

export function tryRecoverFromChunkLoadFailure(
  details: string,
  now = Date.now(),
  replaceLocation?: (url: string) => void,
): boolean {
  if (typeof window === 'undefined' || !isChunkLoadFailure(details)) {
    return false;
  }

  const lastAttemptRaw = window.sessionStorage.getItem(CHUNK_RELOAD_SESSION_KEY);
  const lastAttempt = lastAttemptRaw ? Number.parseInt(lastAttemptRaw, 10) : 0;
  if (Number.isFinite(lastAttempt) && lastAttempt > 0 && now - lastAttempt < CHUNK_RELOAD_COOLDOWN_MS) {
    return false;
  }

  window.sessionStorage.setItem(CHUNK_RELOAD_SESSION_KEY, String(now));
  const reloadUrl = new URL(window.location.href);
  reloadUrl.searchParams.set(CHUNK_RELOAD_QUERY_PARAM, String(now));
  const replace = replaceLocation ?? ((url: string) => window.location.replace(url));
  replace(reloadUrl.toString());
  return true;
}
