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: ["mycontrol.js"]
            });

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

        });

      });

    });

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

});


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

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