<script lang="ts">
  import {type Instance} from "tippy.js"
  import {hash, formatTimestampAsTime} from "@welshman/lib"
  import type {TrustedEvent, EventContent} from "@welshman/util"
  import {thunks, mergeThunks, pubkey, deriveProfileDisplay, sendWrapped} from "@welshman/app"
  import {isMobile} from "@lib/html"
  import MenuDots from "@assets/icons/menu-dots.svg?dataurl"
  import Icon from "@lib/components2/Icon.svelte"
  import Button from "@lib/components2/Button.svelte"
  import Tippy from "@lib/components2/Tippy.svelte"
  import TapTarget from "@lib/components2/TapTarget.svelte"
  import ProfileCircle from "@app/components/ProfileCircle.svelte"
  import Content from "@app/components/Content.svelte"
  import ReactionSummary from "@app/components/ReactionSummary.svelte"
  import ThunkFailure from "@app/components/ThunkFailure.svelte"
  import ProfileDetail from "@app/components/ProfileDetail.svelte"
  import ChatMessageMenu from "@app/components/ChatMessageMenu.svelte"
  import ChatMessageMenuMobile from "@app/components/ChatMessageMenuMobile.svelte"
  import {colors} from "@app/theme"
  import {makeDelete} from "@app/deletes"
  import {makeReaction} from "@app/reactions"
  import {pushModal} from "@app/modal"

  interface Props {
    event: TrustedEvent
    replyTo: (event: TrustedEvent) => void
    canEdit?: (event: TrustedEvent) => boolean
    onEdit?: (event: TrustedEvent) => void
    pubkeys: string[]
    showPubkey?: boolean
  }

  const {event, replyTo, canEdit, onEdit, pubkeys, showPubkey = false}: Props = $props()

  const isOwn = event.pubkey === $pubkey
  const profileDisplay = deriveProfileDisplay(event.pubkey)
  const thunk = mergeThunks($thunks.filter(t => t.event.id === event.id))
  const [_, colorValue] = colors[hash(event.pubkey) % colors.length]

  const reply = () => replyTo(event)
  const edit = canEdit?.(event) ? () => onEdit?.(event) : undefined

  const deleteReaction = (event: TrustedEvent) =>
    sendWrapped({event: makeDelete({event, protect: false}), recipients: pubkeys, pow: 16})

  const createReaction = (template: EventContent) =>
    sendWrapped({
      event: makeReaction({event, protect: false, ...template}),
      recipients: pubkeys,
      pow: 16,
    })

  const openProfile = () => pushModal(ProfileDetail, {pubkey: event.pubkey})

  const showMobileMenu = () => pushModal(ChatMessageMenuMobile, {event, pubkeys, reply, edit})

  const togglePopover = () => {
    if (popoverIsVisible) {
      popover?.hide()
    } else {
      popover?.show()
    }
  }

  let popover: Instance | undefined = $state()
  let popoverIsVisible = $state(false)
</script>

{#if thunk}
  <ThunkFailure showToastOnRetry {thunk} class="mt-1" />
{/if}
<div
  data-event={event.id}
  class="group flex items-center justify-end gap-1 px-2"
  class:flex-row-reverse={!isOwn}>
  {#if !isMobile}
    <Tippy
      bind:popover
      component={ChatMessageMenu}
      props={{event, pubkeys, popover, replyTo, edit}}
      params={{
        interactive: true,
        trigger: "manual",
        onShow() {
          popoverIsVisible = true
        },
        onHidden() {
          popoverIsVisible = false
        },
      }}>
      <button
        type="button"
        class="opacity-0 transition-all"
        class:group-hover:opacity-100={!isMobile}
        onclick={togglePopover}>
        <Icon icon={MenuDots} size={4} />
      </button>
    </Tippy>
  {/if}
  <div class="flex min-w-0 flex-col" class:items-end={isOwn}>
    <TapTarget
      class="cl-surface-alt mx-1 mb-2 flex min-w-[100px] cursor-auto flex-col gap-1 rounded-2xl px-4 py-3 text-left lg:max-w-2xl"
      onTap={showMobileMenu}>
      {#if showPubkey}
        <div class="flex items-center gap-2">
          {#if !isOwn}
            <Button onclick={openProfile} class="flex items-center gap-1">
              <ProfileCircle pubkey={event.pubkey} class="cl-border" size={4} />
              <div class="flex items-center gap-2">
                <Button onclick={openProfile} class="text-sm font-bold" style="color: {colorValue}">
                  {$profileDisplay}
                </Button>
              </div>
            </Button>
          {/if}
          <span class="cl-text-subtle whitespace-nowrap text-xs"
            >{formatTimestampAsTime(event.created_at)}</span>
        </div>
      {/if}
      <div class="text-sm">
        <Content showEntire {event} />
      </div>
    </TapTarget>
    <div class="z-feature -mt-4 ml-4 flex items-center gap-2">
      <ReactionSummary {event} {deleteReaction} {createReaction} noTooltip />
    </div>
  </div>
</div>
