Vue.component('addPatientNote', {
    props: ['routes', 'addNote', 'params'],

    data() {
        return {
            form: { id: null, content: '' },
            loading: false,
            errors: {},
            _tinymce: null,
            _tinymceBound: false,
            _attachTimer: null
        };
    },

    mounted() {
        if (this.addNote) this.applyParams(this.params);
        this.bindWysiwyg();
    },

    beforeDestroy() {
        if (this._attachTimer) clearTimeout(this._attachTimer);
        if (this._tinymce && this._tinymceBound) {
            this._tinymce.off('keyup change input');
            this._tinymceBound = false;
        }
    },

    watch: {
        addNote(val) {
            if (val) {
                this.applyParams(this.params);
                this.$nextTick(() => {
                    this.bindWysiwyg();
                    this.seedEditorFromForm();
                });
            } else {
                this.resetForm();
                this.clearEditor();
            }
        },
        params: {
            deep: true,
            immediate: true,
            handler(p) {
                this.form.id = null;
                this.form.content = '';
                this._orderId = p && p.orderID ? String(p.orderID) : '';
                if (this.addNote) {
                    this.applyParams(p);
                    this.$nextTick(() => this.seedEditorFromForm());
                }
            }
        },
        'form.content'(val) {
            if ((val || '').trim().length && this.errors.general) {
                this.$delete(this.errors, 'general');
            }
        }
    },

    methods: {
        bindWysiwyg() {
            const tryAttach = () => {
                if (window.tinymce) {
                    const ed = tinymce.get('patientNotesInput');
                    if (ed) {
                        this._tinymce = ed;

                        if (!this._tinymceBound) {
                            const syncFromEditor = () => {
                                this.form.content = this._tinymce.getContent({ format: 'html' }) || '';
                                const text = (this._tinymce.getContent({ format: 'text' }) || '').trim();
                                if (text && this.errors.general) this.$delete(this.errors, 'general');
                            };
                            this._tinymce.on('keyup change input', syncFromEditor);
                            this._tinymceBound = true;
                        }

                        if (typeof ed.getDoc === 'function' && ed.getDoc()) {
                            this.seedEditorFromForm();
                        } else {
                            ed.once('init', () => this.seedEditorFromForm());
                        }
                        return;
                    }
                }
                this._attachTimer = setTimeout(tryAttach, 150);
            };
            tryAttach();
        },

        seedEditorFromForm() {
            if (!this._tinymce) return;
            const setNow = () => {
                if (typeof this._tinymce.getDoc === 'function' && this._tinymce.getDoc()) {
                    this._tinymce.setContent(this.form.content || '');
                    if (this._tinymce.undoManager) this._tinymce.undoManager.clear();
                } else {
                    this._tinymce.once('init', setNow);
                }
            };
            setNow();
        },

        clearEditor() {
            if (!this._tinymce) return;
            const clearNow = () => {
                if (typeof this._tinymce.getDoc === 'function' && this._tinymce.getDoc()) {
                    this._tinymce.setContent('');
                    if (this._tinymce.undoManager) this._tinymce.undoManager.clear();
                } else {
                    this._tinymce.once('init', clearNow);
                }
            };
            clearNow();
        },

        applyParams(p) {
            this.resetForm();
            if (p && p.id) {
                this.form.id = p.id;
                // accept either p.content (HTML) or p.note (plain text)
                this.form.content = p.content || p.note || '';
            }
        },

        resetForm() {
            this.errors = {};
            this.form = { id: null, content: '' };
        },

        close() {
            this.$parent.emitEvent('hideAddNote');
            $('.overlayCloseButton').trigger('click');
        },

        cancel() { this.close(); },

        store() {
            if (this.loading) return;
            this.errors = {};

            // Get HTML & TEXT from TinyMCE or fallback textarea
            const ed = (window.tinymce && tinymce.get('patientNotesInput')) || this._tinymce || null;
            let html = (this.form.content || '').trim();
            let text = '';

            if (ed) {
                html = (ed.getContent({ format: 'html' }) || '').trim();
                text = (ed.getContent({ format: 'text' }) || '').replace(/\u00A0/g, ' ').trim();
            } else {
                const raw = (this.$el.querySelector('#patientNotesInput')?.value || '').trim();
                text = raw || html.replace(/<[^>]*>/g, ' ').replace(/&nbsp;/gi, ' ').trim();
            }

            if (!text.length) {
                this.$set(this.errors, 'general', 'Please enter a note.');
                return;
            }

            // Optional order id (associate with an order if present)
            const orderId =
                (this.params && this.params.orderID) ||
                this.$el.querySelector('input[name="order_id"]')?.value || '';

            this.loading = true;

            // Build payload; include order_id only if we have a value
            const payload = {
                // force create unless you *intentionally* support editing
                id: null,
                note: text,    // plain text
                content: html  // HTML
            };
            if (orderId) {
                payload.order_id = orderId;     // preferred key
                payload.orderID  = orderId;     // belt & braces if backend uses camelCase
            }

            this.$http.post(this.routes['admin-member-notes-store'], payload)
                .then(({ data }) => {
                    this.loading = false;

                    if (data && data.errors) {
                        this.errors = data.errors || {};
                        return;
                    }

                    // clear editor
                    if (ed) ed.setContent('');
                    this.form.content = '';


                    // Then notify lists to reload after a tiny delay
                    setTimeout(() => {
                        this.$parent.emitEvent('newNoteAdded', { order_id: orderId || null });
                    }, 50);
                    // close overlay
                    this._closeAddNoteOverlay();
                })
                .catch(() => {
                    this.loading = false;
                    this.$set(this.errors, 'general', 'Unable to save note. Please try again.');
                });
        },
        _closeAddNoteOverlay() {
            const sel = '#addPatientNote';

            // 1) Try any visible overlay container and click its close button
            const $visibleContainers = $('.mtcOverlayContainer:visible, .overlayContainer:visible, .overlayContentInner:visible, .overlayBox:visible');
            if ($visibleContainers.length) {
                const $c = $visibleContainers.first();
                // common close buttons used by our overlay variants
                const $btn = $c.find('.mtcOverlayClose, .overlayCloseButton, .overlayClose').first();
                if ($btn.length) {
                    $btn.trigger('click');
                    return;
                }
                // some builds expose a method
                if (typeof $c.mtcOverlay === 'function') {
                    try { $c.mtcOverlay('close'); return; } catch (e) {}
                }
            }

            // 2) Try the opener element (anchor OR icon) that targets #addPatientNote
            const $opener = $('.mtcOverlay[href="' + sel + '"], .addPatientNoteButton[href="' + sel + '"]');
            if ($opener.length && typeof $opener.mtcOverlay === 'function') {
                try { $opener.mtcOverlay('close'); return; } catch (e) {}
            }

            // 3) Global fallbacks
            try { $('.mtcOverlayClose, .overlayCloseButton, .overlayClose').last().trigger('click'); } catch (e) {}
            try { $(document).trigger($.Event('keydown', { which: 27 })); } catch (e) {}

            // 4) Final belt-and-braces: hide the source node (plugin usually clones it)
            $(sel).hide();
        },
        emitEvent(name, data) {
            this.$parent.emitEvent(name, data);
        }
    }
});
