<script lang="ts">
  import { onMount } from 'svelte';
  import Screen from '../components/Screen.svelte';
  import { app, handleError } from '../lib/app.svelte';
  import { gateway } from '../lib/gateway';
  import { t, type MessageKey } from '../lib/i18n/index.svelte';
  import { gamesPlayed, winRate } from '../lib/stats';
  import type { Stats } from '../lib/model';

  let stats = $state<Stats | null>(null);

  onMount(async () => {
    if (app.profile?.isGuest) return;
    try {
      stats = await gateway.statsGet();
    } catch (e) {
      handleError(e);
    }
  });

  const cards = $derived<{ key: MessageKey; value: string | number }[]>(
    stats
      ? [
          { key: 'stats.wins', value: stats.wins },
          { key: 'stats.losses', value: stats.losses },
          { key: 'stats.draws', value: stats.draws },
          { key: 'stats.played', value: gamesPlayed(stats) },
          { key: 'stats.winRate', value: `${winRate(stats)}%` },
          { key: 'stats.maxGame', value: stats.maxGamePoints },
          { key: 'stats.maxWord', value: stats.maxWordPoints },
        ]
      : [],
  );
</script>

<Screen title={t('stats.title')} back="/">
  <div class="page">
    {#if app.profile?.isGuest}
      <p class="muted">{t('stats.guestHint')}</p>
    {:else if stats}
      <div class="grid">
        {#each cards as c (c.key)}
          <div class="card">
            <span class="num">{c.value}</span>
            <span class="lbl">{t(c.key)}</span>
          </div>
        {/each}
      </div>
    {/if}
  </div>
</Screen>

<style>
  .page {
    padding: var(--pad);
  }
  .muted {
    color: var(--text-muted);
  }
  .grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  .card {
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding: 18px 16px;
    border: 1px solid var(--border);
    background: var(--surface);
    border-radius: var(--radius);
  }
  .num {
    font-size: 1.7rem;
    font-weight: 700;
  }
  .lbl {
    color: var(--text-muted);
    font-size: 0.85rem;
  }
</style>
