// ==============================
// 🔥 GLOBAL DATA
// ==============================
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 || !response.ok) {
                    reject(response?.error || "Driver Error");
                    return;
                }

                resolve(response.machine_id);

            }

        );

    });

}

// load existing data
chrome.storage.local.get(null, (data) => {
  finalData = data || {};
  if (!finalData.journey_details) {
    finalData.journey_details = {};
  }
});

// ==============================
// 📅 CALENDAR SYSTEM
// ==============================
document.addEventListener('DOMContentLoaded', () => {

  const dateInput = document.getElementById('journey-date');
  const calendarIcon = document.getElementById('calendar-icon');
  const calendarContainer = document.getElementById('calendar-container');
  const monthYearElement = document.getElementById('month-year');
  const prevMonthButton = document.getElementById('prev-month');
  const nextMonthButton = document.getElementById('next-month');
  const daysElement = document.getElementById('calendar-days');

  let currentDate = new Date();

  calendarIcon.onclick = (e) => {
    e.stopPropagation();
    calendarContainer.style.display =
      calendarContainer.style.display === "block" ? "none" : "block";
    renderCalendar();
  };

  dateInput.onclick = (e) => {
    e.stopPropagation();
    calendarContainer.style.display =
      calendarContainer.style.display === "block" ? "none" : "block";
    renderCalendar();
  };

  document.addEventListener('click', (e) => {
    if (!calendarContainer.contains(e.target)) {
      calendarContainer.style.display = 'none';
    }
  });

  calendarContainer.onclick = (e) => e.stopPropagation();

  function renderCalendar() {
    daysElement.innerHTML = "";

    let year = currentDate.getFullYear();
    let month = currentDate.getMonth();
    let today = new Date();

    let firstDay = new Date(year, month, 1).getDay();
    let lastDate = new Date(year, month + 1, 0).getDate();

    monthYearElement.innerText =
      currentDate.toLocaleString("default", { month: "long" }) + " " + year;

    for (let i = 0; i < firstDay; i++) {
      daysElement.appendChild(document.createElement("div"));
    }

    for (let i = 1; i <= lastDate; i++) {
      let day = document.createElement("div");
      day.innerText = i;

      if (
        i === today.getDate() &&
        month === today.getMonth() &&
        year === today.getFullYear()
      ) {
        day.style.background = "#22c55e";
        day.style.color = "white";
      }

      day.onclick = () => {
        let d = String(i).padStart(2, "0");
        let m = String(month + 1).padStart(2, "0");
        let formatted = `${d}/${m}/${year}`;

        dateInput.value = formatted;
        finalData.journey_details.date = formatted;
        chrome.storage.local.set(finalData);
        calendarContainer.style.display = "none";
      };

      daysElement.appendChild(day);
    }
  }

  nextMonthButton.onclick = () => {
    currentDate.setMonth(currentDate.getMonth() + 1);
    renderCalendar();
  };

  prevMonthButton.onclick = () => {
    currentDate.setMonth(currentDate.getMonth() - 1);
    renderCalendar();
  };


function validateForm() {

  // 🔐 LOGIN
  let username = document.getElementById("irctc-login").value.trim();
  let password = document.getElementById("irctc-password").value.trim();

  if (!username) {
    alert("❌ Username required");
    return false;
  }

  if (!password) {
    alert("❌ Password required");
    return false;
  }



  // 🚆 JOURNEY
  let from = document.getElementById("from").value.trim();
  let to = document.getElementById("to").value.trim();
  let date = document.getElementById("journey-date").value.trim();

  if (!from) {
    alert("❌ Source required");
    return false;
  }

  if (!to) {
    alert("❌ Destination required");
    return false;
  }

  if (!date) {
    alert("❌ Date required");
    return false;
  }

  // 🚆 CLASS & QUOTA
  let cls = document.getElementById("journey-class-input").value;
let quota = document.getElementById("quota-input").value;

if (!cls) {
  alert("❌ Select Class");
  return false;
}

if (!quota) {
  alert("❌ Select Quota");
  return false;
}

// 🔥 SAVE QUOTA
chrome.storage.local.set({
  quota: quota
});

  // 🚆 TRAIN
  let train = document.getElementById("train-no").value.trim();

  if (!/^\d{5}/.test(train)) {
    alert("❌ Enter valid Train Number");
    return false;
  }

  // 📱 MOBILE
  let mobile = document.getElementById("mobile").value.trim();

  if (!/^\d{10}$/.test(mobile)) {
    alert("❌ Enter valid Mobile Number");
    return false;
  }

  // 👤 PASSENGER 1 (mandatory)
  let name1 = document.getElementById("p1-name").value.trim();
  let age1 = document.getElementById("p1-age").value.trim();
  let gender1 = document.getElementById("p1-gender").value;

  if (!name1) {
    alert("❌ Passenger 1 Name required");
    return false;
  }

  if (!/^\d+$/.test(age1)) {
    alert("❌ Passenger 1 Age invalid");
    return false;
  }

  if (!gender1) {
    alert("❌ Passenger 1 Gender required");
    return false;
  }

  // 👥 OPTIONAL PASSENGERS (2–4)
  for (let i = 2; i <= 4; i++) {

    let name = document.getElementById(`p${i}-name`).value.trim();
    let age = document.getElementById(`p${i}-age`).value.trim();
    let gender = document.getElementById(`p${i}-gender`).value;

    if (name || age || gender) {

      if (!name) {
        alert(`❌ Passenger ${i} Name required`);
        return false;
      }

      if (!/^\d+$/.test(age)) {
        alert(`❌ Passenger ${i} Age invalid`);
        return false;
      }

      if (!gender) {
        alert(`❌ Passenger ${i} Gender required`);
        return false;
      }
    }
  }

  // 💳 PAYMENT
  let payment = document.getElementById("payment-mode").value;

  if (!payment) {
    alert("❌ Select Payment Mode");
    return false;
  }

  return true;
}

  
  // ==============================
  // 🔥 SAVE BUTTON (FINAL FIX)
  // ==============================
  document.getElementById("submit-btn").onclick = () => {

    if (!validateForm()) return;

    finalData.irctc_credentials = {
      user_name: document.getElementById("irctc-login").value,
      password: document.getElementById("irctc-password").value
    };
// 🔥 TRAIN FIX ADD
let trainInput = document.getElementById("train-no").value;
let trainNo = trainInput.split("-")[0].trim();

let paymentMode = document.getElementById("payment-mode").value;

finalData.journey_details = {
  ...finalData.journey_details,
  from: document.getElementById("from").value,
  to: document.getElementById("to").value,
  class: document.getElementById("journey-class-input").value,
  quota: document.getElementById("quota-input").value,
  train_no: trainNo,

  mobile: document.getElementById("mobile").value,
  auto_upgradation:
  document.getElementById(
    "auto-upgradation"
  )?.checked || false,
  confirm_berth:
  document.getElementById(
    "confirm-berth"
  )?.checked || false,
insurance_choice:
  document.querySelector(
    "input[name='insurance']:checked"
  )?.value || "YES",
  payment_mode: paymentMode, // ✅ clean
  passengers: []
};

    // ======================
    // 🔥 PASSENGER SAVE FIX
    // ======================
    for (let i = 1; i <= 6; i++) {

      let name = document.getElementById(`p${i}-name`).value.trim();
      let age = document.getElementById(`p${i}-age`).value.trim();
      let gender = document.getElementById(`p${i}-gender`).value;
      let berth = document.getElementById(`p${i}-berth`).value;

      if (name && age && gender) {
        finalData.journey_details.passengers.push({
          name,
          age,
          gender,
          berth
        });
      }
    }

    console.log("🚀 FINAL DATA:", finalData);

    chrome.storage.local.set(finalData, () => {
      alert("✅ Data Saved Successfully");
    });
  };



  // ==============================
  // 🔄 LOAD DATA
  // ==============================
  chrome.storage.local.get(null, (data) => {

    let d = data.journey_details || {};

    if (d.payment_mode) {
      document.getElementById("payment-mode").value = d.payment_mode;
    }

  });




 function initButtons() {





  // 👉 START BOOKING (SECURE VERSION 🔐)
  const startBtn = document.getElementById("connect-btn");

  if (startBtn) {
    startBtn.addEventListener("click", async () => {

let deviceId = await getDeviceId();

let licenseData = await chrome.storage.local.get([
    "license"
]);

if (!licenseData.license) {

    alert("License not found");

    return;

}

      // 🔥 BUTTON LOADING STATE
      startBtn.disabled = true;
      startBtn.innerText = "Checking...";

      try {

let licenseData = await chrome.storage.local.get([
    "license"
]);

let response = await fetch(
"http://localhost/tatkal_safer/api/check-license.php?license="
+ encodeURIComponent(licenseData.license)
+ "&device_id="
+ encodeURIComponent(deviceId)
);

let data = await response.json();

console.log("STATUS:", data.status);


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

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

  startBtn.disabled = false;
  startBtn.innerText = "Start Booking";

  return;
}

if (data.status === "active") {
          // 🔐 DOUBLE VERIFY (ANTI BYPASS)
let verifyAgain = await fetch(
"http://localhost/tatkal_safer/api/check-license.php?license="
+ encodeURIComponent(licenseData.license)
+ "&device_id="
+ encodeURIComponent(deviceId)
);

          let verifyData = await verifyAgain.json();

          if (verifyData.status !== "active") {
            alert("Plan expired ❌");
            startBtn.disabled = false;
            startBtn.innerText = "Start Booking";
            return;
          }

chrome.runtime.sendMessage({ action: "START_BOOKING" });

        } else {

          alert("Use after buying our plan ❌");

          window.open(
            "https://tatkalsafer.xyz/plans.php",
            "_blank"
          );

        }

      } catch (e) {
        alert("Server Error");
        console.log("ERROR:", e);
      }

      // 🔄 RESET BUTTON
      startBtn.disabled = false;
      startBtn.innerText = "Start Booking";

    });
  }

}


// ==============================
// RUN AFTER PAGE LOAD
// ==============================
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initButtons);
} else {
  initButtons();
}

});





