<script lang="ts">
  import {
    auth,
    closeLogin,
    loginWithExtension,
    loginWithNsec,
  } from "$lib/auth.svelte";
  import { tick } from "svelte";

  let view = $state<"extension" | "nsec">("extension");
  let nsec = $state("");
  let error = $state<string | null>(null);
  let busy = $state(false);
  let nsecInput = $state<HTMLInputElement | null>(null);

  const hasExtension = $derived(
    typeof window !== "undefined" && !!window.nostr,
  );

  function reset() {
    view = "extension";
    nsec = "";
    error = null;
  }

  async function handleExtension() {
    if (busy) return;
    error = null;
    busy = true;
    try {
      await loginWithExtension();
      closeLogin();
      reset();
    } catch (e) {
      error = e instanceof Error ? e.message : "Failed to login";
    } finally {
      busy = false;
    }
  }

  async function handleNsec() {
    if (busy || !nsec.trim()) return;
    error = null;
    busy = true;
    try {
      await loginWithNsec(nsec);
      closeLogin();
      reset();
    } catch (e) {
      error = e instanceof Error ? e.message : "Failed to login";
    } finally {
      busy = false;
    }
  }

  function onClose() {
    if (busy) return;
    closeLogin();
    reset();
  }

  async function showNsecView() {
    view = "nsec";
    error = null;
    await tick();
    nsecInput?.focus();
  }

  function showExtensionView() {
    view = "extension";
    error = null;
  }

  function onKeydown(e: KeyboardEvent) {
    if (!auth.loginModalOpen) return;
    if (e.key === "Escape") onClose();
  }
</script>

<svelte:window onkeydown={onKeydown} />

{#if auth.loginModalOpen}
  <div class="fixed inset-0 z-50 flex items-center justify-center p-4">
    <button
      type="button"
      aria-label="Close login"
      class="absolute inset-0 bg-black/40"
      onclick={onClose}
    ></button>
    <div
      class="relative w-full max-w-sm rounded-lg bg-white dark:bg-neutral-900 p-6 shadow-xl"
      role="dialog"
      aria-modal="true"
      aria-labelledby="login-title"
    >
      <button
        type="button"
        onclick={onClose}
        aria-label="Close"
        class="absolute top-3 right-3 text-2xl leading-none text-neutral-400 dark:text-neutral-500 hover:text-neutral-700 dark:hover:text-neutral-300"
      >
        ×
      </button>

      <h2 id="login-title" class="mb-4 text-lg font-semibold text-neutral-900 dark:text-neutral-100">
        {view === "extension" ? "Log in" : "Log in with nsec"}
      </h2>

      {#if error}
        <div
          class="mb-3 rounded border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700"
          role="alert"
        >
          {error}
        </div>
      {/if}

      {#if view === "extension"}
        <button
          onclick={handleExtension}
          disabled={busy || !hasExtension}
          class="bg-accent hover:bg-accent-hover w-full rounded px-3 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"
        >
          {busy ? "Connecting…" : "Log in with extension"}
        </button>
        {#if !hasExtension}
          <p class="mt-2 text-xs text-neutral-500 dark:text-neutral-400">
            No Nostr extension detected in this browser.
          </p>
        {/if}
        <button
          type="button"
          onclick={showNsecView}
          class="text-accent mt-4 block w-full text-center text-sm hover:underline"
        >
          Or log in using your nsec
        </button>
      {:else}
        <label for="nsec-input" class="sr-only">nsec</label>
        <input
          id="nsec-input"
          bind:this={nsecInput}
          type="password"
          placeholder="nsec1…"
          bind:value={nsec}
          disabled={busy}
          autocomplete="off"
          autocapitalize="off"
          autocorrect="off"
          spellcheck="false"
          onkeydown={(e) => e.key === "Enter" && handleNsec()}
          class="focus:ring-accent w-full rounded border border-neutral-200 dark:border-neutral-700 px-3 py-2 font-mono text-sm focus:ring-1 focus:outline-none disabled:opacity-50"
        />
        <button
          onclick={handleNsec}
          disabled={busy || !nsec.trim()}
          class="bg-accent hover:bg-accent-hover mt-3 w-full rounded px-3 py-2 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"
        >
          {busy ? "Logging in…" : "Log in"}
        </button>
        <p class="mt-2 text-xs text-neutral-500 dark:text-neutral-400">
          Your key is kept in this browser. Use only for testing.
        </p>
        <button
          type="button"
          onclick={showExtensionView}
          class="text-accent mt-4 block w-full text-center text-sm hover:underline"
        >
          Log in with extension
        </button>
      {/if}
    </div>
  </div>
{/if}
