function bindSidebarToggle() {
    const button = document.querySelector("[data-sidebar-toggle]");
    const sidebar = document.querySelector("[data-sidebar]");
    const overlay = document.querySelector("[data-sidebar-overlay]");
    
    if (!button || !sidebar) {
        return;
    }

    function openSidebar() {
        sidebar.classList.add("open");
        if (overlay) {
            overlay.classList.add("active");
        }
        button.classList.add("open");
    }

    function closeSidebar() {
        sidebar.classList.remove("open");
        if (overlay) {
            overlay.classList.remove("active");
        }
        button.classList.remove("open");
    }

    function toggleSidebar() {
        if (sidebar.classList.contains("open")) {
            closeSidebar();
        } else {
            openSidebar();
        }
    }

    button.addEventListener("click", toggleSidebar);
    
    if (overlay) {
        overlay.addEventListener("click", closeSidebar);
    }

    // Close sidebar on escape key
    document.addEventListener("keydown", (e) => {
        if (e.key === "Escape" && sidebar.classList.contains("open")) {
            closeSidebar();
        }
    });

    // Close sidebar when clicking a nav link on mobile
    const navLinks = document.querySelectorAll(".sidebar-nav .nav-link");
    navLinks.forEach(link => {
        link.addEventListener("click", () => {
            if (window.innerWidth <= 768) {
                closeSidebar();
            }
        });
    });
}

function renderDashboardChart() {
    const canvas = document.getElementById("dashboardChart");
    if (!canvas || typeof Chart === "undefined") {
        return;
    }

    const chartData = canvas.dataset.chart ? JSON.parse(canvas.dataset.chart) : [];
    if (!chartData || chartData.length === 0) {
        return;
    }

    const labels = chartData.map(item => {
        const date = new Date(item.label + "T00:00:00");
        return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
    });
    const values = chartData.map(item => item.value);

    const ctx = canvas.getContext("2d");
    new Chart(ctx, {
        type: "line",
        data: {
            labels: labels,
            datasets: [{
                label: "Registrations",
                data: values,
                borderColor: "#2c7da0",
                backgroundColor: "rgba(44, 125, 160, 0.1)",
                borderWidth: 3,
                fill: true,
                tension: 0.4,
                pointBackgroundColor: "#2c7da0",
                pointBorderColor: "#ffffff",
                pointBorderWidth: 2,
                pointRadius: 5,
                pointHoverRadius: 7,
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: "rgba(15, 23, 42, 0.9)",
                    titleFont: { size: 13, weight: "600" },
                    bodyFont: { size: 12 },
                    padding: 12,
                    cornerRadius: 8,
                    displayColors: false,
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        color: "#475569",
                        font: { size: 11, weight: "500" }
                    }
                },
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1,
                        color: "#475569",
                        font: { size: 11, weight: "500" }
                    },
                    grid: {
                        color: "rgba(0, 0, 0, 0.06)",
                        drawBorder: false
                    }
                }
            }
        }
    });
}