// ==============================
// 🔥 AUTOCOMPLETE (PRO VERSION)
// ==============================
function setupAuto(inputId) {

  const input = document.getElementById(inputId);

  let list = document.createElement("div");
  list.style.background = "white";
  list.style.color = "black";
  list.style.maxHeight = "150px";
  list.style.overflowY = "auto";
  list.style.position = "absolute";
 
  list.style.zIndex = "9999";

  document.body.appendChild(list);

  let selectedIndex = -1;
  let currentItems = [];

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

    let val = input.value.toUpperCase();
    list.innerHTML = "";
    selectedIndex = -1;
    currentItems = [];

    if (!val || !stations || !stations.length) return;

    const rect = input.getBoundingClientRect();
    list.style.left = rect.left + "px";
    list.style.top = (rect.bottom + window.scrollY) + "px";
    list.style.width = rect.width + "px";

    let result = stations.filter(s => {

  let code =
    s.code.toUpperCase();

  let name =
    s.name.toUpperCase();

  return (
    code.startsWith(val) ||
    name.startsWith(val)
  );

}).slice(0, 5);

    currentItems = result;

    result.forEach((s, index) => {
      let item = document.createElement("div");
      item.innerText = `${s.name} - ${s.code}`;
      item.style.padding = "6px";
      item.style.cursor = "pointer";

      // 🔥 hover effect
      item.onmouseover = () => highlight(index);
      item.onclick = () => selectItem(index);

      list.appendChild(item);
    });

    // 🔥 AUTO SELECT FIRST
    if (result.length > 0) {
      highlight(0);
    }

  });

  // ==============================
  // 🔥 KEYBOARD CONTROL
  // ==============================
  input.addEventListener("keydown", (e) => {

    if (!currentItems.length) return;

    if (e.key === "ArrowDown") {
      e.preventDefault();
      selectedIndex = (selectedIndex + 1) % currentItems.length;
      highlight(selectedIndex);
    }

    if (e.key === "ArrowUp") {
      e.preventDefault();
      selectedIndex = (selectedIndex - 1 + currentItems.length) % currentItems.length;
      highlight(selectedIndex);
    }

    if (e.key === "Enter") {
      e.preventDefault();
      if (selectedIndex >= 0) {
        selectItem(selectedIndex);
      }
    }

  });

  // ==============================
  // 🔥 FUNCTIONS
  // ==============================
  function highlight(index) {
    let items = list.children;

    for (let i = 0; i < items.length; i++) {
      items[i].style.background = i === index ? "#e0e0e0" : "white";
    }

    selectedIndex = index;
  }

  function selectItem(index) {
    let s = currentItems[index];
    input.value = `${s.name} - ${s.code}`;
    list.innerHTML = "";
  }

  // 🔥 click outside hide
  document.addEventListener("click", (e) => {
    if (!input.contains(e.target)) {
      list.innerHTML = "";
    }
  });

}

