<template>
    <div :class="getMessageClass()" :data-message-id="message.id">
        <!-- EveAI Logo buiten de scroller, vast aan de bubble -->
        <img 
            v-if="message.sender === 'ai'" 
            :src="staticUrl('/assets/img/eveai_logo.svg')"
            alt="EveAI" 
            class="ai-message-logo"
        />
        <!-- Normal text messages -->
        <template v-if="message.type === 'text'">
            <div class="message-content" style="width: 100%;" ref="messageContent">
                <!-- Voortgangstracker voor AI berichten met task_id - ALLEEN VOOR LAATSTE AI MESSAGE -->
                <progress-tracker 
                    v-if="message.sender === 'ai' && message.taskId && isLatestAiMessage" 
                    :task-id="message.taskId"
                    :api-prefix="apiPrefix"
                    :is-latest-ai-message="isLatestAiMessage"
                    :is-in-input-area="isInInputArea"
                    class="message-progress"
                    @specialist-complete="handleSpecialistComplete"
                    @specialist-error="handleSpecialistError"
                ></progress-tracker>
                <!-- Form data display if available (alleen in user messages) -->
                <div v-if="hasMeaningfulFormValues(message)" class="form-display user-form-values">
                    <dynamic-form
                        :form-data="message.formData"
                        :form-values="message.formValues"
                        :api-prefix="apiPrefix"
                        :read-only="true"
                        hide-actions
                        class="message-form user-form"
                    ></dynamic-form>
                </div>

                <!-- Formulier in AI berichten -->
                <div v-if="message.formData && message.sender === 'ai'" class="form-display ai-form-values" style="margin-top: 15px;">
                    <!-- Dynamisch toevoegen van Material Symbols Outlined voor iconen -->
                    <table class="form-result-table">
                        <thead v-if="message.formData.title || message.formData.name || message.formData.icon">
                            <tr>
                                <th colspan="2">
                                    <div class="form-header">
                                        <span v-if="message.formData.icon" class="material-symbols-outlined">{{ message.formData.icon }}</span>
                                        <span>{{ message.formData.title || message.formData.name }}</span>
                                    </div>
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(field, fieldId) in message.formData.fields" :key="fieldId">
                                <td class="field-label">{{ field.name }}:</td>
                                <td class="field-value">
                                    <input 
                                        v-if="field.type === 'str' || field.type === 'string' || field.type === 'int' || field.type === 'integer' || field.type === 'float'"
                                        :type="field.type === 'int' || field.type === 'integer' || field.type === 'float' ? 'number' : 'text'"
                                        :placeholder="field.placeholder || ''"
                                        class="form-input"
                                    >
                                    <textarea 
                                        v-else-if="field.type === 'text'"
                                        :placeholder="field.placeholder || ''"
                                        :rows="field.rows || 3"
                                        class="form-textarea"
                                    ></textarea>
                                    <select 
                                        v-else-if="field.type === 'enum'"
                                        class="form-select"
                                    >
                                        <option value="">Selecteer een optie</option>
                                        <option 
                                            v-for="option in (field.allowedValues || field.allowed_values || [])" 
                                            :key="option"
                                            :value="option"
                                        >
                                            {{ option }}
                                        </option>
                                    </select>
                                    <div v-else-if="field.type === 'boolean'" class="toggle-switch">
                                        <input type="checkbox" class="toggle-input">
                                        <span class="toggle-slider">
                                            <span class="toggle-knob"></span>
                                        </span>
                                    </div>
                                    <input 
                                        v-else
                                        type="text"
                                        :placeholder="field.placeholder || ''"
                                        class="form-input"
                                    >
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Bericht tekst -->
                <div v-if="message.content" class="message-text" v-html="renderedMessage"></div>
            </div>
        </template>

        <!-- Error messages -->
        <template v-else-if="message.type === 'error'">
            <div class="message-content error-content">
                <div class="form-error">
                    {{ message.content }}
                </div>
                <button v-if="message.retryable" @click="$emit('retry-message', message.id)" class="retry-btn">
                    {{ messageTexts.retry }}
                </button>
            </div>
        </template>

        <!-- Other message types -->
        <template v-else>
            <div class="message-content" ref="messageContent">
                <div class="message-text" v-html="formatMessage(message.content)"></div>
            </div>
        </template>
    </div>
