<script lang="ts">
  import { t } from '../lib/i18n/index.svelte';
  import { installMode, promptInstall } from '../lib/pwa.svelte';
  import Modal from './Modal.svelte';

  // Platform-adaptive: 'oneTap' fires the native Chromium install dialog; 'iosInstructions' opens
  // the manual Share -> Add-to-Home-Screen guide (iOS Safari has no programmatic install); 'hidden'
  // renders nothing (already installed, inside a Telegram/VK Mini App, or an unsupported browser).
  const mode = $derived(installMode());
  let showIos = $state(false);

  function onClick(): void {
    // promptInstall must run synchronously from this gesture — the deferred prompt is gated on it.
    if (mode === 'oneTap') void promptInstall();
    else if (mode === 'iosInstructions') showIos = true;
  }
</script>

{#if mode !== 'hidden'}
  <button type="button" class="install" onclick={onClick}>
    <img src="favicon.svg" alt="" width="40" height="40" />
    <span class="text">
      <span class="title">{t('install.title')}</span>
      <span class="subtitle">{t('install.subtitle')}</span>
    </span>
  </button>
{/if}

{#if showIos}
  <Modal title={t('install.iosTitle')} onclose={() => (showIos = false)}>
    <ol class="steps">
      <li>{t('install.iosStep1')}</li>
      <li>{t('install.iosStep2')}</li>
      <li>{t('install.iosStep3')}</li>
    </ol>
    <button type="button" class="ok" onclick={() => (showIos = false)}>{t('common.ok')}</button>
  </Modal>
{/if}

<style>
  .install {
    display: flex;
    align-items: center;
    gap: 12px;
    width: 100%;
    text-align: left;
    padding: 12px;
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    background: var(--surface);
    color: var(--text);
    cursor: pointer;
  }
  .install img {
    flex: none;
    border-radius: 8px;
  }
  .text {
    display: flex;
    flex-direction: column;
    gap: 2px;
    min-width: 0;
  }
  .title {
    font-weight: 600;
  }
  .subtitle {
    font-size: 0.85rem;
    color: var(--text-muted);
    line-height: 1.35;
  }
  .steps {
    margin: 0 0 16px;
    padding-left: 1.25rem;
    line-height: 1.6;
  }
  .ok {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid var(--accent);
    background: var(--accent);
    color: var(--accent-text);
    border-radius: var(--radius-sm);
  }
</style>