// INIT
document.addEventListener("DOMContentLoaded", () => {
  setupAuto("from");
  setupAuto("to");
});





// ==============================
// 🚆 TRAIN AUTOCOMPLETE (FINAL PRO VERSION)
// ==============================
document.addEventListener("DOMContentLoaded", () => {

  const input = document.getElementById("train-no");
  const list = document.getElementById("train-suggestions");
list.style.border = "none";

list.style.outline = "none";

list.style.boxShadow =
  "0 8px 20px rgba(0,0,0,0.25)";

list.style.borderRadius = "10px";

list.style.background =
  "rgba(255, 255, 255, 0.95)";
  if (!input || !list) return;

  let currentIndex = -1;
  let items = [];

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

    let val = input.value.toLowerCase().trim();
    list.innerHTML = "";
    currentIndex = -1;

    if (!val || typeof trainNumbers === "undefined") return;

    // 🔥 SMART FILTER (MULTIPLE RESULT)
    let result = trainNumbers.filter(t => {
      let txt = t.toLowerCase();
      return txt.startsWith(val)
  || txt.includes(" " + val);
    }).slice(0, 10);

    result.forEach((t, index) => {

      let item = document.createElement("div");
      item.innerText = t;
      item.style.padding = "6px";
      item.style.cursor = "pointer";

      item.onclick = () => {
        input.value = t; // 🔥 FULL TEXT (number + name)
        list.innerHTML = "";
      };

      list.appendChild(item);
    });

    items = list.querySelectorAll("div");
  });

  // ======================
  // ⌨️ KEYBOARD SUPPORT
  // ======================
  input.addEventListener("keydown", (e) => {

    if (!items.length) return;

    if (e.key === "ArrowDown") {
      currentIndex++;
      highlight();
    }

    else if (e.key === "ArrowUp") {
      currentIndex--;
      highlight();
    }

    else if (e.key === "Enter") {
      e.preventDefault();
      if (currentIndex > -1 && items[currentIndex]) {
        items[currentIndex].click();
      }
    }
  });

  function highlight() {
    items.forEach(item => {
      item.style.background = "white";
      item.style.color = "black";
    });

    if (currentIndex >= items.length) currentIndex = 0;
    if (currentIndex < 0) currentIndex = items.length - 1;

    items[currentIndex].style.background = "#3b82f6";
    items[currentIndex].style.color = "#fff";
  }

});







