<script>
  import "../../app.css";
  import { onMount, onDestroy } from "svelte";
  import { listen } from "@tauri-apps/api/event";
  import { getCurrentWindow } from "@tauri-apps/api/window";
  import { settings } from "$lib/stores/page.svelte.js";
  import {
    getPreferences,
    updatePreferences,
    applyExternalPreferences,
    PREFERENCES_CHANGED_EVENT,
  } from "$lib/stores/preferences.svelte.js";
  import Titlebar from "$lib/components/Titlebar.svelte";
  import { loadOsInfo, isLinux } from "$lib/utils/osInfo.js";

  let { children } = $props();
  let glowing = $state(false);
  let unlistenFocus = null;
  let unlistenPrefs = null;
  let useCustomChrome = $state(false);

  const prefs = getPreferences();

  // Theme — sync legacy settings to preferences store (same as main layout)
  $effect(() => {
    const legacyTheme = settings.theme;
    const mapped = legacyTheme === "Light" ? "light" : legacyTheme === "Dark" ? "dark" : "system";
    if (prefs.theme !== mapped) {
      updatePreferences({ theme: mapped });
    }
  });

  // Listen for settings changes from main window
  if (typeof window !== "undefined") {
    window.addEventListener("storage", (e) => {
      if (e.key === "kon_settings" && e.newValue) {
        try {
          Object.assign(settings, JSON.parse(e.newValue));
        } catch {}
      }
    });
  }

  onMount(async () => {
    loadOsInfo()
      .then(() => { useCustomChrome = !isLinux(); })
      .catch(() => {});
    try {
      unlistenFocus = await listen("task-window-focus", () => {
        glowing = true;
        setTimeout(() => { glowing = false; }, 700);
        // Auto-focus quick-add input
        const input = document.querySelector("[data-quick-add]");
        if (input) input.focus();
      });
    } catch {}

    try {
      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);
      });
    } catch {}
  });

  onDestroy(() => {
    if (unlistenFocus) unlistenFocus();
    if (unlistenPrefs) unlistenPrefs();
  });

  // Escape to close
  function handleKeydown(e) {
    if (e.key === "Escape") {
      getCurrentWindow().close();
    }
  }
</script>

<svelte:window onkeydown={handleKeydown} />

<div class="h-screen w-screen overflow-hidden grain border border-border shadow-xl animate-float-enter flex flex-col {glowing ? 'animate-glow-pulse' : ''}">
  {#if useCustomChrome}
    <Titlebar compact />
  {/if}
  <div class="flex-1 min-h-0 overflow-hidden">
    {@render children()}
  </div>
</div>
