<script lang="ts">
  import { invoke } from '@tauri-apps/api/core';
  import { listen } from '@tauri-apps/api/event';
  import type { UnlistenFn } from '@tauri-apps/api/event';
  import { onMount } from 'svelte';

  interface Props {
    onComplete: () => void;
  }

  let { onComplete }: Props = $props();

  let variant = $state<'cpu' | 'cuda'>('cpu');
  let downloading = $state(false);
  let downloadProgress = $state({ downloaded: 0, total: 0, percent: 0 });
  let error = $state('');
  let success = $state(false);

  let unlisten: UnlistenFn | null = null;

  onMount(() => {
    return () => {
      unlisten?.();
    };
  });

  function formatBytes(bytes: number): string {
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
    if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(0)} MB`;
    return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
  }

  async function startDownload() {
    downloading = true;
    error = '';
    success = false;

    unlisten = await listen<{ downloaded: number; total: number; percent: number }>(
      'sidecar-download-progress',
      (event) => {
        downloadProgress = event.payload;
      }
    );

    try {
      await invoke('download_sidecar', { variant });
      success = true;
      // Brief pause so the user sees "Complete" before the screen goes away
      setTimeout(() => {
        onComplete();
      }, 800);
    } catch (err) {
      error = String(err);
    } finally {
      downloading = false;
      unlisten?.();
      unlisten = null;
    }
  }
</script>

<div class="setup-overlay">
  <div class="setup-card">
    <h1 class="app-title">Voice to Notes</h1>
    <h2 class="setup-heading">First-Time Setup</h2>
    <p class="setup-description">
      Voice to Notes needs to download its AI engine to transcribe audio.
    </p>

    {#if !downloading && !success}
      <div class="variant-options">
        <label class="variant-option" class:selected={variant === 'cpu'}>
          <input type="radio" name="variant" value="cpu" bind:group={variant} />
          <div class="variant-info">
            <span class="variant-label">Standard (CPU)</span>
            <span class="variant-desc">Works on all computers (~500 MB download)</span>
          </div>
        </label>
        <label class="variant-option" class:selected={variant === 'cuda'}>
          <input type="radio" name="variant" value="cuda" bind:group={variant} />
          <div class="variant-info">
            <span class="variant-label">GPU Accelerated (CUDA)</span>
            <span class="variant-desc">Faster transcription with NVIDIA GPU (~2 GB download)</span>
          </div>
        </label>
      </div>

      {#if error}
        <div class="error-box">
          <p class="error-text">{error}</p>
          <button class="btn-retry" onclick={startDownload}>Retry</button>
        </div>
      {:else}
        <button class="btn-download" onclick={startDownload}>
          Download &amp; Install
        </button>
      {/if}
    {:else if downloading}
      <div class="progress-section">
        <div class="progress-bar-track">
          <div class="progress-bar-fill" style="width: {downloadProgress.percent}%"></div>
        </div>
        <p class="progress-text">
          {downloadProgress.percent}% — {formatBytes(downloadProgress.downloaded)} / {formatBytes(downloadProgress.total)}
        </p>
        <p class="progress-hint">Downloading {variant === 'cuda' ? 'GPU' : 'CPU'} engine...</p>
      </div>
    {:else if success}
      <div class="success-section">
        <div class="success-icon">&#10003;</div>
        <p class="success-text">Setup complete!</p>
      </div>
    {/if}
  </div>
</div>

<style>
  .setup-overlay {
    position: fixed;
    inset: 0;
    background: #0a0a23;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
  }

  .setup-card {
    background: #16213e;
    border: 1px solid #2a3a5e;
    border-radius: 12px;
    padding: 2.5rem 3rem;
    max-width: 480px;
    width: 90vw;
    color: #e0e0e0;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
    text-align: center;
  }

  .app-title {
    font-size: 1.8rem;
    margin: 0 0 0.25rem;
    color: #e94560;
    font-weight: 700;
  }

  .setup-heading {
    font-size: 1.1rem;
    margin: 0 0 0.75rem;
    color: #e0e0e0;
    font-weight: 500;
  }

  .setup-description {
    font-size: 0.9rem;
    color: #b0b0b0;
    margin: 0 0 1.5rem;
    line-height: 1.5;
  }

  .variant-options {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    margin-bottom: 1.5rem;
    text-align: left;
  }

  .variant-option {
    display: flex;
    align-items: flex-start;
    gap: 0.75rem;
    padding: 0.85rem 1rem;
    border: 1px solid #2a3a5e;
    border-radius: 8px;
    cursor: pointer;
    transition: border-color 0.15s, background 0.15s;
  }

  .variant-option:hover {
    border-color: #4a5568;
    background: rgba(255, 255, 255, 0.02);
  }

  .variant-option.selected {
    border-color: #e94560;
    background: rgba(233, 69, 96, 0.08);
  }

  .variant-option input[type='radio'] {
    margin-top: 0.2rem;
    accent-color: #e94560;
    flex-shrink: 0;
  }

  .variant-info {
    display: flex;
    flex-direction: column;
    gap: 0.2rem;
  }

  .variant-label {
    font-size: 0.9rem;
    font-weight: 500;
    color: #e0e0e0;
  }

  .variant-desc {
    font-size: 0.78rem;
    color: #888;
  }

  .btn-download {
    background: #e94560;
    border: none;
    color: white;
    padding: 0.7rem 1.5rem;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.9rem;
    font-weight: 500;
    width: 100%;
    transition: background 0.15s;
  }

  .btn-download:hover {
    background: #d63851;
  }

  .progress-section {
    margin-top: 0.5rem;
  }

  .progress-bar-track {
    width: 100%;
    height: 8px;
    background: #1a1a2e;
    border-radius: 4px;
    overflow: hidden;
    border: 1px solid #2a3a5e;
  }

  .progress-bar-fill {
    height: 100%;
    background: #e94560;
    border-radius: 4px;
    transition: width 0.3s ease;
  }

  .progress-text {
    margin: 0.75rem 0 0;
    font-size: 0.85rem;
    color: #e0e0e0;
    font-variant-numeric: tabular-nums;
  }

  .progress-hint {
    margin: 0.35rem 0 0;
    font-size: 0.78rem;
    color: #888;
  }

  .error-box {
    background: rgba(233, 69, 96, 0.1);
    border: 1px solid rgba(233, 69, 96, 0.3);
    border-radius: 8px;
    padding: 1rem;
  }

  .error-text {
    color: #e94560;
    font-size: 0.85rem;
    margin: 0 0 0.75rem;
    word-break: break-word;
    line-height: 1.4;
  }

  .btn-retry {
    background: #e94560;
    border: none;
    color: white;
    padding: 0.5rem 1.25rem;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.85rem;
    font-weight: 500;
  }

  .btn-retry:hover {
    background: #d63851;
  }

  .success-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.5rem;
    padding: 1rem 0;
  }

  .success-icon {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: rgba(78, 205, 196, 0.15);
    color: #4ecdc4;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    font-weight: 700;
  }

  .success-text {
    color: #4ecdc4;
    font-size: 1rem;
    margin: 0;
    font-weight: 500;
  }
</style>
