<template>
    <div class="jsonViewer">
        <span v-if="isString" class="jsonViewer__string">{{ data }}</span>
        <template v-else>
            <button
                v-if="isCollapsed"
                class="jsonViewer__toggle jsonViewer__toggle--collapsed"
                @click="isCollapsed = false"
            >
                {{ collapsedText }}
            </button>
            <div v-else class="jsonViewer__content">
                <button
                    class="jsonViewer__collapse-btn"
                    @click="isCollapsed = true"
                >
                    −
                </button>
                <pre class="jsonViewer__pre">{{ formattedJson }}</pre>
            </div>
        </template>
    </div>
</template>

<script>
export default {
    name: 'JsonViewer',
    props: {
        data: {
            type: [String, Object, Array],
            default: null
        },
        collapsed: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            isCollapsed: this.collapsed
        };
    },
    computed: {
        parsed() {
            if (typeof this.data === 'string') {
                try {
                    return JSON.parse(this.data);
                } catch (e) {
                    return null;
                }
            }
            return this.data;
        },
        isString() {
            return typeof this.data === 'string' && this.parsed === null;
        },
        collapsedText() {
            if (Array.isArray(this.parsed)) {
                return `[...] (${this.parsed.length} items)`;
            }
            return '{...}';
        },
        formattedJson() {
            return JSON.stringify(this.parsed, null, 2);
        }
    }
};
</script>

<style lang="less">
@import "../../../../styles/admin/elements/chat/JsonViewer.less";
</style>
