<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, Mic } from 'lucide-svelte';
  import LumotiaButton from "$lib/ui/LumotiaButton.svelte";
  import LumotiaNotice from "$lib/ui/LumotiaNotice.svelte";
  import LumotiaProgress from "$lib/ui/LumotiaProgress.svelte";

  // ---------------------------------------------------------------------------
  // Onboarding event helpers (best-effort — failures are logged, never blocking)
  // ---------------------------------------------------------------------------
  async function recordEvent(event: string, skipped = false, notes: string | null = null) {
    try {
      await invoke("record_onboarding_event", {
        event,
        version: "0.1.0",
        skipped,
        notes,
      });
    } catch (err) {
      console.warn("[onboarding] Could not record event:", event, err);
    }
  }

  // ---------------------------------------------------------------------------
  // Core download state
  // ---------------------------------------------------------------------------
  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;
  });

  // ---------------------------------------------------------------------------
  // Test-recording step state
  // ---------------------------------------------------------------------------
  // We use the documented fallback: a button that defers the real test to the
  // main UI rather than re-implementing the full DictationPage recording stack
  // here. The inline recording stack is ~150 lines of DictationPage machinery
  // (audio capture, chunked transcription, LLM cleanup) — too risky to
  // duplicate. Fallback is documented per task spec.
  type TestStep = "idle" | "prompt" | "done_skip";
  let testStep = $state<TestStep>("idle");

  async function deferTestToMainUi() {
    await recordEvent("test_recording", true, "deferred_to_main_ui");
    testStep = "done_skip";
    setTimeout(() => {
      advanceToRituals();
    }, 1000);
  }

  // ---------------------------------------------------------------------------
  // Probe + download
  // ---------------------------------------------------------------------------
  async function probe() {
    probing = true;
    error = "";
    try {
      systemInfo = await invoke("probe_system");
      models = await invoke("rank_models");
      await recordEvent("permissions_granted");
      probing = false;
    } catch (e) {
      error = `Hardware probe failed. This usually means a missing system library or a permission issue.\n\nDetail: ${e}`;
      probing = false;
    }
  }

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

    // 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.
    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";
      }

      await recordEvent("model_ready", false, modelId);

      ready = true;
      // Brief "Ready" beat, then onto the test-recording step.
      setTimeout(() => {
        ready = false;
        testStep = "prompt";
      }, 1500);
    } catch (e) {
      error = `The download did not complete. Check your internet connection and try again.\n\nDetail: ${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();
    }
  }

  // ---------------------------------------------------------------------------
  // After test-recording: advance to rituals or dictation
  // ---------------------------------------------------------------------------
  function advanceToRituals() {
    if (settings.ritualsPromptSeen) {
      page.current = "dictation";
    } else {
      testStep = "idle";
      ritualsStep = "morning";
    }
  }

  // ---------------------------------------------------------------------------
  // Phase 5: forced-choice rituals + autostart prompts.
  // ---------------------------------------------------------------------------
  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";
      await recordEvent("completed", false, settings.modelSize ?? null);
      setTimeout(() => { page.current = "dictation"; }, 900);
    }
  }

  async function skipRituals() {
    settings.ritualsPromptSeen = true;
    saveSettings();
    await recordEvent("completed", false, settings.modelSize ?? null);
    page.current = "dictation";
  }

  async 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();
    await recordEvent("skipped", true, "skipped_from_model_select");
    page.current = "dictation";
  }

  // ---------------------------------------------------------------------------
  // Mount: fire "started" event + kick off hardware probe
  // ---------------------------------------------------------------------------
  $effect(() => {
    recordEvent("started");
    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">Let's make sure everything works.</p>
    </div>

  {:else if testStep === "prompt"}
    <!-- Sub-task 4: pre-supplied test-recording prompt (fallback path) -->
    <div class="w-full max-w-md mx-auto text-center">
      <Mic size={32} strokeWidth={1.5} class="text-accent mx-auto mb-3" />
      <h2 class="text-xl font-medium text-text">Try a test recording</h2>
      <p class="text-sm text-text-secondary mt-3 leading-relaxed">
        Read this sentence aloud so we can confirm your microphone and the transcription are working.
      </p>
      <blockquote class="mt-4 px-4 py-3 rounded-lg bg-bg-input border-l-4 border-accent text-left">
        <p class="text-sm text-text italic leading-relaxed">
          "Today is a good day to test my microphone and see how the transcription looks."
        </p>
      </blockquote>
      <p class="text-xs text-text-tertiary mt-3 leading-relaxed">
        The main dictation screen is just a button press away. Try your first real recording there — it's the same experience you'll use every day.
      </p>
      <div class="flex items-center justify-center gap-3 mt-6">
        <LumotiaButton variant="primary" onclick={deferTestToMainUi}>
          Open the main app and try recording there
        </LumotiaButton>
      </div>
      <button
        class="mt-5 text-xs text-text-tertiary hover:text-text-secondary underline"
        style="transition-duration: var(--duration-ui)"
        onclick={skipRituals}
      >Skip and go straight to the app</button>
    </div>

  {:else if testStep === "done_skip"}
    <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">Almost there</h2>
      <p class="text-sm text-text-secondary mt-2">Taking you to the app now.</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">
        <LumotiaButton variant="secondary" onclick={() => answerMorning(false)}>No thanks</LumotiaButton>
        <LumotiaButton variant="primary" onclick={() => answerMorning(true)}>Yes, turn it on</LumotiaButton>
      </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">
        <LumotiaButton variant="secondary" onclick={() => answerEvening(false)}>No thanks</LumotiaButton>
        <LumotiaButton variant="primary" onclick={() => answerEvening(true)}>Yes, turn it on</LumotiaButton>
      </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">
        <LumotiaButton
          variant="secondary"
          disabled={autostartApplying}
          onclick={() => answerAutostart(false)}
        >No thanks</LumotiaButton>
        <LumotiaButton
          variant="primary"
          loading={autostartApplying}
          disabled={autostartApplying}
          onclick={() => answerAutostart(true)}
        >{autostartApplying ? 'Saving…' : 'Yes, launch at login'}</LumotiaButton>
      </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="mt-6">
        <LumotiaProgress value={downloadProgress} max={100} ariaLabel="Model download progress" />
      </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}
    <!-- Model selection + error recovery -->
    <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}
        <!-- Sub-task 5: failure recovery — plain-English error + Try again / Skip -->
        <div class="mt-4">
          <LumotiaNotice tone="danger" title="Something went wrong">
            <p class="whitespace-pre-line leading-relaxed">{error}</p>
            <div class="flex gap-2 mt-3">
              <LumotiaButton variant="destructive" size="sm" onclick={() => { error = ""; probe(); }}>
                Try again
              </LumotiaButton>
              <LumotiaButton variant="tertiary" size="sm" onclick={skipSetup}>
                Skip this step
              </LumotiaButton>
            </div>
          </LumotiaNotice>
        </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>
