import type { TripStep } from "@/types";

export function updateSelectedStepParam(current: URLSearchParams, stepId: string | null): URLSearchParams {
  const next = new URLSearchParams(current);
  if (stepId) next.set("step", stepId);
  else next.delete("step");
  return next;
}

export function resolveSelectedTripStep(steps: TripStep[], stepId: string | null): TripStep | null {
  if (!stepId) return null;
  return steps.find((step) => step.id === stepId) ?? null;
}

export type StepSelectionScope = "planner" | "traveler";

export function getStepSelectionStorageKey(scope: StepSelectionScope, tripId: string): string {
  return `triptale:selected-step:${scope}:${tripId}`;
}

export function rememberSelectedStep(storage: Storage, scope: StepSelectionScope, tripId: string, stepId: string): void {
  storage.setItem(getStepSelectionStorageKey(scope, tripId), stepId);
}

export function getRememberedStep(storage: Storage, scope: StepSelectionScope, tripId: string): string | null {
  return storage.getItem(getStepSelectionStorageKey(scope, tripId));
}

export function clearRememberedStep(storage: Storage, scope: StepSelectionScope, tripId: string): void {
  storage.removeItem(getStepSelectionStorageKey(scope, tripId));
}

export function buildRememberedTripUrl(storage: Storage, scope: StepSelectionScope, tripId: string): string {
  const base = scope === "planner" ? `/dashboard/trips/${tripId}/itinerary` : `/voyageur/trips/${tripId}`;
  const stepId = getRememberedStep(storage, scope, tripId);
  return stepId ? `${base}?step=${encodeURIComponent(stepId)}` : base;
}
