console.log("🔥 Background Script Running");

// ==============================
// 🚀 START BOOKING (FIXED)
// ==============================

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {

  if (message.action === "START_BOOKING") {

    console.log("🚆 Opening IRCTC (New Tab)...");

    // 🔥 SAME WINDOW (INCOGNITO SAFE FIX)
    chrome.windows.getCurrent((win) => {

      chrome.tabs.create({
        windowId: win.id, // ✅ FIXED (no jump)
        url: "https://www.irctc.co.in/nget/train-search",
        active: true
      }, (tab) => {

        // ✅ WAIT FOR FULL LOAD
        chrome.tabs.onUpdated.addListener(function listener(tabId, info) {

          if (tabId === tab.id && info.status === "complete") {

            console.log("✅ Page Loaded → Injecting Script");

            chrome.scripting.executeScript({
              target: { tabId: tab.id },
              files: [ "statuspanel.js","mycontrol.js"]
            });

            chrome.tabs.onUpdated.removeListener(listener);
          }

        });

      });

    });

    sendResponse({ status: "started" });
    return true;
  }

});


// ==============================
// ✅ ON INSTALL
// ==============================

chrome.runtime.onInstalled.addListener(() => {
  console.log("✅ Extension Installed Successfully");
});

// ==============================
// NATIVE DRIVER
// ==============================
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {

  if (message.action !== "GET_MACHINE_ID")
    return;

  chrome.runtime.sendNativeMessage(
    "com.tatkalsafer.driver",
    {
      action: "machine_id"
    },
    (response) => {
      

if (chrome.runtime.lastError) {

    const err = chrome.runtime.lastError.message.toLowerCase();

    if (
        err.includes("specified native messaging host not found") ||
        err.includes("native messaging host not found")
    ) {

        sendResponse({
            ok: false,
            type: "driver_not_installed",
            error: "Tatkal Safer Driver is not installed."
        });

        return;
    }

    if (
        err.includes("native host has exited") ||
        err.includes("failed to start native host") ||
        err.includes("could not establish connection")
    ) {

        sendResponse({
            ok: false,
            type: "driver_not_running",
            error: "Tatkal Safer Driver is installed but not running."
        });

        return;
    }

    sendResponse({
        ok: false,
        type: "driver_error",
        error: chrome.runtime.lastError.message
    });

    return;
}

      sendResponse({
        ok: true,
        machine_id: response.machine_id
      });

    });

  return true;

});