<script lang="ts">
  import '../app.css';
  import { sessionManager } from '../lib/services/auth/session-manager.js';
  import { onMount } from 'svelte';
  import { browser } from '$app/environment';
  import { page } from '$app/stores';
  import type { Snippet } from 'svelte';
  import { isNewVersionAvailable } from '../lib/services/version-manager.js';
  import UpdateModal from '../lib/components/modals/UpdateModal.svelte';

  interface Props {
    children: Snippet;
  }

  let { children }: Props = $props();
  let showUpdateModal = $state(false);

  // Initialize theme and preferences from localStorage immediately (before any components render)
  if (browser) {
    // Initialize theme
    const storedTheme = localStorage.getItem('theme');
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    const shouldBeDark = storedTheme === 'dark' || (!storedTheme && prefersDark);
    if (shouldBeDark) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }

    // Initialize other preferences
    const textSize = localStorage.getItem('textSize') || 'medium';
    const lineSpacing = localStorage.getItem('lineSpacing') || 'normal';
    const contentWidth = localStorage.getItem('contentWidth') || 'medium';
    
    document.documentElement.setAttribute('data-text-size', textSize);
    document.documentElement.setAttribute('data-line-spacing', lineSpacing);
    document.documentElement.setAttribute('data-content-width', contentWidth);

    // Try to restore session synchronously if possible
    // This ensures session is restored before any components render
    (async () => {
      try {
        if (!sessionManager.isLoggedIn()) {
          await sessionManager.restoreSession();
        }
      } catch (error) {
        console.error('Failed to restore session:', error);
      }
    })();
  }

  // Also restore in onMount as fallback
  onMount(async () => {
    try {
      // Only restore if there's no active session
      // This prevents overwriting sessions that were just created during login
      if (!sessionManager.isLoggedIn()) {
        await sessionManager.restoreSession();
      }
      
      if (browser) {
        // Check for post-update redirect
        const postUpdateRedirect = sessionStorage.getItem('postUpdateRedirect');
        if (postUpdateRedirect) {
          sessionStorage.removeItem('postUpdateRedirect');
          const { goto } = await import('$app/navigation');
          goto(postUpdateRedirect);
          return;
        }

        // Check for new version
        const { isNewVersionAvailable, getStoredVersion, getAppVersion, storeVersion } = await import('../lib/services/version-manager.js');
        const storedVersion = getStoredVersion();
        const currentVersion = await getAppVersion();
        
        // If no stored version, this is a first-time user - route to about page and store version
        if (!storedVersion) {
          const { goto } = await import('$app/navigation');
          const currentPath = window.location.pathname;
          // Only redirect if not already on about page or login page
          if (currentPath !== '/about' && currentPath !== '/login') {
            goto('/about');
          }
          // Store current version for future checks
          await storeVersion(currentVersion);
        } else if (await isNewVersionAvailable()) {
          showUpdateModal = true;
        }
      }
      
      // Start archive scheduler (background compression of old events)
      const { startArchiveScheduler } = await import('../lib/services/cache/archive-scheduler.js');
      startArchiveScheduler();
      
      // Preload GIFs in background for faster picker loading
      const { preloadGifs } = await import('../lib/services/nostr/gif-preloader.js');
      preloadGifs().catch(() => {
        // Non-critical, ignore errors
      });
    } catch (error) {
      console.error('Failed to restore session:', error);
    }
  });

  function handleUpdateComplete() {
    showUpdateModal = false;
  }

  // Track current route when user is logged in (for redirect after logout)
  $effect(() => {
    if (sessionManager.isLoggedIn() && browser) {
      const currentRoute = $page.url.pathname + $page.url.search;
      // Don't store /login as the route to return to
      if (currentRoute !== '/login') {
        sessionManager.storeLoginRedirect(currentRoute);
      }
    }
  });
</script>

{@render children()}

{#if showUpdateModal}
  <UpdateModal onComplete={handleUpdateComplete} />
{/if}
