<script lang="ts">
  import { onMount } from "svelte";
  import { push } from "svelte-spa-router";
  import { loadStoredIdentityMeta, unlockIdentity, deleteStoredIdentity } from "../lib/identity-store.js";
  import { session } from "../lib/store.svelte.js";

  let meta = $state<{ handle: string; server: string; primary: string; created_at: string } | null>(null);
  let passphrase = $state("");
  let error = $state<string | null>(null);
  let working = $state(false);

  onMount(async () => {
    meta = await loadStoredIdentityMeta();
    if (!meta) push("/");
  });

  async function submit() {
    working = true;
    error = null;
    try {
      const id = await unlockIdentity(passphrase);
      session.setUnlocked(id);
      passphrase = "";
      push("/dashboard");
    } catch (e) {
      error = (e as Error).message;
    } finally {
      working = false;
    }
  }

  async function forget() {
    if (!confirm("Delete the local copy of this account? You'll need your seed to restore.")) return;
    await deleteStoredIdentity();
    session.lock();
    push("/");
  }
</script>

<div class="space-y-6 max-w-md">
  <h1 class="text-2xl font-bold text-gray-900">Unlock</h1>

  {#if meta}
    <p class="text-sm text-gray-600">
      Unlocking <span class="font-mono font-semibold">{meta.handle}@{meta.server}</span>
    </p>

    <form
      class="space-y-3"
      onsubmit={(e) => { e.preventDefault(); submit(); }}
    >
      <input
        type="password"
        bind:value={passphrase}
        placeholder="passphrase"
        autocomplete="current-password"
        class="w-full px-3 py-2 border border-gray-300 rounded-md"
      />

      {#if error}
        <p class="text-sm text-red-700 bg-red-50 border border-red-200 rounded p-3">
          {error}
        </p>
      {/if}

      <button
        type="submit"
        class="px-4 py-2 bg-gray-900 text-white rounded-md hover:bg-gray-700 disabled:opacity-50"
        disabled={working || passphrase.length === 0}
      >
        {working ? "Unlocking…" : "Unlock"}
      </button>
    </form>

    <button
      class="text-xs text-gray-500 hover:text-red-700 underline"
      onclick={forget}
    >
      Forget this account on this device
    </button>
  {/if}
</div>
