<script lang="ts">
  import { decryptMnemonic } from "$lib/wallet.svelte";
  import { browser } from "$app/environment";

  let {
    open = $bindable(),
    unlock,
  }: { open: boolean; unlock: (pw: string) => void } = $props();

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

  $effect(() => {
    if (open) dialogEl?.showModal();
    else dialogEl?.close();
  });

  function closeDialog() {
    open = false;
  }

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

    error = "";
    isValidating = true;

    try {
      if (!browser) throw new Error("Not in browser");
      const encryptedSeed = localStorage.getItem("seed");
      if (!encryptedSeed) throw new Error("No encrypted seed found");
      await decryptMnemonic(encryptedSeed, password);
      unlock(password);
      password = "";
      error = "";
    } catch (err) {
      error = "Incorrect password";
      console.error("Password validation failed:", err);
    } finally {
      isValidating = false;
    }
  }
</script>

{#if open}
  <dialog bind:this={dialogEl} onclose={closeDialog}>
    <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: rgba(0, 0, 0, 1);
  }
  h2 {
    margin-top: 0;
    margin-bottom: 1rem;
  }
  p {
    margin-top: 0;
    margin-bottom: 1.25rem;
    font-size: 0.75rem;
  }
  input {
    width: 100%;
  }
</style>
