<script lang="ts">
  import {Client} from "@pomade/core"
  import type {SessionPomade} from "@welshman/app"
  import {session} from "@welshman/app"
  import {preventDefault} from "@lib/html"
  import AltArrowLeft from "@assets/icons/alt-arrow-left.svg?dataurl"
  import AltArrowRight from "@assets/icons/alt-arrow-right.svg?dataurl"
  import Icon from "@lib/components2/Icon.svelte"
  import Button from "@lib/components2/Button.svelte"
  import Spinner from "@lib/components2/Spinner.svelte"
  import Modal from "@lib/components2/Modal.svelte"
  import ModalBody from "@lib/components2/ModalBody.svelte"
  import ModalHeader from "@lib/components2/ModalHeader.svelte"
  import ModalTitle from "@lib/components2/ModalTitle.svelte"
  import ModalSubtitle from "@lib/components2/ModalSubtitle.svelte"
  import ModalFooter from "@lib/components2/ModalFooter.svelte"
  import {pushModal} from "@app/modal"
  import KeyRecoveryConfirm from "@app/components/KeyRecoveryConfirm.svelte"

  const {
    email,
    clientOptions: {peers},
  } = $session as SessionPomade

  const requestRecovery = async () => {
    const {peersByPrefix} = await Client.requestChallenge(email, peers)

    pushModal(KeyRecoveryConfirm, {peersByPrefix})
  }

  const submit = async () => {
    loading = true

    try {
      await requestRecovery()
    } finally {
      loading = false
    }
  }

  const back = () => history.back()

  let loading = $state(false)
</script>

<Modal tag="form" onsubmit={preventDefault(submit)}>
  <ModalBody>
    <ModalHeader>
      <ModalTitle>Recover your Key</ModalTitle>
      <ModalSubtitle>Take control over your cryptographic identity</ModalSubtitle>
    </ModalHeader>
    <p>
      When you signed up, your Nostr secret key was split into multiple pieces and stored on
      separate third-party servers to keep it safe.
    </p>
    <p>
      If you're ready to take control of your cryptographic identity, click below. We'll confirm
      your email by sending you some recovery codes.
    </p>
  </ModalBody>
  <ModalFooter>
    <Button variant="ghost" onclick={back}>
      <Icon icon={AltArrowLeft} />
      Go back
    </Button>
    <Button type="submit" variant="primary" disabled={loading}>
      <Spinner {loading}>Request recovery</Spinner>
      <Icon icon={AltArrowRight} />
    </Button>
  </ModalFooter>
</Modal>
