<script lang="ts">
  // @ts-nocheck
  import { invoke } from "@tauri-apps/api/core";
  import { listen } from "@tauri-apps/api/event";
  import { page, settings } from "$lib/stores/page.svelte.js";
  import UnicodeSpinner from "$lib/components/UnicodeSpinner.svelte";
  import { Download, CheckCircle } from 'lucide-svelte';

  let systemInfo = $state(null);
  let models = $state([]);
  let probing = $state(true);
  let downloading = $state(false);
  let downloadProgress = $state(0);
  let downloadingModel = $state("");
  let error = $state("");
  let ready = $state(false);
  let downloadStartedAt = $state(0);

  /** Estimated minutes remaining based on progress so far */
  let estimatedMinutes = $derived.by(() => {
    if (!downloading || downloadProgress <= 0 || !downloadStartedAt) return 0;
    const elapsed = (Date.now() - downloadStartedAt) / 1000;
    const total = elapsed / (downloadProgress / 100);
    const remaining = total - elapsed;
    return remaining / 60;
  });

  async function probe() {
    try {
      systemInfo = await invoke("probe_system");
      models = await invoke("rank_models");
      probing = false;
    } catch (e) {
      error = `Hardware probe failed: ${e}`;
      probing = false;
    }
  }

  async function downloadAndGo(modelId) {
    downloading = true;
    downloadingModel = modelId;
    downloadProgress = 0;
    downloadStartedAt = Date.now();

    const unlisten = await listen("model-download-progress", (event) => {
      downloadProgress = event.payload.percent;
    });

    const unlistenParakeet = await listen("parakeet-download-progress", (event) => {
      downloadProgress = event.payload.percent;
    });

    try {
      if (modelId.startsWith("whisper-")) {
        // backend's whisper_model_id accepts the full model id via its
        // `other => ModelId::new(other)` fallback, so pass the id through
        // unchanged rather than maintaining a fragile lowercased alias map.
        await invoke("download_model", { size: modelId });
        await invoke("load_model", { size: modelId });

        const idToLabel = {
          "whisper-tiny-en": "Tiny",
          "whisper-base-en": "Base",
          "whisper-small-en": "Small",
          "whisper-distil-small-en": "Distil-S",
          "whisper-medium-en": "Medium",
          "whisper-distil-large-v3": "Distil-L",
        };
        settings.engine = "whisper";
        settings.modelSize = idToLabel[modelId] ?? "Base";
      } else if (modelId.startsWith("parakeet-")) {
        await invoke("download_parakeet_model", { name: "ctc-int8" });
        await invoke("load_parakeet_model", { name: "ctc-int8" });
        settings.engine = "parakeet";
      }

      ready = true;
      setTimeout(() => {
        page.current = "dictation";
      }, 1500);
    } catch (e) {
      error = `Download failed: ${e}`;
      downloading = false;
    } finally {
      unlisten();
      unlistenParakeet();
    }
  }

  function skipSetup() {
    page.current = "dictation";
  }

  // Start probing on mount
  probe();
</script>

<div class="flex flex-col items-center justify-center h-full px-8 py-12 max-w-xl mx-auto">
  {#if probing}
    <div class="text-center">
      <UnicodeSpinner type="dots" speed={80} classes="text-2xl text-accent" />
      <h2 class="text-xl font-medium text-text mt-4">Checking your hardware</h2>
      <p class="text-sm text-text-secondary mt-2">One moment.</p>
    </div>

  {:else if ready}
    <div class="text-center">
      <CheckCircle size={40} strokeWidth={1.5} class="text-success mx-auto" />
      <h2 class="text-xl font-medium text-text mt-4">Ready to go</h2>
      <p class="text-sm text-text-secondary mt-2">Press the button. Start talking. That's it.</p>
    </div>

  {:else if downloading}
    <div class="text-center w-full">
      <Download size={32} strokeWidth={1.5} class="text-accent mx-auto mb-3" />
      <h2 class="text-xl font-medium text-text">Downloading model</h2>
      <p class="text-sm text-text-secondary mt-2">{downloadingModel}</p>
      <div class="w-full bg-bg-input rounded-full h-2 mt-6">
        <div
          class="bg-accent h-2 rounded-full"
          style="width: {downloadProgress}%; transition-duration: var(--duration-ui)"
        ></div>
      </div>
      <p class="text-xs text-text-tertiary mt-2">{downloadProgress}%</p>
      {#if estimatedMinutes > 2}
        <p class="text-xs text-text-secondary mt-3">Download in background — this may take a while</p>
      {/if}
    </div>

  {:else}
    <div class="w-full">
      <h2 class="text-2xl font-medium text-text text-center">Welcome to Kon</h2>
      <p class="text-sm text-text-secondary text-center mt-2">Press the button. Start talking. That's it.</p>

      {#if error}
        <div class="mt-4 p-3 rounded-lg bg-danger/10 text-danger text-sm">{error}</div>
      {/if}

      {#if systemInfo}
        <div class="mt-8 p-4 rounded-lg bg-bg-input border border-border">
          <h3 class="text-xs font-medium text-text-tertiary uppercase tracking-wider mb-3">Your system</h3>
          <div class="grid grid-cols-2 gap-2 text-sm">
            <span class="text-text-secondary">RAM</span>
            <span class="text-text">{Math.round(systemInfo.ram_mb / 1024)} GB</span>
            <span class="text-text-secondary">CPU</span>
            <span class="text-text truncate" title={systemInfo.cpu_brand}>{systemInfo.cpu_brand}</span>
            <span class="text-text-secondary">Cores</span>
            <span class="text-text">{systemInfo.cpu_cores}</span>
            <span class="text-text-secondary">OS</span>
            <span class="text-text">{systemInfo.os}</span>
          </div>
        </div>
      {/if}

      {#if models.length > 0}
        <div class="mt-6">
          <h3 class="text-xs font-medium text-text-tertiary uppercase tracking-wider mb-3">Pick a model</h3>
          <p class="text-xs text-text-tertiary mb-3">One tap — we handle the rest.</p>
          <div class="space-y-2">
            {#each models as model, i}
              <button
                class="w-full text-left p-3 rounded-lg border
                  {i === 0 ? 'border-accent bg-accent/5 hover:bg-accent/10' : 'border-border bg-bg-input hover:bg-hover'}"
                style="transition-duration: var(--duration-ui)"
                onclick={() => downloadAndGo(model.id)}
                disabled={model.is_downloaded}
              >
                <div class="flex items-center justify-between">
                  <div>
                    <span class="text-sm font-medium text-text">{model.display_name}</span>
                    {#if i === 0}
                      <span class="ml-2 text-[10px] px-1.5 py-0.5 rounded-full bg-accent/15 text-accent font-medium">Recommended</span>
                    {/if}
                    {#if model.is_downloaded}
                      <span class="ml-2 text-[10px] px-1.5 py-0.5 rounded-full bg-success/15 text-success font-medium">Downloaded</span>
                    {/if}
                  </div>
                  <span class="text-xs text-text-tertiary">{model.disk_size_mb} MB</span>
                </div>
                <p class="text-xs text-text-secondary mt-1">{model.description}</p>
              </button>
            {/each}
          </div>
        </div>
      {/if}

      <button
        class="mt-6 text-xs text-text-tertiary hover:text-text-secondary underline"
        style="transition-duration: var(--duration-ui)"
        onclick={skipSetup}
      >
        Skip setup — I'll configure later
      </button>
    </div>
  {/if}
</div>
