import $ from 'jquery';
import data from './data';
import './popover';

/**
 * Emoji trigger for the chat pop-up widget (the floating window). The trigger is rendered into the window
 * input addons by PeepSoEmoji::filter_message_input_addons() (class .ps-js-chat-emoji). A delegated click
 * opens the shared EmojiPopover anchored to the clicked window's trigger and inserts into that window's
 * .ps-chat__window-input. One popover is reused across windows; the active textarea is tracked.
 */
$(function () {
	let popover = null;
	let $target = null;

	function getPopover() {
		if (!popover) {
			popover = new (peepso.class('EmojiPopover'))({
				onPick: glyph => {
					if ($target && $target.length) data.insertAtCursor($target, glyph);
				}
			});
		}
		return popover;
	}

	$(document).on('click', '.ps-js-chat-emoji', function (e) {
		e.preventDefault();
		e.stopPropagation();

		const $trigger = $(this);
		const $win = $trigger.closest('.ps-js-chat-window');
		const $ta = $win.find('.ps-chat__window-input').first();
		if (!$ta.length) return;

		const pop = getPopover();
		const sameAnchor = pop.isOpen() && pop.$anchor && pop.$anchor[0] === $trigger[0];

		if (sameAnchor) {
			pop.close();
		} else {
			$target = $ta;
			pop.open($trigger);
		}
	});
});
