// --- Image Handling Logic ---
let uploadedImagesBase64 = []; // List of base64 strings
const imgPreviewZone = document.getElementById('imgPreviewZone');
const dropArea = document.getElementById('dropArea');
const fileInput = document.getElementById('fileInput');

// Drag & drop
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(ev => {
    dropArea.addEventListener(ev, preventDefaults, false);
});
function preventDefaults(e) { e.preventDefault(); e.stopPropagation(); }

dropArea.addEventListener('drop', handleDrop, false);
function handleDrop(e) {
    const dt = e.dataTransfer;
    const files = dt.files;
    handleFiles(files);
}

// Paste event
document.addEventListener('paste', e => {
    if (e.clipboardData && e.clipboardData.items) {
        const items = e.clipboardData.items;
        const files = [];
        for (let i=0; i<items.length; i++) {
            if (items[i].type.indexOf('image') !== -1) {
                files.push(items[i].getAsFile());
            }
        }
        if (files.length > 0) handleFiles(files);
    }
});

function handleFiles(files) {
    Array.from(files).forEach(file => {
        if (!file.type.match('image.*')) return;
        const reader = new FileReader();
        reader.onload = (e) => {
            const b64 = e.target.result;
            uploadedImagesBase64.push(b64);
            renderPreviews();
        };
        reader.readAsDataURL(file);
    });
    fileInput.value = ''; // Reset
}

function renderPreviews() {
    if (uploadedImagesBase64.length > 0) {
        imgPreviewZone.classList.add('has-images');
        imgPreviewZone.innerHTML = uploadedImagesBase64.map((b64, idx) => `
            <div class="preview-item">
                <img src="${b64}">
                <button class="rm-btn" onclick="removeImg(${idx})">✕</button>
            </div>
        `).join('');
    } else {
        imgPreviewZone.classList.remove('has-images');
        imgPreviewZone.innerHTML = '';
    }
}

function removeImg(idx) {
    uploadedImagesBase64.splice(idx, 1);
    renderPreviews();
}

// --- Chat Logic ---
const messagesEl = document.getElementById('chatMessages');
const inputEl = document.getElementById('chatInput');
const sendBtn = document.getElementById('sendBtn');
const pipelineEl = document.getElementById('pipelineSteps');
const pathBadge = document.getElementById('pathBadge');

function addMsg(type, html, meta, userImages = []) {
    const div = document.createElement('div');
    div.className = 'msg ' + type;
    
    let inner = '';
    if (userImages.length > 0) {
        userImages.forEach(b64 => {
            inner += `<img class="user-img" src="${b64}">`;
        });
    }
    inner += html;
    
    div.innerHTML = inner;
    if (meta && type === 'ai') {
        const metaDiv = document.createElement('div');
        metaDiv.className = 'meta';
        metaDiv.innerHTML = meta;
        div.appendChild(metaDiv);
    }
    messagesEl.appendChild(div);
    messagesEl.scrollTop = messagesEl.scrollHeight;
}

function renderPipeline(pipeline, elapsedMs, agentPath) {
    pipelineEl.innerHTML = '';
    pathBadge.textContent = agentPath + ' · ' + elapsedMs + 'ms';
    pipeline.forEach((step) => {
        const div = document.createElement('div');
        div.className = `p-step s-${step.step}`;
        
        let content = String(step.content).replace(/</g,'&lt;').replace(/>/g,'&gt;');
        if (step.step === 'tool_result' && typeof marked !== 'undefined') {
            try { content = marked.parse(step.content); } catch(e){}
        }
        
        div.innerHTML = `<div class="step-label">${step.label}</div><div class="step-content">${content}</div>`;
        pipelineEl.appendChild(div);
    });
    pipelineEl.scrollTop = pipelineEl.scrollHeight;
}

async function sendMsg() {
    const query = inputEl.value.trim();
    if (!query && uploadedImagesBase64.length === 0) return;

    const payloadImages = [...uploadedImagesBase64];
    const displayQuery = query || (payloadImages.length > 0 ? "*(Gửi hình ảnh)*" : "");
    
    inputEl.value = '';
    uploadedImagesBase64 = [];
    renderPreviews();
    sendBtn.disabled = true;

    addMsg('user', displayQuery, null, payloadImages);
    
    const thinkingEl = document.createElement('div');
    thinkingEl.className = 'msg ai thinking';
    thinkingEl.innerHTML = '<span></span><span></span><span></span>';
    messagesEl.appendChild(thinkingEl);
    messagesEl.scrollTop = messagesEl.scrollHeight;

    try {
        const resp = await fetch('/api/image-search/chat', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ query: query, images: payloadImages })
        });
        const data = await resp.json();
        thinkingEl.remove();

        if (data.status === 'success') {
            const meta = `⏱ ${data.elapsed_ms}ms · ${data.agent_path}`;
            const parsedResp = marked.parse ? marked.parse(data.response) : data.response.replace(/\n/g, '<br>');
            addMsg('ai', parsedResp, meta);
            if (data.pipeline) {
                renderPipeline(data.pipeline, data.elapsed_ms, data.agent_path);
            }
        } else {
            addMsg('error', '❌ Lỗi: ' + (data.message || 'Unknown Error'));
        }
    } catch (e) {
        thinkingEl.remove();
        addMsg('error', '❌ Lỗi kết nối: ' + e.message);
    } finally {
        sendBtn.disabled = false;
        inputEl.focus();
    }
}