

// ======================
// 🛡️ STABILITY SYSTEM
// ======================

window.APP_SAFE = {

  started: false,
  bookingRunning: false,
  paymentRunning: false,
  captchaRunning: false,

  intervals: [],

  errors: 0

};

function addSafeInterval(fn, delay = 500) {

  let id = setInterval(async () => {

    try {

      await fn();

    } catch (e) {

      APP_SAFE.errors++;

      console.log("❌ Interval Error:", e);

    }

  }, delay);

  APP_SAFE.intervals.push(id);

  return id;
}

function clearAllIntervals() {

  APP_SAFE.intervals.forEach(clearInterval);

  APP_SAFE.intervals = [];

}

window.addEventListener("error", (e) => {

  APP_SAFE.errors++;

  console.log("❌ GLOBAL ERROR:", e.message);

});

window.addEventListener("unhandledrejection", (e) => {

  APP_SAFE.errors++;

  console.log("❌ PROMISE ERROR:", e.reason);

});

console.log("🛡️ Stability Loaded");




// captcha popup show final

function showWLPopup(wlText = "WL") {

  if (document.getElementById("wl-popup")) return;

  let overlay = document.createElement("div");
  overlay.id = "wl-popup";

  overlay.innerHTML = `
    <div style="
      position:fixed;
      top:0;
      left:0;
      width:100%;
      height:100%;
      background:rgba(0,0,0,0.6);
      display:flex;
      align-items:center;
      justify-content:center;
      z-index:999999;
    ">
      <div style="
        width:320px;
        background:#111;
        color:#fff;
        padding:20px;
        border-radius:10px;
        text-align:center;
        box-shadow:0 0 20px rgba(0,0,0,0.5);
      ">

        <h3 style="
  margin-bottom:15px;
  color:#ffcc00;
  white-space:nowrap;
  font-size:18px;
">
  ⚠️ NO SEATS AVAILABLE
</h3>

        <p style="
          font-size:16px;
          line-height:1.7;
          margin-bottom:20px;
          color:#00ffcc;
          font-weight:bold;
        ">
          ⚠️ ${wlText} Detected<br>
          Continue booking?
        </p>

        <button id="wl-yes" style="
          margin:10px;
          padding:8px 18px;
          background:green;
          color:#fff;
          border:none;
          border-radius:5px;
          cursor:pointer;
          font-weight:bold;
        ">
          YES
        </button>

        <button id="wl-no" style="
          margin:10px;
          padding:8px 18px;
          background:red;
          color:#fff;
          border:none;
          border-radius:5px;
          cursor:pointer;
          font-weight:bold;
        ">
          NO
        </button>

      </div>
    </div>
  `;

  document.body.appendChild(overlay);

  // ======================
  // ✅ YES → CONTINUE
  // ======================
  document.getElementById("wl-yes").onclick = () => {

    console.log("✅ WL CONTINUE");

    overlay.remove();

    window.pauseAutomation = false;

    // 🔥 CONTINUE BUTTON
    let continueBtn = Array.from(document.querySelectorAll("button"))
      .find(b =>
        b.innerText &&
        b.innerText.toLowerCase().includes("continue")
      );

    if (continueBtn) {

      continueBtn.scrollIntoView({ block: "center" });

      setTimeout(() => {

        realClick(continueBtn);

        console.log("🚀 Continue After WL");

      }, 300);

    } else {

      console.log("❌ Continue Button Not Found");

    }

  };

  // ======================
  // ❌ NO → STOP
  // ======================
  document.getElementById("wl-no").onclick = () => {

    console.log("❌ WL STOP");

    overlay.remove();

    window.stopAutomation = true;
    window.pauseAutomation = true;

  };
}



// ======================
// 👀 ULTRA WL DETECT (FINAL GUARANTEED)
// ======================
function startWLObserver() {

  if (window.wlStarted) return;
  window.wlStarted = true;

  console.log("👀 WL FORCE DETECTOR STARTED");

  let tries = 0;

  let interval = setInterval(() => {


// 🔒 BLOCK DURING LOGIN
let loginPopup = document.querySelector("app-login");

if (loginPopup) {
  return;
}

// 🔒 ONLY PASSENGER PAGE
let passengerPage =
  document.body.innerText.includes("Passenger Details");

if (!passengerPage) {
  return;
}

// ======================
// 🔥 WL DETECT
// ======================
let text = document.body.innerText.toUpperCase();

// 🔴 NO SEATS AVAILABLE
if (text.includes("NO SEATS AVAILABLE")) {

    console.log("🔥 NO SEATS AVAILABLE");

    if (!document.getElementById("wl-popup")) {
        showWLPopup("NO SEATS AVAILABLE");
    }

    clearInterval(interval);
    return;
}


let match = text.match(/(GNWL|PQWL|RLWL|WL)\d+/g);

if (match) {

  let wlValue = match.join(" / ");

  console.log("🔥 WL DETECTED:", wlValue);

  if (!document.getElementById("wl-popup")) {
    showWLPopup(wlValue);
  }

  clearInterval(interval);
  return;
}

    tries++;

    // 🔥 1. DIRECT IRCTC DIALOG (MOST IMPORTANT)
    let dialog = document.querySelector("mat-dialog-container");

    if (dialog) {

      let text = dialog.innerText?.toUpperCase();

      if (text && text.includes("NO SEATS AVAILABLE")) {

        console.log("🔥 WL DETECTED (DIALOG)");

        if (!document.getElementById("wl-popup")) {
          showWLPopup();
        }

        clearInterval(interval);
        return;
      }
    }

    // 🔥 2. BUTTON BASE DETECT (VERY STRONG)
    let yesBtn = Array.from(document.querySelectorAll("button"))
      .find(b => b.innerText.toLowerCase().includes("yes"));

    let noBtn = Array.from(document.querySelectorAll("button"))
      .find(b => b.innerText.toLowerCase().includes("no"));

    if (yesBtn && noBtn) {

      let parent = yesBtn.closest("div");

      if (parent && parent.innerText.toUpperCase().includes("NO SEATS")) {

        console.log("🔥 WL DETECTED (BUTTON BASE)");

        if (!document.getElementById("wl-popup")) {
          showWLPopup();
        }

        clearInterval(interval);
        return;
      }
    }

    // 🔁 fallback limit
    if (tries > 20) {
      clearInterval(interval);
      console.log("⚠️ WL detect timeout");
    }

  }, 150);
}



// ======================
// 🔒 GLOBAL LOCKS
// ======================
window.continueLock = false;
window.payClicked = false;
window.paymentStarted = false;
window.actionLock = {};
window.pauseAutomation = false;
window.stopAutomation = false;

console.log("🔥 IRCTC FINAL AUTOMATION");



// ======================
// ⚡ FAST DOM CACHE
// ======================

window.DOM_CACHE = {};

function getCached(selector) {

  let el = window.DOM_CACHE[selector];

  // existing valid element
  if (el && document.contains(el)) {
    return el;
  }

  // find again
  el = document.querySelector(selector);

  if (el) {
    window.DOM_CACHE[selector] = el;
  }

  return el;
}


