<script lang="ts">
  import Bell from "@assets/icons/bell.svg?dataurl"
  import Icon from "@lib/components/Icon.svelte"
  import Button from "@lib/components/Button.svelte"
  import Modal from "@lib/components/Modal.svelte"
  import ModalBody from "@lib/components/ModalBody.svelte"
  import ModalHeader from "@lib/components/ModalHeader.svelte"
  import ModalTitle from "@lib/components/ModalTitle.svelte"
  import ModalSubtitle from "@lib/components/ModalSubtitle.svelte"
  import ModalFooter from "@lib/components/ModalFooter.svelte"
  import Spinner from "@lib/components/Spinner.svelte"
  import {enableNotifications} from "@app/util/notifications"
  import {pushToast} from "@app/util/toast"

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

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

    try {
      if (await enableNotifications()) {
        pushToast({message: "Notifications enabled!"})
        dismiss()
      } else {
        pushToast({
          theme: "error",
          message: "Failed to request notification permissions.",
        })
      }
    } finally {
      loading = false
    }
  }

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

<Modal>
  <ModalBody>
    <ModalHeader>
      <ModalTitle>
        <span class="flex items-center gap-2">
          <Icon icon={Bell} />
          Enable notifications
        </span>
      </ModalTitle>
      <ModalSubtitle>
        Get notified when you receive new direct messages, even when Flotilla is in the background.
      </ModalSubtitle>
    </ModalHeader>
  </ModalBody>
  <ModalFooter>
    <Button class="btn btn-link" onclick={dismiss} disabled={loading}>Not now</Button>
    <Button class="btn btn-primary" onclick={enable} disabled={loading}>
      <Spinner {loading}>Enable</Spinner>
    </Button>
  </ModalFooter>
</Modal>
