<template>
    <h2 class="link" @click="openForum()">{{ $t('socialnetwork.forum.title') }} {{ forumName }}</h2>
    <h3 v-if="forumTopic">{{ forumTopic }}</h3>
    <ul class="messages">
        <li v-for="message in messages" :key="message.id">
            <div v-html="sanitizedMessage(message)"></div>
            <div class="footer">
                <span class="link" @click="openProfile(message.lastMessageUser.hashedId)">
                    {{ message.lastMessageUser.username }}
                </span>
                <span>{{ new Date(message.createdAt).toLocaleString() }}</span>
            </div>
        </li>
    </ul>

    <div class="editor-container">
        <EditorContent v-if="editor" :editor="editor" class="editor" />
    </div>
    <button @click="saveNewMessage">{{ $t('socialnetwork.forum.createNewMesssage') }}</button>
</template>

<script>
import { Editor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import apiClient from '../../utils/axios'
import DOMPurify from 'dompurify'

export default {
    name: 'ForumTopicView',
    components: {
        EditorContent,
    },
    data() {
        return {
            forumTopicId: '',
            forumTopic: null,
            forumName: null,
            forumId: 0,
            messages: [],
            editor: null,
        }
    },
    mounted() {
        this.forumTopicId = this.$route.params.id;
        this.loadForumTopic();

        this.editor = new Editor({
            extensions: [StarterKit],
            content: '',
            editable: true,
            editorProps: { attributes: { class: 'pm-root' } },
        });
    },
    beforeUnmount() {
        if (this.editor) {
            this.editor.destroy();
        }
    },
    methods: {
        async loadForumTopic() {
            try {
                const response = await apiClient.get(`/api/forum/topic/${this.forumTopicId}`);
                this.setContent(response.data);
            } catch (error) {
                console.error(error);
            }
        },
        setContent(data) {
            this.forumTopic = data.title;
            this.forumName = data.forum.name;
            this.forumId = data.forum.id;
            this.messages = data.messages;
        },
        async openProfile(id) {
            this.$root.$refs.userProfileDialog.userId = id;
            this.$root.$refs.userProfileDialog.open();
        },
        async saveNewMessage() {
            const content = this.editor ? this.editor.getHTML() : '';
            if (!content.trim()) return;

            try {
                const url = `/api/forum/topic/${this.forumTopicId}/message`;
                const response = await apiClient.post(url, { content });
                this.editor.commands.clearContent();
                this.setContent(response.data);
            } catch (error) {
                console.error(error);
            }
        },
        openForum() {
            this.$router.push(`/socialnetwork/forum/${this.forumId}`);
        },
        sanitizedMessage(message) {
            return DOMPurify.sanitize(message.text);
        }
    }
}
</script>
<style lang="scss" scoped>
.messages {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

.messages > li {
    border: 1px solid #7BBE55;
    margin-bottom: 0.25em;
    padding: 0.5em;
}

.messages > li > .footer {
    color: #F9A22C;
    font-size: 0.7em;
    margin-top: 0.5em;
    display: flex;
}

.messages > li > .footer > span:first-child {
    flex: 1;
}

.messages > li > .footer > span:last-child {
    text-align: right;
}

.editor-container {
    margin-top: 1rem;
    border: 1px solid #ccc;
    padding: 0;
    min-height: 260px;
    background-color: white;
}

.editor {
    min-height: 260px;
    outline: none;
    cursor: text;
}
.editor :deep(.ProseMirror) {
    min-height: 260px;
    outline: none;
    padding: 10px;
    box-sizing: border-box;
    width: 100%;
}
.editor :deep(.ProseMirror p) { margin: 0 0 .6rem; }
.editor :deep(.ProseMirror p:first-child) { margin-top: 0; }
.editor :deep(.ProseMirror-focused) { outline: 2px solid rgba(100,150,255,.35); }
</style>