// ======================
// 🖱️ REAL USER CLICK
// ======================
function realClick(el) {

  if (!el) return;

  let rect = el.getBoundingClientRect();

  let x = rect.left + rect.width / 2;
  let y = rect.top + rect.height / 2;

  ["mousedown", "mouseup", "click"].forEach(type => {
    el.dispatchEvent(new MouseEvent(type, {
      view: window,
      bubbles: true,
      cancelable: true,
      clientX: x,
      clientY: y
    }));
  });
}





// ======================
// HELPER
// ======================
function setVal(el, val) {
  if (!el || !val) return;

  const setter = Object.getOwnPropertyDescriptor(
    HTMLInputElement.prototype,
    "value"
  ).set;

  setter.call(el, val);

  el.dispatchEvent(new Event("input", { bubbles: true }));
  el.dispatchEvent(new Event("change", { bubbles: true }));
}

function sleep(ms) {
  return new Promise(r => setTimeout(r, ms));
}


// ======================
// 🚦 GLOBAL SMART FLOW
// ======================

window.FLOW = {

  running: false,

  async waitUntil(checkFn, timeout = 30000, delay = 200) {

    let start = Date.now();

    while (Date.now() - start < timeout) {

      try {

        let ok = await checkFn();

        if (ok) {
          return true;
        }

      } catch (e) {}

      await sleep(delay);
    }

    return false;
  }

};


// ======================
// ⏳ WAIT FOR PAGE LOAD
// ======================
async function waitForLoadingToFinish(timeout = 30000) {

  console.log("⏳ Waiting Loading Finish...");

  let start = Date.now();

  while (Date.now() - start < timeout) {

    let loader =
      document.querySelector(".ng-animating") ||
      document.querySelector(".ui-progress-spinner") ||
      document.querySelector("p-progressspinner") ||
      document.querySelector(".loading") ||
      document.querySelector(".spinner");

    // ✅ loader gone
    if (!loader) {

      await sleep(120);

      console.log("✅ Loading Finished");

      return true;
    }

    await sleep(200);
  }

  console.log("❌ Loading Timeout");

  return false;
}



// ======================
// ⌨️ HUMAN TYPING (ADD HERE)
// ======================
async function typeLikeHuman(el, text, delay = 120) {
  if (!el || !text) return;

  el.focus();
  el.value = "";

  for (let i = 0; i < text.length; i++) {
    el.value += text[i];

    el.dispatchEvent(new Event("input", { bubbles: true }));

    let randomDelay = delay + Math.random() * 80;
    await new Promise(r => setTimeout(r, randomDelay));
  }

  el.dispatchEvent(new Event("change", { bubbles: true }));
}

// ======================
// 🔐 LOGIN AUTO TYPING (SAFE)
// ======================
let loginDone = false;

let loginInterval = addSafeInterval(async () => {

  if (loginDone) return;

  let user = document.querySelector("input[formcontrolname='userid']");
  let pass = document.querySelector("input[type='password']");

  if (user && pass && user.offsetParent !== null) {

    chrome.storage.local.get(null, async (data) => {

      loginDone = true;
      clearInterval(loginInterval);

      console.log("⌨️ Typing Username...");
showStep("⌨️ Typing Username...");

      // 🔥 small delay before typing
      await new Promise(r => setTimeout(r, 500 + Math.random()*400));

      await typeLikeHuman(user, data.irctc_credentials?.user_name, 20);

      await new Promise(r => setTimeout(r, 400));

      console.log("⌨️ Typing Password...");
      showStep("🔑 Typing Password...");

      await typeLikeHuman(pass, data.irctc_credentials?.password, 20);

      console.log("✅ Login typing done");
      // ======================
// 🔐 AUTO SIGN IN CLICK
// ======================
setTimeout(() => {

  let signBtn = Array.from(document.querySelectorAll("button"))
    .find(b =>
      b.innerText &&
      b.innerText.trim().toUpperCase() === "SIGN IN"
    );

  if (signBtn && !signBtn.disabled) {

    signBtn.scrollIntoView({ block: "center" });

    setTimeout(async () => {

      realClick(signBtn);

      console.log("🚀 SIGN IN CLICKED");
showStep("🚀 Signing In...");
      console.log("⏳ Waiting Login...");
showStep("⏳ Verifying Login...");
      let loggedIn = false;

      for (let i = 0; i < 150; i++) {

const loginPopup = document.querySelector("app-login");

// FROM input থাকলেই Login Success
const fromInput = document.querySelector(
    "input[aria-autocomplete='list']"
);

if (!loginPopup && fromInput) {

    console.log("✅ Login Confirmed");
showStep("✅ Login Successful");
    loggedIn = true;

    break;

}

          await sleep(200);

      }

      if (!loggedIn) {

          console.log("❌ Login Failed");

          return;

      }

    }, 100);

  } else {

    console.log("❌ SIGN IN BUTTON NOT FOUND");

  }

}, 150);

    });

  }

}, 500);

