<script lang="ts">
  import { onMount } from 'svelte';
  import { browser } from '$app/environment';
  import { pwaInstallManager } from '$lib/client/PWAInstallManager';
  import Chip from './Chip.svelte';
  import Bell from './ic/Bell.svelte';
  import Share from './ic/Share.svelte';
  import Download from './ic/Download.svelte';
  import Spark from './ic/Spark.svelte';

  let showPrompt = $state(false);
  let showFallback = $state(false);
  let canInstall = $state(false);
  let installing = $state(false);
  let userEngaged = $state(false);
  let unsubscribe: (() => void) | null = null;

  onMount(() => {
    if (pwaInstallManager.isDismissed() || pwaInstallManager.isStandalone()) return;

    unsubscribe = pwaInstallManager.onInstallStateChange((installable) => {
      canInstall = installable;
      if (installable && userEngaged && !pwaInstallManager.isDismissed()) {
        setTimeout(() => { showPrompt = true; }, 2000);
      } else if (!installable && userEngaged && !pwaInstallManager.isStandalone() && !pwaInstallManager.isDismissed()) {
        setTimeout(() => { showFallback = true; }, 5000);
      }
    });

    const detectEngagement = () => { userEngaged = true; };
    document.addEventListener('scroll', detectEngagement, { once: true });
    document.addEventListener('click', detectEngagement, { once: true });
    document.addEventListener('keydown', detectEngagement, { once: true });

    return () => {
      unsubscribe?.();
      document.removeEventListener('scroll', detectEngagement);
      document.removeEventListener('click', detectEngagement);
      document.removeEventListener('keydown', detectEngagement);
    };
  });

  async function handleInstall() {
    installing = true;
    try {
      const result = await pwaInstallManager.showInstallPrompt();
      if (result === 'accepted') { showPrompt = false; showFallback = false; }
      else if (result === 'dismissed') handleDismiss();
    } catch (e) {
      console.error('Install failed:', e);
    } finally {
      installing = false;
    }
  }

  function handleDismiss() {
    showPrompt = false;
    showFallback = false;
    pwaInstallManager.setDismissed();
  }
</script>

<!-- InstallSheet bottom sheet -->
{#if showPrompt && canInstall}
  <!-- svelte-ignore a11y_click_events_have_key_events -->
  <!-- svelte-ignore a11y_no_static_element_interactions -->
  <div class="overlay ic-fade" onclick={handleDismiss}>
    <div class="sheet ic-slide-up" onclick={(e) => e.stopPropagation()}>
      <!-- Handle -->
      <div class="handle-row"><div class="handle"></div></div>

      <div class="inner">
        <!-- App identity -->
        <div class="app-row">
          <img src="/icon-256.png" alt="InstaChef" width="58" height="58" class="app-icon" />
          <div>
            <Chip color="var(--pink)" bg="rgba(225,48,108,0.12)" mono>
              <Spark size={10} color="var(--pink)" /> INSTALL
            </Chip>
            <div class="ic-display app-name">Put InstaChef on your home screen</div>
          </div>
        </div>

        <!-- Feature grid -->
        <div class="feature-grid">
          {#each [
            { Icon: Share, color: 'var(--purple)', t: 'Share-sheet target', d: 'Send links from Instagram in one tap.' },
            { Icon: Bell, color: 'var(--pink)', t: 'Push when ready', d: 'Buzz on save, retry, or fail.' },
            { Icon: Download, color: 'var(--orange)', t: 'Works offline', d: 'Browse saved recipes anywhere.' },
            { Icon: Spark, color: 'var(--yellow)', t: 'Faster too', d: 'Launches like a native app.' },
          ] as f}
            <div class="feature-card">
              <f.Icon size={16} color={f.color} />
              <div class="feature-title">{f.t}</div>
              <div class="feature-desc">{f.d}</div>
            </div>
          {/each}
        </div>

        <!-- Install button -->
        <button class="ic-btn-reset install-btn" onclick={handleInstall} disabled={installing}>
          {#if installing}
            Installing…
          {:else}
            <Download size={18} color="#fff" /> Install InstaChef
          {/if}
        </button>
        <button class="ic-btn-reset later-btn" onclick={handleDismiss}>Maybe later</button>
      </div>
    </div>
  </div>
{/if}

<!-- Fallback hint (iOS Safari etc.) -->
{#if showFallback && !canInstall && browser && !pwaInstallManager.isStandalone()}
  <div class="fallback ic-slide-up">
    <div class="fallback-inner">
      <div class="fallback-text">
        <div class="fallback-title">Install InstaChef</div>
        <div class="fallback-sub">{pwaInstallManager.getInstallInstructions()}</div>
      </div>
      <button class="ic-btn-reset close-fallback" onclick={handleDismiss} aria-label="Dismiss">✕</button>
    </div>
  </div>
{/if}

<style>
  .overlay {
    position: fixed;
    inset: 0;
    z-index: 70;
    display: flex;
    align-items: flex-end;
    background: rgba(0, 0, 0, 0.42);
  }
  .sheet {
    width: 100%;
    border-radius: 32px 32px 0 0;
    background: var(--bg);
    box-shadow: 0 -20px 60px rgba(0, 0, 0, 0.3);
  }
  .handle-row {
    display: flex;
    justify-content: center;
    margin-bottom: 16px;
    padding-top: 14px;
  }
  .handle {
    width: 44px;
    height: 5px;
    border-radius: 99px;
    background: var(--border-strong);
  }
  .inner {
    padding: 0 22px 30px;
  }
  .app-row {
    display: flex;
    align-items: center;
    gap: 14px;
    margin-bottom: 18px;
  }
  .app-icon {
    border-radius: 16px;
    box-shadow: 0 8px 22px rgba(225, 48, 108, 0.35);
    flex-shrink: 0;
  }
  .app-name {
    font-size: 22px;
    line-height: 1.1;
    color: var(--ink);
    margin-top: 6px;
  }
  .feature-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
    margin-bottom: 18px;
  }
  .feature-card {
    padding: 12px;
    border-radius: 16px;
    background: var(--surface);
    border: 1px solid var(--border);
  }
  .feature-title {
    font-size: 13px;
    font-weight: 700;
    margin: 6px 0 2px;
    color: var(--ink);
  }
  .feature-desc {
    font-size: 11px;
    color: var(--muted);
    line-height: 1.35;
  }
  .install-btn {
    width: 100%;
    background: var(--brand-gradient);
    color: #fff;
    padding: 16px;
    border-radius: 99px;
    font-size: 15px;
    font-weight: 700;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    box-shadow: var(--shadow-lg);
    margin-bottom: 8px;
  }
  .later-btn {
    width: 100%;
    padding: 12px;
    color: var(--muted);
    font-size: 13px;
    font-weight: 600;
  }
  .fallback {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 50;
    padding: 12px 16px 34px;
    background: var(--bg);
    border-top: 1px solid var(--border);
    box-shadow: 0 -8px 24px rgba(0, 0, 0, 0.12);
  }
  .fallback-inner {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  .fallback-text {
    flex: 1;
  }
  .fallback-title {
    font-size: 14px;
    font-weight: 700;
    color: var(--ink);
    margin-bottom: 2px;
  }
  .fallback-sub {
    font-size: 12px;
    color: var(--muted);
  }
  .close-fallback {
    color: var(--muted);
    font-size: 16px;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 99px;
    background: var(--surface-2);
    flex-shrink: 0;
  }
</style>