export type SettingsSection = 'account' | 'appearance' | 'assistant' | 'billing';

export type RouteState =
  | { name: 'home' }
  | { name: 'conversation'; conversationId: string }
  | { name: 'settings'; section: SettingsSection };

export const SETTINGS_SECTIONS: SettingsSection[] = [
  'account',
  'appearance',
  'assistant',
  'billing',
];

const DEFAULT_SETTINGS_SECTION: SettingsSection = 'account';

const normalizeHash = (hash: string) => (
  hash.replace(/^#/, '').replace(/^\/?/, '/')
);

export const parseAppRoute = (hash: string): RouteState => {
  const path = normalizeHash(hash || '#/');
  const segments = path.split('/').filter(Boolean);

  if (segments.length === 0) return { name: 'home' };

  if (segments[0] === 'c' && segments[1]) {
    return { name: 'conversation', conversationId: decodeURIComponent(segments[1]) };
  }

  if (segments[0] === 'settings') {
    const section = segments[1] as SettingsSection | undefined;
    return {
      name: 'settings',
      section: section && SETTINGS_SECTIONS.includes(section) ? section : DEFAULT_SETTINGS_SECTION,
    };
  }

  return { name: 'home' };
};

export const buildAppHash = (route: RouteState) => {
  if (route.name === 'conversation') {
    return `#/c/${encodeURIComponent(route.conversationId)}`;
  }
  if (route.name === 'settings') {
    return `#/settings/${route.section}`;
  }
  return '#/';
};