// ======================
// 🚆 MAIN FLOW
// ======================
(async () => {

  await sleep(1500);

  if (window.stopAutomation) {
  console.log("⛔ Automation Stopped");
  return;
}

if (window.pauseAutomation) {
  console.log("⏸️ Automation Paused");
  return;
}



  chrome.storage.local.get(null, async (data) => {

    let inputs = document.querySelectorAll("input[aria-autocomplete='list']");

if (inputs.length >= 2) {

  console.log("⌨️ Typing FROM...");
  await typeLikeHuman(inputs[0], data?.journey_details?.from, 10);

  await sleep(200);

  console.log("⌨️ Typing TO...");
  await typeLikeHuman(inputs[1], data?.journey_details?.to, 10);

  await sleep(300);
}

  

    let dateInput = document.querySelectorAll("input[type='text']")[2];

if (dateInput) {

  dateInput.click();
  await sleep(300);

  let [day, month, year] = data.journey_details?.date.split("/");

  day = parseInt(day);
  month = parseInt(month) - 1;
  year = parseInt(year);

  let tries = 0;

  while (tries < 12) {

    let title = document.querySelector(".ui-datepicker-title");

    if (!title) break;

    let text = title.innerText.trim(); // e.g. May 2026
    let current = new Date(text);

    let currentMonth = current.getMonth();
    let currentYear = current.getFullYear();

    if (currentMonth === month && currentYear === year) {

      // 🎯 select date
      document.querySelectorAll(".ui-datepicker-calendar td a").forEach(d => {
        if (parseInt(d.innerText) === day) {
          d.click();
        }
      });

      break;

    } else {

      let nextBtn = document.querySelector(".ui-datepicker-next");

      if (nextBtn) {
        nextBtn.click();
        await sleep(100);
      } else {
        break;
      }

    }

    tries++;
  }
}

    await sleep(400);

    let dropdown = document.querySelector(".ui-dropdown");

    if (dropdown) {
      dropdown.click();
      await sleep(100);

      document.querySelectorAll("li.ui-dropdown-item").forEach(item => {
        if (item.innerText.includes("(" + data.journey_details?.class + ")")) {
          item.click();
        }
      });
    }

    await sleep(400);


// ======================
// 🎯 AUTO SELECT QUOTA (FINAL FIX)
// ======================
async function selectQuotaIRCTC(quotaText = "TATKAL") {

  let dropdowns = document.querySelectorAll(".ui-dropdown");

  let quotaDropdown = null;

  // 🔥 ONLY find dropdown which contains quota label
  dropdowns.forEach(d => {

    let label = d.querySelector(".ui-dropdown-label");

    if (!label) return;

    let text = label.innerText.toUpperCase();

    // 👉 quota dropdown always has these values
    if (
      text === "GENERAL" ||
      text === "TATKAL" ||
      text === "PREMIUM TATKAL"
    ) {
      quotaDropdown = d;
    }

  });

  if (!quotaDropdown) {
    console.log("❌ Quota dropdown not found");
    return;
  }

  // 🔥 open dropdown
  quotaDropdown.click();
  await sleep(100);

  // 🔥 visible panel
  let panel = [...document.querySelectorAll(".ui-dropdown-panel")]
    .find(p => p.offsetParent !== null);

  if (!panel) {
    console.log("❌ Panel not found");
    return;
  }

  let items = panel.querySelectorAll("li.ui-dropdown-item");

  // 🔥 exact match only
  for (let item of items) {

    let txt = item.innerText
      .replace(/\s+/g, " ")
      .trim()
      .toUpperCase();

    if (txt === quotaText.toUpperCase()) {
      item.click();
      console.log("✅ FINAL SELECT:", txt);
      return;
    }
  }

  console.log("❌ Not found:", quotaText);
}


// 🔥 CALL ADDED HERE
   let quota = data.journey_details?.quota || "GN";

let map = {
  GN: "GENERAL",
  TQ: "TATKAL",
  PT: "PREMIUM TATKAL"
};

await selectQuotaIRCTC(map[quota]);
    await sleep(100);

    


 // ======================
// 🔥 STRONG SEARCH CLICK (FINAL FIX)
// ======================
for (let i = 0; i < 15; i++) {

  // 🔥 Tatkal login protection
  let quota = (data.journey_details?.quota || "").toUpperCase();

  let loginPopup = document.querySelector("app-login");

  if (
    (quota === "TQ" || quota === "PT") &&
    loginPopup
  ) {

    console.log("⏳ Waiting Login Before Tatkal Search");

    await sleep(1000);
    continue;
  }

  // 🔍 Search button
  let btn =
  getCached("button.search_btn");

  // ✅ Click
  if (btn && !btn.disabled && btn.offsetParent !== null) {
if (window.actionLock.search)
  return;

window.actionLock.search = true;
    realClick(btn);

    console.log("🚀 Search Click SUCCESS");

    await waitForLoadingToFinish();

    break;
  }

  await sleep(500);
}
   

// ======================
// ⏳ WAIT FOR TRAIN LOAD
// ======================
async function waitForTrainList() {

    console.log("⏳ Waiting Train List...");

    let timeout = Date.now() + 15000;

    while (Date.now() < timeout) {

        let visible = [...document.querySelectorAll("app-train-avl-enq")]
            .filter(t => t.offsetParent !== null);

        if (visible.length > 0) {

            console.log("✅ Train List Loaded :", visible.length);

            return visible;

        }

        await sleep(200);

    }

    console.log("❌ Train List Timeout");

    return [];

}
// ======================
// 🚆 TRAIN SELECT FINAL
// ======================

// 🔥 extract number
let fullTrain = data.journey_details?.train_no || "";
let trainNo = fullTrain.split("-")[0].trim();

// 🔥 ADD HERE
window.finalClass = data.journey_details?.class;

window.finalTrain =
  data.journey_details?.train_no;

// 🔥 wait for trains
let trains = await waitForTrainList();
for (let train of trains) {

  let match = train.innerText.match(/\((\d{5})\)/);

  if (match && match[1] === trainNo) {
    console.log("🚆 TRAIN FOUND CORRECT");
    showStep("🚆 TRAIN SELECTED");
await waitForLoadingToFinish();



// ======================
// 🎯 FINAL CLASS SELECT FIX
// ======================
let targetClass = data.journey_details?.class;
let classSelected = false;

for (let i = 0; i < 5; i++) {

  let tabs = train.querySelectorAll("span, strong");

  for (let tab of tabs) {

    let txt = tab.innerText?.toUpperCase();

    if (txt && txt.includes(targetClass)) {

      // tab.scrollIntoView({ block: "center" });

      await sleep(100);

      realClick(tab);

      console.log("🎯 Class Selected FIXED:", targetClass);

      classSelected = true;
      break;
    }
  }
await waitForLoadingToFinish();
  if (classSelected) break;

  await sleep(350);
}

// 🔥 delay বাড়াও
await sleep(250);


    // ======================
    // 🔄 REFRESH
    // ======================
    let refreshBtn = Array.from(train.querySelectorAll("*"))
      .find(el => el.innerText && el.innerText.toLowerCase().includes("refresh"));

    if (refreshBtn) {
      realClick(refreshBtn);
      console.log("🔄 Refresh Clicked");
      await waitForLoadingToFinish();
    }

await sleep(500);



        
// ======================
// GET FRESH TRAIN CARD
// ======================

let freshTrain = [...document.querySelectorAll("app-train-avl-enq")]
    .find(t => t.innerText.includes(trainNo));

if (freshTrain) {

    train = freshTrain;

    console.log("✅ Fresh Train Loaded");

}

train.scrollIntoView({
    behavior: "smooth",
    block: "center"
});

let wl = [...train.querySelectorAll("div.pre-avl")]
    .find(card => {

        let txt = card.innerText.toUpperCase();

        return txt.includes("AVAILABLE") ||
               txt.includes("RAC") ||
               txt.includes("WL");

    });

if (wl) {

    await sleep(800);

    let clicked = false;

    for (let retry = 1; retry <= 3; retry++) {

        // প্রতি Retry-তে নতুন Element নাও
        wl = [...train.querySelectorAll("div.pre-avl")]
            .find(card => {

                let txt = card.innerText.toUpperCase();

                return txt.includes("AVAILABLE") ||
                       txt.includes("RAC") ||
                       txt.includes("WL");

            });

        if (!wl) {

            console.log("❌ AVL Card Missing");

            break;

        }

        wl.scrollIntoView({
            behavior: "smooth",
            block: "center"
        });

        realClick(wl);

        console.log("🎯 AVL Click :", retry);

        await sleep(400);

        await waitForLoadingToFinish();

        // নতুন করে Element ধরো
        wl = [...train.querySelectorAll("div.pre-avl")]
            .find(card => card.classList.contains("selected-class"));

        if (wl) {

            clicked = true;

            console.log("✅ AVL Selected");

            break;

        }

    }

    if (!clicked) {

        console.log("❌ AVL Selection Failed");

    }

}
    // ======================
// 🚀 BOOK NOW (STABLE)
// ======================
async function clickBookNow(train) {

  for (let i = 0; i < 10; i++) {

    let bookBtn = Array.from(train.querySelectorAll("button"))
      .find(btn => btn.innerText && btn.innerText.toLowerCase().includes("book"));

    if (bookBtn && bookBtn.offsetParent !== null) {

      // bookBtn.scrollIntoView({ block: "center" });

      await sleep(50);
if (window.actionLock.book)
  return;

window.actionLock.book = true;
      realClick(bookBtn);

      console.log("🚀 BOOK CLICK SUCCESS");

      // 🔥 ADD THIS
      startWLObserver();

      return true;
    }

    await sleep(300);
  }

  console.log("❌ Book Button Not Found");
  return false;
}

// ======================
// 🔧 QUOTA + TATKAL FLOW (FINAL CLEAN)
// ======================
let quota = (data.journey_details?.quota || "").toUpperCase();

if (quota === "TQ" || quota === "PT") {

  // 🔒 run once only
  if (!window.tatkalStarted) {

    window.tatkalStarted = true;

    console.log("⏳ Tatkal Mode → Waiting...");

    // ======================
// 📢 CENTER MESSAGE
// ======================
setTimeout(() => {

  let old = document.getElementById("tatkal-msg");
  if (old) old.remove();

  let msg = document.createElement("div");
  msg.id = "tatkal-msg";

  let cls = (window.finalClass || "").toUpperCase().trim();
  let isSleeperOr2S = (cls === "SL" || cls === "2S");

  let hitTime = isSleeperOr2S ? "11:00:08" : "10:00:08";

  msg.innerText = `⏳ Please wait... Tatkal Booking Hitting Time ${hitTime}`;

  // 🔥 CENTER STYLE (same as before)
  msg.style.position = "fixed";
  msg.style.top = "20px";
  msg.style.left = "50%";
  msg.style.transform = "translateX(-50%)";
  msg.style.background = "#000";
  msg.style.color = "#00ffcc";
  msg.style.padding = "10px 18px";
  msg.style.borderRadius = "6px";
  msg.style.fontSize = "13px";
  msg.style.fontWeight = "bold";
  msg.style.zIndex = "9999";
  msg.style.boxShadow = "0 0 8px rgba(0,255,200,0.5)";

  document.body.appendChild(msg);

}, 0);


// ======================
// 🕒 LIVE CLOCK (TOP RIGHT)
// ======================
setTimeout(() => {

  let oldClock = document.getElementById("tatkal-clock");
  if (oldClock) oldClock.remove();

  let clock = document.createElement("div");
  clock.id = "tatkal-clock";

  clock.style.position = "fixed";
  clock.style.top = "10px";
  clock.style.right = "20px";
  clock.style.background = " red";
  clock.style.color = "#ffff";
  clock.style.padding = "6px 12px";
  clock.style.borderRadius = "6px";
  clock.style.fontSize = "13px";
  clock.style.fontWeight = "bold";
  clock.style.zIndex = "9999";

  document.body.appendChild(clock);

  // 🔥 LIVE TIME UPDATE
  setInterval(() => {
    let now = new Date();

    let h = String(now.getHours()).padStart(2, "0");
    let m = String(now.getMinutes()).padStart(2, "0");
    let s = String(now.getSeconds()).padStart(2, "0");

    clock.innerText = `🕒 ${h}:${m}:${s}`;
  }, 1000);

}, 0);

    // 🔥 LIVE TIME (SL / 2S = 11AM, AC = 10AM)
    let cls = (window.finalClass || "").toUpperCase().trim();

    let isSleeperOr2S = (cls === "SL" || cls === "2S");

    let targetHour = isSleeperOr2S ? 11 : 10;
    let targetMinute = 0;

    console.log("⏰ Waiting Tatkal Time:", targetHour + ":" + targetMinute);

  let tatkalInterval = setInterval(async () => {

  let now = new Date();

  // 👉 শুধু এই অংশটা replace করো
  let targetSecond = 8;

  let isSameTime =
    now.getHours() === targetHour &&
    now.getMinutes() === targetMinute &&
    now.getSeconds() <= targetSecond;

  let isPastTime =
    now.getHours() > targetHour ||
    (now.getHours() === targetHour && now.getMinutes() > targetMinute) ||
    (now.getHours() === targetHour &&
     now.getMinutes() === targetMinute &&
     now.getSeconds() > targetSecond);

  if (isSameTime || isPastTime) {

    clearInterval(tatkalInterval);

    console.log("🚀 TATKAL HIT / RETRY START");

    document.getElementById("tatkal-msg")?.remove();
    document.getElementById("tatkal-clock")?.remove();


      if (refreshBtn) {

  refreshBtn.click(); // ✅ simple click

  console.log("🔄 Refresh (Single)");

  await waitForLoadingToFinish();
  await sleep(300);
}

       
await sleep(500);

// ======================
// GET FRESH TRAIN CARD
// ======================

let freshTrain = [...document.querySelectorAll("app-train-avl-enq")]
    .find(t => t.innerText.includes(trainNo));

if (freshTrain) {

    train = freshTrain;

    console.log("✅ Fresh Train Loaded");

}

train.scrollIntoView({
    behavior: "smooth",
    block: "center"
});

let wl = [...train.querySelectorAll("div.pre-avl")]
    .find(card => {

        let txt = card.innerText.toUpperCase();

        return txt.includes("AVAILABLE") ||
               txt.includes("RAC") ||
               txt.includes("WL");

    });

if (wl) {

    await sleep(800);

    let clicked = false;

    for (let retry = 1; retry <= 3; retry++) {

        // প্রতি Retry-তে নতুন Element নাও
        wl = [...train.querySelectorAll("div.pre-avl")]
            .find(card => {

                let txt = card.innerText.toUpperCase();

                return txt.includes("AVAILABLE") ||
                       txt.includes("RAC") ||
                       txt.includes("WL");

            });

        if (!wl) {

            console.log("❌ AVL Card Missing");

            break;

        }

        wl.scrollIntoView({
            behavior: "smooth",
            block: "center"
        });

        realClick(wl);

        console.log("🎯 AVL Click :", retry);

        await sleep(400);

        await waitForLoadingToFinish();

        // নতুন করে Element ধরো
        wl = [...train.querySelectorAll("div.pre-avl")]
            .find(card => card.classList.contains("selected-class"));

        if (wl) {

            clicked = true;

            console.log("✅ AVL Selected");

            break;

        }

    }

    if (!clicked) {

        console.log("❌ AVL Selection Failed");

    }

}
// ======================
// 🚀 BOOK NOW
// ======================
let bookBtn = Array.from(train.querySelectorAll("button"))
  .find(b => b.innerText.toLowerCase().includes("book"));

if (bookBtn) {
  await sleep(1200);
  realClick(bookBtn);
  console.log("🚀 BOOK CLICKED (TATKAL)");

  // 🔥 ADD THIS
  startWLObserver();

} else {
  console.log("❌ Book button not found");
}

      }

    }, 250);

  }

}else {

  // ======================
  // 🚀 NORMAL BOOKING
  // ======================
  await clickBookNow(train);

}

    break;
  }

}
  });

})();

