var AppLog = "";
var isStarted = "";
var HataDurum = "";
var CalisanSekmeId = 0;
var CalisanSekmeIndex = 0;

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
  if (msg.isStarted) {
    AppLog = msg.AppLog;
    isStarted = msg.isStarted;
    HataDurum = msg.HataDurum;
    if (HataDurum == true) {
      chrome.browserAction.setBadgeBackgroundColor({ color: "#9e0606" });
      chrome.browserAction.setBadgeText({ text: "Hata" });
    } else {
      chrome.browserAction.setBadgeBackgroundColor({ color: "#00a65a" });
      chrome.browserAction.setBadgeText({ text: "OK" });
    }
  }

  if (msg.method == "Dashboard")
    sendResponse({
      "isStarted": isStarted,
      "HataDurum": HataDurum,
      "AppLog": AppLog
    });

  if (msg.YenidenBaslat) {
    if (CalisanSekmeId != undefined && CalisanSekmeId > 0) {
      setTimeout(function () {
        chrome.tabs.sendMessage(CalisanSekmeId, { PageReload: true });
      }, 1800000);
    } else {
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        if (tabs[0]) {
          chrome.tabs.sendMessage(tabs[0].id, { SekmeBulunamadi: true });
        }
      });
    }
  }

  if (msg.AktifSekmeBilgileri) {
    CalisanSekmeId = sender.tab.id;
    CalisanSekmeIndex = parseInt(sender.tab.index) + 1;
    console.log(CalisanSekmeId);
    chrome.browserAction.setBadgeBackgroundColor({ color: "#00a65a" });
    chrome.browserAction.setBadgeText({ text: "On" });
  }

  if (msg.SekmeKapat) {
    var tabID = sender.tab.id;
    setTimeout(function () { SekmeKapat(tabID); }, 500);
  }

  if (msg.YeniSekme) {
    var newURL = msg.Url;
    setTimeout(function () { chrome.tabs.create({ url: newURL }); }, 100);
    setTimeout(function () {
      chrome.browserAction.setBadgeBackgroundColor({ color: "#00a65a" });
      chrome.browserAction.setBadgeText({ text: "On" });
    }, 10000);
  }

  if (msg.UygulamaKapatildi) {
    stopCrashRecovery();
  }
});

function SekmeKapat(tabID) {
  chrome.tabs.remove(tabID, function () {});
}

// ─── Crash Recovery (Out of Memory / Aw Snap!) ───────────────────────────────
var crashCheckTimer = null;

function startCrashRecovery() {
  if (crashCheckTimer) return;
  console.log('[BookOutlet BG] Crash recovery başlatıldı');

  crashCheckTimer = setInterval(function () {
    chrome.storage.sync.get(['isStarted'], function (item) {
      if (!item.isStarted) {
        stopCrashRecovery();
        return;
      }

      if (!CalisanSekmeId || CalisanSekmeId <= 0) return;

      chrome.tabs.get(CalisanSekmeId, function (tab) {
        if (chrome.runtime.lastError) {
          console.log('[BookOutlet BG] Sekme bulunamadı:', chrome.runtime.lastError.message);
          return;
        }

        var crashed = false;

        // 1. Sekme discarded (bellek boşaltıldı)
        if (tab.discarded) crashed = true;

        // 2. Chrome hata sayfası (Aw, Snap!)
        if (tab.url && tab.url.indexOf('chrome-error://') !== -1) crashed = true;

        // 3. Unloaded
        if (tab.status === 'unloaded') crashed = true;

        if (crashed) {
          console.log('[BookOutlet BG] Sekme çökmüş! Reload ediliyor...');
          chrome.browserAction.setBadgeBackgroundColor({ color: "#e08e0b" });
          chrome.browserAction.setBadgeText({ text: "!" });
          chrome.tabs.reload(CalisanSekmeId, { bypassCache: true });
        }
      });
    });
  }, 30000); // 30 saniyede bir kontrol
}

function stopCrashRecovery() {
  if (crashCheckTimer) {
    clearInterval(crashCheckTimer);
    crashCheckTimer = null;
    console.log('[BookOutlet BG] Crash recovery durduruldu');
  }
}

// Sekme reload sonrası badge güncelle
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  if (tabId !== CalisanSekmeId) return;
  if (changeInfo.status !== 'complete') return;
  if (!tab.url || tab.url.indexOf('bookoutlet.com') === -1) return;

  chrome.storage.sync.get(['isStarted'], function (item) {
    if (item.isStarted) {
      chrome.browserAction.setBadgeBackgroundColor({ color: "#00a65a" });
      chrome.browserAction.setBadgeText({ text: "On" });
      console.log('[BookOutlet BG] Sekme yüklendi:', tab.url);
    }
  });
});

// isStarted değişince crash recovery başlat/durdur
chrome.storage.onChanged.addListener(function (changes) {
  if (changes.isStarted) {
    if (changes.isStarted.newValue === true) {
      startCrashRecovery();
    } else {
      stopCrashRecovery();
    }
  }
});

// Başlangıçta kontrol
chrome.storage.sync.get(['isStarted'], function (item) {
  if (item.isStarted) startCrashRecovery();
});