</template>

<script>
// Import benodigde componenten
import DynamicForm from './DynamicForm.vue';
import ProgressTracker from './ProgressTracker.vue';
import { useIconManager } from '../js/composables/useIconManager.js';
import { useComponentTranslations } from '../js/services/LanguageProvider.js';
import { renderMarkdown } from '../js/utils/markdownRenderer.js';

export default {
    name: 'ChatMessage',
    components: {
        'dynamic-form': DynamicForm,
        'progress-tracker': ProgressTracker
    },
    setup(props) {
        const { watchIcon } = useIconManager();
        
        // Watch message.formData.icon for automatic icon loading
        watchIcon(() => props.message.formData?.icon);
        
        // Use component translations from provider (English as base language)
        const originalTexts = {
            retry: 'Try again',
            copy: 'Copy',
            timestamp: 'Timestamp',
            errorMessage: 'An error occurred while processing your request.'
        };
        
        const { translations, isLoading, error, currentLanguage } = useComponentTranslations(
            'chat_message', 
            originalTexts
        );
        
        // Helper to build environment-aware static asset URLs
        const staticUrl = (p) => {
            try {
                if (typeof window !== 'undefined' && typeof window.staticUrl === 'function') {
                    return window.staticUrl(p);
                }
            } catch (e) {}
            const base = '/static/';
            return base + String(p || '').replace(/^\/+/, '');
        };
        
        return {
            messageTexts: translations,
            translationLoading: isLoading,
            translationError: error,
            currentLanguage,
            staticUrl
        };
    },
    props: {
        message: {
            type: Object,
            required: true,
            validator: (message) => {
                return message.id && message.content !== undefined && message.sender && message.type;
            }
        },
        isSubmittingForm: {
            type: Boolean,
            default: false
        },
        apiPrefix: {
            type: String,
            default: ''
        },
        isLatestAiMessage: {
            type: Boolean,
            default: false
        },
        isInInputArea: {
            type: Boolean,
            default: false
        }
    },
    emits: ['image-loaded', 'retry-message', 'specialist-complete', 'specialist-error'],
    data() {
        return {
            formVisible: true
        };
    },
    created() {
        // Icon loading is now handled automatically by useIconManager composable
        
        // Sla de originele inhoud op voor het eerste bericht als we in een conversatie zitten met slechts één bericht
        if (this.message.sender === 'ai' && !this.message.originalContent) {
            this.message.originalContent = this.message.content;
        }
    },
    mounted() {
        // Reset initial scroll position to top for the inner bubble
        this.$nextTick(() => {
            const el = this.$refs.messageContent;
            if (el && typeof el.scrollTop !== 'undefined') {
                el.scrollTop = 0;
            }
        });
    },
    watch: {
            isActiveContext(newVal, oldVal) {
                // When moving from active (input/sticky) to history, reset scroll to top
                if (oldVal === true && newVal === false) {
                    this.$nextTick(() => {
                        const el = this.$refs.messageContent;
                        if (el && typeof el.scrollTop !== 'undefined') {
                            el.scrollTop = 0;
                        }
                    });
                }
            }
        },
        beforeUnmount() {
        // Component cleanup if needed
    },
    computed: {
                renderedMessage() {
                    const content = this.message?.content ?? '';
                    if (!content) return '';
                    // Only render markdown for AI messages and text type
                    if (this.message.sender !== 'ai' || this.message.type !== 'text') {
                        // plain text fallback
                        return String(content)
                            .replace(/&/g, '&amp;')
                            .replace(/</g, '&lt;')
                            .replace(/>/g, '&gt;')
                            .replace(/\"/g, '&quot;')
                            .replace(/'/g, '&#39;')
                            .replace(/\n/g, '<br>');
                    }
                    return renderMarkdown(content, {
                        allowInlineHTML: false,
                        enableTables: true,
                        enableBreaks: true,
                        enableImages: false,
                        enableCodeBlocks: false,
                        allowInlineCode: false,
                        linkTargetBlank: true,
                        sidebarAccent: false
                    });
                },
            isActiveContext() {
                // active if in input area or sticky area
                return !!(this.isInInputArea || this.isInStickyArea);
            },
        hasFormData() {
            return this.message.formData && 
                  ((Array.isArray(this.message.formData.fields) && this.message.formData.fields.length > 0) ||
                   (typeof this.message.formData.fields === 'object' && Object.keys(this.message.formData.fields).length > 0));
        },
        hasFormValues() {
            return this.message.formValues && Object.keys(this.message.formValues).length > 0;
        }
    },
    methods: {
        hasMeaningfulFormValues(message) {
            // Check if message is user message and has formValues
            if (!message || message.sender !== 'user' || !message.formValues) {
                return false;
            }

            // Check if formData exists and has fields
            if (!message.formData || !message.formData.fields || Object.keys(message.formData.fields).length === 0) {
                return false;
            }

            // Check if formValues object exists and isn't empty
            if (!message.formValues || Object.keys(message.formValues).length === 0) {
                return false;
            }

            // Check if any formValues have actual meaningful content
            const hasActualValues = Object.entries(message.formValues).some(([key, value]) => {
                // Skip if the field doesn't exist in formData
                if (!message.formData.fields[key]) return false;
                
                // Check for meaningful values
                if (value === null || value === undefined) return false;
                if (typeof value === 'string' && value.trim() === '') return false;
                if (typeof value === 'boolean') return true; // Boolean values are always meaningful
                if (Array.isArray(value) && value.length === 0) return false;
                
                return true;
            });

            return hasActualValues;
        },


        handleSpecialistError(eventData) {
            console.log('ChatMessage received specialist-error event:', eventData);

            // Create an error message with correct styling
            this.message.type = 'error';
            this.message.content = eventData.message || this.messageTexts.errorMessage;
            this.message.retryable = true;
            this.message.error = true; // Add error flag for styling

            // Bubble up to parent component for further handling
            this.$emit('specialist-error', {
                messageId: this.message.id,
                ...eventData
            });
        },

        handleSpecialistComplete(eventData) {
            console.log('ChatMessage received specialist-complete event:', eventData);

            // Update de inhoud van het bericht met het antwoord
            if (eventData.answer) {
                console.log('Updating message content with answer:', eventData.answer);
                this.message.content = eventData.answer;
                this.message.originalContent = eventData.answer;
            } else {
                console.error('No answer in specialist-complete event data');
            }

            // Bubble up naar parent component voor eventuele verdere afhandeling
            this.$emit('specialist-complete', {
                messageId: this.message.id,
                answer: eventData.answer,
                form_request: eventData.form_request,  // Wordt nu door ChatApp verwerkt
                result: eventData.result,
                interactionId: eventData.interactionId,
                taskId: eventData.taskId
            });
        },

        formatMessage(content) {
            if (!content) return '';

            // Enhanced markdown-like formatting
            return content
                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                .replace(/\*(.*?)\*/g, '<em>$1</em>')
                .replace(/`(.*?)`/g, '<code>$1</code>')
                .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>')
                .replace(/\n/g, '<br>');
        },

        removeMessage() {
            // Dit zou een event moeten triggeren naar de parent component
        },

        reactToMessage(emoji) {
            // Implementatie van reacties zou hier komen
        },

        getMessageClass() {
            let classes = `message ${this.message.sender}`;
            
            // Add 'has-form' class for user messages with formulieren
            if (this.message.sender === 'user' && this.hasMeaningfulFormValues(this.message)) {
                classes += ' has-form';
            }
            
            // Add class for temporarily positioned AI messages
            if (this.message.isTemporarilyAtBottom) {
                classes += ' temporarily-at-bottom';
            }
            
            // Add class for messages in sticky area
            if (this.isInStickyArea) {
                classes += " sticky-area";
            }
            
            // Add class for messages in input area
            if (this.isInInputArea) {
                classes += " input-area";
            }
            
            return classes;
        }
    }
};
</script>

<style scoped>
/* chat-message.css */

/* Algemene styling voor berichten */
.message {
    max-width: 90%;
    margin-bottom: 15px;
    width: auto;
}

.message.user {
    margin-left: auto;
}

.message.ai {
    margin-right: auto;
}

/* User messages with forms get fixed width of 90% */
.message.user.has-form {
    width: auto; /* niet breder maken dan standaard */
    max-width: 100%;
}

/* Styling for temporarily positioned AI messages */
.message.ai.temporarily-at-bottom {
    background-color: var(--ai-message-background);
    color: var(--ai-message-text-color);
    opacity: 0.9;
    border-radius: 8px;
    padding: 8px;
    margin: 8px 0;
}

/* Styling for messages in sticky area - override history colors with active colors */
.message.sticky-area .message-content {
    background: var(--ai-message-background);
    color: var(--ai-message-text-color);
}

/* Override message bubble colors for sticky area */
.message.sticky-area.user .message-content,
.message.sticky-area.ai .message-content {
    background: var(--ai-message-background) !important;
    color: var(--ai-message-text-color) !important;
    border: 1px solid var(--ai-message-text-color);
    border-radius: 8px;
    padding: 12px;
}

/* Active styling for messages in input area */
.message.input-area .message-content {
    background-color: var(--ai-message-background);
    color: var(--ai-message-text-color);
    border-radius: 8px;
    padding: 12px;
}
.message-content {
    font-family: Arial, sans-serif;
    font-size: 12px;
    max-width: 100%;
    padding: 8px;
    border-radius: 10px;
    word-wrap: break-word;
    position: relative;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    transition: all 0.2s ease;
    display: inline-block;
    width: 100%;
    box-sizing: border-box;
}

/* EveAI Logo styling voor AI berichten */
/* Position relative on the message container to anchor the logo (sibling of .message-content) */
.message.ai {
    position: relative;
}
.ai-message-logo {
    position: absolute;
    top: -20px;
    left: -5px;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background-color: var(--ai-message-background);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
    z-index: 10;
    pointer-events: none;
}

/* Formulier styling */
.form-display {
    color: var(--human-message-text-color);
    font-family: inherit;
}

/* Neutraliseer dynamic-form look binnen message bubble voor user-form-values */
.user-form-values .message-form .dynamic-form {
    background: transparent;
    box-shadow: none;
    padding: 0;
    max-width: 100%;
    box-sizing: border-box;
}
.user-form-values .message-form .form-readonly,
.user-form-values .message-form .form-field-readonly,
.user-form-values .message-form .field-label,
.user-form-values .message-form .field-value {
    max-width: 90%;
    box-sizing: border-box;
}

/* Tabel styling voor formulieren */
.form-result-table {
    width: 100%;
    border-collapse: collapse;
    font-family: inherit;
}

.form-result-table th {
    padding: 8px;
    text-align: left;
    border-bottom: 1px solid #e0e0e0;
    font-weight: 600;
    font-family: Arial, sans-serif;
    font-size: 14px;
}

.form-result-table td {
    padding: 8px;
    border-bottom: 1px solid #f0f0f0;
    font-family: Arial, sans-serif;
    font-size: 14px;
}

.form-result-table td:first-child {
    font-weight: 500;
    width: 35%;
}

/* Styling voor formulier invoervelden */
.form-result-table input.form-input,
.form-result-table textarea.form-textarea,
.form-result-table select.form-select {
    width: 100%;
    padding: 6px;
    border-radius: 4px;
    border: 1px solid var(--human-message-text-color);
    font-family: Arial, sans-serif;
    font-size: 14px;
    background-color: var(--human-message-background);
    color: var(--human-message-text-color);
}

.form-result-table textarea.form-textarea {
    resize: vertical;
    min-height: 60px;
}

/* Styling voor tabel cellen */
.form-result-table .field-label {
    padding: 8px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: 500;
    width: 35%;
    vertical-align: top;
}

.form-result-table .field-value {
    padding: 8px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: top;
}

/* Toggle Switch styling */
.toggle-switch {
    position: relative;
    display: inline-block;
    width: 50px;
    height: 24px;
}

.toggle-input {
    opacity: 0;
    width: 0;
    height: 0;
}

.toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: .4s;
    border-radius: 24px;
}

.toggle-knob {
    position: absolute;
    content: '';
    height: 18px;
    width: 18px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    transition: .4s;
    border-radius: 50%;
}

/* Material icon styling */
.material-symbols-outlined {
    vertical-align: middle;
    margin-right: 8px;
    font-size: 20px;
}

.form-header {
    display: flex;
    align-items: center;
    padding: 8px;
    border-bottom: 1px solid #e0e0e0;
}

/* Zorgt dat het lettertype consistent is */
.message-text {
    color: var(--ai-message-text-color);
    font-family: Arial, sans-serif;
    font-size: 14px;
    white-space: normal;
    word-break: break-word;
}

/* Markdown typography inside message text */
.message-text :deep(h1),
.message-text :deep(h2),
.message-text :deep(h3),
.message-text :deep(h4) {
    margin: 0.8rem 0 0.4rem;
    color: var(--ai-message-text-color);
}
.message-text :deep(p) {
    margin: 0 0 0.6rem 0;
}
.message-text :deep(ul),
.message-text :deep(ol) {
    padding-left: 1.2rem;
    margin: 0.4rem 0 0.6rem;
}
.message-text :deep(li) {
    margin: 0.2rem 0;
}
.message-text :deep(a) {
    color: var(--primary-color);
    text-decoration: underline;
}
.message-text :deep(table) {
    width: 100%;
    border-collapse: collapse;
    margin: 0.6rem 0;
    overflow-x: auto;
    display: block;
}
.message-text :deep(th),
.message-text :deep(td) {
    border: 1px solid #e0e0e0;
    padding: 6px 8px;
    text-align: left;
}
.message-text :deep(th) {
    background: rgba(0,0,0,0.05);
    font-weight: 600;
}
.message-text :deep(blockquote) {
    border-left: 3px solid var(--primary-color);
    padding-left: 10px;
    margin: 0.6rem 0;
    color: var(--ai-message-text-color);
    opacity: 0.9;
}
.message-text :deep(hr) { 
    border: 0; border-top: 1px solid #ddd; margin: 0.8rem 0; 
}

/* Form error styling */
.form-error {
    color: red;
    padding: 10px;
    font-family: Arial, sans-serif;
    font-size: 14px;
}

.error-content {
    background-color: #ffebee;
    border: 1px solid #f44336;
    border-radius: 4px;
    padding: 10px;
}

.retry-btn {
    margin-top: 10px;
    padding: 8px 16px;
    background-color: #f44336;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.retry-btn:hover {
    background-color: #d32f2f;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .message {
        max-width: 95%;
    }
    
    /* User messages with forms: hou zelfde breedte als gewone tekst */
    .message.user.has-form {
        width: auto;
        max-width: 100%;
    }
    
    .form-result-table td:first-child {
        width: 40%;
    }
}
/* migrated from global css: message-content visuals */
.message.user .message-content {
    background: var(--human-message-background);
    color: var(--human-message-text-color);
    border-bottom-right-radius: 4px;
}

