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

  // hintShare is shown to one decimal in the active locale's notation ("4.8%" / "4,8%").
  function hintShare(s: Stats): string {
    const pct = hintSharePercent(s).toLocaleString(i18n.locale, {
      minimumFractionDigits: 1,
      maximumFractionDigits: 1,
    });
    return `${pct}%`;
  }

  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.played', value: gamesPlayed(stats) },
          { key: 'stats.wins', value: stats.wins },
          { key: 'stats.draws', value: stats.draws },
          { key: 'stats.losses', value: stats.losses },
          { key: 'stats.moves', value: stats.moves },
          { key: 'stats.hintShare', value: hintShare(stats) },
          { key: 'stats.maxGame', value: stats.maxGamePoints },
          { key: 'stats.winRate', value: `${winRate(stats)}%` },
        ]
      : [],
  );

  // The best move is shown as a full-width breakdown with the word itself, one row per
  // variant the player has played, in catalogue order (the backend lists only non-empty
  // variants). It replaces the former single "best move" number card.
  const ORDER = ALL_VARIANTS.map((v) => v.id);
  const bestMoves = $derived<BestMove[]>(
    stats ? [...stats.bestMoves].sort((a, b) => ORDER.indexOf(a.variant) - ORDER.indexOf(b.variant)) : [],
  );
</script>

<Screen title={t('stats.title')} back="/">
  <div class="page">
    {#if app.profile?.isGuest}
      <!-- The opening word links to the profile screen, where a guest signs in (the same wording
           and link New Game shows a guest under its lone variant). -->
      <p class="muted">
        <button class="hintlink" onclick={() => navigate('/profile')}>{t('common.signInLink')}</button>{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 bestMoves.length > 0}
        <div class="card bestmove">
          <span class="lbl">{t('stats.maxWord')}</span>
          <div class="rows">
            {#each bestMoves as bm (bm.variant)}
              <span class="variant">{t(variantNameKey(bm.variant))}</span>
              <span class="score">{bm.score}</span>
              <span class="wordcell"><WordTiles word={bm.word} variant={bm.variant} /></span>
            {/each}
          </div>
        </div>
      {/if}
    {/if}
  </div>
</Screen>

<style>
  .page {
    padding: var(--pad);
  }
  .muted {
    color: var(--text-muted);
  }
  /* The inline link-styled button opening the guest stub (mirrors New Game's .hintlink). */
  .hintlink {
    background: none;
    border: none;
    padding: 0;
    color: var(--accent);
    font: inherit;
    text-decoration: underline;
    cursor: pointer;
  }
  .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;
  }
  .bestmove {
    margin-top: 12px;
    gap: 12px;
  }
  /* Two lines per variant: the variant label on its own line, then the score and the word
     tiles below it. One shared grid so the score column aligns across all rows — the score
     right-aligned in its column, the word left-aligned. */
  .rows {
    display: grid;
    /* score column (sized to the widest score) then the word; minmax(0, 1fr) lets the word
       shrink below its tiles' intrinsic width on a narrow screen (the cell then scrolls). */
    grid-template-columns: auto minmax(0, 1fr);
    align-items: center;
    row-gap: 4px;
    column-gap: 8px;
  }
  .variant {
    grid-column: 1 / -1;
    color: var(--text-muted);
    font-size: 0.95rem;
  }
  /* Extra space above each variant after the first, separating the variant blocks while the
     variant-to-score gap stays tight (row-gap). */
  .variant:not(:first-child) {
    margin-top: 10px;
  }
  .wordcell {
    justify-self: start;
    min-width: 0;
    overflow-x: auto;
  }
  .score {
    justify-self: end;
    font-weight: 700;
    font-variant-numeric: tabular-nums;
  }
</style>
