Vue.component('patientMessages', {
    props: ['routes','events','initialThreads'],

    data() {
        const initialProvided = Array.isArray(this.initialThreads);
        const initial = initialProvided ? this.initialThreads.slice() : [];
        return {
            records: initial,        // always an array
            hasLoaded: initialProvided,
            loading: false,
            display: 3,
            showingAll: false,
        };
    },

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

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

    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;
        }
    },

    methods: {
        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-messages-load')
                : null;
            if (cached) {
                const list = Array.isArray(cached.threads) ? cached.threads : [];
                vm.records = list;
                vm.loading = false;
                vm.hasLoaded = true;
                if (typeof vm.cacheBootstrap === 'function') {
                    vm.cacheBootstrap('admin-patient-messages-load', { threads: list.slice() });
                }
                return;
            }

            this.loading = true;

            this.$http.post(this.routes['admin-patient-messages-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-messages-load:', e, payload);
                            payload = {};
                        }
                    }

                    const list = Array.isArray(payload?.threads) ? payload.threads : [];
                    vm.records = list;
                    vm.loading = false;
                    vm.hasLoaded = true;
                    if (typeof vm.cacheBootstrap === 'function') {
                        vm.cacheBootstrap('admin-patient-messages-load', { threads: list.slice() });
                    }
                })
                .catch((err) => {
                    console.error('Messages load failed:', err);
                    this.loading = false;
                    this.records = []; // keep array to avoid render errors
                });
        },

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

        toggleMessages(index) {
            const list = Array.isArray(this.records) ? this.records : [];
            const row = list[index];
            if (!row) return; // guard bad index

            if (typeof row.visible === 'undefined') {
                this.$set(row, 'visible', true);
            } else {
                this.$set(row, 'visible', !row.visible);
            }
        }
    },
});
