"use client";

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

const BILLING_STATE_KEY = "popiart-billing-page-state";

export function BillingPageState() {
  const pathname = usePathname();
  const router = useRouter();
  const searchParams = useSearchParams();

  useEffect(() => {
    const hasQuery = searchParams.toString().length > 0;
    if (hasQuery) {
      try {
        window.sessionStorage.setItem(BILLING_STATE_KEY, searchParams.toString());
      } catch {
        // Ignore storage write failures.
      }
      return;
    }

    try {
      const stored = window.sessionStorage.getItem(BILLING_STATE_KEY);
      if (stored) {
        router.replace(`${pathname}?${stored}`);
      }
    } catch {
      // Ignore storage read failures.
    }
  }, [pathname, router, searchParams]);

  return null;
}
