"use client";

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

function storageKey(shopId: string): string {
  return `shop_product_wizard_listing_id_${shopId}`;
}

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

export function clearProductWizardId(shopId: string): void {
  if (typeof window === "undefined") return;
  localStorage.removeItem(storageKey(shopId));
}

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

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

  useEffect(() => {
    if (!shopId) return;
    const stored =
      typeof window !== "undefined" ? localStorage.getItem(storageKey(shopId)) : null;

    if (!stored) {
      router.replace(`/shops/${shopId}/products/new/name`);
      return;
    }

    setListingId(stored);
  }, [router, shopId]);

  return listingId;
}
