/** @odoo-module **/

import { registerComposerAction } from "@mail/core/common/composer_actions";
import { _t } from "@web/core/l10n/translation";
import { session } from "@web/session";
import { usePopover } from "@web/core/popover/popover_hook";
import { TemplatePickerPopover } from "@do_mail_quick_templates/components/template_picker/template_picker";

/**
 * Inject a "Templates" button into the chatter composer toolbar.
 *
 * Odoo 19 renders composer toolbar buttons from the `mail.composer/actions`
 * registry (addons/mail/static/src/core/common/composer_actions.js), so we
 * register a declarative action rather than patching the component / template
 * (the approach the SRS described targets the old v16 ChatterComposer that no
 * longer exists). UX is identical: an icon button that opens the picker
 * popover.
 *
 * Visibility (Section 2.3 / 2.9 / EC-04):
 *   - feature enabled for the company AND user in group_template_user are both
 *     resolved server-side and surfaced via session_info as
 *     `session.do_mail_quick_templates_enabled` (synchronous, no flicker);
 *   - only shown inside a chatter (not the Discuss app / channels) and not
 *     while editing an existing message.
 */
registerComposerAction("do_mail_quick_templates.insert_template", {
    condition: ({ composer, owner }) =>
        session.do_mail_quick_templates_enabled &&
        owner.env.inChatter &&
        !composer.message,
    icon: "fa fa-file-text-o",
    name: _t("Insert Template"),
    sequence: 35,
    setup() {
        this.popover = usePopover(TemplatePickerPopover, {
            position: "bottom-end",
            popoverClass: "o_mqt_popover_root",
        });
    },
    onSelected({ composer, owner }, ev) {
        const thread = composer.targetThread;
        this.popover.open(ev.currentTarget, {
            composer,
            owner,
            resModel: thread?.model,
            resId: thread?.id,
            close: () => this.popover.close(),
        });
    },
});