// ======================
// 👤 PASSENGER FILL FINAL (FIXED)
// ======================
async function fillPassengerDetails() {

  console.log("👤 Passenger Start");
showStep("👤 Filling Passenger Details...");
  await sleep(200);

  chrome.storage.local.get(null, async (data) => {

    let passengers = data.journey_details?.passengers;
    let mobile = data.journey_details?.mobile;

    if (!passengers || passengers.length === 0) return;

function getNames() {
  return Array.from(document.querySelectorAll("input[placeholder='Full Name as per Govt. ID']"))
    .filter(el => el.offsetParent !== null);

    }

    let names = getNames();

    let addBtn = [...document.querySelectorAll("button, a")]
      .find(el => el.innerText.includes("Add Passenger"));

    // ➕ ADD ROW
    while (names.length < passengers.length) {

      addBtn?.click();

      let prev = names.length;

      for (let i = 0; i < 10; i++) {
        await sleep(400);
        let updated = getNames();
        if (updated.length > prev) {
          names = updated;
          break;
        }
      }

      names = getNames();
    }

    let ages = Array.from(document.querySelectorAll("input[placeholder='Age']"))
      .filter(el => el.offsetParent !== null);

    let genders = Array.from(
      document.querySelectorAll("select[formcontrolname='passengerGender']")
    ).filter(el => el.offsetParent !== null);

    // ======================
    // 🧾 FILL PASSENGERS
    // ======================
    for (let i = 0; i < passengers.length; i++) {

      let p = passengers[i];

      setVal(names[i], p.name);
  setVal(ages[i], p.age);

      if (genders[i]) {
        genders[i].value = p.gender;
        genders[i].dispatchEvent(new Event("change", { bubbles: true }));
        // ======================
// 🛏️ BERTH AUTO SELECT (FINAL PERFECT)
// ======================
await sleep(150);

let berths = Array.from(
  document.querySelectorAll("select[formcontrolname='passengerBerthChoice']")
).filter(el => el.offsetParent !== null);

if (berths[i] && p.berth) {

  let map = {
    "LOWER": "LB",
    "LB": "LB",
    "MIDDLE": "MB",
    "MB": "MB",
    "UPPER": "UB",
    "UB": "UB",
    "SIDE LOWER": "SL",
    "SL": "SL",
    "SIDE UPPER": "SU",
    "SU": "SU"
  };

  let key = p.berth.toUpperCase().trim();
  let val = map[key];

  if (val) {

    berths[i].value = val;
    berths[i].dispatchEvent(new Event("change", { bubbles: true }));

    console.log("🛏️ BERTH SELECTED:", val);

  } else {
    console.log("❌ Invalid berth:", p.berth);
  }
}
      }
      await sleep(120);
    }



    // ======================
    // 📱 MOBILE
    // ======================
    let mobileInput = document.querySelector(
      "input[formcontrolname='mobileNumber'], input[placeholder*='Mobile']"
    );

    if (mobileInput && mobile) {
      setVal(mobileInput, mobile);
      console.log("📱 Mobile Filled");
    }

    // ======================
// ⬆️ AUTO UPGRADATION CONTROL
// ======================

try {

  await sleep(1000);

  let shouldCheck =
    !!data.journey_details
      ?.auto_upgradation;

  let label = document.querySelector(
    'label[for="autoUpgradation"]'
  );

  if (!label) {

    console.log(
      "❌ Auto Upgradation label missing"
    );

  }

  // ======================
  // ✅ WANT CHECKED
  // ======================

  else if (shouldCheck) {

    let checkbox =document.querySelector("#autoUpgradation");

    if (
      checkbox &&
      !checkbox.checked
    ) {

      label.click();

      console.log(
        "✅ Auto Upgradation Checked"
      );

    }

  }

  // ======================
  // ❌ WANT UNCHECKED
  // ======================

  else {

    let checkbox =
      document.querySelector(
        "#autoUpgradation"
      );

    if (
      checkbox &&
      checkbox.checked
    ) {

      label.click();

      console.log(
        "❌ Auto Upgradation Unchecked"
      );

    }

  }

} catch (e) {

  console.log(
    "❌ Auto Upgrade Error:",
    e
  );

}

    // ======================
// ✅ FINAL CONFIRM BERTH ARE ALLOTED CHECK/UNCHECKD FUNGTION.
// ======================

await sleep(1000);

let confirmInput =
  document.querySelector(
    "#confirmberths"
  );

let shouldCheck =
  !!data.journey_details
    ?.confirm_berth;

if (!confirmInput) {

  console.log(
    "❌ Confirm berth input missing"
  );

}

// ======================
// ✅ WANT CHECKED
// ======================

else if (shouldCheck) {

  if (!confirmInput.checked) {

    confirmInput.click();

    console.log(
      "✅ Confirm Berth Checked"
    );

  } else {

    console.log(
      "✅ Confirm Berth Already Checked"
    );

  }

}

// ======================
// ❌ WANT UNCHECKED
// ======================

else {

  if (confirmInput.checked) {

    confirmInput.click();

    console.log(
      "❌ Confirm Berth Unchecked"
    );

  } else {

    console.log(
      "❌ Confirm Berth Already Unchecked"
    );

  }

}

        // ======================
// 🛡️ ULTIMATE FINAL INSURANCE
// ======================

try {

  let insurance =
    (
      data.journey_details
        ?.insurance_choice || "YES"
    ).toUpperCase();

  await sleep(500);

  // 🔥 YES LABEL
  let yesLabel = document.querySelector(
    'label[for="travelInsuranceOptedYes-0"]'
  );

  // 🔥 NO LABEL
  let noLabel = document.querySelector(
    'label[for="travelInsuranceOptedNo-0"]'
  );

  // ======================
  // ❌ NO INSURANCE
  // ======================

  if (insurance === "NO" && noLabel) {

    let noRadio =
      noLabel.querySelector(
        '[role="radio"]'
      );

    if (noRadio) {

      noRadio.click();

      console.log(
        "🛡️ NO INSURANCE SELECTED"
      );

    }

  }

  // ======================
  // ✅ YES INSURANCE
  // ======================

  else if (
    insurance === "YES" &&
    yesLabel
  ) {

    let yesRadio =
      yesLabel.querySelector(
        '[role="radio"]'
      );

    if (yesRadio) {

      yesRadio.click();

      console.log(
        "🛡️ YES INSURANCE SELECTED"
      );

    }

  }

} catch (e) {

  console.log(
    "❌ Insurance Error:",
    e
  );

}
    console.log("✅ PASSENGERS FILLED");
showStep("✅ Passenger Details Filling");

await waitForLoadingToFinish();
    await sleep(600);
    // ======================
    // 💳 PAYMENT PREP
    // ======================
    await sleep(800);

    let isHomePage =
  window.location.href.includes("train-search") ||
  document.querySelector("app-home") ||
  document.querySelector("app-train-search");

if (!isHomePage) {
  window.scrollTo(0, document.body.scrollHeight);
}

// ======================
// 🚀 FINAL CONTINUE (ONLY ONE PLACE)
// ======================
setTimeout(async () => {

    if (window.continueLock) return;
    window.continueLock = true;

    // ✅ Page পুরো Ready হওয়ার জন্য অপেক্ষা
    await waitForLoadingToFinish();
    await sleep(1000);

    // ✅ Form Validation Check
    let invalid = document.querySelectorAll(".ng-invalid");

    if (invalid.length > 0) {

        console.log("❌ Form Not Ready :", invalid.length);

        showStep("❌ Waiting Form...");

        window.continueLock = false;

        return;

    }

    // শুধুমাত্র Visible Continue Button খুঁজবে
    let btn = [...document.querySelectorAll("button")]
        .find(b => {

            let txt = b.innerText?.trim()?.toLowerCase();

            return (
                txt === "continue" &&
                !b.disabled &&
                b.offsetParent !== null &&
                b.getBoundingClientRect().width > 0 &&
                b.getBoundingClientRect().height > 0
            );

        });

    if (!btn) {

        console.log("❌ Continue Button Not Found");

        window.continueLock = false;

        return;

    }

    btn.scrollIntoView({
        block: "center",
        behavior: "smooth"
    });

    await sleep(300);

    realClick(btn);

    console.log("🚀 Continue Clicked (FINAL)");

}, 400);

  });

}


