<script lang="ts">
  import { authenticateWithNIP07 } from '../../lib/services/nostr/auth-handler.js';
  import { isNIP07Available } from '../../lib/services/auth/nip07-signer.js';
  import { goto } from '$app/navigation';
  import { onMount } from 'svelte';
  import { nostrClient } from '../../lib/services/nostr/nostr-client.js';

  onMount(async () => {
    await nostrClient.initialize();
  });

  let error = $state<string | null>(null);
  let loading = $state(false);

  async function loginWithNIP07() {
    if (!isNIP07Available()) {
      error = 'NIP-07 extension not available. Please install a Nostr extension like Alby or nos2x.';
      return;
    }

    loading = true;
    error = null;

    try {
      await authenticateWithNIP07();
      goto('/');
    } catch (err) {
      error = err instanceof Error ? err.message : 'Authentication failed';
    } finally {
      loading = false;
    }
  }
</script>

<main class="container mx-auto px-4 py-8 max-w-md">
  <h1 class="text-2xl font-bold mb-4 text-fog-text dark:text-fog-dark-text">Login</h1>

  {#if error}
    <div class="bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded mb-4">
      {error}
    </div>
  {/if}

  <div class="space-y-4">
    <button
      onclick={loginWithNIP07}
      disabled={loading}
      class="w-full px-4 py-2 bg-fog-accent dark:bg-fog-dark-accent text-white hover:opacity-90 disabled:opacity-50 transition-colors rounded"
    >
      {loading ? 'Connecting...' : 'Login with NIP-07'}
    </button>

    <p class="text-sm text-fog-text-light dark:text-fog-dark-text-light">
      Other authentication methods (nsec, anonymous) coming soon...
    </p>
  </div>
</main>
