<script lang="ts">
  import Screen from '../components/Screen.svelte';
  import TabBar from '../components/TabBar.svelte';
  import ChatScreen from './ChatScreen.svelte';
  import CheckScreen from './CheckScreen.svelte';
  import { t } from '../lib/i18n/index.svelte';
  import { getCachedGame } from '../lib/gamecache';

  // The in-game comms hub: a single nav bar + bottom tab bar hosting Chat and the word
  // Dictionary. Tabs switch in place, so the back control always returns to the game. The
  // Dictionary tab is offered only while the game is active (mirrors the old "check word"); an
  // honest-AI game has no Chat, so it shows the Dictionary alone.
  type CommsTab = 'chat' | 'dictionary';
  let { id, initialTab = 'chat' }: { id: string; initialTab?: CommsTab } = $props();

  // The game is rendered (and cached) before its comms open, so the cache tells us whether
  // it is still active without another fetch; an unknown game keeps the Dictionary offered.
  const active = $derived(getCachedGame(id)?.view.game.status !== 'finished');
  // An honest-AI game has no chat at all, so its hub is Dictionary-only.
  const vsAi = $derived(getCachedGame(id)?.view.game.vsAi ?? false);
  // Seeded once from the entry route's tab, then owned locally. The effect keeps the tab valid:
  // an AI game has only the Dictionary; a finished non-AI game has only Chat (a stale Dictionary
  // deep-link falls back to Chat).
  // An honest-AI game has only the Dictionary, so start there regardless of the entry route — this
  // keeps ChatScreen (which fetches chat over the network) from mounting even for a beat, which would
  // otherwise raise an error toast in offline mode.
  // svelte-ignore state_referenced_locally
  let tab = $state<CommsTab>(vsAi ? 'dictionary' : initialTab);
  $effect(() => {
    if (vsAi) tab = 'dictionary';
    else if (tab === 'dictionary' && !active) tab = 'chat';
  });
</script>

<Screen
  title={t(tab === 'chat' ? 'game.chat' : 'game.checkWord')}
  back={`/game/${id}`}
  scroll={tab === 'dictionary'}
  column={tab === 'chat'}
>
  {#if tab === 'chat'}
    <ChatScreen {id} />
  {:else}
    <CheckScreen {id} />
  {/if}

  {#snippet tabbar()}
    <TabBar>
      {#if !vsAi}
        <button class="tab" class:active={tab === 'chat'} onclick={() => (tab = 'chat')}>
          <span class="face"><span class="sq" aria-hidden="true">💬</span><span class="lbl">{t('game.chat')}</span></span>
        </button>
      {/if}
      {#if active}
        <button class="tab" class:active={tab === 'dictionary'} onclick={() => (tab = 'dictionary')}>
          <span class="face"><span class="sq" aria-hidden="true">🔎</span><span class="lbl">{t('game.dictionary')}</span></span>
        </button>
      {/if}
    </TabBar>
  {/snippet}
</Screen>