// ======================
// 💳 FINAL COMPLETE PAYMENT FLOW (FIXED)
// ======================
setTimeout(() => {

  if (window.paymentStarted) return;
  window.paymentStarted = true;



  let isHomePage =
  window.location.href.includes("train-search") ||
  document.querySelector("app-home") ||
  document.querySelector("app-train-search");

if (!isHomePage) {
  window.scrollTo(0, document.body.scrollHeight);
}

  let upiInterval = addSafeInterval(() => {

    let done = false;

    document.querySelectorAll("tr").forEach(row => {

      let txt = row.innerText?.toLowerCase();

      if (txt && txt.includes("bhim") && txt.includes("upi")) {

        let radio = row.querySelector(".ui-radiobutton-box");

        if (radio && !radio.classList.contains("ui-state-active")) {
          radio.click();
          console.log("✅ BHIM/UPI MODE SELECTED");
        }

        done = true;
      }
    });

    if (done) {
      clearInterval(upiInterval);
      

      // ❌ Continue REMOVE (already done before)

      setTimeout(() => {

        let multiInterval = addSafeInterval(() => {

          let found = false;

          document.querySelectorAll("label, span, div").forEach(el => {

            let txt = el.innerText?.toLowerCase();

            if (txt && txt.includes("multiple payment")) {
                      // 🔥 একবারই Show করবে
        if (!window.paymentFlowShown) {
          window.paymentFlowShown = true;

          console.log("💳 Payment Flow Start");
          showStep("💳 Opening Payment...");
        }
              el.click();
              console.log("✅ MULTIPLE PAYMENT SELECTED");
                showStep("💳 Selecting Payment Mode...");
              found = true;
            }

          });

          if (found) {
            clearInterval(multiInterval);

            selectPaymentGateway().then(() => {

              setTimeout(() => {

                if (window.payClicked) return;
                window.payClicked = true;

                let btn2 = Array.from(document.querySelectorAll("button"))
                  .find(b => b.innerText.toLowerCase().includes("pay & book"));

                if (btn2) {

                  btn2.disabled = false;
                  btn2.scrollIntoView({ block: "center" });

                  setTimeout(() => {
                    realClick(btn2);
                  }, 50);

                  console.log("🚀 Pay & Book Clicked");
                  showStep("🚀 Pay & Book...");
                }

              }, 200);

            });

          }

        }, 500);

      }, 300);
    }

  }, 500);

}, 500);


