function formatUptime(seconds) {
    if (seconds < 0) return "0s";

    const days = Math.floor(seconds / (3600 * 24));
    const hours = Math.floor((seconds % (3600 * 24)) / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);

    const parts = [];
    if (days > 0) parts.push(`${days}d`);
    if (hours > 0) parts.push(`${hours}h`);
    if (minutes > 0) parts.push(`${minutes}m`);
    parts.push(`${secs}s`);

    return parts.join(" ");
}

function updateUptime() {
    const elements = document.querySelectorAll(".uptime-display, #uptime-display");
    elements.forEach(el => {
        const startTimestamp = parseInt(el.getAttribute("data-start-timestamp"), 10);
        if (isNaN(startTimestamp)) return;

        const now = Date.now();
        const elapsedSeconds = (now - startTimestamp) / 1000;

        el.textContent = formatUptime(elapsedSeconds);
    });
}

document.addEventListener("DOMContentLoaded", () => {
    // Initialize Lucide Icons
    if (window.lucide) {
        window.lucide.createIcons();
    }

    // Update immediately to prevent stale content flash if possible
    updateUptime();
    // Update every second
    setInterval(updateUptime, 1000);

    // WebSocket Connection
    const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
    const wsUrl = `${protocol}//${window.location.host}/ws`;

    function connectWs() {
        const ws = new WebSocket(wsUrl);
        const statusIndicator = document.querySelector(".status-indicator");

        ws.onopen = () => {
            console.log("WS Connected");
            if (statusIndicator) statusIndicator.classList.add("online");
        };

        ws.onmessage = (event) => {
            try {
                const msg = JSON.parse(event.data);
                if (msg.type === "HEARTBEAT") {
                    updateVitals(msg.data);
                } else if (msg.type === "WELCOME") {
                    console.log(msg.message);
                } else if (msg.type === "LOG") {
                    appendToActivityFeed(msg.data);
                }
            } catch (e) {
                console.error("WS Parse Error", e);
            }
        };

        function updateVitals(data) {
            // Update Stats
            if (data.guildCount !== undefined) {
                const el = document.getElementById("stat-servers");
                if (el) el.textContent = data.guildCount;
            }
            if (data.userCount !== undefined) {
                const el = document.getElementById("stat-users");
                if (el) el.textContent = data.userCount;
            }
            if (data.commandCount !== undefined) {
                const el = document.getElementById("stat-commands");
                if (el) el.textContent = data.commandCount;
            }
            if (data.ping !== undefined) {
                const el = document.getElementById("stat-ping");
                if (el) el.textContent = `${data.ping < 0 ? "?" : data.ping}ms`;

                const trend = document.getElementById("stat-ping-trend");
                if (trend) {
                    trend.className = `stat-trend ${data.ping < 100 ? "up" : "down"}`;
                    const icon = trend.querySelector('i');
                    if (icon) {
                        icon.setAttribute('data-lucide', data.ping < 100 ? "check-circle" : "alert-circle");
                        if (window.lucide) window.lucide.createIcons();
                    }
                    const text = trend.querySelector('span');
                    if (text) text.textContent = data.ping < 100 ? "Excellent" : "Decent";
                }
            }

            // Update System Health
            if (data.memory !== undefined) {
                const el = document.getElementById("stat-memory");
                if (el && data.memoryTotal) {
                    el.textContent = `${data.memory} / ${data.memoryTotal} MB`;
                } else if (el) {
                    el.textContent = `${data.memory} MB`;
                }

                const bar = document.getElementById("stat-memory-bar");
                if (bar && data.memoryTotal) {
                    const percent = Math.min(100, (data.memory / data.memoryTotal) * 100);
                    bar.style.width = `${percent}%`;
                }
            }

            if (data.uptime !== undefined) {
                // We handle uptime fluidly in updateUptime() using data-start-timestamp.
                // We just ensure the attribute is kept in sync if needed (though startTimestamp shouldn't change).
                const elements = document.querySelectorAll(".uptime-display, #uptime-display");
                elements.forEach(el => {
                    const currentStart = parseInt(el.getAttribute("data-start-timestamp"), 10);
                    const newStart = Math.floor(Date.now() - (data.uptime * 1000));
                    // Only update if there's a significant drift (> 5s)
                    if (isNaN(currentStart) || Math.abs(currentStart - newStart) > 5000) {
                        el.setAttribute("data-start-timestamp", newStart);
                    }
                });
            }
        }

        function appendToActivityFeed(log) {
            const list = document.querySelector(".activity-feed");
            if (!list) return;

            const item = document.createElement("li");
            item.className = "activity-item";

            const timeSpan = document.createElement("span");
            timeSpan.className = "time";
            timeSpan.textContent = log.timestamp;

            const messageSpan = document.createElement("span");
            messageSpan.className = "message";
            messageSpan.textContent = log.message;

            item.appendChild(timeSpan);
            item.appendChild(messageSpan);

            // Prepend
            list.insertBefore(item, list.firstChild);
            if (list.children.length > 50) list.lastChild.remove();
        }

        ws.onclose = () => {
            console.log("WS Disconnected");
            if (statusIndicator) statusIndicator.classList.remove("online");
            // Retry in 5s
            setTimeout(connectWs, 5000);
        };

        ws.onerror = (err) => {
            console.error("WS Error", err);
            ws.close();
        };
    }

    // Action Buttons
    document.querySelectorAll(".btn[data-action]").forEach(btn => {
        btn.addEventListener("click", async () => {
            const action = btn.getAttribute("data-action");
            const actionName = btn.textContent.trim();

            if (action === "restart_bot") {
                if (!confirm("Are you sure you want to restart the bot? This will cause a brief downtime.")) {
                    return;
                }
            }

            btn.disabled = true;
            const originalText = btn.textContent;
            btn.textContent = "Processing...";

            try {
                const response = await fetch("/api/actions", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ action })
                });

                const result = await response.json();
                if (result.success) {
                    alert(`${actionName} successful: ${result.message}`);
                    if (action === "restart_bot") {
                        btn.textContent = "Restarting...";
                        setTimeout(() => window.location.reload(), 5000);
                    } else {
                        btn.disabled = false;
                        btn.textContent = originalText;
                    }
                } else {
                    alert(`Error: ${result.error}`);
                    btn.disabled = false;
                    btn.textContent = originalText;
                }
            } catch (err) {
                console.error("Action error:", err);
                alert("Failed to execute action. Check console.");
                btn.disabled = false;
                btn.textContent = originalText;
            }
        });
    });

    connectWs();
});
