'use strict';

const requestId = window.CHAT_REQUEST_ID;
let refreshTimer = null;

/* ========== TOAST ========== */
function showToast(msg, isErr) {
    const el = document.getElementById('toast');
    el.textContent = msg;
    el.className = 'show' + (isErr ? ' error' : '');
    clearTimeout(el._t);
    el._t = setTimeout(() => el.className = '', 3000);
}

/* ========== FORMAT TIME ========== */
function formatTime(dateStr) {
    if (!dateStr) return '';
    const d = new Date(dateStr);
    if (isNaN(d)) return '';
    return d.toLocaleTimeString('he-IL', { hour: '2-digit', minute: '2-digit' });
}

/* ========== RENDER MESSAGES ========== */
function renderMessages(messages) {
    const win = document.getElementById('chat-window');

    if (!messages.length) {
        win.innerHTML = `
            <div class="chat-empty">
                <div class="chat-empty-icon">💬</div>
                <p>אין הודעות עדיין. שלחו את ההודעה הראשונה!</p>
            </div>`;
        return;
    }

    const wasAtBottom = win.scrollHeight - win.scrollTop - win.clientHeight < 60;

    win.innerHTML = '';
    messages.forEach(msg => {
        const div = document.createElement('div');
        div.className = `message ${msg.is_mine ? 'mine' : 'theirs'}`;
        div.innerHTML = `
            <span class="msg-sender">${msg.first_name}</span>
            <span class="msg-text">${escapeHtml(msg.message_text)}</span>
            ${msg.created_at ? `<span class="msg-time">${formatTime(msg.created_at)}</span>` : ''}
        `;
        win.appendChild(div);
    });

    if (wasAtBottom) win.scrollTop = win.scrollHeight;
}

/* ========== ESCAPE HTML ========== */
function escapeHtml(str) {
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
}

/* ========== LOAD MESSAGES ========== */
async function loadMessages() {
    try {
        const res  = await fetch(`../api/get_messages.php?request_id=${requestId}`);
        const data = await res.json();
        renderMessages(Array.isArray(data) ? data : []);
    } catch {
        /* שגיאת רשת – לא מציגים toast כדי לא להציף את המשתמש */
    }
}

/* ========== SEND MESSAGE ========== */
async function sendMessage(formData) {
    const btn   = document.getElementById('btn-send');
    const input = document.getElementById('msgInput');

    btn.disabled = true;
    try {
        const res  = await fetch('../api/send_message.php', { method: 'POST', body: formData });
        const data = await res.json();

        if (data && data.error) {
            showToast(data.error, true);
        } else {
            input.value = '';
            await loadMessages();
            /* גלילה לסוף לאחר שליחה */
            const win = document.getElementById('chat-window');
            win.scrollTop = win.scrollHeight;
        }
    } catch {
        showToast('שגיאת תקשורת, נסו שוב', true);
    } finally {
        btn.disabled = false;
        input.focus();
    }
}

/* ========== FORM SUBMIT ========== */
document.getElementById('messageForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const input = document.getElementById('msgInput');
    if (!input.value.trim()) return;
    const formData = new FormData(e.target);
    await sendMessage(formData);
});

/* ========== ENTER KEY (שליחה עם Enter, שורה חדשה עם Shift+Enter) ========== */
document.getElementById('msgInput').addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        document.getElementById('messageForm').dispatchEvent(new Event('submit', { cancelable: true }));
    }
});

/* ========== AUTO REFRESH ========== */
function startAutoRefresh(intervalMs = 3000) {
    stopAutoRefresh();
    refreshTimer = setInterval(loadMessages, intervalMs);
}

function stopAutoRefresh() {
    if (refreshTimer) { clearInterval(refreshTimer); refreshTimer = null; }
}

/* עצור רענון כשהטאב לא פעיל, חדש כשחוזרים */
document.addEventListener('visibilitychange', () => {
    if (document.hidden) stopAutoRefresh();
    else { loadMessages(); startAutoRefresh(); }
});

/* ========== INIT ========== */
loadMessages();
startAutoRefresh();
