<script lang="ts">
  // @ts-nocheck
  import "../app.css";
  import { onMount, onDestroy } from "svelte";
  import { invoke } from "@tauri-apps/api/core";
  import Sidebar from "$lib/Sidebar.svelte";
  import TaskSidebar from "$lib/components/TaskSidebar.svelte";
  import Titlebar from "$lib/components/Titlebar.svelte";
  import ToastViewport from "$lib/components/ToastViewport.svelte";
  import ResizeHandles from "$lib/components/ResizeHandles.svelte";
  import { hasTauriRuntime } from "$lib/utils/runtime.js";
  import { loadOsInfo, isLinux } from "$lib/utils/osInfo.js";
  import { page, settings, saveSettings } from "$lib/stores/page.svelte.js";
  import {
    getPreferences,
    updatePreferences,
    applyExternalPreferences,
    PREFERENCES_CHANGED_EVENT,
  } from "$lib/stores/preferences.svelte.js";
  import { profilesStore } from "$lib/stores/profiles.svelte.ts";
  import { getCurrentWindow } from "@tauri-apps/api/window";
  import { listen } from "@tauri-apps/api/event";
  import { toasts } from "$lib/stores/toasts.svelte.js";
  import { initI18n } from "$lib/i18n";

  import { page as sveltePage } from "$app/stores";

  // Set up svelte-i18n once per app instance. Safe to call from every
  // window — initI18n guards itself against re-init.
  initI18n();

  let { children } = $props();

  const prefs = getPreferences();
  const tauriRuntimeAvailable = hasTauriRuntime();

  // On Linux Kon uses native KWin/Mutter decorations (see
  // src-tauri/tauri.linux.conf.json and windows.rs). Frameless custom
  // chrome stays for macOS and Windows. Default to false so Linux users
  // don't see a flash of custom titlebar before loadOsInfo resolves.
  let useCustomChrome = $state(false);


  // Detect secondary windows (float, viewer) — they use +layout@.svelte
  // but as a fallback, hide chrome if the URL matches
  let isSecondaryWindow = $derived(
    $sveltePage.url.pathname.startsWith("/float") ||
    $sveltePage.url.pathname.startsWith("/viewer")
  );

  // Theme — migrate from old class-based to new data-attribute system
  // The preferences store handles DOM application via data-theme attribute
  $effect(() => {
    // Sync legacy settings.theme → preferences store
    const legacyTheme = settings.theme;
    const mapped = legacyTheme === "Light" ? "light" : legacyTheme === "Dark" ? "dark" : "system";
    if (prefs.theme !== mapped) {
      updatePreferences({ theme: mapped });
    }
  });

  // Global hotkey registration — dual backend
  // Wayland: evdev via kon-hotkey crate (works without display server)
  // X11/macOS/Windows: tauri-plugin-global-shortcut (native)
  let registeredHotkey = null;
  let hotkeyBackend = $state("unknown"); // "evdev" | "tauri" | "unavailable"

  async function initHotkeyBackend() {
    if (!tauriRuntimeAvailable) {
      hotkeyBackend = "unavailable";
      return;
    }
    try {
      const isWayland = await invoke("is_wayland_session");
      if (isWayland) {
        // Try evdev backend first (Wayland-compatible)
        try {
          await invoke("check_hotkey_access");
          hotkeyBackend = "evdev";
          console.log("Hotkey backend: evdev (Wayland)");
        } catch (err) {
          console.warn("evdev hotkey access denied:", err);
          console.warn("Add your user to the 'input' group for global hotkeys on Wayland");
          hotkeyBackend = "unavailable";
        }
      } else {
        hotkeyBackend = "tauri";
        console.log("Hotkey backend: tauri-plugin-global-shortcut (X11)");
      }
    } catch {
      // Fallback to tauri plugin if detection fails
      hotkeyBackend = "tauri";
    }
  }

  async function registerGlobalHotkey(hotkey) {
    if (!tauriRuntimeAvailable) return;
    if (hotkeyBackend === "unknown") return; // not yet initialised

    try {
      if (hotkeyBackend === "evdev") {
        // evdev backend: start or update the Rust-side listener
        if (registeredHotkey) {
          await invoke("update_evdev_hotkey", { hotkey });
        } else {
          await invoke("start_evdev_hotkey", { hotkey });
        }
        registeredHotkey = hotkey;
      } else if (hotkeyBackend === "tauri") {
        // Tauri plugin backend (X11/macOS/Windows)
        const mod = await import("@tauri-apps/plugin-global-shortcut");
        if (registeredHotkey) {
          await mod.unregister(registeredHotkey).catch(() => {});
        }
        await mod.register(hotkey, () => {
          if (page.current !== "dictation") page.current = "dictation";
          requestAnimationFrame(() => {
            window.dispatchEvent(new CustomEvent("kon:toggle-recording"));
          });
        });
        registeredHotkey = hotkey;
      }
    } catch (err) {
      console.error("Hotkey registration failed:", err);
      const msg = err instanceof Error ? err.message : String(err);
      toasts.error(
        "Hotkey not registered",
        `${hotkey} — ${msg}. Reverted to ${registeredHotkey ?? "previous value"}.`,
      );
      // Revert the in-memory setting to the last successfully-registered hotkey
      // so the UI does not lie about what is actually bound.
      if (registeredHotkey && registeredHotkey !== hotkey) {
        settings.globalHotkey = registeredHotkey;
        saveSettings();
      }
    }
  }

  // Listen for evdev hotkey events from the Rust backend.
  //
  // Debounce window: evdev autorepeat, a sticky-key compositor quirk,
  // or a user's nervous double-tap can all deliver the same press
  // twice within ~100 ms — which, without debouncing, toggles the
  // recording into and out of the same frame and loses the capture.
  // Matches Handy #1143 ('first press records nothing, second works').
  // This is the UX side of brief item #4; the audio-stream warm-up
  // side is owned by Workstream A.
  const HOTKEY_DEBOUNCE_MS = 120;
  let lastHotkeyAtMs = 0;
  let unlistenEvdev = null;
  async function setupEvdevListener() {
    if (!tauriRuntimeAvailable) return;
    const { listen } = await import("@tauri-apps/api/event");
    unlistenEvdev = await listen("kon:hotkey-pressed", () => {
      const now = Date.now();
      if (now - lastHotkeyAtMs < HOTKEY_DEBOUNCE_MS) return;
      lastHotkeyAtMs = now;
      if (page.current !== "dictation") page.current = "dictation";
      requestAnimationFrame(() => {
        window.dispatchEvent(new CustomEvent("kon:toggle-recording"));
      });
    });
  }

  $effect(() => {
    if (hotkeyBackend === "evdev" && !unlistenEvdev) {
      setupEvdevListener();
    }
  });

  $effect(() => {
    if (hotkeyBackend !== "unknown") {
      registerGlobalHotkey(settings.globalHotkey);
    }
  });

  // Apply font size setting as CSS variable (legacy — kept for backwards compat)
  $effect(() => {
    document.documentElement.style.setProperty("--font-size-transcript", `${settings.fontSize}px`);
  });

  // Check whether the keydown originates from a text input (avoid triggering while typing)
  function isInputFocused(e) {
    const tag = e.target?.tagName;
    return tag === "INPUT" || tag === "TEXTAREA" || e.target?.isContentEditable;
  }

  function handleKeydown(e) {
    if (e.key === "Escape" && page.taskSidebarOpen) {
      page.taskSidebarOpen = false;
      return;
    }
    if (e.key === "[" && !isInputFocused(e)) {
      settings.sidebarCollapsed = !settings.sidebarCollapsed;
      saveSettings();
    }
  }

  function handleResize() {
    if (window.innerWidth < 900 && !settings.sidebarCollapsed) {
      settings.sidebarCollapsed = true;
      saveSettings();
    }
  }

  // Cross-window preference sync: apply updates broadcast by any other
  // window (float, viewer) while skipping our own echoes.
  let unlistenPrefs = null;
  async function setupPreferencesSync() {
    if (!tauriRuntimeAvailable) return;
    let ownLabel = null;
    try { ownLabel = getCurrentWindow().label; } catch {}
    unlistenPrefs = await listen(PREFERENCES_CHANGED_EVENT, (event) => {
      const payload = event?.payload;
      if (!payload || payload.source === ownLabel) return;
      applyExternalPreferences(payload.prefs);
    });
  }

  // Capture global frontend errors and forward to the Rust error_log via
  // log_frontend_error. Best-effort: never let the error handler itself
  // throw, never crash the app over a logging failure.
  // (Diagnostics layer 1 — local only, never transmitted)
  let onWindowError = null;
  let onUnhandledRejection = null;

  function installGlobalErrorCapture() {
    if (!hasTauriRuntime()) return;

    const safeLog = (context, message, stack) => {
      try {
        invoke("log_frontend_error", { context, message: String(message ?? ""), stack: stack ?? null })
          .catch(() => { /* swallow — diagnostic logging must never throw */ });
      } catch { /* same */ }
    };

    onWindowError = (ev) => {
      safeLog(
        "window.onerror",
        ev?.message || ev?.error?.message || "Unknown error",
        ev?.error?.stack || null,
      );
    };

    onUnhandledRejection = (ev) => {
      const reason = ev?.reason;
      const msg = (reason && (reason.message || String(reason))) || "Unhandled rejection";
      safeLog("unhandledrejection", msg, reason?.stack || null);
    };

    window.addEventListener("error", onWindowError);
    window.addEventListener("unhandledrejection", onUnhandledRejection);
  }

  onMount(async () => {
    // Auto-collapse if window is already narrow on first load
    handleResize();
    window.addEventListener("resize", handleResize);

    // Cross-window preference sync (no-op outside Tauri).
    setupPreferencesSync();

    // Diagnostics: capture every uncaught frontend error to error_log.
    installGlobalErrorCapture();

    // OS detection: warm the cache so components can use modKeyLabel() /
    // isMac() / isWayland() synchronously after first render. We also
    // use the result to decide whether to render the custom Titlebar +
    // ResizeHandles (non-Linux) or rely on native decorations (Linux).
    loadOsInfo()
      .then(() => { useCustomChrome = !isLinux(); })
      .catch(() => { /* fallback already populated */ });

    if (!tauriRuntimeAvailable) {
      hotkeyBackend = "unavailable";
      return;
    }

    // Detect and initialise the correct hotkey backend
    await initHotkeyBackend();

    // Load profiles (per-profile vocabulary + initial prompt). Task 15.
    await profilesStore.load();

    try {
      const whisper = await invoke("list_models");
      const parakeet = await invoke("list_parakeet_models");
      if (whisper.length === 0 && parakeet.length === 0) {
        page.current = "first-run";
      }
    } catch {
      // If commands fail, skip first-run check
    }

    // Background update check — non-blocking, silent on failure
    invoke("check_for_update")
      .then((version) => {
        if (version) {
          toasts.info(`Kon ${version} is available. Download and restart to update.`);
        }
      })
      .catch(() => { /* update check failure must not affect the app */ });

    // Meeting auto-capture: poll the process list and toast when a match
    // appears (edge-triggered — no repeat toasts until the app goes away
    // and comes back). We never start recording from this signal; the
    // user decides whether to hit the hotkey.
    if (tauriRuntimeAvailable) {
      let previous: Set<string> = new Set();
      meetingCapturePoller = window.setInterval(async () => {
        if (!settings.meetingAutoCapture) { previous = new Set(); return; }
        const patterns = settings.meetingAutoCaptureApps;
        if (!Array.isArray(patterns) || patterns.length === 0) return;
        try {
          const matches: string[] = await invoke("detect_meeting_processes", { patterns });
          const current = new Set(matches);
          for (const match of matches) {
            if (!previous.has(match)) {
              toasts.info(
                `${match[0].toUpperCase()}${match.slice(1)} detected`,
                `Press ${settings.globalHotkey} to start recording.`,
              );
            }
          }
          previous = current;
        } catch { /* ignore — backend may be mid-restart */ }
      }, 15000);
    }
  });

  let meetingCapturePoller: number | null = null;

  onDestroy(() => {
    window.removeEventListener("resize", handleResize);
    if (onWindowError) window.removeEventListener("error", onWindowError);
    if (onUnhandledRejection) window.removeEventListener("unhandledrejection", onUnhandledRejection);
    if (meetingCapturePoller !== null) {
      window.clearInterval(meetingCapturePoller);
      meetingCapturePoller = null;
    }
    if (!tauriRuntimeAvailable) {
      return;
    }
    if (hotkeyBackend === "evdev") {
      invoke("stop_evdev_hotkey").catch(() => {});
    } else if (hotkeyBackend === "tauri" && registeredHotkey) {
      import("@tauri-apps/plugin-global-shortcut")
        .then((mod) => mod.unregister(registeredHotkey))
        .catch(() => {});
    }
    if (unlistenEvdev) {
      unlistenEvdev();
    }
    if (unlistenPrefs) {
      unlistenPrefs();
    }
  });
