"use client";

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

const STORAGE_KEY = "shop_wizard_shop_id";

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

export function clearShopWizardId(): 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 getShopWizardId(): string | null {
  if (typeof window === "undefined") return null;
  return localStorage.getItem(STORAGE_KEY);
}

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

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

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

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

  return shopId;
}
