{% extends "base.html" %}

{% block css %}
.timestamp {
    min-width: 10em;
}
.chat-packet:nth-of-type(odd) {
    background-color: #3a3a3a;
}
.chat-packet {
    border-bottom: 1px solid #555;
    padding: 8px;
    border-radius: 8px;
}
.chat-packet:nth-of-type(even) {
    background-color: #333333;
}
@keyframes flash {
    0% { background-color: #ffe066; }
    100% { background-color: inherit; }
}
.chat-packet.flash {
    animation: flash 3.5s ease-out;
}

/* New CSS for smaller Replying to text */
.replying-to {
    font-size: 0.85em;
    color: #ccc;
}
{% endblock %}

{% block body %}
<div id="chat-container">
    <div class="container" id="chat-log">
        {% for packet in packets %}
        <div
            class="row chat-packet"
            data-packet-id="{{ packet.id }}"
            role="article"
            aria-label="Chat message from {{ packet.from_node.long_name or (packet.from_node_id | node_id_to_hex) }}"
        >
            <span class="col-2 timestamp" title="{{ packet.import_time.isoformat() }}">
                {{ packet.import_time.strftime('%-I:%M:%S %p - %m/%d/%Y') }}
            </span>
            <span class="col-2 channel">
                <a href="/packet/{{ packet.id }}" title="View packet details">✉️</a>
                {{ packet.from_node.channel }}
            </span>
            <span class="col-3 username">
                <a href="/packet_list/{{ packet.from_node_id }}" title="View all packets from this node">
                    {{ packet.from_node.long_name or (packet.from_node_id | node_id_to_hex) }}
                </a>
            </span>
            <span class="col-5 message">
                {{ packet.payload }}
                {% if packet.raw_mesh_packet.decoded.reply_id %}
                <span class="replying-to">
                    (Replying to: <a href="/packet/{{ packet.raw_mesh_packet.decoded.reply_id }}">{{ packet.raw_mesh_packet.decoded.reply_id }}</a>)
                </span>
                {% endif %}
            </span>
        </div>
        {% else %}
        <p class="text-muted">No packets found.</p>
        {% endfor %}
    </div>
</div>

<script>
let lastTime = null;
const chatContainer = document.querySelector("#chat-log");

// Initialize lastTime from DOM
const firstPacket = chatContainer.querySelector(".chat-packet");
if (firstPacket) {
    lastTime = firstPacket.querySelector(".timestamp")?.getAttribute("title");
}

// Track rendered packet IDs
const renderedPacketIds = new Set();
document.querySelectorAll(".chat-packet").forEach(div => {
    const id = div.dataset.packetId;
    if (id) renderedPacketIds.add(id);
});

function escapeHtml(text) {
    const div = document.createElement("div");
    div.textContent = text;
    return div.innerHTML;
}

async function fetchUpdates() {
    try {
        const url = new URL("/chat/updates", window.location.origin);
        if (lastTime) {
            url.searchParams.set("last_time", lastTime);
        }

        const response = await fetch(url);
        const data = await response.json();

        if (data.packets && data.packets.length > 0) {
            for (const packet of data.packets) {
                if (renderedPacketIds.has(packet.id)) continue;
                renderedPacketIds.add(packet.id);

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

                const date = new Date(packet.import_time);
                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}`;

                div.innerHTML = `
                    <span class="col-2 timestamp" title="${packet.import_time}">
                        ${formattedTimestamp}
                    </span>
                    <span class="col-2 channel">
                        <a href="/packet/${packet.id}" title="View packet details">✉️</a> ${packet.channel}
                    </span>
                    <span class="col-3 username">
                        <a href="/packet_list/${packet.from_node_id}" title="View all packets from this node">
                            ${packet.long_name || (packet.from_node_id || '').toString(16)}
                        </a>
                    </span>
                    <span class="col-5 message">
                        ${escapeHtml(packet.payload)}
                        ${packet.reply_id
                            ? `<span class="replying-to">(Replying to: <a href="/packet/${packet.reply_id}">${packet.reply_id}</a>)</span>`
                            : ''}
                    </span>
                `;

                chatContainer.prepend(div);
                setTimeout(() => div.classList.remove("flash"), 2500);
            }
        }

        if (data.latest_import_time) {
            lastTime = data.latest_import_time;
        }
    } catch (err) {
        console.error("Fetch error:", err);
    }
}

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