<script lang="ts">
  import { onMount } from 'svelte';
  import { confirmDeeplink } from '../lib/app.svelte';
  import { setLocale, t } from '../lib/i18n/index.svelte';

  let { token }: { token: string } = $props();
  // busy → (a login navigates into the app) | linked | merge | error. The token rides
  // the URL fragment (#/confirm/<token>), which is never sent to the server, so a plain
  // link prefetch cannot reach it — confirm on load. The manual six-digit code in the
  // same email is the fallback if an aggressive scanner runs the page first.
  let stage = $state<'busy' | 'linked' | 'merge' | 'error'>('busy');

  onMount(async () => {
    // The email carries the recipient's language on the link (?lang), so this
    // session-less page renders in it rather than the default.
    const query = window.location.hash.split('?')[1] ?? '';
    const lang = new URLSearchParams(query).get('lang');
    if (lang === 'ru' || lang === 'en') setLocale(lang);

    if (!token) {
      stage = 'error';
      return;
    }
    try {
      const r = await confirmDeeplink(token);
      stage = r === 'merge_required' ? 'merge' : 'linked';
    } catch {
      stage = 'error';
    }
  });
</script>

<main class="confirm">
  <div class="card">
    {#if stage === 'busy'}
      <p class="muted">{t('confirm.busy')}</p>
    {:else if stage === 'error'}
      <p class="err">{t('confirm.expired')}</p>
    {:else}
      <div class="brand">{t('app.brand')}</div>
      <p class="ok">{stage === 'merge' ? t('confirm.merge') : t('confirm.linked')}</p>
      <p class="muted">{t('confirm.close')}</p>
    {/if}
  </div>
</main>

<style>
  .confirm {
    height: 100%;
    display: grid;
    place-items: center;
    padding: 16px;
  }
  .card {
    width: min(94vw, 360px);
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    box-shadow: var(--shadow);
    padding: 24px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  .brand {
    font-weight: 700;
    letter-spacing: 0.04em;
    color: var(--accent);
  }
  p {
    margin: 0;
  }
  .muted {
    color: var(--text-muted);
    font-size: 0.9rem;
  }
  .ok {
    font-weight: 600;
  }
  .err {
    color: var(--danger, #c0392b);
  }
</style>
