<script>
  import { onMount } from 'svelte';
  import { goto, afterNavigate } from '$app/navigation';
  import { page } from '$app/stores';
  import { getJSON } from '$lib/api.js';
  import HubBar from '$lib/components/HubBar.svelte';
  import { pushGameStatesBatch } from '$lib/gamesync.js';
  import { initPrefs } from '$lib/prefs.svelte.js';
  import { auth } from '$lib/auth.svelte.js';
  import { isDevGated, blockedForViewer } from '$lib/devgate.js';
  import { trackGame } from '$lib/analytics.js';
  import WordGame from '$lib/components/WordGame.svelte';
  import WordSearchGame from '$lib/components/WordSearchGame.svelte';
  import BloomGame from '$lib/components/BloomGame.svelte';
  import MatchGame from '$lib/components/MatchGame.svelte';

  // Screen is derived from the URL so the device/browser Back button steps through
  // Hub → Game Selection → Game (each screen is its own history entry), instead of
  // jumping straight out of /play.
  let sp = $derived($page.url.searchParams);
  let game = $derived(['wordsearch', 'bloom', 'match'].includes(sp.get('game')) ? sp.get('game') : 'word');
  let view = $derived(!sp.get('game') ? 'hub' : (sp.get('v') ? 'play' : 'select'));
  // Bloom v: 'daily' (shared Center Circle) | 'free-center' | 'free-wild'.
  let bloomMode = $derived(sp.get('v') === 'daily' ? 'daily' : 'free');
  let bloomFormat = $derived(sp.get('v') === 'free-wild' ? 'wild' : 'center');
  // Hide an in-dev game's card from non-admins, and bounce them off its route.
  let bloomBlocked = $derived(blockedForViewer('bloom', auth.user, $page.url));
  let bloomStatus = $state(null);
  let variant = $derived(['5', '6'].includes(sp.get('v')) ? sp.get('v') : '5');
  let wsSize = $derived(['small', 'med', 'large'].includes(sp.get('v')) ? sp.get('v') : 'med');
  // Memory Match. v = "<mode>-<format>-<tier>" e.g. daily-icons-standard / free-colors-expert.
  let matchBlocked = $derived(blockedForViewer('match', auth.user, $page.url));
  let matchParts = $derived((sp.get('v') || '').split('-'));
  let matchMode = $derived(matchParts[0] === 'free' ? 'free' : 'daily');
  let matchFormat = $derived(matchParts[1] === 'colors' ? 'colors' : 'icons');
  let matchTier = $derived(['gentle', 'standard', 'expert'].includes(matchParts[2]) ? matchParts[2] : 'standard');
  let matchStatus = $state(null);
  let matchFmt = $state('icons');   // format toggle on the Match selection screen

  let date = $state('');
  let wordStatus = $state({ 5: null, 6: null });
  let wsStatus = $state(null);

  function readWord(v) {
    try {
      const s = JSON.parse(localStorage.getItem(`goodnews:word:${v}:${date}`) || 'null');
      const tries = (s?.guesses || []).length;
      // Surface in-progress too (so "continue on another device" shows on the card),
      // not just finished games.
      if (s && (s.status === 'won' || s.status === 'lost' || (s.status === 'playing' && tries > 0))) {
        return { status: s.status, tries, max: v === '6' ? 7 : 6 };
      }
    } catch { /* ignore */ }
    return null;
  }
  function readWsSize(sz) {
    try {
      const s = JSON.parse(localStorage.getItem(`goodnews:wordsearch:${sz}:${date}`) || 'null');
      if (s && Array.isArray(s.foundWords)) return { status: s.status, found: s.foundWords.length, ms: s.ms };
    } catch { /* ignore */ }
    return null;
  }
  function readBloom() {
    try {
      const s = JSON.parse(localStorage.getItem(`goodnews:bloom:${date}`) || 'null');
      if (s && Array.isArray(s.found)) return { count: s.found.length, full: !!s.full };
    } catch { /* ignore */ }
    return null;
  }
  // All daily Match boards (any tier × format) for the day.
  const MATCH_TIERS = [
    ['gentle', 'Gentle', '4×3 · 6 pairs'],
    ['standard', 'Standard', '4×4 · 8 pairs'],
    ['expert', 'Expert', '6×4 · match 3 of a kind'],
  ];
  const MATCH_VARIANTS = MATCH_TIERS.flatMap(([t]) => ['icons', 'colors'].map((f) => `${t}-${f}`));
  const MATCH_VS = ['daily', 'free'].flatMap((m) =>
    ['icons', 'colors'].flatMap((f) => MATCH_TIERS.map(([t]) => `${m}-${f}-${t}`)));
  function readMatchVariant(v) {
    try { return JSON.parse(localStorage.getItem(`goodnews:match:${v}:${date}`) || 'null'); } catch { return null; }
  }
  function readMatch() {
    let best = null;
    for (const v of MATCH_VARIANTS) {
      const s = readMatchVariant(v);
      if (!s) continue;
      if (s.done) return { done: true };
      const count = (s.matched || []).length;
      if (count > 0 && (!best || count > best.count)) best = { done: false, count };
    }
    return best;
  }
  function refreshStatus() {
    wordStatus = { 5: readWord('5'), 6: readWord('6') };
    let ws = null;
    for (const sz of ['small', 'med', 'large']) {
      const s = readWsSize(sz);
      if (s && s.status === 'done') { ws = s; break; }
      if (s && s.found > 0 && !ws) ws = s;
    }
    wsStatus = ws;
    bloomStatus = readBloom();
    matchStatus = readMatch();
  }
  function fmtMs(ms) {
    const s = Math.round(ms / 1000);
    return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
  }

  // The hub itself reconciles every game with the server (signed-in), so cards
  // show cross-device status WITHOUT having to open each game first, and this
  // device's local progress gets uploaded even for games it hasn't reopened.
  // Every daily board the hub surfaces, as [game, variant, localStorage key]. Match
  // includes all tier×format variants so cross-device progress shows without opening
  // the game.
  function gameSpecs() {
    return [
      ['word', '5', `goodnews:word:5:${date}`],
      ['word', '6', `goodnews:word:6:${date}`],
      ['wordsearch', 'small', `goodnews:wordsearch:small:${date}`],
      ['wordsearch', 'med', `goodnews:wordsearch:med:${date}`],
      ['wordsearch', 'large', `goodnews:wordsearch:large:${date}`],
      ['bloom', '', `goodnews:bloom:${date}`],
      ...MATCH_VARIANTS.map((v) => ['match', v, `goodnews:match:${v}:${date}`]),
    ];
  }
  // One batch request reconciles ALL boards (instead of a dozen calls on every /play
  // load — that fan-out was tripping the boot-slow beacon). Still server-merged, so
  // cross-device pull is preserved.
  async function syncAllGames() {
    if (!auth.user || !date) return;
    const specs = gameSpecs();
    const items = specs.map(([game, variant, key]) => {
      let local = null;
      try { local = JSON.parse(localStorage.getItem(key) || 'null'); } catch { /* ignore */ }
      return { game, variant, state: local || {} };
    });
    const states = await pushGameStatesBatch(date, items);
    if (states) {
      const keyOf = (g, v) => specs.find((s) => s[0] === g && s[1] === v)?.[2];
      for (const { game, variant, state } of states) {
        if (!state) continue;
        const merged = { ...state };
        if (game === 'wordsearch') merged.status = merged.ms ? 'done' : 'playing'; // card reads .status
        const key = keyOf(game, variant);
        if (key) { try { localStorage.setItem(key, JSON.stringify(merged)); } catch { /* ignore */ } }
      }
    }
    refreshStatus();
  }

  // Hub card one-liners
  function wordLabel() {
    const a = wordStatus['5'], b = wordStatus['6'];
    if (!a && !b) return 'Guess the day’s word';
    const part = (s, mx) => !s ? '–' : s.status === 'won' ? `${s.tries}/${mx}` : s.status === 'lost' ? 'X' : `${s.tries}…`;
    return `Today · 5:${part(a, 6)}  6:${part(b, 7)}`;
  }
  function wsHubLabel() {
    if (!wsStatus) return 'Find the day’s themed words';
    if (wsStatus.status === 'done') return `Today: cleared${wsStatus.ms ? ' · ' + fmtMs(wsStatus.ms) : ''}`;
    if (wsStatus.found > 0) return `Today: ${wsStatus.found} found`;
    return 'Find the day’s themed words';
  }
  function bloomHubLabel() {
    if (!bloomStatus || !bloomStatus.count) return 'Make words from today’s letters';
    if (bloomStatus.full) return 'Today: Full Bloom 🌸';
    return `Today: ${bloomStatus.count} ${bloomStatus.count === 1 ? 'word' : 'words'}`;
  }

  function matchHubLabel() {
    if (!matchStatus) return 'Match the day’s pairs';
    if (matchStatus.done) return 'Today: cleared';
    return `Today: ${matchStatus.count} matched`;
  }
  function matchOpt(t) {
    const s = readMatchVariant(`${t}-${matchFmt}`);
    if (!s) return 'Play';
    if (s.done) return 'Cleared';
    const c = (s.matched || []).length;
    return c > 0 ? `${c} matched` : 'Play';
  }

  // Game-selection option statuses
  function wordOpt(v) {
    const s = wordStatus[v];
    if (!s) return 'Play';
    if (s.status === 'won') return `Solved ${s.tries}/${s.max}`;
    if (s.status === 'lost') return 'Out of guesses';
    return `Continue · ${s.tries}/${s.max}`;
  }
  function wsOpt(sz) {
    const s = readWsSize(sz);
    if (!s) return 'Play';
    if (s.status === 'done') return `Cleared${s.ms ? ' · ' + fmtMs(s.ms) : ''}`;
    if (s.found > 0) return `${s.found} found`;
    return 'Play';
  }

  // Forward navigations push a history entry (via goto). The in-app Back button
  // pops it (history.back) when we have in-app history, but on a direct deep link
  // (no in-app history) it navigates to the parent screen instead of leaving the
  // site. Device Back stays browser-native either way.
  let appNavDepth = 0;
  let cameFromApp = $state(false);   // arrived via in-app nav (e.g. the hub) → Back returns there
  function leavePlay() {
    if (cameFromApp && typeof history !== 'undefined') history.back();
    else goto('/home3', { replaceState: true });
  }
  function openGame(g) { appNavDepth++; goto('/play?game=' + g); }
  function pick(v) { appNavDepth++; goto('/play?game=' + game + '&v=' + v); }
  function back() {
    if (appNavDepth > 0) { appNavDepth--; history.back(); }
    else goto(view === 'play' ? '/play?game=' + game : '/play');
  }

  // Canonicalize shareable/bookmarked URLs: unknown game → hub; invalid v for the
  // game → its default (replaceState, so it doesn't add a history entry). An in-dev
  // game's route bounces non-admins back to the hub.
  $effect(() => {
    const g = sp.get('game'), v = sp.get('v');
    if (g && !['word', 'wordsearch', 'bloom', 'match'].includes(g)) { goto('/play', { replaceState: true }); return; }
    if (g && blockedForViewer(g, auth.user, $page.url)) { goto('/play', { replaceState: true }); return; }
    if (g && v) {
      const valid = g === 'word' ? ['5', '6']
                  : g === 'wordsearch' ? ['small', 'med', 'large']
                  : g === 'match' ? MATCH_VS
                  : ['daily', 'free-center', 'free-wild'];
      const def = g === 'word' ? '5' : g === 'wordsearch' ? 'med' : g === 'match' ? 'daily-icons-standard' : 'daily';
      if (!valid.includes(v)) goto(`/play?game=${g}&v=${def}`, { replaceState: true });
    }
  });

  // Any puzzle on mobile = a focused viewport: lock scroll + hide footer. Cleanup
  // ALWAYS removes the class (re-run or unmount), so leaving /play can't strand it.
  $effect(() => {
    if (typeof document === 'undefined') return;
    if (view === 'play') {
      document.documentElement.classList.add('playing-game');
      return () => document.documentElement.classList.remove('playing-game');
    }
  });

  const WS_OPTS = [
    ['small', 'Small', 'cozy · 8×8'],
    ['med', 'Medium', 'balanced · 11×11'],
    ['large', 'Large', 'a longer sit · 14×14'],
  ];

  let wsTheme = $state('');

  onMount(async () => {
    // Share-loop acquisition: record an arrival when someone lands via a shared game
    // link (gameShareUrl tags it utm_source=game_share), attributed to that game.
    if ($page.url.searchParams.get('utm_source') === 'game_share') trackGame(game, 'arrival');
    initPrefs();   // so the reader's chosen calm set is available on a direct /play landing
    try { date = (await getJSON('/api/puzzle/word?variant=5')).date; } catch { /* offline */ }
    try { wsTheme = (await getJSON('/api/puzzle/wordsearch?variant=med')).theme; } catch { /* offline */ }
    refreshStatus();
    syncAllGames();   // signed-in: pull cross-device status into the cards + upload local progress
  });
  // Refresh hub/selection statuses whenever we land on a screen (incl. Back).
  afterNavigate(({ from }) => { if (from) cameFromApp = true; refreshStatus(); });
