import { KeyboardEvent, MouseEvent, useCallback } from 'react';
import { Room } from 'matrix-js-sdk';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { resolveClickedEmoji } from './resolveClickedEmoji';
import { sendEmojiConfettiEvent } from './sendEmojiConfetti';
import { useEmojiConfetti } from './useEmojiConfetti';

export function useJumboEmojiConfetti(room: Room) {
  const mx = useMatrixClient();
  const { bursts, removeBurst, triggerLocalBurst, registerOwnEventId } = useEmojiConfetti(room);

  const handleJumboEmojiClick = useCallback(
    (targetEventId: string, body: string, event: MouseEvent<HTMLElement> | KeyboardEvent<HTMLElement>) => {
      const clicked = resolveClickedEmoji(event, body);
      if (!clicked) return;

      const emojis = [clicked.emoji];

      triggerLocalBurst(targetEventId, emojis, clicked.origin);
      sendEmojiConfettiEvent(mx, room.roomId, targetEventId, emojis)
        .then((response) => {
          const eventId = response?.event_id;
          if (eventId) registerOwnEventId(eventId);
        })
        .catch((error) => {
          console.error('[emoji-confetti] Failed to send confetti event:', error);
        });
    },
    [mx, registerOwnEventId, room.roomId, triggerLocalBurst]
  );

  return {
    bursts,
    removeBurst,
    handleJumboEmojiClick,
  };
}