// ======================
// 🎯 GATEWAY SELECT FUNCTION
// ======================
async function selectPaymentGateway() {

  return new Promise((resolve) => {

    chrome.storage.local.get(null, async (data) => {

      let method = (data.journey_details?.payment_mode || "").toLowerCase().trim();

      if (method === "phonpe") method = "phonepe";

      let tries = 0;

      let interval = setInterval(() => {

        tries++;

        let cards = document.querySelectorAll("div");

        let clicked = false;

        cards.forEach(card => {

          let txt = card.innerText?.toLowerCase();

          if (!txt) return;

          if (
            (method === "paytm" && txt.includes("paytm")) ||
            (method === "phonepe" && txt.includes("phonepe")) ||
            (method === "razorpay" && txt.includes("razorpay")) ||
            (method === "payu" && txt.includes("payu"))
          ) {

            card.scrollIntoView({ block: "center" });

            setTimeout(() => {
              card.click();
            }, 150);

            console.log("✅ GATEWAY CLICKED:", method);
          showStep("🏦 Selecting Payment Gateway...");
            clicked = true;
          }

        });

        if (clicked) {
          clearInterval(interval);
          resolve(true);
        }

        if (tries > 25) {
          clearInterval(interval);
          resolve(false);
        }

      }, 150);

    });

  });
}

// ======================
// RUN
// ======================
let done = false;

let interval = setInterval(() => {

  if (done) return;

 let nameBox = document.querySelector("input[placeholder='Full Name as per Govt. ID']");

  if (nameBox && nameBox.offsetParent !== null) {
    done = true;
    clearInterval(interval);
    fillPassengerDetails();
  }

}, 1000);







// ======================
// 🔥 AUTO CONTINUE CLICK
// ======================
function clickSubmitButton() {

    let btn = [...document.querySelectorAll("button.mob-bot-btn.search_btn")]
        .find(b =>
            b.innerText.trim().toLowerCase() === "continue"
        );

    if (!btn) {

        console.log("❌ Continue Button Not Found");

        return;

    }

    console.log("✅ Continue Button Found");

    btn.scrollIntoView({
        block: "center"
    });

    setTimeout(() => {

        realClick(btn);

        console.log("🚀 Continue Clicked");

    }, 400);

}



// ======================
// 🤖 OCR AUTO SOLVE FINAL
// ======================
async function autoSolveCaptcha(imgSrc, inputEl, popupInput, btn) {

  try {

    console.log("🤖 OCR Started");
showStep("🤖 Solving Captcha...");
    // ======================
    // 🖼️ DIRECT CAPTCHA CAPTURE
    // ======================

    let captchaImg = document.querySelector("img.captcha-img");

    if (!captchaImg) {

      console.log("❌ Captcha image not found");

      return;
    }

    let canvas = document.createElement("canvas");

    canvas.width = captchaImg.naturalWidth;
    canvas.height = captchaImg.naturalHeight;

    let ctx = canvas.getContext("2d");

    ctx.drawImage(captchaImg, 0, 0);

    let blob = await new Promise(resolve => {
      canvas.toBlob(resolve, "image/jpeg", 1);
    });

    console.log("🖼️ Captcha Captured");

// ======================
// 🤖 TRUECAPTCHA OCR
// ======================

// Blob → Base64
let base64 = await new Promise(resolve => {

    let reader = new FileReader();

    reader.onloadend = () => {

        resolve(reader.result.split(",")[1]);

    };

    reader.readAsDataURL(blob);

});

let api = await fetch("https://api.apitruecaptcha.org/one/gettext", {

    method: "POST",

    headers: {
        "Content-Type": "application/json",
        "Accept": "application/json"
    },

    body: JSON.stringify({

        userid: "sh964789@gmail.com",

        apikey: "hLY1gobBKasq98msbfoS",

        data: base64

    })

});

console.log("HTTP Status :", api.status);

let responseText = await api.text();

console.log("Server Response :", responseText);

if (!api.ok) {

    console.log("❌ TrueCaptcha API Error");

    return;

}

let result = JSON.parse(responseText);

let captcha = (result.result || "").trim();

console.log("✅ OCR Result :", captcha);
showStep("⌨️ Filling Captcha...");
    // ======================
    // ❌ INVALID OCR
    // ======================

    if (
      !captcha ||
      captcha.toLowerCase() === "empty" ||
      captcha.length < 4
    ) {

      console.log("❌ Invalid Captcha OCR");

      return;
    }

    // ======================
    // 📝 POPUP INPUT FILL
    // ======================

    popupInput.value = captcha;

    // ======================
    // 🔥 ANGULAR SAFE INPUT
    // ======================

    const nativeInputValueSetter =
      Object.getOwnPropertyDescriptor(
        window.HTMLInputElement.prototype,
        "value"
      ).set;

    nativeInputValueSetter.call(inputEl, captcha);

    inputEl.dispatchEvent(
      new Event("input", { bubbles: true })
    );

    inputEl.dispatchEvent(
      new Event("change", { bubbles: true })
    );

    inputEl.dispatchEvent(
      new KeyboardEvent("keyup", { bubbles: true })
    );

    console.log("✅ Captcha Filled:", captcha);
showStep("⌨️ Captcha Fill Successfuly");
    // ======================
    // 🚀 AUTO SUBMIT
    // ======================

    setTimeout(() => {

      btn.click();

    }, 800);

  } catch (e) {

    console.log("❌ OCR Failed:", e);

  }

}