</script>

<svelte:head>
  <!-- Canonical/OG/description for /play are baked into the static play.html at build
       time (scripts/patch-play-head.mjs) so non-JS social scrapers get them; we keep
       only the browser-tab title + dev-gate noindex here to avoid duplicate tags. -->
  <title>Play · Upbeat Bytes — calm daily games</title>
  {#if isDevGated(game)}<meta name="robots" content="noindex" />{/if}
</svelte:head>

<HubBar active="games" />

<main class="container page" class:gameview={view === 'play'}>
  <!-- Back row under HubBar, consistent with the other hub pages. In a game it steps back
       (selection / hub); on the games landing it leaves Play (to where you came from). -->
  <button class="gameback" onclick={view === 'hub' ? leavePlay : back}>
    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M15 18l-6-6 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
    {view === 'hub' ? 'Back' : (view === 'play' ? 'Game Selection' : 'Play Hub')}
  </button>
  {#if view === 'hub'}
    <div class="arcade-head">
      <span class="eyelash" aria-hidden="true"></span>
      <h1 class="play-title">Play</h1>
      <span class="head-div" aria-hidden="true"></span>
      <p class="head-sub">A few little games, fresh every morning. Pick one and dive in.</p>
    </div>

    <div class="arcade">
      <button class="tile tile-word" onclick={() => openGame('word')}>
        <span class="motif m-word" aria-hidden="true">
          {#each ['B', 'Y', 'T', 'E', '', '', '', '', '', ''] as ch}
            <span class="wt" class:on={ch}>{ch}</span>
          {/each}
        </span>
        <span class="foot">
          <span class="t-name">Daily Word</span>
          <span class="t-clue">Today’s word · 5 or 6 letters</span>
        </span>
      </button>

      <button class="tile tile-ws" onclick={() => openGame('wordsearch')}>
        <span class="motif m-ws" aria-hidden="true">
          <span class="wrow">G A M E S</span>
          <span class="wrow hl">B Y T E S</span>
          <span class="wrow">W O R D S</span>
          <span class="wrow">S O L V E</span>
        </span>
        <span class="foot">
          <span class="t-name">Word Search</span>
          <span class="t-clue">Today’s themed grid</span>
        </span>
      </button>

      {#if !bloomBlocked}
        <button class="tile tile-bloom" onclick={() => openGame('bloom')}>
          <span class="motif m-bloom" aria-hidden="true">
            <span class="petal pc">T</span>
            <span class="petal p1">A</span><span class="petal p2">E</span><span class="petal p3">G</span>
            <span class="petal p4">L</span><span class="petal p5">R</span><span class="petal p6">Y</span>
          </span>
          <span class="foot">
            <span class="t-name">Bloom{#if isDevGated('bloom')}<span class="devtag">dev</span>{/if}</span>
            <span class="t-clue">Today’s letter garden</span>
          </span>
        </button>
      {/if}

      {#if !matchBlocked}
        <button class="tile tile-match" onclick={() => openGame('match')}>
          <span class="motif m-match" aria-hidden="true">
            {#each [0, 1, 2, 3, 4, 5, 6, 7] as i}
              <span class="mm" class:flip={i === 1 || i === 6}>{#if i === 1 || i === 6}<span class="dot"></span>{/if}</span>
            {/each}
          </span>
          <span class="foot">
            <span class="t-name">Memory Match{#if isDevGated('match')}<span class="devtag">dev</span>{/if}</span>
            <span class="t-clue">Today’s board</span>
          </span>
        </button>
      {/if}

      <!-- teased, not built yet -->
      <div class="tile tile-bubble soon">
        <span class="motif m-bubble" aria-hidden="true">
          {#each ['a', 'b', 'c', 'd', 'a', 'd', 'c', 'b', 'a', 'c', 'b', 'd'] as k}<span class="bub b-{k}"></span>{/each}
        </span>
        <span class="ribbon">Coming soon</span>
        <span class="foot">
          <span class="t-name">Bubble Blaster</span>
          <span class="t-clue">A gentle bubble-pop puzzle</span>
        </span>
      </div>

      <div class="tile tile-more soon">
        <span class="more-plus" aria-hidden="true">+</span>
        <span class="t-name">More coming soon</span>
        <span class="t-clue">Little games in the workshop</span>
      </div>
    </div>

  {:else if view === 'select'}
    <h1 class="seltitle">{game === 'word' ? 'Daily Word' : game === 'wordsearch' ? 'Word Search' : game === 'match' ? 'Memory Match' : 'Bloom'}</h1>
    {#if game === 'wordsearch' && wsTheme}
      <div class="themecard">
        <span class="tc-label">Today’s theme</span>
        <span class="tc-name">{wsTheme}</span>
      </div>
    {/if}
    <p class="sub">{game === 'word' ? 'Pick your length.' : game === 'wordsearch' ? 'Pick your size.' : game === 'match' ? 'Pick a format, then today’s board or free play.' : 'Play today’s shared puzzle, or graze freely.'}</p>
    <div class="opts">
      {#if game === 'match'}
        <div class="seg">
          <button class="segbtn" class:on={matchFmt === 'icons'} onclick={() => (matchFmt = 'icons')}>Memory · icons</button>
          <button class="segbtn" class:on={matchFmt === 'colors'} onclick={() => (matchFmt = 'colors')}>Color Match</button>
        </div>
        <p class="grp">Today’s board — shared daily</p>
        {#each MATCH_TIERS as [t, name, desc] (t)}
          <button class="opt" onclick={() => pick(`daily-${matchFmt}-${t}`)}>
            <span class="opt-main"><strong>{name}</strong><span>{desc}</span></span>
            <span class="opt-go" class:done={readMatchVariant(`${t}-${matchFmt}`)?.done}>{matchOpt(t)}</span>
          </button>
        {/each}
        <p class="grp">Free play — fresh boards anytime</p>
        {#each MATCH_TIERS as [t, name, desc] (t)}
          <button class="opt" onclick={() => pick(`free-${matchFmt}-${t}`)}>
            <span class="opt-main"><strong>{name}</strong><span>{desc}</span></span>
            <span class="opt-go">Play</span>
          </button>
        {/each}
      {:else if game === 'bloom'}
        <button class="opt" onclick={() => pick('daily')}>
          <span class="opt-main"><strong>Today’s Bloom</strong><span>the shared daily · center letter</span></span>
          <span class="opt-go" class:done={bloomStatus && bloomStatus.count > 0}>{bloomStatus && bloomStatus.count ? (bloomStatus.full ? 'Full Bloom 🌸' : `${bloomStatus.count} found`) : 'Play'}</span>
        </button>
        <button class="opt" onclick={() => pick('free-center')}>
          <span class="opt-main"><strong>Free Play · Center Circle</strong><span>fresh wheels anytime · center letter</span></span>
          <span class="opt-go">Play</span>
        </button>
        <button class="opt" onclick={() => pick('free-wild')}>
          <span class="opt-main"><strong>Free Play · Wild Bloom</strong><span>fresh wheels · use any letters</span></span>
          <span class="opt-go">Play</span>
        </button>
      {:else if game === 'word'}
        <button class="opt" onclick={() => pick('5')}>
          <span class="opt-main"><strong>Daily Word</strong><span>5 letters · 6 guesses</span></span>
          <span class="opt-go" class:done={wordStatus['5']}>{wordOpt('5')}</span>
        </button>
        <button class="opt" onclick={() => pick('6')}>
          <span class="opt-main"><strong>Long Word</strong><span>6 letters · 7 guesses</span></span>
          <span class="opt-go" class:done={wordStatus['6']}>{wordOpt('6')}</span>
        </button>
      {:else}
        {#each WS_OPTS as [sz, name, desc] (sz)}
          <button class="opt" onclick={() => pick(sz)}>
            <span class="opt-main"><strong>{name}</strong><span>{desc}</span></span>
            <span class="opt-go" class:done={readWsSize(sz)}>{wsOpt(sz)}</span>
          </button>
        {/each}
      {/if}
    </div>

  {:else if view === 'play'}
    {#if game === 'word'}
      <WordGame {variant} onstatus={refreshStatus} />
    {:else if game === 'wordsearch'}
      <WordSearchGame size={wsSize} onstatus={refreshStatus} />
    {:else if game === 'bloom'}
      {#key sp.get('v')}
        <BloomGame mode={bloomMode} format={bloomFormat} onstatus={refreshStatus} />
      {/key}
    {:else if game === 'match'}
      {#key sp.get('v')}
        <MatchGame mode={matchMode} format={matchFormat} tier={matchTier} {date} onstatus={refreshStatus} />
      {/key}
    {/if}
  {/if}
</main>

<style>
  /* in-game step-back, below the shared HubBar (matches the hub Back affordance) */
  .gameback { color: var(--accent-deep); font-size: 0.9rem; font-weight: 600; display: inline-flex;
              align-items: center; gap: 6px; background: none; border: none; font-family: inherit;
              cursor: pointer; padding: 6px 10px 6px 0; margin-bottom: 4px;
              -webkit-tap-highlight-color: transparent; }
  .gameback svg { width: 16px; height: 16px; display: block; transition: transform 0.15s ease; }
  .gameback:hover { color: var(--accent); }
  .gameback:hover svg { transform: translateX(-2px); }
  .page { padding: 16px 20px 70px; }
  h1 { font-size: clamp(2rem, 5vw, 2.6rem); margin: 6px 0 6px; }
  .seltitle { font-size: clamp(1.7rem, 4.5vw, 2.2rem); }
  .sub { color: var(--muted); margin: 0 0 24px; max-width: 540px; }
  .themecard { background: var(--accent-soft); border-radius: 16px; padding: 16px 22px;
               margin: 8px 0 24px; max-width: 460px; text-align: center; box-shadow: var(--shadow); }
  .tc-label { display: block; text-transform: uppercase; letter-spacing: 0.13em; font-size: 0.66rem;
              font-family: var(--label); font-weight: 600; color: var(--accent-deep); margin-bottom: 4px; }
  /* Memory Match selection: format toggle + grouped tier options */
  .seg { display: flex; gap: 6px; background: var(--bg); border: 1px solid var(--line);
         border-radius: 12px; padding: 4px; margin-bottom: 6px; }
  .segbtn { flex: 1; padding: 9px 10px; border: none; border-radius: 9px; background: none;
            font-family: inherit; font-size: 0.9rem; color: var(--muted); cursor: pointer; }
  .segbtn.on { background: var(--surface); color: var(--accent-deep); font-weight: 600; box-shadow: var(--shadow); }
  .grp { margin: 14px 0 2px; font-family: var(--label); text-transform: uppercase; letter-spacing: 0.04em;
         font-size: 0.7rem; color: var(--muted); }
  .tc-name { font-family: var(--serif); font-size: 1.7rem; color: var(--accent-deep); line-height: 1.15; }

  /* ===== Arcade hub (CD "Play - Arcade"): colored game tiles, whole-card tap, no
     dashboard/streaks/XP — just games. Fonts match the rest of the hub. ===== */
  @font-face { font-family: 'Hanken Grotesk'; src: url('/fonts/hanken-var.woff2') format('woff2'); font-weight: 400 800; font-style: normal; font-display: swap; }
  @font-face { font-family: 'Newsreader'; src: url('/fonts/newsreader-var.woff2') format('woff2'); font-weight: 400 600; font-style: normal; font-display: swap; }
  @font-face { font-family: 'Space Mono'; src: url('/fonts/space-mono-latin.woff2') format('woff2'); font-weight: 400; font-style: normal; font-display: swap; }

  .arcade-head { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; margin: 2px 0 24px; }
  .eyelash { width: 34px; height: 4px; border-radius: 2px; background: #f0a830; flex: none; }
  .play-title { font-family: 'Newsreader', Georgia, serif; font-weight: 600; font-size: clamp(2.4rem, 6vw, 3.1rem); color: #e5882a; letter-spacing: -0.015em; line-height: 0.9; margin: 0; }
  .head-div { width: 1px; height: 32px; background: rgba(120, 95, 50, 0.22); flex: none; }
  .head-sub { color: var(--muted); font-size: 15px; line-height: 1.45; max-width: 340px; margin: 0; }

  .arcade { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; }
  .tile {
    position: relative; min-width: 0; min-height: 244px; border-radius: 22px; overflow: hidden;
    border: none; padding: 0; margin: 0; width: 100%; box-sizing: border-box; display: block;
    cursor: pointer; text-align: left; color: inherit; font-family: 'Hanken Grotesk', sans-serif;
    transition: transform 0.18s cubic-bezier(.34, 1.4, .5, 1), box-shadow 0.18s ease;
    -webkit-tap-highlight-color: transparent;
  }
  .tile:hover { transform: translateY(-5px); }
  .tile.soon { cursor: default; }
  .tile.soon:hover { transform: none; }
  .tile-word { background: #f0a830; box-shadow: 0 12px 26px -10px rgba(224, 148, 31, 0.55); }
  .tile-ws { background: #2f7fb0; box-shadow: 0 12px 26px -10px rgba(47, 127, 176, 0.55); }
  .tile-bloom { background: #5a9b63; box-shadow: 0 12px 26px -10px rgba(90, 155, 99, 0.55); }
  .tile-match { background: #c0688c; box-shadow: 0 12px 26px -10px rgba(192, 104, 140, 0.55); }
  .tile-bubble { background: linear-gradient(160deg, #6a6fc6, #4a4ea0); box-shadow: 0 12px 26px -10px rgba(74, 78, 160, 0.55); }
  .tile-more { background: #efe6d4; border: 1.5px dashed #cdbb9a; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 9px; padding: 24px; text-align: center; }

  .foot { position: absolute; left: 0; right: 0; bottom: 0; padding: 30px 18px 15px; display: flex; flex-direction: column; gap: 3px; background: linear-gradient(to top, rgba(50, 33, 12, 0.62), transparent); }
  .t-name { font-weight: 800; font-size: 19px; color: #fff; }
  .t-clue { font-family: 'Space Mono', monospace; font-size: 10.5px; letter-spacing: 0.03em; color: rgba(255, 255, 255, 0.84); }
  .tile-more .t-name { color: #6f6757; font-size: 16px; }
  .tile-more .t-clue { color: #a89a7c; }
  .more-plus { font-family: 'Newsreader', serif; font-size: 42px; line-height: 1; color: #cdbb9a; }
  .ribbon { position: absolute; top: 14px; right: 14px; font-family: 'Space Mono', monospace; font-size: 9.5px; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: #fff; background: rgba(0, 0, 0, 0.3); padding: 5px 10px; border-radius: 12px; }
  .devtag { margin-left: 8px; font-size: 0.58rem; font-family: 'Space Mono', monospace; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: #fff; background: rgba(0, 0, 0, 0.32); border-radius: 5px; padding: 2px 6px; vertical-align: middle; }

  /* tile motifs — decorative; clipped by the tile's overflow:hidden */
  .motif { position: absolute; inset: 0; pointer-events: none; }
  .m-word { padding: 22px 22px 0; display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px; align-content: start; }
  .wt { aspect-ratio: 1; box-sizing: border-box; border: 2.5px solid rgba(255, 255, 255, 0.45); border-radius: 8px; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: clamp(15px, 3.4vw, 22px); color: #cf7d1c; }
  .wt.on { background: #fff; border-color: #fff; }
  .m-ws { padding: 24px 22px 0; display: flex; flex-direction: column; gap: 6px; font-weight: 700; font-size: 15px; letter-spacing: 0.26em; }
  .wrow { display: flex; justify-content: center; color: rgba(255, 255, 255, 0.42); padding: 4px 0; }
  .wrow.hl { background: rgba(255, 255, 255, 0.93); color: #2f7fb0; border-radius: 9px; box-shadow: 0 2px 9px rgba(0, 0, 0, 0.12); }
  .m-bloom .petal { position: absolute; width: 42px; height: 42px; border-radius: 50%; background: #fff; color: #4f8a58; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 18px; box-shadow: 0 3px 7px rgba(0, 0, 0, 0.1); }
  .m-bloom .pc { width: 50px; height: 50px; background: #3e7a47; color: #fff; font-size: 22px; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); z-index: 1; left: 50%; top: 40%; transform: translate(-50%, -50%); }
  .m-bloom .p1 { left: 50%; top: 40%; transform: translate(-50%, -50%) translate(0, -56px); }
  .m-bloom .p2 { left: 50%; top: 40%; transform: translate(-50%, -50%) translate(48px, -28px); }
  .m-bloom .p3 { left: 50%; top: 40%; transform: translate(-50%, -50%) translate(48px, 28px); }
  .m-bloom .p4 { left: 50%; top: 40%; transform: translate(-50%, -50%) translate(0, 56px); }
  .m-bloom .p5 { left: 50%; top: 40%; transform: translate(-50%, -50%) translate(-48px, 28px); }
  .m-bloom .p6 { left: 50%; top: 40%; transform: translate(-50%, -50%) translate(-48px, -28px); }
  .m-match { padding: 24px 24px 56px; display: grid; grid-template-columns: repeat(4, 1fr); gap: 9px; align-content: start; }
  .mm { aspect-ratio: 1; border-radius: 9px; background: rgba(255, 255, 255, 0.2); display: flex; align-items: center; justify-content: center; }
  .mm.flip { background: #fff; }
  .mm .dot { width: 17px; height: 17px; border-radius: 50%; background: #c0688c; }
  .m-bubble { padding: 20px; display: flex; flex-wrap: wrap; gap: 8px; align-content: flex-start; }
  .bub { width: 38px; height: 38px; border-radius: 50%; box-shadow: 0 3px 8px rgba(0, 0, 0, 0.14); }
  .b-a { background: radial-gradient(circle at 32% 28%, #fff, #f0a830 62%); }
  .b-b { background: radial-gradient(circle at 32% 28%, #fff, #e8607f 62%); }
  .b-c { background: radial-gradient(circle at 32% 28%, #fff, #4fb0e0 62%); }
  .b-d { background: radial-gradient(circle at 32% 28%, #fff, #6ad0a8 62%); }

  @media (max-width: 880px) { .arcade { grid-template-columns: repeat(2, 1fr); } }
  @media (max-width: 560px) { .arcade { grid-template-columns: 1fr; } }

  /* Game-selection options */
  .opts { display: flex; flex-direction: column; gap: 12px; max-width: 460px; }
  .opt {
    display: flex; align-items: center; justify-content: space-between; gap: 14px;
    background: var(--surface); border: 1px solid var(--line); border-radius: 14px;
    padding: 16px 18px; cursor: pointer; font: inherit; color: var(--ink);
    box-shadow: var(--shadow); transition: border-color 0.14s ease, transform 0.14s ease;
  }
  .opt:hover { border-color: var(--accent); transform: translateY(-1px); }
  .opt-main { display: flex; flex-direction: column; text-align: left; }
  .opt-main strong { font-size: 1.1rem; }
  .opt-main span { color: var(--muted); font-size: 0.82rem; }
  .opt-go { flex-shrink: 0; font-size: 0.82rem; font-weight: 600; color: #fff; background: var(--accent);
            border-radius: 999px; padding: 6px 14px; }
  .opt-go.done { background: var(--accent-soft); color: var(--accent-deep); }

  /* Full-height game layout on mobile so the keyboard is always reachable. */
  @media (max-width: 720px) {
    .page.gameview {
      height: calc(100dvh - 64px); padding: 10px 16px 0;
      display: flex; flex-direction: column; overflow: hidden;
    }
  }
</style>
