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

/**
 * Emoji button for the comment/reply composer. The button is rendered by
 * PeepSoEmoji::filter_commentsbox_interactions() (class .ps-js-comment-emoji); a delegated listener opens
 * the shared EmojiPopover anchored to whichever button was clicked and inserts into that comment's
 * textarea. One popover instance is reused across all comment boxes; the active textarea is tracked so the
 * pick lands in the right field.
 */
$(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-comment-emoji', function (e) {
		e.preventDefault();
		e.stopPropagation();

		const $button = $(this);
		const $box = $button.closest('.ps-js-comment-new, .ps-js-comment-edit');
		const $ta = $box.find('.ps-comments__input, .cstream-form-text, textarea').first();
		if (!$ta.length) return;

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

		if (sameAnchor) {
			pop.close(); // clicking the same button again closes it
		} else {
			$target = $ta;
			pop.open($button); // re-anchors to this comment's button
		}
	});
});