</script>

<svelte:window onkeydown={handleKeydown} />


{#if isSecondaryWindow}
  <!-- Secondary windows (float, viewer) render children only — no shell chrome -->
  {@render children()}
{:else}
  <div class="flex flex-col h-screen w-screen overflow-hidden grain">
    {#if useCustomChrome}
      <Titlebar />
    {/if}
    <div class="flex flex-1 min-h-0 relative">
      {#if page.current !== "first-run"}
        <Sidebar />
      {/if}
      <div class="flex-1 overflow-hidden bg-bg">
        {@render children()}
      </div>
      {#if page.taskSidebarOpen && page.current !== "first-run"}
        <div class="w-[280px] min-w-[280px] shadow-xl">
          <TaskSidebar />
        </div>
      {/if}
    </div>
  </div>
{/if}

<!-- Global toast viewport. Mounted once at the app root so any component
     can call toasts.error(...), toasts.success(...) etc and have it render
     in the bottom-right of the viewport. (Day 3 of the upgrade plan) -->
<ToastViewport />

<!-- Invisible resize margins for frameless (macOS/Windows). On Linux we
     use native decorations, so ResizeHandles would compete with the
     compositor's own resize and is suppressed. -->
{#if useCustomChrome}
  <ResizeHandles />
{/if}