function bindEmailPageActions() {
    const fetchButton = document.getElementById("fetchUserButton");
    const sendButton = document.getElementById("sendEmailButton");
    const responseBox = document.getElementById("emailResponse");

    if (!fetchButton || !sendButton) {
        return;
    }

    let fetchedUserId = null;

    if (fetchButton) {
        fetchButton.addEventListener("click", async () => {
            const oldEmail = document.getElementById("oldEmail")?.value?.trim();
            if (!oldEmail) {
                showFlashMessage("Please enter an email address.", "error");
                return;
            }

            try {
                const params = new URLSearchParams({ old_email: oldEmail });
                const res = await fetch(`/admin/api/emails/user-lookup?${params}`);
                const data = await res.json();

                if (!res.ok || data.error) {
                    showFlashMessage(data.error || data.message || "User not found.", "error");
                    return;
                }

                fetchedUserId = data.user.id;
                sessionStorage.setItem("fetched_user_id", data.user.id);

                const userCard = document.getElementById("emailUserCard");
                const userName = document.getElementById("emailUserName");
                const userEmail = document.getElementById("emailUserExistingEmail");
                const userPhone = document.getElementById("emailUserPhone");
                const userImage = document.getElementById("emailUserImage");

                if (userCard) userCard.classList.remove("hidden");
                if (userName) userName.textContent = data.user.name || "N/A";
                if (userEmail) userEmail.textContent = data.user.email || "N/A";
                if (userPhone) userPhone.textContent = data.user.phone || "No phone";
                if (userImage) {
                    userImage.src = data.user.s3_image_url || data.user.image_url || "";
                    userImage.alt = `${data.user.name} preview`;
                }

                showFlashMessage("User found! You can now send the email.", "success");
            } catch (err) {
                console.error("Fetch user error:", err);
                showFlashMessage("Failed to fetch user. Please try again.", "error");
            }
        });
    }

    if (sendButton) {
        sendButton.addEventListener("click", async () => {
            const newEmail = document.getElementById("newEmail")?.value?.trim();
            const oldEmail = document.getElementById("oldEmail")?.value?.trim();

            if (!newEmail) {
                showFlashMessage("Please enter a new email address.", "error");
                return;
            }

            if (!fetchedUserId && !sessionStorage.getItem("fetched_user_id")) {
                showFlashMessage("Please fetch the user first before sending email.", "error");
                return;
            }

            if (!oldEmail) {
                showFlashMessage("Please enter the old email address.", "error");
                return;
            }

            if (responseBox) {
                responseBox.textContent = "Sending email...";
            }

            try {
                const res = await fetch("/admin/api/emails/send", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({
                        old_email: oldEmail,
                        new_email: newEmail
                    })
                });

                const data = await res.json();

                if (!res.ok || data.error) {
                    if (responseBox) {
                        responseBox.textContent = `Error: ${data.error || "Failed to send email"}`;
                    }
                    showFlashMessage(data.error || "Failed to send email.", "error");
                    return;
                }

                if (responseBox) {
                    responseBox.textContent = `Success! Email sent to ${newEmail}\nUser ID: ${data.user_id}\nLogged images: ${data.logged_images}`;
                }
                showFlashMessage(`Email sent successfully to ${newEmail}!`, "success");

                document.getElementById("newEmail").value = "";
            } catch (err) {
                console.error("Send email error:", err);
                if (responseBox) {
                    responseBox.textContent = "Error: Failed to send email. Please try again.";
                }
                showFlashMessage("Failed to send email. Please try again.", "error");
            }
        });
    }
}

