/**
 * PI FYAD — Client-side utilities
 */

(function () {
    "use strict";

    /**
     * Copy clipboard export text to system clipboard.
     */
    window.copyClipboard = function () {
        const textarea = document.getElementById("clipboard-export");
        if (!textarea) return;

        textarea.select();
        textarea.setSelectionRange(0, textarea.value.length);

        navigator.clipboard
            .writeText(textarea.value)
            .then(function () {
                showToast("Copied to clipboard!", "success");
            })
            .catch(function () {
                // Fallback: execCommand
                try {
                    document.execCommand("copy");
                    showToast("Copied to clipboard!", "success");
                } catch (e) {
                    showToast("Failed to copy. Please select and copy manually.", "danger");
                }
            });
    };

    /**
     * Show a Bootstrap toast notification.
     */
    function showToast(message, type) {
        type = type || "info";

        var container = document.getElementById("pi-toast-container");
        if (!container) {
            container = document.createElement("div");
            container.id = "pi-toast-container";
            container.className = "toast-container position-fixed bottom-0 end-0 p-3";
            container.style.zIndex = "1100";
            document.body.appendChild(container);
        }

        var toastEl = document.createElement("div");
        toastEl.className = "toast align-items-center text-bg-" + type + " border-0";
        toastEl.setAttribute("role", "alert");
        toastEl.innerHTML =
            '<div class="d-flex">' +
            '<div class="toast-body">' + escapeHtml(message) + "</div>" +
            '<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>' +
            "</div>";

        container.appendChild(toastEl);

        var toast = new bootstrap.Toast(toastEl, { delay: 3000 });
        toast.show();

        toastEl.addEventListener("hidden.bs.toast", function () {
            toastEl.remove();
        });
    }

    /**
     * Auto-refresh extractor countdowns every 60 seconds.
     */
    function initExtractorCountdowns() {
        var countdownEls = document.querySelectorAll("[data-expiry]");
        if (countdownEls.length === 0) return;

        setInterval(function () {
            countdownEls.forEach(function (el) {
                var expiry = new Date(el.dataset.expiry);
                var now = new Date();
                var diff = expiry - now;

                if (diff <= 0) {
                    el.textContent = "Expired";
                    el.className = "text-danger";
                    return;
                }

                var days = Math.floor(diff / 86400000);
                var hours = Math.floor((diff % 86400000) / 3600000);
                var minutes = Math.floor((diff % 3600000) / 60000);

                var parts = [];
                if (days > 0) parts.push(days + "d");
                if (hours > 0) parts.push(hours + "h");
                if (minutes > 0) parts.push(minutes + "m");

                el.textContent = parts.join(" ") || "<1m";
            });
        }, 60000);
    }

    /**
     * AJAX clipboard export for template detail page.
     */
    window.exportTemplateClipboard = function (templateId) {
        var csrfToken = document.querySelector("[name=csrfmiddlewaretoken]");
        var token = csrfToken ? csrfToken.value : "";

        fetch("/pi/templates/" + templateId + "/clipboard/", {
            method: "POST",
            headers: {
                "X-CSRFToken": token,
                "Content-Type": "application/json",
            },
        })
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {
                if (data.clipboard) {
                    navigator.clipboard
                        .writeText(data.clipboard)
                        .then(function () {
                            showToast("Template copied to clipboard!", "success");
                        })
                        .catch(function () {
                            // Fallback: put in textarea
                            var textarea = document.getElementById("clipboard-export");
                            if (textarea) {
                                textarea.value = data.clipboard;
                                showToast("Template loaded — copy from the text area.", "info");
                            }
                        });
                }
            })
            .catch(function () {
                showToast("Failed to export template.", "danger");
            });
    };

    /**
     * Escape HTML entities for safe insertion.
     */
    function escapeHtml(str) {
        var div = document.createElement("div");
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    }

    // Initialize on DOM ready
    document.addEventListener("DOMContentLoaded", function () {
        initExtractorCountdowns();
    });
})();
