<script lang="ts">
  import {nthEq} from "@welshman/lib"
  import type {TrustedEvent} from "@welshman/util"
  import {getListTags, getEventTagValues} from "@welshman/util"
  import {pin, unpin, tagEvent, userPinList, waitForThunkError} from "@welshman/app"
  import {Router} from "@welshman/router"
  import Pin from "@assets/icons/pin.svg?dataurl"
  import TrashBin2 from "@assets/icons/trash-bin-2.svg?dataurl"
  import Icon from "@lib/components/Icon.svelte"
  import Button from "@lib/components/Button.svelte"
  import Confirm from "@lib/components/Confirm.svelte"
  import {publishDelete} from "@app/deletes"
  import {pushModal} from "@app/modal"
  import {pushToast} from "@app/toast"

  type Props = {
    event: TrustedEvent
    onClose: () => void
  }

  const {event, onClose}: Props = $props()

  const relays = Router.get().Event(event).getUrls()
  const pinnedIds = $derived(getEventTagValues(getListTags($userPinList)))
  const isPinned = $derived(pinnedIds.includes(event.id))

  const togglePin = async () => {
    onClose()

    const thunk = isPinned ? await unpin(event.id) : await pin(tagEvent(event).find(nthEq(0, "e"))!)

    const error = await waitForThunkError(thunk)

    if (error) {
      pushToast({theme: "error", message: "Failed to update pinned notes."})
    } else {
      pushToast({message: isPinned ? "Note unpinned." : "Note pinned to your profile."})
    }
  }

  const confirmDelete = () => {
    onClose()

    pushModal(Confirm, {
      title: "Delete Note",
      message: "Are you sure you want to delete this note?",
      confirm: async () => {
        await publishDelete({event, relays, protect: false})

        pushToast({message: "Delete request sent."})
      },
    })
  }
</script>

<ul class="menu whitespace-nowrap rounded-box bg-base-100 p-2 shadow-md">
  <li>
    <Button onclick={togglePin}>
      <Icon size={4} icon={Pin} />
      {isPinned ? "Unpin from profile" : "Pin to profile"}
    </Button>
  </li>
  <li>
    <Button onclick={confirmDelete} class="text-error">
      <Icon size={4} icon={TrashBin2} />
      Delete note
    </Button>
  </li>
</ul>
