<script>
  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 TaskTimer from "$lib/components/TaskTimer.svelte";
  import { page, settings, saveSettings } from "$lib/stores/page.svelte.js";
  import { getPreferences, updatePreferences } from "$lib/stores/preferences.svelte.js";

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

  let { children } = $props();

  const prefs = getPreferences();

  // Task timer — bound component for cross-page timer control
  let taskTimer = $state(null);

  function handleStartTimer(e) {
    if (taskTimer) {
      const { id, text, duration } = e.detail;
      taskTimer.startTimer(id, text, duration || 120);
    }
  }

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

  // Recording indicator dot (follows mouse)
  let mouseX = $state(0);
  let mouseY = $state(0);

  function handleMouseMove(e) {
    mouseX = e.clientX;
    mouseY = e.clientY;
  }

  // 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
  let registeredHotkey = null;

  async function registerGlobalHotkey(hotkey) {
    try {
      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);
    }
  }

  $effect(() => {
    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();
    }
  }

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

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

  onDestroy(() => {
    window.removeEventListener("resize", handleResize);
    window.removeEventListener("kon:start-timer", handleStartTimer);
    if (registeredHotkey) {
      import("@tauri-apps/plugin-global-shortcut")
        .then((mod) => mod.unregister(registeredHotkey))
        .catch(() => {});
    }
  });
</script>

<svelte:window onmousemove={handleMouseMove} onkeydown={handleKeydown} />

{#if page.recording}
  <div
    class="fixed w-3 h-3 rounded-full bg-danger animate-pulse-soft pointer-events-none"
    style="left: {mouseX + 18}px; top: {mouseY + 18}px; z-index: 100;"
  ></div>
{/if}

{#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">
    <Titlebar />
    <div class="flex flex-1 min-h-0 relative">
      {#if page.current !== "first-run"}
        <Sidebar />
      {/if}
      <div class="flex-1 overflow-hidden bg-bg flex flex-col">
        <!-- Active timer (persists across page navigation) -->
        <TaskTimer bind:this={taskTimer} />
        <div class="flex-1 overflow-hidden">
          {@render children()}
        </div>
      </div>
    </div>
  </div>

  <!-- Task sidebar as overlay — doesn't shrink main content -->
  {#if page.taskSidebarOpen && page.current !== "first-run" && !isSecondaryWindow}
    <!-- svelte-ignore a11y_click_events_have_key_events -->
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <div
      class="fixed inset-0 z-40"
      onclick={(e) => { if (e.target === e.currentTarget) page.taskSidebarOpen = false; }}
    >
      <!-- Backdrop tint (click this area to close) -->
      <!-- svelte-ignore a11y_no_static_element_interactions -->
      <div
        class="absolute inset-0 bg-black/10"
        onclick={() => { page.taskSidebarOpen = false; }}
      ></div>
      <!-- Sidebar panel (clicks here stay in the sidebar) -->
      <div
        class="absolute top-[36px] right-0 bottom-0 w-[280px] z-50 shadow-xl"
        onclick={(e) => e.stopPropagation()}
      >
        <TaskSidebar />
      </div>
    </div>
  {/if}
{/if}
