{% extends "base.html" %}

{% block css %}
.timestamp {
    min-width: 10em;
    color: #ccc;
}

.chat-packet:nth-of-type(odd) { background-color: #3a3a3a; }
.chat-packet {
    border-bottom: 1px solid #555;
    padding: 3px 6px;
    border-radius: 6px;
    margin: 0;
}

/* Same column spacing as before */
.chat-packet > [class^="col-"] {
    padding-left: 10px !important;
    padding-right: 10px !important;
    padding-top: 1px !important;
    padding-bottom: 1px !important;
}

.chat-packet:nth-of-type(even) { background-color: #333333; }

.channel {
    font-style: italic;
    color: #bbb;
}
.channel a {
    font-style: normal;
    color: #999;
}

@keyframes flash {
    0% { background-color: #ffe066; }
    100% { background-color: inherit; }
}
.chat-packet.flash { animation: flash 3.5s ease-out; }

.replying-to {
    font-size: 0.8em;
    color: #aaa;
    margin-top: 2px;
    padding-left: 10px;
}
.replying-to .reply-preview { color: #aaa; }
{% endblock %}

{% block body %}
<div id="chat-container" class="mt-3">

    <!-- ⭐ CHAT TITLE WITH ICON, aligned to container ⭐ -->
    <div class="container px-2">
        <h2 style="color:white; margin:0 0 10px 0;">
            <span class="icon">💬</span>
            <span data-translate="chat_title"></span>
        </h2>
    </div>

    <div class="container" id="chat-log"></div>
</div>

<script>
document.addEventListener("DOMContentLoaded", async () => {
    const chatContainer = document.querySelector("#chat-log");
    if (!chatContainer) return console.error("#chat-log not found");

    let lastTime = null;
    const renderedPacketIds = new Set();
    const packetMap = new Map();
    let chatLang = {};

    /* ==========================================================
       TRANSLATIONS FOR CHAT PAGE
       ========================================================== */
    function applyTranslations(dict, root=document) {
        root.querySelectorAll("[data-translate]").forEach(el => {
            const key = el.dataset.translate;
            const val = dict[key];
            if (!val) return;
            if (el.placeholder) el.placeholder = val;
            else el.textContent = val;
        });
    }

    async function loadChatLang() {
        try {
            const cfg = await window._siteConfigPromise;
            const langCode = cfg?.site?.language || "en";
            const res = await fetch(`/api/lang?lang=${langCode}&section=chat`);
            chatLang = await res.json();

            // Apply to existing DOM
            applyTranslations(chatLang);
        } catch (err) {
            console.error("Chat translation load failed:", err);
        }
    }

    /* ==========================================================
       SAFE HTML
       ========================================================== */
    function escapeHtml(text) {
        const div = document.createElement("div");
        div.textContent = text ?? "";
        return div.innerHTML;
    }

    /* ==========================================================
       RENDERING PACKETS
       ========================================================== */
    function renderPacket(packet, highlight = false) {
        if (renderedPacketIds.has(packet.id)) return;
        renderedPacketIds.add(packet.id);
        packetMap.set(packet.id, packet);

        let date;
        if (packet.import_time_us && packet.import_time_us > 0) {
            date = new Date(packet.import_time_us / 1000);
        } else if (packet.import_time) {
            date = new Date(packet.import_time);
        } else {
            date = new Date();
        }

        const formattedTime = date.toLocaleTimeString([], {
            hour:"numeric",
            minute:"2-digit",
            second:"2-digit",
            hour12:true
        });
        const formattedDate =
            `${(date.getMonth()+1).toString().padStart(2,"0")}/` +
            `${date.getDate().toString().padStart(2,"0")}/` +
            `${date.getFullYear()}`;

        const formattedTimestamp = `${formattedTime} - ${formattedDate}`;

        let replyHtml = "";
        if (packet.reply_id) {
            const parent = packetMap.get(packet.reply_id);
            const replyPrefix = `<i data-translate="replying_to"></i>`;
            if (parent) {
                replyHtml = `
                    <div class="replying-to">
                        ${replyPrefix}
                        <strong>${escapeHtml((parent.long_name || "").trim() || `Node ${parent.from_node_id}`)}</strong>:
                        ${escapeHtml(parent.payload || "")}
                    </div>`;
            } else {
                replyHtml = `
                    <div class="replying-to">
                        ${replyPrefix}
                        <a href="/packet/${packet.reply_id}">${packet.reply_id}</a>
                    </div>`;
            }
        }

        const div = document.createElement("div");
        div.className = "row chat-packet" + (highlight ? " flash" : "");
        div.dataset.packetId = packet.id;

        div.innerHTML = `
            <span class="col-2 timestamp" title="${packet.import_time_us}">
                ${formattedTimestamp}
            </span>

            <span class="col-2 channel">
                <a href="/packet/${packet.id}" title="${chatLang.view_packet_details || 'View details'}">🔎</a>
                ${escapeHtml(packet.channel || "")}
            </span>

            <span class="col-3 nodename">
                <a href="/node/${packet.from_node_id}">
                    ${escapeHtml((packet.long_name || "").trim() || `Node ${packet.from_node_id}`)}
                </a>
            </span>

            <span class="col-5 message">
                ${escapeHtml(packet.payload)}${replyHtml}
            </span>
        `;

        chatContainer.prepend(div);

        // Translate newly added DOM
        applyTranslations(chatLang, div);

        if (highlight) setTimeout(() => div.classList.remove("flash"), 2500);
    }

    function renderPacketsEnsureDescending(packets, highlight=false) {
        if (!Array.isArray(packets) || packets.length===0) return;
        const sortedDesc = packets.slice().sort((a,b)=>{
            const aTime = a.import_time_us || (new Date(a.import_time).getTime() * 1000);
            const bTime = b.import_time_us || (new Date(b.import_time).getTime() * 1000);
            return bTime - aTime;
        });
        for (let i=sortedDesc.length-1; i>=0; i--) {
            renderPacket(sortedDesc[i], highlight);
        }
    }

    /* ==========================================================
       FETCHING PACKETS
       ========================================================== */
    async function fetchInitial() {
        try {
            const resp = await fetch("/api/packets?portnum=1&limit=100");
            const data = await resp.json();
            if (data?.packets?.length) renderPacketsEnsureDescending(data.packets);
            lastTime = data?.latest_import_time || lastTime;
        } catch(err){
            console.error("Initial fetch error:", err);
        }
    }

    async function fetchUpdates() {
        try {
            const url = new URL("/api/packets?portnum=1", window.location.origin);
            url.searchParams.set("limit","100");
            if (lastTime) url.searchParams.set("since", lastTime);
            const resp = await fetch(url);
            const data = await resp.json();
            if (data?.packets?.length) renderPacketsEnsureDescending(data.packets, true);
            lastTime = data?.latest_import_time || lastTime;
        } catch(err){
            console.error("Fetch updates error:", err);
        }
    }

    /* ==========================================================
       INIT
       ========================================================== */
    await loadChatLang();     // load translations FIRST
    await fetchInitial();     // then fetch initial packets

    setInterval(fetchUpdates, 5000);
});
</script>

{% endblock %}