// ======================
// 🎯 SHOW POPUP
// ======================
function showCaptchaPopupPro(imgSrc, inputEl) {

  // duplicate prevent
  if (document.getElementById("proCaptchaInput")) return;

  console.log("🔥 Popup Open");

  let overlay = document.createElement("div");

  overlay.style = `
    position:fixed;
    top:0; left:0;
    width:100%; height:100%;
    background:rgba(0,0,0,0.7);
    display:flex;
    align-items:center;
    justify-content:center;
    z-index:999999;
  `;

  overlay.innerHTML = `
    <div style="
      width:320px;
      padding:20px;
      border-radius:15px;
      background: #111;
      text-align:center;
      color:#fff;
      font-family:Arial;
    ">
      <h3>🔐 Enter Captcha</h3>

      <img src="${imgSrc}" style="width:220px;margin:10px;border-radius:6px;" />

      <input id="proCaptchaInput" type="text"
        placeholder="ENTER CAPTCHA"
        style="
          width:100%;
          padding:10px;
          font-size:22px;
          text-align:center;
          background:#000;
          color:#ffffff;
          -webkit-text-fill-color:#ffffff;
          text-shadow:0 0 6px rgba(255,255,255,0.9);
          caret-color:#ffffff;
          letter-spacing:3px;
        "
      />

      <button id="proCaptchaBtn"
        style="
          margin-top:10px;
          padding:10px;
          width:100%;
          background:green;
          color:#fff;
          border:none;
          border-radius:6px;
          cursor:pointer;
        ">
        🚀 Final Submit
      </button>
    </div>
  `;

  document.body.appendChild(overlay);

  let popupInput = document.getElementById("proCaptchaInput");
  let btn = document.getElementById("proCaptchaBtn");

  popupInput.focus();

  // ======================
  // 🤖 OCR AUTO START
  // ======================

  autoSolveCaptcha(imgSrc, inputEl, popupInput, btn);

  // ======================
  // 🔥 AUTO SUBMIT
  // ======================

  popupInput.addEventListener("input", () => {

    if (popupInput.value.trim().length >= 4) {

      setTimeout(() => btn.click(), 700);

    }

  });

  // ======================
  // 🚀 FINAL SUBMIT
  // ======================

  btn.addEventListener("click", async () => {

    let val = popupInput.value.trim();

    if (!val) return;

    // ======================
    // 🔥 ANGULAR SAFE INPUT
    // ======================

    const nativeInputValueSetter =
      Object.getOwnPropertyDescriptor(
        window.HTMLInputElement.prototype,
        "value"
      ).set;

    nativeInputValueSetter.call(inputEl, val);

    inputEl.dispatchEvent(
      new Event("input", { bubbles: true })
    );

    inputEl.dispatchEvent(
      new Event("change", { bubbles: true })
    );

    inputEl.dispatchEvent(
      new KeyboardEvent("keyup", { bubbles: true })
    );

    console.log("✅ Captcha Final Filled:", val);
    // ======================
// 🔐 LOGIN AUTO SIGN IN
// ======================

let loginPopup =
  document.querySelector("app-login");

if (loginPopup) {

  console.log("🔐 Login Captcha Solved");

  await sleep(1200);

  let signBtn = Array.from(
    document.querySelectorAll("button")
  ).find(b => {

    let txt =
      b.innerText?.trim().toUpperCase();

    return (
      txt === "SIGN IN" &&
      b.offsetParent !== null &&
      !b.disabled
    );

  });

  if (signBtn) {

    signBtn.scrollIntoView({
      block: "center"
    });

    await sleep(300);
if (window.actionLock.signin2)
  return;

window.actionLock.signin2 = true;
    realClick(signBtn);

    console.log("🚀 SIGN IN CLICKED");

  }

}

    overlay.remove();

    // ======================
    // 🔥 WL CHECK AFTER CAPTCHA
    // ======================

    setTimeout(() => {

      let text = document.body.innerText.toUpperCase();

      let match = text.match(/\b(GNWL|PQWL|RLWL|WL)\d+\b/);

      if (match) {

        let wlValue = match[0];

        console.log("🔥 WL AFTER CAPTCHA:", wlValue);

        showWLPopup(wlValue);

        return;
      }

      // ======================
      // 🚀 AUTO CONTINUE
      // ======================

      clickSubmitButton();

    }, 500);

  });

}

// ======================
// 🔁 SMART DETECTION ENGINE
// ======================
let lastCaptcha = "";
let popupOpen = false;

addSafeInterval(() => {

  // ======================
// 🔐 LOGIN + PASSENGER CAPTCHA DETECT
// ======================

let img =

  document.querySelector("img.captcha-img") ||

  document.querySelector("img[alt*='captcha']") ||

  document.querySelector("img[src*='captcha']");



let input =

  document.querySelector("#captcha") ||

  document.querySelector(
    "input[formcontrolname='captcha']"
  ) ||

  document.querySelector(
    "input[placeholder*='Captcha']"
  ) ||

  document.querySelector(
    "input[placeholder*='captcha']"
  );

  if (!img || !input || img.offsetParent === null) return;

  let current = img.src;

  // 👉 first time (IMPORTANT FIX)
  if (!lastCaptcha) {
    lastCaptcha = current;

    console.log("🎯 First Captcha Detected");
    showCaptchaPopupPro(current, input);
    return;
  }

  // 👉 new captcha (wrong হলে)
  if (current !== lastCaptcha) {

    console.log("🔁 New Captcha Detected");

    lastCaptcha = current;

    // popup already open না থাকলে
    if (!document.getElementById("proCaptchaInput")) {
      showCaptchaPopupPro(current, input);
    }
  }

}, 300);


// ==========================================
// 🚀 AUTO CONTINUE IF CAPTCHA NOT FOUND
// ==========================================

addSafeInterval(async () => {

    // Captcha থাকলে কিছু করবে না
    const captcha =
        document.querySelector("img.captcha-img") ||
        document.querySelector("img[src*='captcha']") ||
        document.querySelector("input[formcontrolname='captcha']");

    if (captcha && captcha.offsetParent !== null)
        return;

    // Passenger Review Page কিনা
    if (!location.href.includes("reviewBooking"))
        return;

    // একবারই চলবে
    if (window.autoContinueClicked)
        return;

    // Continue Button
    const btn =
        document.querySelector("button.train_Search") ||
        [...document.querySelectorAll("button")]
            .find(b => b.textContent.trim().toLowerCase().includes("continue"));

    if (!btn)
        return;

    window.autoContinueClicked = true;

    console.log("✅ No Captcha");
    console.log("🚀 Auto Continue");

    await sleep(700);

    realClick(btn);

}, 300);




