/**
 * useQueryParams Hook
 * 
 * Safe hook to access URL query parameters without requiring Suspense boundary.
 * Works on client-side only, returns empty URLSearchParams during SSR/prerendering.
 * 
 * @example
 * ```tsx
 * const params = useQueryParams();
 * const flow = params.get('flow');
 * const hasFlow = params.has('flow');
 * const allTags = params.getAll('tags');
 * ```
 */

'use client';

import { usePathname } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';

/**
 * Hook to safely access URL query parameters without useSearchParams()
 * 
 * This hook reads query parameters directly from window.location.search,
 * avoiding the need for Suspense boundaries that useSearchParams() requires.
 * 
 * Automatically updates when URL changes (navigation, back/forward, etc.)
 * Uses pathname from Next.js to detect route changes and polls for query param changes.
 * 
 * Returns a URLSearchParams object with get(), getAll(), has(), etc.
 * 
 * @returns URLSearchParams object (empty during SSR)
 */
export function useQueryParams(): URLSearchParams {
  const pathname = usePathname();
  const [queryParams, setQueryParams] = useState<URLSearchParams>(() => {
    if (typeof window === 'undefined') {
      return new URLSearchParams();
    }
    return new URLSearchParams(window.location.search);
  });
  const lastSearchRef = useRef<string>('');

  useEffect(() => {
    if (typeof window === 'undefined') return;

    const updateQueryParams = () => {
      const currentSearch = window.location.search;
      if (currentSearch !== lastSearchRef.current) {
        lastSearchRef.current = currentSearch;
        setQueryParams(new URLSearchParams(currentSearch));
      }
    };

    // Update when pathname changes (Next.js navigation)
    updateQueryParams();

    // Listen to popstate (back/forward navigation)
    window.addEventListener('popstate', updateQueryParams);

    // Poll for query param changes (for router.push with same pathname)
    // This handles cases where Next.js router.push updates query params without changing pathname
    const intervalId = setInterval(updateQueryParams, 100);

    return () => {
      window.removeEventListener('popstate', updateQueryParams);
      clearInterval(intervalId);
    };
  }, [pathname]);

  return queryParams;
}

