<script lang="ts">
  // @ts-nocheck
  import { invoke } from "@tauri-apps/api/core";
  import { listen } from "@tauri-apps/api/event";
  import { page, settings, saveSettings } from "$lib/stores/page.svelte.js";
  import UnicodeSpinner from "$lib/components/UnicodeSpinner.svelte";
  import { toasts } from "$lib/stores/toasts.svelte.js";
  import { Download, CheckCircle, Sunrise, Moon, Play } 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 the model is already on disk, skip the download step so the user
      // can replay onboarding without re-downloading. download_model is a
      // no-op for present files in current builds, but we belt-and-brace by
      // checking is_downloaded first.
      const alreadyDownloaded = (models ?? []).find((m) => m.id === modelId)?.is_downloaded ?? false;

      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.
        if (!alreadyDownloaded) {
          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-")) {
        if (!alreadyDownloaded) {
          await invoke("download_parakeet_model", { name: "ctc-int8" });
        }
        await invoke("load_parakeet_model", { name: "ctc-int8" });
        settings.engine = "parakeet";
      }

      ready = true;
      // Brief "Ready" beat, then onto the rituals prompt (or straight
      // to dictation if the user has already seen it).
      setTimeout(() => {
        if (settings.ritualsPromptSeen) {
          page.current = "dictation";
        } else {
          ready = false;
          ritualsStep = "morning";
        }
      }, 1500);
    } catch (e) {
      error = `Download failed: ${e}`;
      downloading = false;
    } finally {
      unlisten();
      unlistenParakeet();
    }
  }

  // Auto-detect is the default surface; the system breakdown and the
  // manual model list live behind a "Choose manually" disclosure so the
  // first-run screen is not a wall of jargon for users who just want to
  // hit one button and start dictating.
  let showManual = $state(false);

  // Phase 5: forced-choice rituals + autostart prompts. Research on
  // libertarian-paternalism nudges (Thaler/Sunstein) says defaults
  // drive uptake, but the ADHD target audience is sensitive to
  // parental framing — so we present explicit opt-in with calm copy
  // rather than defaulting anything on.
  type RitualsStep = "idle" | "morning" | "evening" | "autostart" | "done";
  let ritualsStep = $state<RitualsStep>("idle");
  let autostartApplying = $state(false);

  function setupAutomatically() {
    if (!models?.length) return;
    downloadAndGo(models[0].id);
  }

  async function answerMorning(yes: boolean) {
    settings.ritualsMorning = yes;
    saveSettings();
    ritualsStep = "evening";
  }

  async function answerEvening(yes: boolean) {
    settings.ritualsEvening = yes;
    saveSettings();
    ritualsStep = "autostart";
  }

  async function answerAutostart(yes: boolean) {
    autostartApplying = true;
    try {
      const plugin = await import("@tauri-apps/plugin-autostart");
      if (yes) {
        await plugin.enable();
        settings.launchAtLogin = true;
      } else {
        // On a true first run this is already off, but replaying
        // onboarding after previously choosing "Yes" must remove the
        // OS-level login item too.
        if (await plugin.isEnabled()) {
          await plugin.disable();
        }
        settings.launchAtLogin = false;
      }
    } catch (err) {
      toasts.warn("Could not update autostart", String(err));
      try {
        const plugin = await import("@tauri-apps/plugin-autostart");
        settings.launchAtLogin = await plugin.isEnabled();
      } catch {}
    } finally {
      autostartApplying = false;
      settings.ritualsPromptSeen = true;
      saveSettings();
      ritualsStep = "done";
      setTimeout(() => { page.current = "dictation"; }, 900);
    }
  }

  function skipRituals() {
    settings.ritualsPromptSeen = true;
    saveSettings();
    page.current = "dictation";
  }

  function skipSetup() {
    // Skipping model download still marks the rituals prompt as seen —
    // the user chose to bypass the walk-through; they can find rituals
    // in Settings when they're ready.
    settings.ritualsPromptSeen = true;
    saveSettings();
    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">A few quick choices, then you're in.</p>
    </div>

  {:else if ritualsStep === "morning"}
    <div class="w-full max-w-md mx-auto text-center">
      <Sunrise size={32} strokeWidth={1.5} class="text-accent mx-auto mb-3" />
      <h2 class="text-xl font-medium text-text">Morning triage?</h2>
      <p class="text-sm text-text-secondary mt-3 leading-relaxed">
        Each morning, pick three things to focus on. Everything else can wait.
      </p>
      <p class="text-[11px] text-text-tertiary mt-3">Off by default. Change anytime in Settings.</p>
      <div class="flex items-center justify-center gap-3 mt-6">
        <button
          class="px-4 py-2 rounded-lg text-sm border border-border text-text-secondary hover:bg-hover"
          onclick={() => answerMorning(false)}
        >No thanks</button>
        <button
          class="px-4 py-2 rounded-lg text-sm bg-accent text-white hover:bg-accent-hover"
          onclick={() => answerMorning(true)}
        >Turn on</button>
      </div>
      <button
        class="mt-5 text-xs text-text-tertiary hover:text-text-secondary underline"
        onclick={skipRituals}
      >Skip these</button>
    </div>

  {:else if ritualsStep === "evening"}
    <div class="w-full max-w-md mx-auto text-center">
      <Moon size={32} strokeWidth={1.5} class="text-accent mx-auto mb-3" />
      <h2 class="text-xl font-medium text-text">Evening wind-down?</h2>
      <p class="text-sm text-text-secondary mt-3 leading-relaxed">
        A page to reflect on what you finished and what's still open — only when you choose to open it.
      </p>
      <p class="text-[11px] text-text-tertiary mt-3">Off by default. Never scheduled.</p>
      <div class="flex items-center justify-center gap-3 mt-6">
        <button
          class="px-4 py-2 rounded-lg text-sm border border-border text-text-secondary hover:bg-hover"
          onclick={() => answerEvening(false)}
        >No thanks</button>
        <button
          class="px-4 py-2 rounded-lg text-sm bg-accent text-white hover:bg-accent-hover"
          onclick={() => answerEvening(true)}
        >Turn on</button>
      </div>
      <button
        class="mt-5 text-xs text-text-tertiary hover:text-text-secondary underline"
        onclick={skipRituals}
      >Skip these</button>
    </div>

  {:else if ritualsStep === "autostart"}
    <div class="w-full max-w-md mx-auto text-center">
      <Play size={32} strokeWidth={1.5} class="text-accent mx-auto mb-3" />
      <h2 class="text-xl font-medium text-text">Launch Kon at login?</h2>
      <p class="text-sm text-text-secondary mt-3 leading-relaxed">
        Kon will be ready as soon as you sign in. Uses your OS's standard autostart.
      </p>
      <p class="text-[11px] text-text-tertiary mt-3">Change anytime in Settings.</p>
      <div class="flex items-center justify-center gap-3 mt-6">
        <button
          class="px-4 py-2 rounded-lg text-sm border border-border text-text-secondary hover:bg-hover"
          onclick={() => answerAutostart(false)}
          disabled={autostartApplying}
        >No thanks</button>
        <button
          class="px-4 py-2 rounded-lg text-sm bg-accent text-white hover:bg-accent-hover disabled:opacity-60"
          onclick={() => answerAutostart(true)}
          disabled={autostartApplying}
        >{autostartApplying ? 'Saving…' : 'Yes'}</button>
      </div>
    </div>

  {:else if ritualsStep === "done"}
    <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">All set</h2>
      <p class="text-sm text-text-secondary mt-2">Press the button. Start talking.</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 models.length > 0}
        <div class="mt-8 flex flex-col items-center">
          <button
            class="px-6 py-3 rounded-xl text-base font-medium bg-accent text-white hover:bg-accent-hover
                   shadow-[0_4px_16px_rgba(232,168,124,0.3)] active:scale-[0.97] transition-all duration-150"
            onclick={setupAutomatically}
          >
            Set up automatically
          </button>
          <p class="mt-2 text-xs text-text-tertiary">
            Picks the best model for your machine — about {models[0]?.disk_size_mb ?? "?"} MB.
          </p>
        </div>

        <button
          class="mt-6 mx-auto block text-xs text-text-secondary hover:text-text underline"
          onclick={() => (showManual = !showManual)}
        >
          {showManual ? 'Hide manual setup' : 'Choose manually'}
        </button>

        {#if showManual}
          {#if systemInfo}
            <div class="mt-4 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}

          <div class="mt-6">
            <h3 class="text-xs font-medium text-text-tertiary uppercase tracking-wider mb-3">Pick a model</h3>
            <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)}
                >
                  <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}
      {/if}

      <button
        class="mt-6 mx-auto block 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>
