<script lang="ts">
  import { goto } from "$app/navigation";
  import Button from "$lib/components/Button.svelte";
  import {
    createMnemonic,
    encryptMnemonic,
    storeEncryptedMnemonic,
    isValidMnemonic,
    openWallet,
  } from "$lib/wallet.svelte";
  import { start as startNwc } from "$lib/nwc.svelte";

  let stage: "choice" | "mnemonic" | "existing" | "password" | "done" =
    "choice";
  let password: string;
  let confirmPassword: string;
  let passwordError = "";
  let userMnemonic = "";
  let mnemonicError = "";

  function chooseNewSeed() {
    userMnemonic = createMnemonic();
    stage = "mnemonic";
  }

  function chooseExistingSeed() {
    stage = "existing";
  }

  function continueToPassword() {
    stage = "password";
  }

  function validateAndContinue() {
    mnemonicError = "";
    const trimmedMnemonic = userMnemonic.trim();

    if (!trimmedMnemonic) {
      mnemonicError = "Please enter your seed phrase";
      return;
    }

    const cleanedMnemonic = cleanMnemonicInput(trimmedMnemonic);

    if (!isValidMnemonic(cleanedMnemonic)) {
      mnemonicError =
        "Invalid seed phrase. Please check your words and try again.";
      return;
    }

    userMnemonic = cleanedMnemonic;
    stage = "password";
  }

  function cleanMnemonicInput(input: string): string {
    const numberedPattern = /\d+\.\s*([a-zA-Z]+)/g;
    const matches = input.match(numberedPattern);

    if (matches) {
      const words = matches.map((match) =>
        match.replace(/\d+\.\s*/, "").trim()
      );
      return words.join(" ");
    }

    return input.replace(/\s+/g, " ");
  }

  async function finishSetup() {
    passwordError = "";
    if (!password || password.length < 8) {
      passwordError = "Password must be at least 8 characters";
      return;
    }
    if (!confirmPassword || password !== confirmPassword) {
      passwordError = "Passwords do not match";
      return;
    }
    const encrypted = await encryptMnemonic(userMnemonic, password);
    storeEncryptedMnemonic(encrypted);
    await openWallet(userMnemonic);

    startNwc();

    goto("/");
  }
</script>

<div class="container">
  {#if stage === "choice"}
    <h1>Wallet Setup</h1>
    <div class="warning">
      This is a web wallet. Your funds <strong>ARE</strong> at risk. Store only amounts
      you are willing to lose. For larger amounts, use a hardware wallet.
    </div>
    <p>Choose how you want to set up your wallet:</p>
    <div class="choice-buttons">
      <Button variant="primary" onclick={chooseNewSeed}>Create New Seed</Button>
      <Button variant="secondary" onclick={chooseExistingSeed}>
        Enter Existing Seed
      </Button>
    </div>
  {:else if stage === "mnemonic"}
    <h1>Wallet Setup</h1>
    <div class="warning">
      This is a web wallet. Your funds <strong>ARE</strong> at risk. Store only amounts
      you are willing to lose. For larger amounts, use a hardware wallet.
    </div>
    <p>
      Please write down these 12 words in order and keep them safe. They are the
      only way to recover your funds.
    </p>
    <div class="mnemonic">
      {#each userMnemonic.split(" ") as word, i}
        <div>{i + 1}. {word}</div>
      {/each}
    </div>
    <div style="margin-top: 1rem;">
      <Button variant="primary" onclick={continueToPassword}>
        I have saved my seed
      </Button>
    </div>
  {:else if stage === "existing"}
    <h1>Enter Existing Seed</h1>
    <p>Enter your existing 12-word seed phrase to restore your wallet.</p>
    <div>
      <textarea
        class="retro-input seed-input"
        placeholder="Enter your 12-word seed phrase separated by spaces"
        bind:value={userMnemonic}
        oninput={(e) => {
          userMnemonic = cleanMnemonicInput(
            (e.target as HTMLTextAreaElement).value
          );
        }}
        rows="3"
      ></textarea>
    </div>
    {#if mnemonicError}
      <p style="color: red;">{mnemonicError}</p>
    {/if}
    <div style="margin-top: 1rem;">
      <Button variant="primary" onclick={validateAndContinue}>Continue</Button>
    </div>
  {:else if stage === "password"}
    <h1>Set Password</h1>
    <p>
      Choose a password (min 8 characters). It will encrypt your seed locally.
    </p>
    <div>
      <input
        type="password"
        class="retro-input"
        placeholder="Password"
        bind:value={password}
      />
    </div>
    <div>
      <input
        type="password"
        class="retro-input"
        placeholder="Confirm Password"
        bind:value={confirmPassword}
      />
    </div>
    {#if passwordError}
      <p style="color: red;">{passwordError}</p>
    {/if}
    <div style="margin-top: 1rem;">
      <Button variant="primary" onclick={finishSetup}>Finish Setup</Button>
    </div>
  {/if}
</div>

<style>
  .choice-buttons {
    display: flex;
    gap: 1rem;
    margin-top: 1rem;
  }
  .seed-input {
    width: 100%;
    min-height: 80px;
    resize: vertical;
    font-family: monospace;
  }
  .mnemonic {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 0.5rem;
    background: #111;
    padding: 1rem;
    border-radius: 6px;
    font-family: monospace;
  }
  .warning {
    background: #330000;
    padding: 0.75rem;
    border-radius: 4px;
    margin-bottom: 1rem;
    color: #ff5555;
  }
</style>