.message.ai .message-content,
.message.bot .message-content {
    background: var(--ai-message-background);
    color: var(--ai-message-text-color);
    margin-right: 20px;
}

/* Hover effects for message bubbles */
.message-content:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

/* Handle empty message content during processing */
.message-content:has(.message-text:empty) .message-progress {
    margin-bottom: 0;
}
.message-content:has(.message-text:empty):not(:has(.message-progress.completed)):not(:has(.message-progress.error)) {
    background: transparent;
    box-shadow: none;
    border: none;
    padding: 0;
    margin: 0;
}

/* Mobile responsiveness moved from global */
@media (max-width: 768px) {
    .message.user .message-content {
        margin-left: 40px;
    }
    .message.ai .message-content,
    .message.bot .message-content {
        margin-right: 5px;
    }
    /* Mobile: place logo inside bubble and prevent overlap with text */
    .message.ai .ai-message-logo {
        top: -12px;
        width: 24px;
        height: 24px;
    }
    .message.ai .message-content {
        /* Reserve space for the in-bubble logo */
        padding-top: 1px; /* 24px logo + margins */
        padding-left: 10px;
    }
}

/* Bubble height constraints and inner scroll containment (apply on all viewports) */
.message .message-content {
    max-height: 33vh; /* fallback */
    overflow-y: auto;
    overscroll-behavior: contain; /* prevent scroll chaining to parent */
    -webkit-overflow-scrolling: touch; /* iOS smooth inertia */
}
/* Active contexts (input area or sticky area): allow up to half viewport */
.message.input-area .message-content,
.message.sticky-area .message-content {
    max-height: 50vh; /* fallback */
}
@supports (max-height: 1svh) {
    .message .message-content { max-height: 33svh; }
    .message.input-area .message-content,
    .message.sticky-area .message-content { max-height: 50svh; }
}
</style>