Vue.component('patientConsultations', {
    props: ['routes','events','initialConsultations','initialToday'],

    data: function() {
        const initialProvided = Array.isArray(this.initialConsultations);
        const initial = initialProvided ? this.initialConsultations.slice() : [];
        const today = this.initialToday || null;
        return {
            records: initial,          // always keep as array
            hasLoaded: initialProvided,
            loading: false,
            display: 3,
            todayDate: today,
            showingAll: false,
            selectedTranscript: null,
            transcriptOpen: false,
        };
    },

   mounted() {
       this.init();
       this.bindTranscriptModal();
   },

    watch: {
        initialConsultations: {
            immediate: true,
            handler(list) {
                if (!Array.isArray(list)) return;
                this.records = list.slice();
                this.hasLoaded = true;
                this.loading = false;
            }
        },
        initialToday: {
            immediate: true,
            handler(value) {
                if (value) {
                    this.todayDate = value;
                }
            }
        }
    },

    computed: {
        canShowAll() {
            const list = Array.isArray(this.records) ? this.records : [];
            if (!list.length) return false;
            if (this.showingAll) return false;
            return list.length > this.display;
        },
        formattedTranscript() {
            const t = this.selectedTranscript;
            const txt = (t && typeof t.display_text === 'string') ? t.display_text : '';
            if (!txt) return '';
            const esc = this.escapeText;
            const comments = (t && t.comments && typeof t.comments === 'object') ? t.comments : {};
            const lines = txt.split(/\r?\n/);
            let out = '';
            let visibleIndex = 0;
            for (let i = 0; i < lines.length; i++) {
                const line = lines[i];
                if (!line.trim()) continue;
                const m = line.match(/^([^:]{1,40}):\s*(.*)$/);
                if (m) {
                    out += '<p class="transcriptModal__line"><strong>'
                        + esc(m[1]) + ':</strong> ' + esc(m[2]) + '</p>';
                } else {
                    out += '<p class="transcriptModal__line">' + esc(line) + '</p>';
                }
                const lineComments = comments[visibleIndex] || comments[String(visibleIndex)];
                if (Array.isArray(lineComments) && lineComments.length) {
                    for (let j = 0; j < lineComments.length; j++) {
                        const c = lineComments[j] || {};
                        const author = c.author ? esc(c.author) : 'Comment';
                        const body = c.text ? esc(c.text) : '';
                        out += '<div class="transcriptModal__comment"><strong>'
                            + author + ':</strong> ' + body + '</div>';
                    }
                }
                visibleIndex++;
            }
            return out;
        }
    },

    methods: {
        escapeText(s) {
            if (s === null || s === undefined) return '';
            return String(s).replace(/[&<>"']/g, function (c) {
                return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
            });
        },
        init() {
            if (this.hasLoaded) return;
            this.load(true);
        },

        load(force = false) {
            if (!force && this.loading) {
                return;
            }
            const vm = this;
            const cached = (!force && this.consumeBootstrap)
                ? this.consumeBootstrap('admin-patient-consultations-load')
                : null;
            if (cached) {
                const list  = Array.isArray(cached.consultations) ? cached.consultations : [];
                const today = cached?.todayDate ?? null;
                vm.records   = list;
                vm.todayDate = today;
                vm.loading   = false;
                vm.hasLoaded = true;
                if (typeof vm.cacheBootstrap === 'function') {
                    vm.cacheBootstrap('admin-patient-consultations-load', {
                        consultations: list.slice(),
                        todayDate: today,
                    });
                }
                return;
            }

            this.loading = true;

            this.$http.post(this.routes['admin-patient-consultations-load'], {})
                .then((response) => {
                    let payload = response.data;

                    // vue-resource 0.9.x may return JSON as a string
                    if (typeof payload === 'string') {
                        try { payload = JSON.parse(payload); }
                        catch (e) {
                            console.error('Invalid JSON from admin-patient-consultations-load', e, payload);
                            payload = {};
                        }
                    }

                    const list  = Array.isArray(payload?.consultations) ? payload.consultations : [];
                    const today = payload?.todayDate ?? null;

                    vm.records   = list;      // keep as array
                    vm.todayDate = today;
                    vm.loading   = false;
                    vm.hasLoaded = true;
                    if (typeof vm.cacheBootstrap === 'function') {
                        vm.cacheBootstrap('admin-patient-consultations-load', {
                            consultations: list.slice(),
                            todayDate: today,
                        });
                    }
                    vm.bindTranscriptModal();
                })
                .catch((err) => {
                    console.error('Consultations load failed:', err);
                    this.loading = false;
                    this.records = [];        // avoid undefined in render
                });
        },

        showAll() {
            this.showingAll = true;
            this.bindTranscriptModal();
        },

        viewTranscript(transcript) {
            this.selectedTranscript = transcript || null;
            this.transcriptOpen = true;
        },

        bindTranscriptModal() {
            const vm = this;
            this.$nextTick(function () {
                $('.transcriptModalButton').mtcOverlay({
                    onClose() {
                        vm.selectedTranscript = null;
                        vm.transcriptOpen = false;
                    },
                });
            });
        },

        transcriptPdfUrl(transcriptId) {
            if (this.routes && this.routes['admin-patient-transcripts-pdf']) {
                return this.routes['admin-patient-transcripts-pdf'].replace('---id---', transcriptId);
            }
            return '#';
        },
    },
});
