<script lang="ts">
  import Landing from './lib/Landing.svelte';
  import Game from './lib/Game.svelte';

  let route: { name: 'landing' } | { name: 'game'; id: string } = $state({ name: 'landing' });

  function parseHash() {
    // Support both pathname-based (joinUrl: /g/<id>) and hash-based (#/g/<id>) routes.
    const hash = location.hash || '';
    const hashMatch = hash.match(/^#\/g\/([a-z0-9]{8})$/);
    if (hashMatch) {
      route = { name: 'game', id: hashMatch[1]! };
      return;
    }
    const pathMatch = location.pathname.match(/^\/g\/([a-z0-9]{8})\/?$/);
    if (pathMatch) {
      route = { name: 'game', id: pathMatch[1]! };
      return;
    }
    route = { name: 'landing' };
  }

  $effect(() => {
    parseHash();
    const handler = () => parseHash();
    window.addEventListener('hashchange', handler);
    return () => window.removeEventListener('hashchange', handler);
  });
</script>

{#if route.name === 'landing'}
  <Landing />
{:else}
  <Game gameId={route.id} />
{/if}
