<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();

    // Tauri unlisten handles must be released on every exit path —
    // declared outside the try so the finally can always call them,
    // but assigned inside so a throw on the second listen() doesn't
    // leak the first one. SettingsPage.svelte:864-880 is the
    // long-form reference pattern (onMount + onDestroy).
    let unlisten: (() => void) | undefined;
    let unlistenParakeet: (() => void) | undefined;

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

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

      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;
      // 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 {
      // Guard against listen() throwing before assigning the unlisten
      // handle — without these checks the finally itself would throw
      // and mask the original error.
      if (unlisten) unlisten();
      if (unlistenParakeet) unlistenParakeet();
    }
  }

  // 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);

  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 {
        // Don't call disable() on a fresh install — there's nothing to
        // disable, and some platforms treat "disable when unset" as an
        // error. Just record the choice.
        settings.launchAtLogin = false;
      }
    } catch (err) {
      toasts.warn("Could not update autostart", String(err));
    } 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">
        On the first launch of the day, a gentle modal shows yesterday's open items and asks you to pick up to three for today. The rest can wait.
      </p>
      <p class="text-[12px] text-text-secondary mt-3">Off by default. You can change your mind any time 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)}
        >Yes, turn it on</button>
      </div>
      <button
        class="mt-5 text-xs text-text-tertiary hover:text-text-secondary underline"
        onclick={skipRituals}
      >Skip all these questions</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 reflective page you can open when you want to close the day. Shows what you finished, names the open loops, then gets out of the way. Never scheduled, never nagging.
      </p>
      <p class="text-[12px] text-text-secondary mt-3">Off by default. Always opt-in.</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)}
        >Yes, turn it on</button>
      </div>
      <button
        class="mt-5 text-xs text-text-tertiary hover:text-text-secondary underline"
        onclick={skipRituals}
      >Skip the rest</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 Lumotia at login?</h2>
      <p class="text-sm text-text-secondary mt-3 leading-relaxed">
        So Lumotia is already there when you need it, especially useful if you said yes to morning triage. Uses your OS's standard autostart. No background tricks, no telemetry.
      </p>
      <p class="text-[12px] text-text-secondary mt-3">You can change this any time 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, launch at login'}</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 Lumotia</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-[12px] 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-[12px] 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>
