<script lang="ts">
  import {
    decryptMnemonic,
    hasMnemonic,
    MNEMONIC_KEY,
    openWallet,
  } from "$lib/wallet.svelte";
  import { browser } from "$app/environment";
  import { onMount, tick } from "svelte";
  import { fly } from "svelte/transition";

  let { onunlock }: { onunlock: () => void } = $props();

  let dialogEl: HTMLDialogElement | null = $state(null);
  let password = $state("");
  let error = $state("");
  let isValidating = $state(false);
  let show = $state(false);

  onMount(async () => {
    show = true;
    await tick();
    dialogEl?.showModal();
  });

  async function attemptUnlock() {
    if (!password.trim()) return;

    error = "";
    isValidating = true;

    try {
      if (!browser) throw new Error("Not in browser");
      if (!hasMnemonic()) throw new Error("No encrypted seed found");
      const encryptedMnemonic = localStorage.getItem(MNEMONIC_KEY)!;
      const mnemonic = await decryptMnemonic(encryptedMnemonic, password);
      await openWallet(mnemonic);
      onunlock();
      dialogEl?.close();
    } catch (err) {
      error = "Incorrect password";
      console.error("Password validation failed:", err);
      isValidating = false;
    }
  }
</script>

{#if show}
  <dialog
    bind:this={dialogEl}
    transition:fly={{ y: 250, duration: 250, delay: 0.5 }}
  >
    <h2>Unlock Wallet</h2>
    <p>Enter your wallet password to decrypt your seed.</p>
    {#if error}
      <p
        style="color: var(--error-color); font-size: 0.7rem; margin-bottom: 1rem;"
      >
        {error}
      </p>
    {/if}
    <input
      type="password"
      class="retro-input"
      bind:value={password}
      placeholder="Password"
      disabled={isValidating}
      onkeydown={(e) => {
        if (e.key === "Enter" && !isValidating) {
          attemptUnlock();
        }
      }}
    />
    <div style="margin-top:1rem;text-align:center;">
      <button
        class="retro-btn primary"
        disabled={isValidating}
        onclick={() => {
          attemptUnlock();
        }}>{isValidating ? "Validating..." : "Unlock"}</button
      >
    </div>
  </dialog>
{/if}

<style>
  dialog {
    z-index: 2000;
  }
  dialog::backdrop {
    background: transparent;
  }
  h2 {
    margin-top: 0;
    margin-bottom: 1rem;
  }
  p {
    margin-top: 0;
    margin-bottom: 1.25rem;
    font-size: 0.75rem;
  }
  input {
    width: 100%;
  }
</style>
