import { hooks } from 'peepso';
import data from './data';
import './popover';

/**
 * Emoji button for the new postbox. The button is rendered by PeepSoEmoji::filter_postbox_options(); on
 * click it opens a body-mounted EmojiPopover anchored to the button (it does not cover the composer). On
 * a pick the glyph is inserted at the textarea caret — no submit-time data filters, it is just text.
 */
peepso.class('PostboxEmoji', function (name, peepso, $) {
	return class {
		constructor(postbox) {
			this.postbox = postbox;
			this.$toggle = postbox.$postbox.find('[data-ps=option][data-id=emoji]');

			if (!this.$toggle.length) {
				return;
			}

			// The picker records the favorite itself; the consumer only inserts the glyph.
			this.popover = new (peepso.class('EmojiPopover'))({
				onPick: glyph => {
					// Let an active postbox type claim insertion — e.g. the background type inserts into its
					// contenteditable (the textarea is hidden while it's active). Otherwise the plain textarea.
					if (!hooks.applyFilters('postbox_emoji_insert', false, glyph, this.postbox)) {
						data.insertAtCursor(this.postbox.$textarea, glyph);
					}
				}
			});

			this.$toggle.on('click', e => {
				e.preventDefault();
				e.stopPropagation();
				this.popover.toggle(this.$toggle);
			});

			// The postbox's mouseup-outside handler fires before the click that inserts the emoji,
			// so collapse() sees an empty textarea and collapses on the very first pick. Guard against
			// that by reporting "not empty" while the picker is open for this specific postbox.
			hooks.addFilter('postbox_is_empty', `emoji-postbox-${postbox.id}`, (empty, pb) => {
				if (this.popover.isOpen() && pb === this.postbox) return false;
				return empty;
			});

			// Close the picker whenever this postbox collapses.
			hooks.addAction('postbox_collapse', `emoji-postbox-${postbox.id}`, pb => {
				if (pb === this.postbox) this.popover.close();
			});
		}
	};
});

hooks.addAction('postbox_init', 'emoji', postbox => new (peepso.class('PostboxEmoji'))(postbox));
