type View = 'Home' | 'Analytics' | 'Campaigns' | 'WIP Reviewer' | 'CopyGenAI' | 'Settings' | 'Profile' | 'Auditing' | 'Knowledge Base' | 'User Management';

export interface UrlNavigationState {
  view: View;
  campaignName: string | null;
  proofId: string | null;
}

const VALID_VIEWS: View[] = ['Home', 'Analytics', 'Campaigns', 'WIP Reviewer', 'CopyGenAI', 'Settings', 'Profile', 'Auditing', 'Knowledge Base', 'User Management'];

export function parseUrlState(): UrlNavigationState {
  const params = new URLSearchParams(window.location.search);
  const view = params.get('view') as View;
  return {
    view: VALID_VIEWS.includes(view) ? view : 'Home',
    campaignName: params.get('campaign'),
    proofId: params.get('proof'),
  };
}

export function buildUrl(state: Partial<UrlNavigationState>): string {
  const params = new URLSearchParams();
  if (state.view && state.view !== 'Home') params.set('view', state.view);
  if (state.campaignName) params.set('campaign', state.campaignName);
  if (state.proofId) params.set('proof', state.proofId);
  const query = params.toString();
  return query ? `?${query}` : '/';
}

export function pushUrlState(state: Partial<UrlNavigationState>): void {
  const newUrl = buildUrl(state);
  // Only push if URL actually changed to avoid duplicate history entries
  if (newUrl !== window.location.pathname + window.location.search) {
    window.history.pushState(state, '', newUrl);
  }
}
