<script lang="ts">
  import Header from '../../lib/components/layout/Header.svelte';
  import CreateEventForm from '../../lib/components/write/CreateEventForm.svelte';
  import { nostrClient } from '../../lib/services/nostr/nostr-client.js';
  import { sessionManager } from '../../lib/services/auth/session-manager.js';
  import { onMount } from 'svelte';
  import { page } from '$app/stores';

  // Read kind from URL synchronously so it's available on first render
  const kindParam = $derived($page.url.searchParams.get('kind'));
  let initialKind = $state<number | null>(null);
  
  // Set initial kind from URL if available
  $effect(() => {
    if (kindParam) {
      const kind = parseInt(kindParam, 10);
      if (!isNaN(kind)) {
        initialKind = kind;
      }
    }
  });
  let initialContent = $state<string | null>(null);
  let initialTags = $state<string[][] | null>(null);
  
  // Subscribe to session changes to reactively update login status
  let currentSession = $state(sessionManager.session.value);
  const isLoggedIn = $derived(currentSession !== null);
  
  // Subscribe to session changes
  $effect(() => {
    const unsubscribe = sessionManager.session.subscribe((session) => {
      currentSession = session;
    });
    return unsubscribe;
  });

  onMount(async () => {
    await nostrClient.initialize();
    
    // Ensure session is restored (fallback in case layout restoration didn't complete)
    if (!sessionManager.isLoggedIn()) {
      try {
        await sessionManager.restoreSession();
      } catch (error) {
        console.error('Failed to restore session in write page:', error);
      }
    }
    
    // Check for highlight data in sessionStorage
    const highlightDataStr = sessionStorage.getItem('aitherboard_highlightData');
    if (highlightDataStr) {
      try {
        const highlightData = JSON.parse(highlightDataStr);
        initialContent = highlightData.content || null;
        initialTags = highlightData.tags || null;
        // Clear sessionStorage after reading
        sessionStorage.removeItem('aitherboard_highlightData');
      } catch (error) {
        console.error('Error parsing highlight data:', error);
      }
    }
  });
</script>

<Header />

<main class="container mx-auto px-4 py-8">
  <div class="write-page">
    <h1 class="text-2xl font-bold mb-6 text-fog-text dark:text-fog-dark-text font-mono">/Write</h1>
    
    {#if !isLoggedIn}
      <div class="login-prompt">
        <p class="text-fog-text dark:text-fog-dark-text mb-4">You must be logged in to write or edit events.</p>
        <a href="/login" class="text-fog-accent dark:text-fog-dark-accent hover:underline">Login here</a>
      </div>
    {:else}
      <div class="form-container">
        <CreateEventForm 
          initialKind={initialKind} 
          initialContent={initialContent}
          initialTags={initialTags}
        />
      </div>
    {/if}
  </div>
</main>

<style>
  .write-page {
    max-width: var(--content-width);
    margin: 0 auto;
    padding: 0 1rem;
  }

  .form-container {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }
</style>
