<script lang="ts">
  import { onMount } from 'svelte';
  import Modal from '../components/Modal.svelte';
  import { app, applyLinkResult, handleError, logout, showToast } from '../lib/app.svelte';
  import { connection } from '../lib/connection.svelte';
  import { gateway } from '../lib/gateway';
  import { loginWidgetAvailable, requestTelegramLogin } from '../lib/telegram';
  import { t } from '../lib/i18n/index.svelte';
  import {
    awayDurationOk,
    awayHours,
    awayMinutes,
    browserOffset,
    isOffsetZone,
    timezoneOffsets,
    validDisplayName,
    validEmail,
  } from '../lib/profileValidation';
  import { ALL_VARIANTS, VARIANT_RULES } from '../lib/variants';
  import type { Variant } from '../lib/model';

  let dn = $state('');
  let tz = $state('+00:00');
  // Away start/end as hour + 10-minute parts, so the picker is a <select> like every
  // other profile control (consistent native control across iOS / desktop).
  let startH = $state('00');
  let startM = $state('00');
  let endH = $state('07');
  let endM = $state('00');
  let blockChat = $state(false);
  let blockFriendRequests = $state(false);
  let notificationsInAppOnly = $state(true);
  let variantPrefs = $state<Variant[]>([]);
  let emailInput = $state('');
  let codeInput = $state('');
  let emailSent = $state(false);
  // A pending irreversible merge surfaced after the code/widget was verified; the
  // dialog confirms it. tgData holds the Telegram widget payload for the merge step.
  let pendingMerge = $state<null | { kind: 'email' | 'telegram'; name: string; games: number; friends: number }>(null);
  let tgData = '';
  const telegramLinkable = loginWidgetAvailable();

  function defaultTz(): string {
    const b = browserOffset();
    return timezoneOffsets.includes(b) ? b : '+00:00';
  }
  function splitTime(hhmm: string): [string, string] {
    const m = /^(\d{2}):(\d{2})$/.exec(hhmm);
    if (!m) return ['00', '00'];
    return [m[1], awayMinutes.includes(m[2]) ? m[2] : '00'];
  }

  // populate loads the editable form from the current profile. The profile screen is
  // edited inline (no edit/cancel toggle), so this runs on mount and after a
  // link/merge swaps the active account.
  function populate() {
    const p = app.profile;
    if (!p) return;
    dn = p.displayName;
    tz = isOffsetZone(p.timeZone) && timezoneOffsets.includes(p.timeZone) ? p.timeZone : defaultTz();
    [startH, startM] = splitTime(p.awayStart);
    [endH, endM] = splitTime(p.awayEnd);
    blockChat = p.blockChat;
    blockFriendRequests = p.blockFriendRequests;
    notificationsInAppOnly = p.notificationsInAppOnly;
    variantPrefs = [...p.variantPreferences];
  }
  onMount(populate);

  const awayStart = $derived(`${startH}:${startM}`);
  const awayEnd = $derived(`${endH}:${endM}`);
  const nameOk = $derived(validDisplayName(dn));
  const awayOk = $derived(awayDurationOk(awayStart, awayEnd));
  const formValid = $derived(nameOk && awayOk && variantPrefs.length >= 1);
  const emailOk = $derived(validEmail(emailInput));

  // toggleVariant flips a variant in the preference set, refusing to remove the last one —
  // the player must allow themselves at least one variant.
  function toggleVariant(id: Variant) {
    if (variantPrefs.includes(id)) {
      if (variantPrefs.length > 1) variantPrefs = variantPrefs.filter((v) => v !== id);
    } else {
      variantPrefs = [...variantPrefs, id];
    }
  }

  async function save() {
    if (!formValid) return;
    try {
      app.profile = await gateway.profileUpdate({
        displayName: dn.trim(),
        preferredLanguage: app.profile!.preferredLanguage, // language lives in Settings
        timeZone: tz,
        awayStart,
        awayEnd,
        blockChat,
        blockFriendRequests,
        notificationsInAppOnly,
        variantPreferences: variantPrefs,
      });
      showToast(t('profile.saved'));
    } catch (e) {
      handleError(e);
    }
  }

  function resetEmail() {
    emailSent = false;
    emailInput = '';
    codeInput = '';
  }

  async function requestEmail() {
    if (!emailOk) return;
    try {
      await gateway.linkEmailRequest(emailInput.trim());
      emailSent = true;
      showToast(t('profile.emailSent', { email: emailInput.trim() }));
    } catch (e) {
      handleError(e);
    }
  }

  async function confirmEmail() {
    try {
      const r = await gateway.linkEmailConfirm(emailInput.trim(), codeInput.trim());
      if (r.status === 'merge_required') {
        pendingMerge = { kind: 'email', name: r.secondaryDisplayName, games: r.secondaryGames, friends: r.secondaryFriends };
        return;
      }
      await applyLinkResult(r);
      populate();
      resetEmail();
      showToast(t('profile.linked'));
    } catch (e) {
      handleError(e);
    }
  }

  async function linkTelegram() {
    try {
      const data = await requestTelegramLogin();
      if (!data) return;
      const r = await gateway.linkTelegram(data);
      if (r.status === 'merge_required') {
        tgData = data;
        pendingMerge = { kind: 'telegram', name: r.secondaryDisplayName, games: r.secondaryGames, friends: r.secondaryFriends };
        return;
      }
      await applyLinkResult(r);
      populate();
      showToast(t('profile.linked'));
    } catch (e) {
      handleError(e);
    }
  }

  async function confirmMerge() {
    if (!pendingMerge) return;
    try {
      const r =
        pendingMerge.kind === 'email'
          ? await gateway.linkEmailMerge(emailInput.trim(), codeInput.trim())
          : await gateway.linkTelegramMerge(tgData);
      await applyLinkResult(r);
      populate();
      pendingMerge = null;
      tgData = '';
      resetEmail();
      showToast(t('profile.merged'));
    } catch (e) {
      handleError(e);
    }
  }
