(() => {
    const root = document.getElementById('vmoda-chat-root');
    if (!root) return;

    const endpoint = root.dataset.endpoint;
    const historyEndpoint = root.dataset.historyEndpoint || '';
    const userId = (root.dataset.userId || '').trim();
    const pageContext = (root.dataset.pageContext || 'General').trim();

    const csrfInput = document.querySelector('#antiforgery-form input[name="__RequestVerificationToken"]');

    const toggle = document.getElementById('vmChatToggle');
    const panel = document.getElementById('vmChatPanel');
    const closeBtn = document.getElementById('vmChatClose');
    const messages = document.getElementById('vmChatMessages');
    const form = document.getElementById('vmChatForm');
    const input = document.getElementById('vmChatInput');
    const sendBtn = document.getElementById('vmChatSend');
    const attachBtn = document.getElementById('vmChatAttach');
    const imageInput = document.getElementById('vmChatImageInput');
    const imagePreview = document.getElementById('vmChatImagePreview');
    const imageThumb = document.getElementById('vmChatImageThumb');
    const imageName = document.getElementById('vmChatImageName');
    const removeImageBtn = document.getElementById('vmChatRemoveImage');
    const quickButtons = root.querySelectorAll('.vm-chat-quick-btn');

    let isSending = false;
    let selectedImage = null;
    let initialized = false;
    let history = [];

    const anonymousConversationKey = 'vmoda_chat_conversation_id';
    const historyPrefix = 'vmoda_chat_history_v3';

    function cryptoRandomId() {
        if (window.crypto && window.crypto.randomUUID) {
            return window.crypto.randomUUID().replaceAll('-', '');
        }
        return `${Date.now()}_${Math.random().toString(36).slice(2, 12)}`;
    }

    function buildConversationId() {
        if (userId) return `usr_${userId}`;

        let stored = localStorage.getItem(anonymousConversationKey);
        if (stored) return stored;

        stored = `guest_${cryptoRandomId()}`;
        localStorage.setItem(anonymousConversationKey, stored);
        return stored;
    }

    const conversationId = buildConversationId();
    const localHistoryKey = `${historyPrefix}_${conversationId}`;

    function loadHistory() {
        try {
            const raw = localStorage.getItem(localHistoryKey);
            if (!raw) return [];
            const parsed = JSON.parse(raw);
            if (!Array.isArray(parsed)) return [];
            return parsed
                .filter(x => x && (x.role === 'user' || x.role === 'assistant') && typeof x.content === 'string')
                .slice(-8);
        } catch {
            return [];
        }
    }

    function saveHistory() {
        try {
            localStorage.setItem(localHistoryKey, JSON.stringify(history.slice(-8)));
        } catch {
        }
    }

    async function loadServerHistory() {
        if (!historyEndpoint) return false;

        try {
            const response = await fetch(`${historyEndpoint}?conversationId=${encodeURIComponent(conversationId)}`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json'
                }
            });

            if (!response.ok) return false;

            const payload = await response.json();
            if (!payload || !payload.ok || !Array.isArray(payload.history)) return false;

            history = payload.history
                .filter(x => x && (x.role === 'user' || x.role === 'assistant') && typeof x.content === 'string')
                .slice(-8);

            saveHistory();
            return true;
        } catch {
            return false;
        }
    }

    async function ensureInitialized() {
        if (initialized) return;

        initialized = true;
        history = loadHistory();

        if (history.length === 0) {
            await loadServerHistory();
        }

        renderInitialConversation();
    }

    function openChat() {
        root.classList.add('is-open');
        panel.setAttribute('aria-hidden', 'false');
        toggle?.setAttribute('aria-expanded', 'true');

        ensureInitialized().then(() => {
            input?.focus();
        });
    }

    function closeChat() {
        root.classList.remove('is-open');
        panel.setAttribute('aria-hidden', 'true');
        toggle?.setAttribute('aria-expanded', 'false');
    }

    function renderInitialConversation() {
        if (!messages) return;

        messages.dataset.initialized = '1';
        messages.innerHTML = '';

        if (history.length === 0) {
            addBotMessage('Hola, soy el asistente de VModa. Puedo ayudarte a encontrar prendas y looks.');
            addMetaMessage('Ejemplos: “necesito ir a una boda” o subí una foto de una prenda.');
            return;
        }

        history.forEach(turn => {
            if (turn.role === 'user') addUserMessage(turn.content);
            else addBotMessage(turn.content);
        });
    }

    function addBubble(text, type) {
        const bubble = document.createElement('div');
        bubble.className = `vm-chat-bubble vm-chat-bubble--${type}`;
        bubble.textContent = text;
        messages.appendChild(bubble);
        scrollToBottom();
        return bubble;
    }

    function addUserMessage(text) {
        addBubble(text, 'user');
    }

    function addBotMessage(text, action) {
        const bubble = addBubble(text, 'bot');

        if (action?.url && action?.label) {
            const actions = document.createElement('div');
            actions.className = 'vm-chat-actions';

            const link = document.createElement('a');
            link.className = 'vm-chat-link-btn';
            link.href = action.url;
            link.target = '_blank';
            link.rel = 'noopener noreferrer';
            link.textContent = action.label;

            actions.appendChild(link);
            bubble.appendChild(actions);
        }
    }

    function addMetaMessage(text) {
        addBubble(text, 'meta');
    }

    function scrollToBottom() {
        messages.scrollTop = messages.scrollHeight;
    }

    function setBusy(busy) {
        isSending = busy;
        if (sendBtn) sendBtn.disabled = busy;
        if (input) input.disabled = busy;
        if (attachBtn) attachBtn.disabled = busy;
        quickButtons.forEach(btn => btn.disabled = busy);
    }

    function createTyping() {
        const typing = document.createElement('div');
        typing.className = 'vm-chat-bubble vm-chat-bubble--bot vm-chat-typing';
        typing.innerHTML = '<span></span><span></span><span></span>';
        messages.appendChild(typing);
        scrollToBottom();
        return typing;
    }

    function autoResize() {
        if (!input) return;
        input.style.height = 'auto';
        input.style.height = `${Math.min(input.scrollHeight, 132)}px`;
    }

    function clearSelectedImage() {
        selectedImage = null;
        if (imageInput) imageInput.value = '';
        if (imageThumb) imageThumb.src = '';
        if (imageName) imageName.textContent = '';
        if (imagePreview) imagePreview.hidden = true;
    }

    function fileToDataUrl(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result);
            reader.onerror = reject;
            reader.readAsDataURL(file);
        });
    }

    async function normalizeImage(file) {
        const dataUrl = await fileToDataUrl(file);
        return {
            name: file.name,
            dataUrl: dataUrl
        };
    }

    async function sendMessage(text) {
        const clean = (text || '').trim();
        if ((!clean && !selectedImage) || isSending) return;

        if (!csrfInput?.value) {
            addBotMessage('No pude iniciar el chat correctamente. Recargá la página e intentá de nuevo.');
            return;
        }

        setBusy(true);
        addUserMessage(clean || 'Imagen enviada');

        history.push({ role: 'user', content: clean || '[imagen]' });
        history = history.slice(-8);
        saveHistory();

        const typing = createTyping();

        try {
            const response = await fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'RequestVerificationToken': csrfInput.value
                },
                body: JSON.stringify({
                    message: clean,
                    history: history.slice(-8),
                    imageDataUrl: selectedImage?.dataUrl || null,
                    imageName: selectedImage?.name || null,
                    conversationId: conversationId,
                    pageContext: pageContext
                })
            });

            const payload = await response.json();
            typing.remove();

            if (!response.ok || !payload?.ok) {
                addBotMessage(payload?.reply || 'No pude responder esa consulta ahora mismo. Probá de nuevo en un momento.');
                return;
            }

            const reply = payload.reply || 'No encontré una respuesta útil para esa consulta.';
            history.push({ role: 'assistant', content: reply });
            history = history.slice(-8);
            saveHistory();

            addBotMessage(reply, payload.escalateToHuman ? {
                url: payload.contactUrl,
                label: payload.contactLabel || 'Contactar soporte'
            } : null);

            if (payload.searchKeywords) {
                const targetUrl = `/Productos/Explorar?q=${encodeURIComponent(payload.searchKeywords)}`;
                setTimeout(() => {
                    window.location.href = targetUrl;
                }, 350);
                return;
            }
        } catch {
            typing.remove();
            addBotMessage('Tuve un problema al procesar la consulta. Intentá nuevamente.');
        } finally {
            clearSelectedImage();
            if (input) input.value = '';
            autoResize();
            setBusy(false);
            openChat();
        }
    }

    function askFromOutside(question) {
        openChat();

        if (!question || !question.trim()) return;

        setTimeout(() => {
            sendMessage(question.trim());
        }, 120);
    }

    toggle?.addEventListener('click', () => root.classList.contains('is-open') ? closeChat() : openChat());
    closeBtn?.addEventListener('click', closeChat);

    form?.addEventListener('submit', async e => {
        e.preventDefault();
        await sendMessage(input.value);
    });

    input?.addEventListener('input', autoResize);

    input?.addEventListener('keydown', async e => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            await sendMessage(input.value);
        }
    });

    quickButtons.forEach(btn => {
        btn.addEventListener('click', async () => {
            await sendMessage(btn.getAttribute('data-question') || '');
        });
    });

    attachBtn?.addEventListener('click', () => imageInput.click());
    removeImageBtn?.addEventListener('click', clearSelectedImage);

    imageInput?.addEventListener('change', async () => {
        const file = imageInput.files?.[0];
        if (!file) return;

        if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) {
            addBotMessage('Usá una imagen JPG, PNG o WEBP.');
            clearSelectedImage();
            return;
        }

        if (file.size > 8 * 1024 * 1024) {
            addBotMessage('La imagen es muy pesada. Probá con una de menos de 8 MB.');
            clearSelectedImage();
            return;
        }

        try {
            selectedImage = await normalizeImage(file);
            imageThumb.src = selectedImage.dataUrl;
            imageName.textContent = file.name;
            imagePreview.hidden = false;
            openChat();
        } catch {
            addBotMessage('No pude leer esa imagen. Probá con otra.');
            clearSelectedImage();
        }
    });

    document.addEventListener('click', e => {
        const trigger = e.target.closest('[data-vm-chat-open]');
        if (!trigger) return;

        e.preventDefault();

        const question = (trigger.getAttribute('data-vm-chat-question') || '').trim();
        if (question) {
            askFromOutside(question);
            return;
        }

        openChat();
    });

    document.addEventListener('keydown', e => {
        if (e.key === 'Escape' && root.classList.contains('is-open')) closeChat();
    });

    window.VModaChat = {
        open: openChat,
        close: closeChat,
        ask: askFromOutside,
        conversationId: () => conversationId
    };
})();
