/**
 * Normalize an Instagram handle from various input formats to a pure username.
 * Browser-side copy of supabase/functions/_shared/normalizeHandles.ts
 */
export function normalizeInstagramHandle(
  raw: string | null | undefined,
): string | null {
  if (!raw || typeof raw !== 'string') return null;

  let handle = raw.trim();
  if (!handle) return null;

  if (handle.includes('instagram.com')) {
    try {
      const urlStr = handle.startsWith('http') ? handle : `https://${handle}`;
      const url = new URL(urlStr);
      const segments = url.pathname.split('/').filter(Boolean);
      handle = segments[0] || '';
    } catch {
      const match = handle.match(/instagram\.com\/([^/?#]+)/);
      handle = match?.[1] || '';
    }
  }

  if (handle.startsWith('@')) {
    handle = handle.slice(1);
  }

  handle = handle.replace(/\/+$/, '');

  return handle || null;
}
