document.addEventListener("DOMContentLoaded", function() {

document.querySelectorAll(".program-link").forEach(link => {
    let userID = link.dataset.userid;
    let templateURL = link.dataset.template;
    
    if (userID && templateURL) {
        link.href = templateURL.replace('{{USER_ID}}', userID);
    }
});


    console.log("Document is fully loaded!");

    var startButton = document.getElementById("startButton");
    var splashScreen = document.getElementById("splash-screen");
    var wizardContainer = document.getElementById("wizard-container");

    if (!startButton) {
        console.error("Start button not found!");
        return;
    }

    startButton.addEventListener("click", function() {
        console.log("Start button clicked!");
        splashScreen.style.display = "none";
        wizardContainer.style.display = "block";
        loadStep(1);
    });

    // ✅ Ensure Front-End Copy Button Works
    setTimeout(function() {
        var copyButton = document.getElementById("copyButton");
        if (copyButton) {
            console.log("✅ Front-End Copy Button found! Adding event listener...");
            copyButton.addEventListener("click", function() {
                console.log("✅ Front-End Copy Button clicked!");
                copyReferralLink();
            });
        } else {
            console.error("❌ Front-End Copy Button NOT found!");
        }
    }, 1000); // Wait 1 second for button to appear

    // ✅ Ensure Back-End Copy Button Works (edit.php)
if (window.location.pathname.includes("edit.php")) {
    setTimeout(function() {
        var editCopyButton = document.getElementById("editCopyButton");

        if (editCopyButton) {
            console.log("✅ Edit Copy Button found! Adding event listener...");
            editCopyButton.addEventListener("click", function() {
                console.log("✅ Edit Copy Button clicked!");
                copyEditReferralLink();
            });
        } else {
            console.log("ℹ️ Edit Copy Button not found (normal if not on edit.php).");
        }
    }, 1500);
}

});

// ✅ Function to Load Steps
function loadStep(step, retries = 3) {
    let params = new URLSearchParams(window.location.search);
    let ref = params.get("ref") || "";

    fetch("scripts/fetchPrograms.php?step=" + step + (ref ? "&ref=" + ref : ""), { cache: "no-store" })
        .then(response => {
            if (!response.ok) throw new Error("HTTP error! Status: " + response.status);
            return response.text();
        })
        .then(html => {
            console.log("Processed HTML response:", html);

            if (!html.trim()) {
                console.error("Error: Empty response from fetchPrograms.php");
                document.getElementById("step-content").innerHTML = "<p style='color:red;'>Error loading content.</p>";
                return;
            }

            document.getElementById("step-content").innerHTML = html;
            attachSaveEvent(); // Attach event to new buttons

            // ✅ Preload the next step in advance
            let nextStep = step + 1;
            fetch("scripts/fetchPrograms.php?step=" + nextStep, { cache: "no-store" })
                .then(response => response.text())
                .then(html => {
                    sessionStorage.setItem("step_" + nextStep, html); // ✅ Cache next step in advance
                    console.log(`✅ Preloaded Step ${nextStep}`);
                })
                .catch(error => console.error(`❌ Failed to preload Step ${nextStep}:`, error));
        })
        .catch(error => {
            if (retries > 0) {
                console.warn(`Retrying fetchPrograms.php (Attempts left: ${retries})...`);
                setTimeout(() => loadStep(step, retries - 1), 2000); // Retry after 2 seconds
            } else {
                console.error("AJAX error after multiple attempts:", error);
                document.getElementById("step-content").innerHTML = "<p style='color:red;'>AJAX request failed. Please try again.</p>";
            }
        });
}

// ✅ Function to Save User ID
function saveUserID(step) {
    var userIDField = document.getElementById("referral-" + step);
    if (!userIDField) {
        console.error("User ID input field not found for step:", step);
        return;
    }

    var userID = userIDField.value.trim();
    if (!userID) {
        alert("Please enter your referral ID before continuing.");
        return;
    }

    let params = new URLSearchParams(window.location.search);
    let ref = params.get("ref") || "";

var button = document.querySelector(".save-user-id[data-step='" + step + "']");
if (button) {
    button.disabled = true; // ✅ Disable button
    button.innerText = "Saving..."; // ✅ Show status
    button.style.opacity = "0.5"; // 🔥 Force opacity
    button.style.cursor = "not-allowed"; // 🔥 Prevent interaction
}


    fetch("scripts/fetchPrograms.php?ref=" + ref, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ step: step, user_id: userID })
    })
    .then(response => response.json())
    .then(data => {
        console.log("Save response:", data);
        if (data.success) {
            loadStep(step + 1); // Move to next step
        } else {
            alert("Failed to save. Try again.");
        }
    })
    .catch(error => console.error("Error:", error))
    .finally(() => {
        if (button) {
            button.disabled = false; // ✅ Re-enable button after request finishes
        }
    });
}

// ✅ Attach Event to Save Buttons
function attachSaveEvent() {
    document.querySelectorAll(".save-user-id").forEach(button => {
        button.addEventListener("click", function() {
            var step = this.dataset.step;
            saveUserID(step);
        });
    });
}

// ✅ Function to Copy Referral Link (Front-End)
function copyReferralLink() {
    var copyText = document.getElementById("referralLink");

    if (!copyText) {
        console.error("❌ Front-End Referral link input not found!");
        return;
    }

    navigator.clipboard.writeText(copyText.value).then(() => {
        console.log("✅ Front-End Text copied: " + copyText.value);
        showCopySuccess();
    }).catch(err => {
        console.error("❌ Clipboard API failed (Front-End):", err);
        fallbackCopyText(copyText);
    });
}

// ✅ Function to Copy Referral Link (Back-End `edit.php`)
function copyEditReferralLink() {
    var copyText = document.getElementById("editReferralLink");

    if (!copyText) {
        console.error("❌ Edit Referral link input not found!");
        return;
    }

    navigator.clipboard.writeText(copyText.value).then(() => {
        console.log("✅ Back-End Text copied: " + copyText.value);
        showCopySuccess();
    }).catch(err => {
        console.error("❌ Clipboard API failed (Back-End):", err);
        fallbackCopyText(copyText);
    });
}

// ✅ Fallback for Unsupported Browsers
function fallbackCopyText(input) {
    input.select();
    document.execCommand("copy");
    showCopySuccess();
}

// ✅ Show "Copied!" Message
function showCopySuccess() {
    var copyMessage = document.getElementById("copySuccess");
    if (copyMessage) {
        copyMessage.style.display = "block";
        copyMessage.innerText = "Copied to clipboard!";
        setTimeout(() => { copyMessage.style.display = "none"; }, 2000);
    }
}
