<script lang="ts">
  import { t } from '../lib/i18n/index.svelte';
  import { insideTelegram, telegramDialogsAvailable, telegramShowPopup } from '../lib/telegram';
  import { LOGIN_BUTTON_ID, gameLimitGuestPopup, gameLimitDurablePopup } from '../lib/nativedialogs';
  import Modal from './Modal.svelte';

  // The New-Game screen raises this when the player taps a start whose kind is at its cap. guest
  // picks the message: a sign-in funnel (a guest plays more by registering) vs a durable account's
  // plain "finish a current game first" notice. onclose dismisses; onlogin routes a guest to sign-in.
  let { open, guest, onclose, onlogin }: { open: boolean; guest: boolean; onclose: () => void; onlogin: () => void } = $props();

  const title = $derived(guest ? t('new.limitGuestTitle') : t('new.limitDurableTitle'));
  const body = $derived(guest ? t('new.limitGuestBody') : t('new.limitDurableBody'));

  // Native path: inside the Mini App with native dialogs, present Telegram's own popup instead of
  // the in-app modal (evaluated at fire time — the SDK loads after mount). A guest popup's login
  // button routes to sign-in; any other dismissal closes. The message here is a plain notice with
  // no gesture-gated follow-up, so a native popup is safe (unlike share/clipboard flows).
  let shown = false;
  $effect(() => {
    if (open && !shown && insideTelegram() && telegramDialogsAvailable()) {
      shown = true;
      const params = guest
        ? gameLimitGuestPopup(title, body, t('common.cancel'), t('new.limitLogin'))
        : gameLimitDurablePopup(title, body, t('common.ok'));
      void telegramShowPopup(params).then((id) => (guest && id === LOGIN_BUTTON_ID ? onlogin() : onclose()));
    } else if (!open) {
      shown = false;
    }
  });
</script>

{#if open && !(insideTelegram() && telegramDialogsAvailable())}
  <Modal {title} onclose={onclose}>
    <p class="msg">{body}</p>
    <div class="actions">
      {#if guest}
        <button class="cancel" onclick={onclose}>{t('common.cancel')}</button>
        <button class="primary" onclick={onlogin}>{t('new.limitLogin')}</button>
      {:else}
        <button class="primary" onclick={onclose}>{t('common.ok')}</button>
      {/if}
    </div>
  </Modal>
{/if}

<style>
  .msg {
    margin: 0 0 16px;
    line-height: 1.5;
  }
  .actions {
    display: flex;
    gap: 8px;
  }
  .actions button {
    flex: 1;
    padding: 10px 12px;
    border-radius: var(--radius-sm);
    border: 1px solid var(--accent);
  }
  .cancel {
    background: transparent;
    color: var(--accent);
  }
  .primary {
    background: var(--accent);
    color: var(--accent-text);
  }
</style>
