// Track open times
let tabOpenTimes = {};

// When a tab is created, store its timestamp
chrome.tabs.onCreated.addListener(tab => {
  tabOpenTimes[tab.id] = Date.now();
});

// When a tab is updated (like URL change), reset timer
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === "complete") {
    tabOpenTimes[tabId] = Date.now();
  }
});

// When a tab is removed, clean up
chrome.tabs.onRemoved.addListener(tabId => {
  delete tabOpenTimes[tabId];
});

// Update badge every second with elapsed time of the active tab
setInterval(() => {
  chrome.tabs.query({active: true, currentWindow: true}, tabs => {
    if (tabs.length === 0) return;
    let tab = tabs[0];
    let now = Date.now();
    let openTime = tabOpenTimes[tab.id] || now;
    let elapsed = Math.floor((now - openTime) / 1000);

    // Show elapsed seconds as badge text
    chrome.action.setBadgeText({text: elapsed + "s"});
    chrome.action.setBadgeBackgroundColor({color: "#1E90FF"}); // orange
  });
}, 1000);

// Closing logic every 5 seconds
setInterval(() => {
  chrome.tabs.query({}, tabs => {
    if (tabs.length > 1) {
      let now = Date.now();

      for (let tab of tabs) {
        let url = tab.url || "";
        if (url.includes("kolotibablo.com")) continue;

        let openTime = tabOpenTimes[tab.id] || now;
        let elapsed = (now - openTime) / 1000;

        // ✅ Close after 120 seconds (2 minutes)
        if (elapsed > 120 && tabs.length > 1) {
          chrome.tabs.remove(tab.id);
          break;
        }
      }
    }
  });
}, 5000);