const password = document.getElementById("irctc-password");
const toggle = document.getElementById("togglePassword");

toggle.addEventListener("click", () => {

  if (password.type === "password") {

    password.type = "text";
    toggle.innerHTML = "👁️‍🗨️";

  } else {

    password.type = "password";
    toggle.innerHTML = "👁️";

  }

});




const from = document.getElementById("from");
const to = document.getElementById("to");
const swap = document.getElementById("swapBtn");

swap.addEventListener("click", () => {

  let temp = from.value;

  from.value = to.value;
  to.value = temp;

  console.log("🔄 Stations Swapped");

});



// ======================
// 📥 LOAD BUTTON SAVED DATA (FINAL)
// ======================

document.getElementById("loadDataBtn")
.addEventListener("click", () => {

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

    let d = data.journey_details || {};
    let login = data.irctc_credentials || {};

    // ======================
    // 🔐 LOGIN DETAILS
    // ======================
    document.getElementById("irctc-login").value =
      login.user_name || "";

    document.getElementById("irctc-password").value =
      login.password || "";

    

    // ======================
    // 🚆 JOURNEY DETAILS
    // ======================
    document.getElementById("from").value =
      d.from || "";

    document.getElementById("to").value =
      d.to || "";

    // 🔥 FULL TRAIN LOAD
    document.getElementById("train-no").value =
      d.train_no || "";

    document.getElementById("journey-date").value =
      d.date || "";

    document.getElementById("journey-class-input").value =
      d.class || "";

    document.getElementById("quota-input").value =
      d.quota || "";

    document.getElementById("mobile").value =
      d.mobile || "";

    // ======================
    // 💳 PAYMENT MODE
    // ======================
    document.getElementById("payment-mode").value =
      d.payment_mode || "";

    // ======================
    // 💰 UPI ID
    // ======================
    let upiInput = document.getElementById("upi-id");

    if (upiInput && d.upi_id) {
      upiInput.value = d.upi_id;
    }

    // ======================
    // 👤 PASSENGERS
    // ======================
    let passengers = d.passengers || [];

    for (let i = 0; i < passengers.length; i++) {

      let p = passengers[i];

      let n = document.getElementById(`p${i+1}-name`);
      let a = document.getElementById(`p${i+1}-age`);
      let g = document.getElementById(`p${i+1}-gender`);
      let b = document.getElementById(`p${i+1}-berth`);

      if (n) n.value = p.name || "";
      if (a) a.value = p.age || "";
      if (g) g.value = p.gender || "";
      if (b) b.value = p.berth || "";
    }
// ======================
// 🎫 EXTRA OPTIONS
// ======================

// Confirm Berth checkbox
let confirmBerth =
  document.getElementById("confirm-berth");

if (confirmBerth) {
  confirmBerth.checked =
    d.confirm_berth || false;
}

// Travel Insurance
let insuranceRadios =
  document.getElementsByName("insurance");

let insuranceValue =
  d.insurance_choice || "YES";

for (let radio of insuranceRadios) {

  radio.checked =
    (radio.value === insuranceValue);

}
// Auto Upgradation checkbox
let autoUpgrade =
  document.getElementById("auto-upgradation");

if (autoUpgrade) {
  autoUpgrade.checked =
    d.auto_upgradation || false;
}
    console.log("✅ FULL DATA LOADED");
if (
  !data ||
  !data.journey_details ||
  !data.journey_details.from
) {

  alert("❌ No Saved Data Found");

  return;
}
    alert("✅ Saved Data Loaded Succesfully");

  });

});