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

/**
 * Emoji button for the legacy postbox — the composer used when EDITING a post (activity.option_edit →
 * ps_postbox) and the legacy main composer. The button is rendered by
 * PeepSoEmoji::filter_postbox_interactions() as a toolbar interaction (class .ps-js-postedit-emoji, inside
 * .ps-postbox--edit); a delegated listener opens the shared EmojiPopover anchored to whichever button was
 * clicked and inserts into that edit's active input. One popover instance is reused across all open edit
 * forms; the target is resolved per click.
 *
 * Two input surfaces: a plain <textarea> for regular posts (simple caret path via data.insertAtCursor), and
 * — when editing a "background" post — an in-place contenteditable (PsPostBackground.editPost makes the
 * post's own .ps-js-activity-background-text editable and HIDES the postbox textarea). For the latter we
 * insert through the element's ContentEditable instance so the glyph lands at the caret and syncs back.
 */
$(function () {
	let popover = null;
	let insert = null; // resolved per open: (glyph) => void

	function getPopover() {
		if (!popover) {
			popover = new (peepso.class('EmojiPopover'))({
				onPick: glyph => { if (insert) insert(glyph); }
			});
		}
		return popover;
	}

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

		const $button = $(this);

		// Background post edited in place: the post's background-text element is contenteditable and the
		// postbox textarea is hidden. Prefer it, and route through its ContentEditable (caret-preserving).
		const ce = $button
			.closest('.ps-post, .ps-js-activity')
			.find('.ps-js-activity-background-text[contenteditable=true]')
			.get(0);

		let fn = null;
		if (ce && ce.peepsoContentEditable) {
			fn = glyph => ce.peepsoContentEditable.insertAtCaret(glyph);
		} else {
			const $ta = $button
				.closest('.ps-postbox--edit')
				.find('.ps-postbox__input, .ps-postbox-textarea, textarea')
				.first();
			if ($ta.length) fn = glyph => data.insertAtCursor($ta, glyph);
		}
		if (!fn) 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 {
			insert = fn;
			pop.open($button); // re-anchors to this edit form's button
		}
	});
});
