// ==============================
// STABLE DEVICE ID
// ==============================
async function getDeviceId() {

    return new Promise((resolve, reject) => {

        chrome.runtime.sendMessage(
            { action: "GET_MACHINE_ID" },

            (response) => {

                console.log("Driver Response:", response);
                console.log("Last Error:", chrome.runtime.lastError);

                if (chrome.runtime.lastError) {
                    reject(chrome.runtime.lastError.message);
                    return;
                }

if (!response) {

    reject({
        type: "driver_not_running",
        message: "Driver not running"
    });

    return;

}

if (!response.ok) {

    reject({
        type: response.type,
        message: response.error
    });

    return;

}

                resolve(response.machine_id);

            }

        );

    });

}

// ==============================
// PAGE LOAD
// ==============================
document.addEventListener("DOMContentLoaded", async () => {

    const activateBox = document.getElementById("activateBox");
    const openBox = document.getElementById("openBox");

    const activateBtn = document.getElementById("activateBtn");
    const openBtn = document.getElementById("openBtn");

    // Already Activated?
let saved = await chrome.storage.local.get([
    "activated",
    "email",
    "license",
    "plan",
    "expiry"
]);

if (saved.activated) {

    activateBox.style.display = "none";
    openBox.style.display = "block";

    const now = new Date();
    const expiry = new Date(saved.expiry.replace(" ", "T"));

let diff = Math.floor(
    (expiry - now) / (1000 * 60 * 60 * 24)
);

    if (diff < 0) diff = 0;

const remaining = document.getElementById("remainingDays");

if (diff <= 0) {

    remaining.innerHTML = "❌ Expired";
    remaining.style.color = "#ff4d4d";

} else if (diff === 1) {

    remaining.innerHTML = "🔴 Expires Tomorrow";
    remaining.style.color = "#ff4d4d";

} else if (diff <= 5) {

    remaining.innerHTML = "🟠 " + diff + " Days Left";
    remaining.style.color = "#ff9800";

} else {

    remaining.innerHTML = "🟢 " + diff + " Days Left";
    remaining.style.color = "#00e676";

}

let formatted = expiry.toLocaleString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    hour12: true
});

formatted = formatted.replace(",", " •");

document.getElementById("expiryDate").innerText = formatted;

}

    // ==========================
    // ACTIVATE LICENSE
    // ==========================
    activateBtn.addEventListener("click", async () => {

let license = document.getElementById("license").value.trim();

if (!license) {

    alert("Enter License Key");

    return;

}

       let deviceId;

try {

    deviceId = await getDeviceId();

} catch (err) {

    switch (err.type) {

        case "driver_not_installed":

            if (confirm(
                "⚠️ Tatkal Safer Driver is not installed.\n\n" +
                "Please download and install Tatkal Safer Driver.\n\n" +
                "Click OK to open download page."
            )) {

                chrome.tabs.create({
                    url: "https://tatkalsafer.xyz/"
                });

            }

            return;

        case "driver_not_running":

            alert(
                "⚠️ Tatkal Safer Driver is installed but not running.\n\n" +
                "Please start the driver and try again."
            );

            return;

        default:

            alert(
                "⚠️ Driver Error\n\n" +
                err.message
            );

            return;

    }

}

        try {

            let response = await fetch(

"http://localhost/tatkal_safer/api/check-license.php?license="
+ encodeURIComponent(license)
+ "&device_id="
+ encodeURIComponent(deviceId)

            );

let data = await response.json();


console.log(data);

if (data.status === "active") {

await chrome.storage.local.set({

    activated: true,

    license: license,

    plan: data.plan,

    expiry: data.expiry

});

document.getElementById("activateBox").style.display = "none";

document.getElementById("openBox").style.display = "block";
const now = new Date();
const expiry = new Date(data.expiry.replace(" ", "T"));

let diff = Math.floor(
    (expiry - now) / (1000 * 60 * 60 * 24)
);

if (diff < 0) diff = 0;
const remaining = document.getElementById("remainingDays");

if (diff <= 0) {

    remaining.innerHTML = "❌ Expired";
    remaining.style.color = "#ff4d4d";

} else if (diff === 1) {

    remaining.innerHTML = "🔴 Expires Tomorrow";
    remaining.style.color = "#ff4d4d";

} else if (diff <= 5) {

    remaining.innerHTML = "🟠 " + diff + " Days Left";
    remaining.style.color = "#ff9800";

} else {

    remaining.innerHTML = "🟢 " + diff + " Days Left";
    remaining.style.color = "#00e676";

}

let formatted = expiry.toLocaleString("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    hour12: true
});

formatted = formatted.replace(",", " •");

document.getElementById("expiryDate").innerText = formatted;

alert("✅ License Activated Successfully");

return;
}

if (data.status === "expired") {

    alert("❌ License Expired");

    return;

}

if (data.status === "invalid_license") {

    alert("❌ Invalid License");

    return;

}

if (data.status === "device_mismatch") {

    alert("❌ License already active on another device");

    return;

}

alert("Activation Failed");

        } catch (e) {

            console.log(e);

            alert(
    "⚠️ Server connection failed.\n\n" +
    "Please check your internet connection and try again."
);

        }

    });

    // ==========================
    // OPEN EXTENSION
    // ==========================
    openBtn.addEventListener("click", () => {

        chrome.windows.getCurrent((win) => {

            chrome.tabs.create({

                windowId: win.id,

                url: chrome.runtime.getURL("dashboard.html")

            });

        });

    });

});


const logoutBtn = document.getElementById("logoutBtn");

logoutBtn?.addEventListener("click", async () => {

    if (!confirm("Logout this license?")) {

        return;

    }

    await chrome.storage.local.remove([

        "activated",

        "email",

        "license",

        "plan",

        "expiry"

    ]);

    location.reload();

});