"use client";

import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

const STORAGE_KEY = "booking_wizard_config_id";

export function saveBookingWizardId(configId: string): void {
  if (typeof window === "undefined") return;
  localStorage.setItem(STORAGE_KEY, configId);
}

export function clearBookingWizardId(): void {
  if (typeof window === "undefined") return;
  localStorage.removeItem(STORAGE_KEY);
}

/** Synchronous, no-redirect read — used by the name step to detect edit mode. */
export function getBookingWizardId(): string | null {
  if (typeof window === "undefined") return null;
  return localStorage.getItem(STORAGE_KEY);
}

/** Reads the in-progress booking-config id saved by the name step; redirects back to it if missing. */
export function useBookingWizardId(): string | null {
  const router = useRouter();
  const [configId, setConfigId] = useState<string | null>(null);

  useEffect(() => {
    const stored = getBookingWizardId();

    if (!stored) {
      router.replace("/settings/booking/new/name");
      return;
    }

    setConfigId(stored);
  }, [router]);

  return configId;
}