function bindTriggerPageActions() {
    const triggerButton = document.getElementById("runTriggerButton");
    const outputBox = document.getElementById("triggerResponse");

    if (!triggerButton) {
        return;
    }

    let statusCheckInterval = null;
    let isProcessing = false;

    // Function to check status
    async function checkStatus() {
        if (isProcessing) return;
        
        try {
            const res = await fetch("/admin/api/trigger/status");

            if (!res.ok) {
                throw new Error(`API returned ${res.status}`);
            }

            const data = await res.json();

            if (!data || !data.status) {
                throw new Error("Invalid response format");
            }

            let text = "";

            if (data.status === "idle") {
                text = "Idle.";
                triggerButton.disabled = false;
                triggerButton.style.opacity = "1";
                triggerButton.style.cursor = "pointer";
            }
            else if (data.status === "running") {
                text = "⏳ Processing... Please wait.\nJob is running in the background.";
                triggerButton.disabled = true;
                triggerButton.style.opacity = "0.6";
                triggerButton.style.cursor = "not-allowed";
            }
            else if (data.status === "completed") {
                text = "✅ Completed\n\n";

                // Safely extract result data
                const result = data.result || {};
                
                if (result.message) {
                    text += result.message + "\n";
                }
                if (result.emails_sent !== undefined) {
                    text += `Emails sent: ${result.emails_sent}\n`;
                }
                if (result.delivery_summary && Object.keys(result.delivery_summary).length > 0) {
                    text += `\nDetails:\n${JSON.stringify(result.delivery_summary, null, 2)}`;
                }
                if (!result.message && !result.emails_sent) {
                    text += JSON.stringify(result, null, 2);
                }

                triggerButton.disabled = false;
                triggerButton.style.opacity = "1";
                triggerButton.style.cursor = "pointer";

                // Stop polling on completion
                if (statusCheckInterval) {
                    clearInterval(statusCheckInterval);
                    statusCheckInterval = null;
                }

                showFlashMessage("Pipeline completed successfully!", "success");
            }
            else if (data.status === "failed") {
                text = "❌ Failed\n\n";

                // Safely extract error details
                const result = data.result || {};
                
                if (result.error) {
                    text += result.error;
                } else if (result.message) {
                    text += result.message;
                } else if (typeof result === "string") {
                    text += result;
                } else {
                    text += "Unknown error occurred. Check server logs for details.";
                }

                triggerButton.disabled = false;
                triggerButton.style.opacity = "1";
                triggerButton.style.cursor = "pointer";

                // Stop polling on failure
                if (statusCheckInterval) {
                    clearInterval(statusCheckInterval);
                    statusCheckInterval = null;
                }

                showFlashMessage("Pipeline failed. Check output for details.", "error");
            }
            else {
                text = `Unknown status: ${data.status}`;
            }

            if (outputBox) {
                outputBox.textContent = text;
            }

        } catch (err) {
            console.error("Status check error:", err);
            if (outputBox) {
                outputBox.textContent = "⚠️ Unable to fetch status. Please refresh or try again.";
            }
        }
    }

    // Check status on page load
    checkStatus();

    // Start polling every 3 seconds
    statusCheckInterval = setInterval(checkStatus, 3000);

    // Button click handler
    triggerButton.addEventListener("click", async () => {
        if (outputBox) {
            outputBox.textContent = "🚀 Starting process...";
        }

        isProcessing = true;
        triggerButton.disabled = true;
        triggerButton.style.opacity = "0.6";
        triggerButton.style.cursor = "not-allowed";

        try {
            const res = await fetch("/admin/api/trigger/run", {
                method: "POST",
                headers: { "Content-Type": "application/json" }
            });

            const data = await res.json();

            if (!res.ok || data.status === "error") {
                if (outputBox) {
                    outputBox.textContent = `❌ Error: ${data.message || "Failed to start job"}`;
                }
                showFlashMessage(data.message || "Failed to start trigger job.", "error");
                triggerButton.disabled = false;
                triggerButton.style.opacity = "1";
                triggerButton.style.cursor = "pointer";
                isProcessing = false;
                return;
            }

            // Job started - status polling will update
            if (outputBox) {
                outputBox.textContent = `🚀 Job #${data.job_id} started.\nProcessing...`;
            }
            showFlashMessage("Trigger job started!", "success");
            isProcessing = false;

            // Immediately check status
            setTimeout(checkStatus, 500);

        } catch (err) {
            console.error("Trigger error:", err);
            if (outputBox) {
                outputBox.textContent = "❌ Error: Request failed. Please try again.";
            }
            showFlashMessage("Failed to run pipeline. Please try again.", "error");
            triggerButton.disabled = false;
            triggerButton.style.opacity = "1";
            triggerButton.style.cursor = "pointer";
            isProcessing = false;
        }
    });
}

function showFlashMessage(message, type = "success") {
    const container = document.querySelector(".flash-container");
    if (!container) {
        const newContainer = document.createElement("div");
        newContainer.className = "flash-container";
        document.querySelector(".admin-main").prepend(newContainer);
    }

    const flash = document.createElement("div");
    flash.className = `flash ${type}`;
    flash.innerHTML = `
        ${message}
        <button class="flash-close" onclick="this.parentElement.remove()">&times;</button>
    `;

    const flashContainer = document.querySelector(".flash-container");
    flashContainer.appendChild(flash);

    setTimeout(() => {
        flash.classList.add("removing");
        setTimeout(() => flash.remove(), 300);
    }, 5000);
}

document.addEventListener("DOMContentLoaded", () => {
    bindSidebarToggle();
    renderDashboardChart();
    bindEmailPageActions();
    bindTriggerPageActions();
});