// ======================
// 💳 FINAL PAY CLICK (FIXED)
// ======================
function handleFinalPaymentClick() {

  console.log("💳 Waiting Pay Button...");

  let donePay = false;

  let payInterval = setInterval(() => {

    if (donePay) return;

    let btn = document.querySelector("button.btn.btn-primary");

    if (btn && btn.innerText.includes("Pay") && btn.offsetParent !== null) {

      donePay = true;
      clearInterval(payInterval);

      console.log("✅ Pay Button Found");

      setTimeout(() => {

        realClick(btn);

        console.log("🚀 Pay Click Done");

      }, 800);

    }

  }, 1000);
}


// ❌ DISABLE THIS
// setTimeout(() => {
//   handleFinalPaymentClick();
// }, 15000);



// ======================
// 📱 AUTO QR CLICK (ULTIMATE FIX)
// ======================
function handleQrAutoClick() {

  console.log("📱 Waiting QR...");

  let tries = 0;

  let interval = setInterval(() => {

    tries++;

    // 🔥 1. direct function call (best)
    if (typeof submitUpiQrForm === "function") {

      try {
        submitUpiQrForm();
        console.log("🚀 QR Triggered (Function)");
        clearInterval(interval);
        return;
      } catch (e) {
        console.log("⚠️ Function call failed");
      }
    }

    // 🔥 2. span click fallback
    let qrBtn = document.querySelector("span[onclick*='submitUpiQrForm']");

    if (qrBtn) {

      try {
        qrBtn.click();
        console.log("🚀 QR Triggered (Click)");
        clearInterval(interval);
        return;
      } catch (e) {}
    }

    // 🔥 3. innerText fallback (last option)
    let alt = Array.from(document.querySelectorAll("span"))
      .find(el => el.innerText.toLowerCase().includes("pay through qr"));

    if (alt) {
      alt.click();
      console.log("🚀 QR Triggered (Text match)");
      clearInterval(interval);
      return;
    }

    // 🔁 retry limit
    if (tries > 15) {
      console.log("❌ QR not found after retries");
      clearInterval(interval);
    }

  }, 800);
}


// ▶️ RUN (IMPORTANT DELAY)
setTimeout(() => {
  handleQrAutoClick();
}, 1500);





// ======================
// 🎉 SUCCESS POPUP OVERLAY FINAL (REAL DATA)
// ======================

// 🔥 REAL DATA EXTRACT
function getIRCTCData() {

  let text = document.body.innerText;

  let pnrMatch = text.match(/PNR\s*[:\-]?\s*(\d{10})/i);
  let pnr = pnrMatch ? pnrMatch[1] : "---";

  let fareMatch = text.match(/₹\s*([\d,]+\.\d+)/);
  let fare = fareMatch ? fareMatch[1] : "---";

  let paymentMatch = text.match(/Payment\s*Mode\s*[:\-]?\s*(.*)/i);
  let payment = paymentMatch ? paymentMatch[1].split("\n")[0] : "---";

  let trainMatch = text.match(/Train\s*[:\-]?\s*(.*)/i);
  let train = trainMatch ? trainMatch[1].split("\n")[0] : "---";

  return { pnr, fare, payment, train };
}


// 🔥 OVERLAY UI
function showSuccessOverlay(data) {

  let overlay = document.createElement("div");

  overlay.innerHTML = `
  <div style="
    position:fixed;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    width:360px;
    background:#2e8b57;
    color:#fff;
    font-family:Arial;
    border-radius:15px;
    overflow:hidden;
    z-index:999999;
    box-shadow:0 0 25px rgba(0,0,0,0.6);
  ">
    
    <div style="background:#0b5fa5;padding:15px;text-align:center;font-size:20px;font-weight:bold;">
      🌲 Success By Tatkal Safer 🌲
    </div>

    <div style="padding:20px;text-align:center;line-height:2;">
      
      <div>PNR: ${data.pnr}</div>
      <div>BOOKING TIME: ${new Date().toLocaleTimeString()}</div>
      <div>FARE: ${data.fare}</div>
      <div>PAYMENT: ${data.payment}</div>
      <div>TRAIN: ${data.train}</div>
    </div>

  </div>
  `;

  document.body.appendChild(overlay);

  // 🔥 auto hide (optional)
  setTimeout(() => {
    overlay.remove();
  }, 15000);
}


// 🔥 SUCCESS DETECT
function detectSuccessPage() {

  let interval = setInterval(() => {

    let text = document.body.innerText.toLowerCase();

    if (
  text.includes("transaction successful") ||
  text.includes("booking confirmed") ||
  (text.includes("pnr") && text.includes("passenger"))
) {

      clearInterval(interval);

      console.log("🎉 SUCCESS PAGE DETECTED");
      showStep("🎉 Booking Successful");
      let data = getIRCTCData();

      console.log("📊 REAL DATA:", data);

      showSuccessOverlay(data);
    }

  }, 1000);
}


// 🔥 RUN
setTimeout(() => {
  detectSuccessPage();
}, 5000);



async function restartTrainFlow() {

  console.log("🔁 Restarting Train Selection");

  let trains = document.querySelectorAll("app-train-avl-enq, div[class*='train']");

  if (!trains.length) return;

  let fullTrain = window.finalTrain || "";
  let trainNo = fullTrain.split("-")[0]?.trim();

  for (let train of trains) {

    let match = train.innerText.match(/\((\d{5})\)/);

    if (match && match[1] === trainNo) {

      console.log("🚆 Train Found (Restart)");

      // 🔥 CLASS SELECT
      let targetClass = window.finalClass || "SL";

      let tabs = train.querySelectorAll("span, strong");

      for (let tab of tabs) {

        if (tab.innerText.toUpperCase().includes(targetClass)) {

          realClick(tab);
          await sleep(300);
          break;
        }
      }

      // 🔥 BOOK CLICK
      let btn = Array.from(train.querySelectorAll("button"))
        .find(b => b.innerText.toLowerCase().includes("book"));

      if (btn) {
        realClick(btn);
        console.log("🚀 Auto Book (Restart)");
      }

      break;
    }

  }

}





// ======================
// 🔁 IRCTC ERROR RECOVERY
// ======================

addSafeInterval(async () => {

  let text =
    document.body.innerText.toLowerCase();

  // 🔥 IRCTC error page detect
  let isErrorPage =

    text.includes("please try again") ||

    text.includes("click here to login") ||

    window.location.href.includes("/error");

  if (!isErrorPage) return;

  console.log("🚨 IRCTC ERROR PAGE DETECTED");

  // 🔥 login button
  let loginBtn = Array.from(
    document.querySelectorAll("button, a")
  ).find(el =>
    el.innerText &&
    el.innerText.toLowerCase().includes("click here to login")
  );

  if (loginBtn) {

    console.log("🔁 RECOVERY LOGIN CLICK");

    realClick(loginBtn);

    // 🔥 prevent spam click
    await sleep(5000);

  }

}, 3000);