</script>

<div class="page">
  {#if app.profile}
    {@const p = app.profile}
    <div class="name">{p.displayName}</div>
    {#if p.isGuest}<span class="badge">{t('profile.guest')}</span>{/if}

    {#if p.isGuest}
      <p class="muted">{t('profile.guestLocked')}</p>
    {:else}
      <form class="edit" onsubmit={(e) => { e.preventDefault(); void save(); }}>
        <label>
          <span>{t('profile.displayName')}</span>
          <input class:invalid={!nameOk} bind:value={dn} maxlength="40" />
        </label>
        <label>
          <span>{t('profile.timezone')}</span>
          <select bind:value={tz}>
            {#each timezoneOffsets as o (o)}<option value={o}>{o}</option>{/each}
          </select>
        </label>
        <fieldset class="away" class:invalid={!awayOk}>
          <legend>{t('profile.awayWindow')}</legend>
          <div class="times">
            <span class="tlabel">{t('profile.from')}</span>
            <select bind:value={startH}>{#each awayHours as h (h)}<option>{h}</option>{/each}</select>
            <span class="colon">:</span>
            <select bind:value={startM}>{#each awayMinutes as m (m)}<option>{m}</option>{/each}</select>
          </div>
          <div class="times">
            <span class="tlabel">{t('profile.to')}</span>
            <select bind:value={endH}>{#each awayHours as h (h)}<option>{h}</option>{/each}</select>
            <span class="colon">:</span>
            <select bind:value={endM}>{#each awayMinutes as m (m)}<option>{m}</option>{/each}</select>
          </div>
          <p class="muted">{t('profile.awayHint')}</p>
        </fieldset>
        <label class="check">
          <input type="checkbox" bind:checked={blockChat} />
          <span>{t('profile.blockChat')}</span>
        </label>
        <label class="check">
          <input type="checkbox" bind:checked={blockFriendRequests} />
          <span>{t('profile.blockFriendRequests')}</span>
        </label>
        <label class="check">
          <input type="checkbox" bind:checked={notificationsInAppOnly} />
          <span>{t('profile.notificationsInAppOnly')}</span>
        </label>
        <fieldset class="prefs">
          <legend>{t('profile.preferences')}</legend>
          <p class="muted">{t('profile.preferencesHint')}</p>
          {#each ALL_VARIANTS as v (v.id)}
            <label class="check pref">
              <input
                type="checkbox"
                checked={variantPrefs.includes(v.id)}
                disabled={variantPrefs.length === 1 && variantPrefs.includes(v.id)}
                onchange={() => toggleVariant(v.id)}
              />
              <span class="pname">{t(v.label)}</span>
              <span class="prule">{t(VARIANT_RULES[v.id])}</span>
            </label>
          {/each}
        </fieldset>
        <div class="formacts">
          <button type="submit" class="btn" disabled={!formValid || !connection.online}>{t('common.save')}</button>
        </div>
      </form>
    {/if}

    <!-- Linking & merge. Hidden for now: we target provider sign-in, and the anonymous
         /app/ guest (whose upgrade path this is) comes later. Kept wired — drop `hidden`
         to re-enable, together with the skipped linking specs in e2e/social.spec.ts. -->
    <section class="emailbox" hidden>
      <h3>{t('profile.linkAccount')}</h3>
      {#if !emailSent}
        <div class="addrow">
          <input
            class:invalid={emailInput.length > 0 && !emailOk}
            bind:value={emailInput}
            placeholder={t('login.emailPlaceholder')}
            type="email"
          />
          <button class="ghost" onclick={requestEmail} disabled={!emailOk || !connection.online}>{t('login.sendCode')}</button>
        </div>
      {:else}
        <div class="addrow">
          <input
            class="codein"
            bind:value={codeInput}
            placeholder={t('profile.emailCode')}
            inputmode="numeric"
            maxlength="6"
          />
          <button class="btn" onclick={confirmEmail} disabled={!connection.online}>{t('common.ok')}</button>
        </div>
      {/if}
      {#if telegramLinkable}
        <button class="ghost tg" onclick={linkTelegram} disabled={!connection.online}>{t('profile.linkTelegram')}</button>
      {/if}
    </section>

    <!-- Logout is hidden for now but kept wired — drop `hidden` to re-enable
         once its entry point is decided; logout() also still runs on an invalid session. -->
    <button class="logout" hidden onclick={() => logout()}>{t('login.title')} / logout</button>
  {/if}
</div>

{#if pendingMerge}
  <Modal title={t('profile.mergeTitle')} onclose={() => (pendingMerge = null)}>
    <p>{t('profile.mergeBody', { name: pendingMerge.name, games: pendingMerge.games, friends: pendingMerge.friends })}</p>
    <p class="warn">{t('profile.mergeIrreversible')}</p>
    <div class="addrow end">
      <button class="ghost" onclick={() => (pendingMerge = null)}>{t('common.cancel')}</button>
      <button class="btn" onclick={confirmMerge} disabled={!connection.online}>{t('profile.mergeConfirm')}</button>
    </div>
  </Modal>
{/if}

<style>
  .page {
    padding: var(--pad);
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  .name {
    font-size: 1.4rem;
    font-weight: 700;
  }
  .badge {
    align-self: flex-start;
    padding: 2px 8px;
    border-radius: 999px;
    background: var(--surface-2);
    color: var(--text-muted);
    font-size: 0.8rem;
  }
  .muted {
    color: var(--text-muted);
    font-size: 0.9rem;
    margin: 0;
  }
  .edit {
    display: flex;
    flex-direction: column;
    gap: 14px;
  }
  .edit > label {
    display: flex;
    flex-direction: column;
    gap: 4px;
    font-size: 0.9rem;
    color: var(--text-muted);
  }
  .edit input:not([type='checkbox']),
  .edit select {
    min-width: 0;
    padding: 9px 11px;
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--text);
    border-radius: var(--radius-sm);
  }
  .invalid {
    border-color: var(--danger, #c0392b) !important;
  }
  .away {
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    padding: 10px 12px;
    margin: 0;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  .away legend {
    color: var(--text-muted);
    font-size: 0.9rem;
    padding: 0 4px;
  }
  .times {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .tlabel {
    min-width: 2.5em;
    color: var(--text-muted);
    font-size: 0.85rem;
  }
  .colon {
    font-weight: 700;
  }
  .check {
    flex-direction: row !important;
    align-items: center;
    gap: 10px !important;
    color: var(--text) !important;
  }
  .prefs {
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    padding: 10px 12px;
    margin: 0;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  .prefs legend {
    color: var(--text-muted);
    font-size: 0.9rem;
    padding: 0 4px;
  }
  .pref {
    align-items: baseline;
  }
  .pname {
    font-weight: 600;
  }
  .prule {
    color: var(--text-muted);
    font-size: 0.8rem;
  }
  .formacts {
    display: flex;
    gap: 10px;
  }
  .btn:disabled {
    opacity: 0.5;
  }
  .emailbox h3 {
    margin: 0 0 8px;
    font-size: 0.95rem;
    color: var(--text-muted);
  }
  .addrow {
    display: flex;
    gap: 8px;
  }
  .addrow input {
    flex: 1;
    min-width: 0;
    padding: 9px 11px;
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--text);
    border-radius: var(--radius-sm);
  }
  .addrow input.codein {
    letter-spacing: 0.3em;
    font-size: 1.1rem;
  }
  .btn {
    align-self: flex-start;
    padding: 9px 14px;
    border: 1px solid var(--accent);
    background: var(--accent);
    color: var(--accent-text);
    border-radius: var(--radius-sm);
  }
  .ghost {
    padding: 9px 14px;
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--text);
    border-radius: var(--radius-sm);
  }
  .ghost:disabled {
    opacity: 0.5;
  }
  .logout {
    margin-top: 8px;
    align-self: flex-start;
    padding: 8px 14px;
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--text);
    border-radius: var(--radius-sm);
  }
</style>
