importScripts('./api-compatibility.js');
importScripts('./crypto-js.min.js');
importScripts('./generate-rsig.js');

// ====================================
// UBER: User-Agent yönetimi — Safari 18.6 / macOS profili
// ====================================
let uberUserAgent = '';
let activeUberToken = null;

const UBER_UA_FALLBACK = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15';

const UBER_DNR_RULE_ID = 9120;
const UBER_DNR_URL_REGEX = '(?i)^https?://([a-z0-9.-]+\\.)*(uber\\.com|cdn-net\\.com|cdn-path\\.com)(:\\d+)?(/|$|\\?|#)';


const UBER_DNR_REMOVE_HEADERS = [
  'sec-ch-ua',
  'sec-ch-ua-mobile',
  'sec-ch-ua-platform',
  'sec-ch-ua-platform-version',
  'sec-ch-ua-full-version-list',
  'sec-ch-ua-full-version',
  'sec-ch-ua-arch',
  'sec-ch-ua-bitness',
  'sec-ch-ua-model',
  'sec-ch-ua-wow64',
  'sec-ch-ua-ua',
  'sec-ch-ua-form-factor',
  'sec-ch-ua-viewport-width',
  'sec-ch-ua-dpr',
  'sec-ch-ua-resolution',
];

async function setupUberHeaderRules() {
  let ua = uberUserAgent || UBER_UA_FALLBACK;

  try {
    await RequestHeaderManager.updateDynamicRules({
      removeRuleIds: [9100, 9101, UBER_DNR_RULE_ID, 9121, 9122]
    });

    const setHeaders = [
      { header: 'User-Agent',      operation: 'set', value: ua },
      { header: 'Accept-Encoding', operation: 'set', value: 'gzip, deflate, br' },
      { header: 'Accept-Language', operation: 'set', value: 'tr-TR,tr;q=0.9' },
    ];

    const removeHeaders = UBER_DNR_REMOVE_HEADERS.map(h => ({
      header: h, operation: 'remove'
    }));

    await RequestHeaderManager.updateDynamicRules({
      addRules: [
        {
          id: UBER_DNR_RULE_ID,
          priority: 1,
          action: {
            type: 'modifyHeaders',
            requestHeaders: [...setHeaders, ...removeHeaders]
          },
          condition: {
            regexFilter: UBER_DNR_URL_REGEX,
            resourceTypes: ['main_frame', 'sub_frame', 'stylesheet', 'script', 'image', 'font', 'object', 'xmlhttprequest', 'ping', 'csp_report', 'media', 'websocket', 'other']
          }
        }
      ]
    });

    console.log(`[Uber] Safari DNR kuralları kuruldu. UA: ${ua.substring(0, 60)}...`);
  } catch (e) {
    console.warn('[Uber] DNR header kuralları uygulanamadı:', e);
  }
}

// ====================================
// UBER: Cookie yardımcıları
// ====================================
function domainMatchesCookie(hostname, cookieDomain) {
  if (!hostname || !cookieDomain) return false;
  const normalized = cookieDomain.startsWith('.') ? cookieDomain.slice(1) : cookieDomain;
  return hostname === normalized || hostname.endsWith(`.${normalized}`);
}

async function buildCookieHeaderForUrl(rawUrl) {
  let target;
  try {
    target = new URL(rawUrl);
  } catch (_) {
    return '';
  }

  try {
    const allCookies = await chrome.cookies.getAll({});
    const pathName = target.pathname || '/';

    const matching = allCookies.filter(cookie => {
      if (!cookie || !cookie.name) return false;
      if (!domainMatchesCookie(target.hostname, cookie.domain || '')) return false;
      if (cookie.secure && target.protocol !== 'https:') return false;
      const cookiePath = cookie.path || '/';
      return pathName.startsWith(cookiePath);
    });

    matching.sort((a, b) => (b.path || '/').length - (a.path || '/').length);
    return matching.map(cookie => `${cookie.name}=${cookie.value}`).join('; ');
  } catch (e) {
    return '';
  }
}

function writeUberFpSeedCookie(seed, chromeFull) {
  if (!seed) return;
  const val = chromeFull ? `${seed}:${chromeFull}` : seed;
  for (const domain of ['.uber.com', '.m.uber.com', '.account.uber.com']) {
    chrome.cookies.set({
      url:            'https://www.uber.com',
      name:           '_ubfp',
      value:          encodeURIComponent(val),
      domain:         domain,
      path:           '/',
      secure:         true,
      httpOnly:       false,
      sameSite:       'no_restriction',
      expirationDate: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60
    }).catch(() => {});
  }
}

// ====================================
// UBER: Proxy işleyicisi — PHP proxy (KuponStore mantığı)
// ====================================
const UBER_PROXY_ENDPOINT = 'https://kuponmarket.online/km-uber-proxy.php';
const UBER_PROXY_API_KEY = 'KM-Uber-Proxy-2026-x7Qm9vR3sT1wZ';

async function applySetCookiesToBrowser(requestUrl, setCookies) {
  if (!setCookies || !setCookies.length) return;
  for (const raw of setCookies) {
    try {
      const parts = raw.split(';').map(s => s.trim());
      const [nameVal, ...attrs] = parts;
      const eqIdx = nameVal.indexOf('=');
      if (eqIdx <= 0) continue;
      const name = nameVal.substring(0, eqIdx);
      const value = nameVal.substring(eqIdx + 1);
      let domain, path = '/', secure = false, httpOnly = false, sameSite = 'no_restriction';
      let expirationDate;
      for (const attr of attrs) {
        const lower = attr.toLowerCase();
        if (lower.startsWith('domain=')) domain = attr.substring(7);
        else if (lower.startsWith('path=')) path = attr.substring(5);
        else if (lower === 'secure') secure = true;
        else if (lower === 'httponly') httpOnly = true;
        else if (lower.startsWith('samesite=')) {
          const sv = lower.substring(9);
          if (sv === 'lax') sameSite = 'lax';
          else if (sv === 'strict') sameSite = 'strict';
          else sameSite = 'no_restriction';
        }
        else if (lower.startsWith('max-age=')) {
          const ma = parseInt(attr.substring(8));
          if (!isNaN(ma)) expirationDate = Math.floor(Date.now() / 1000) + ma;
        }
        else if (lower.startsWith('expires=')) {
          const d = new Date(attr.substring(8));
          if (!isNaN(d.getTime())) expirationDate = Math.floor(d.getTime() / 1000);
        }
      }
      if (!domain) {
        try { domain = new URL(requestUrl).hostname; } catch (_) { continue; }
      }
      const urlDomain = domain.startsWith('.') ? domain.substring(1) : domain;
      const cookieData = { url: `https://${urlDomain}`, name, value, domain, path, secure, httpOnly, sameSite };
      if (expirationDate) cookieData.expirationDate = expirationDate;
      await chrome.cookies.set(cookieData).catch(() => {});
    } catch (_) {}
  }
}

async function handleUberProxyRequest(request, sendResponse) {
  try {
    if (!request.url) throw new Error('URL eksik');

    let bodyPayload = null;
    if (request.body) {
      bodyPayload = typeof request.body === 'string' ? request.body : JSON.stringify(request.body);
    }

    const outboundHeaders = Object.assign({}, request.headers || {});
    const hasCookieHeader = Object.keys(outboundHeaders).some(k => k.toLowerCase() === 'cookie');
    if (!hasCookieHeader) {
      const cookieHeader = await buildCookieHeaderForUrl(request.url);
      if (cookieHeader) outboundHeaders.Cookie = cookieHeader;
    }

    const response = await fetch(UBER_PROXY_ENDPOINT, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': UBER_PROXY_API_KEY,
      },
      body: JSON.stringify({
        url: request.url,
        method: request.method || 'GET',
        headers: outboundHeaders,
        body: bodyPayload
      })
    });

    const responseText = await response.text();
    let finalStatus = response.status;
    let finalData = responseText;
    let finalHeaders = {};
    response.headers.forEach((value, key) => { finalHeaders[key.toLowerCase()] = value; });
    let setCookies = [];

    try {
      const envelope = JSON.parse(responseText);
      if (envelope && envelope.success === false) {
        sendResponse({
          success: false,
          error: envelope.error || envelope.curl_error || 'Proxy error',
          status: envelope.status || response.status,
          headers: {},
          data: '',
        });
        return true;
      }
      if (envelope && envelope.status !== undefined) {
        finalStatus = envelope.status;
        finalData = typeof envelope.data === 'string' ? envelope.data : JSON.stringify(envelope.data || '');
        if (envelope.headers && typeof envelope.headers === 'object') finalHeaders = envelope.headers;
        if (Array.isArray(envelope.setCookies)) setCookies = envelope.setCookies.filter(v => typeof v === 'string' && v);
      }
    } catch (e) {}

    if (!setCookies.length && typeof finalHeaders['set-cookie'] === 'string') {
      setCookies = finalHeaders['set-cookie'].split('\n').map(v => v.trim()).filter(Boolean);
    }

    if (setCookies.length) await applySetCookiesToBrowser(request.url, setCookies);

    sendResponse({ success: true, status: finalStatus, statusText: 'OK', headers: finalHeaders, data: finalData });
    return true;
  } catch (error) {
    console.error('Background: Uber proxy istek hatası:', error);
    sendResponse({ success: false, error: error.message || 'Bilinmeyen hata', headers: {} });
    return true;
  }
}

// ====================================
// UBER: Türkçe isim üretimi
// ====================================
const TURKISH_MALE_NAMES = [
  'Ahmet', 'Mehmet', 'Mustafa', 'Ali', 'Hasan', 'Hüseyin', 'İbrahim', 'Osman',
  'Yusuf', 'Murat', 'Ömer', 'Fatih', 'Emre', 'Burak', 'Serkan', 'Kerem',
  'Cem', 'Kaan', 'Eren', 'Barış', 'Tolga', 'Onur', 'Deniz', 'Enes',
  'Furkan', 'Umut', 'Berkay', 'Uğur', 'Volkan', 'Gökhan', 'Tuncay', 'Selim',
  'Oğuz', 'Caner', 'Alper', 'Koray', 'Erdem', 'Serhat', 'Batuhan', 'Arda',
  'Görkem', 'Çağlar', 'Taylan', 'Hakan', 'Sinan', 'Berk', 'Doruk', 'Yiğit'
];

const TURKISH_FEMALE_NAMES = [
  'Fatma', 'Ayşe', 'Emine', 'Hatice', 'Zeynep', 'Elif', 'Merve', 'Büşra',
  'Esra', 'Ebru', 'Seda', 'Özlem', 'Gamze', 'Derya', 'Pınar', 'Gül',
  'Sevgi', 'Tuğba', 'Sibel', 'Yasemin', 'Gizem', 'İrem', 'Cansu', 'Melis',
  'Ece', 'Dilara', 'Aslı', 'Zehra', 'Şeyma', 'Beyza', 'Buse', 'Nur',
  'Selin', 'Ceren', 'Nazlı', 'Deniz', 'Damla', 'Şule', 'Burcu', 'Nesrin',
  'Gülşen', 'Meltem', 'Nilgün', 'Sevda', 'Havva', 'Sema', 'Hande', 'Bengü'
];

const TURKISH_SURNAMES = [
  'Yılmaz', 'Kaya', 'Demir', 'Çelik', 'Şahin', 'Yıldız', 'Yıldırım', 'Öztürk',
  'Aydın', 'Özdemir', 'Arslan', 'Doğan', 'Kılıç', 'Aslan', 'Çetin', 'Kara',
  'Koç', 'Kurt', 'Özkan', 'Şimşek', 'Polat', 'Korkmaz', 'Çakır', 'Erdoğan',
  'Güneş', 'Ak', 'Aksoy', 'Acar', 'Avcı', 'Aktaş', 'Tekin', 'Çiçek',
  'Kaplan', 'Bozkurt', 'Güler', 'Işık', 'Duman', 'Ateş', 'Bal', 'Gündüz',
  'Taş', 'Bulut', 'Ünal', 'Yavuz', 'Bilgin', 'Erdem', 'Karaca', 'Eren'
];

function generateRandomTurkishName(gender = 'male') {
  const names = gender === 'female' ? TURKISH_FEMALE_NAMES : TURKISH_MALE_NAMES;
  const firstName = names[Math.floor(Math.random() * names.length)];
  const lastName = TURKISH_SURNAMES[Math.floor(Math.random() * TURKISH_SURNAMES.length)];
  return { firstName, lastName };
}

// ====================================
// UBER: Site verilerini temizleme
// ====================================
async function clearUberSiteData(domains) {
  const domainList = Array.isArray(domains) ? domains : [domains];
  try {
    const allCookies = await chrome.cookies.getAll({});
    const removePromises = [];
    for (const cookie of allCookies) {
      const dom = (cookie.domain || '').toLowerCase();
      for (const target of domainList) {
        if (dom.includes(target)) {
          const url = "http" + (cookie.secure ? "s" : "") + "://" +
            (cookie.domain.startsWith('.') ? cookie.domain.substring(1) : cookie.domain) +
            cookie.path;
          removePromises.push(chrome.cookies.remove({ url, name: cookie.name }).catch(() => {}));
          break;
        }
      }
    }
    await Promise.all(removePromises);

    try {
      await BrowsingDataManager.remove({
        origins: domainList.map(d => `https://${d}`)
      }, {
        cache: true, cacheStorage: true, cookies: true,
        indexedDB: true, localStorage: true, serviceWorkers: true
      });
    } catch (_) {}

    try {
      const existingTabs = await chrome.tabs.query({ url: '*://*.uber.com/*' });
      for (const tab of existingTabs) {
        if (tab.id) {
          chrome.scripting.executeScript({
            target: { tabId: tab.id },
            func: () => {
              try {
                localStorage.clear();
                sessionStorage.clear();
                if (indexedDB && indexedDB.databases) {
                  indexedDB.databases().then(dbs => {
                    dbs.forEach(db => { if (db.name) indexedDB.deleteDatabase(db.name); });
                  });
                }
                if (caches) {
                  caches.keys().then(names => {
                    names.forEach(name => caches.delete(name));
                  });
                }
              } catch (e) {}
            },
            world: 'MAIN'
          }).catch(() => {});
        }
      }
    } catch (e) {}
  } catch (e) {
    console.error('Uber site verileri temizleme hatası:', e);
  }
}

// ====================================
// UBER: İsim güncelleme
// ====================================
async function updateUberUserName(firstName, lastName, rawCookies, tabId) {
  const requestId = crypto.randomUUID();
  const marketingId = rawCookies.find(c => c.name === "marketing_vistor_id")?.value || "";
  const referer = "https://account.uber.com/update-display-name";

  const ruleId = 9001;
  await chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: [ruleId],
    addRules: [{
      id: ruleId,
      priority: 100,
      action: {
        type: "modifyHeaders",
        requestHeaders: [
          { header: "origin",         operation: "set", value: "https://account.uber.com" },
          { header: "referer",        operation: "set", value: referer },
          { header: "sec-fetch-site", operation: "set", value: "same-origin" }
        ]
      },
      condition: {
        urlFilter: "account.uber.com/api/updateUserInfo",
        resourceTypes: ["xmlhttprequest"]
      }
    }]
  });

  try {
    const response = await fetch(
      "https://account.uber.com/api/updateUserInfo?localeCode=tr-TR",
      {
        method: "POST",
        credentials: "include",
        redirect: "manual",
        headers: {
          "content-type": "application/json",
          "accept": "*/*",
          "x-uber-country-iso2": "TR",
          "x-uber-client-name": "uam_desktop",
          "x-uber-request-uuid": requestId,
          "x-uber-device": "",
          "x-uber-device-model": "",
          "x-uber-device-os": "10",
          "x-uber-tenancy": "",
          "x-uber-decision-engine-is-shadow": "true",
          "x-uber-device-location-latitude": "",
          "x-uber-client-version": "",
          "x-uber-device-mobile-iso2": "",
          "x-uber-client-session": "",
          "x-uber-client-id": "",
          "x-uber-auth-sso-id": "",
          "x-uber-device-location-longitude": "",
          "x-uber-marketing-id": marketingId,
          "x-uber-app-device-id": "",
          "x-uber-app-variant": "",
          "x-uber-device-id": "",
          "x-csrf-token": "x",
          "x-uber-device-language": "",
          "x-uber-device-udid": "",
          "x-uber-identity-entrypoint": "uam"
        },
        body: JSON.stringify({
          userInfoUpdate: {
            userInfoUpdateType: "NAME",
            name: { firstname: firstName, lastname: lastName }
          }
        })
      }
    );

    if (response.ok || response.type === "opaqueredirect" || response.status === 0) {
      console.log(`[Uber] İsim güncellendi: ${firstName} ${lastName}`);
      return;
    }

    const text = await response.text().catch(() => "");
    throw new Error(`Uber isim güncelleme başarısız (${response.status}): ${text.substring(0, 200)}`);
  } finally {
    await chrome.declarativeNetRequest.updateDynamicRules({ removeRuleIds: [ruleId] });
  }
}

// ====================================
// UBER: Cookie'leri set etme
// ====================================
async function setUberCookies(cookies) {
  const nowInSeconds = Math.floor(Date.now() / 1000);
  const ONE_YEAR = 365 * 24 * 60 * 60;
  const THIRTY_DAYS = 30 * 24 * 60 * 60;

  const uberDomains = ['uber.com', 'cdn-net.com', 'cdn-path.com'];
  for (const cookie of cookies) {
    try {
      const dom = (cookie.domain || '').toLowerCase();
      const isUberCookie = uberDomains.some(d => dom.includes(d));
      if (!isUberCookie) continue;

      const domain = cookie.domain || '.uber.com';
      const domainForUrl = domain.startsWith('.') ? domain.substring(1) : domain;
      const cookieData = {
        url: `https://${domainForUrl}`,
        name: cookie.name,
        value: cookie.value,
        domain: domain,
        path: cookie.path || '/',
        secure: true,
        httpOnly: cookie.httpOnly || false,
        sameSite: 'no_restriction'
      };

      let expiresSeconds = cookie.expires || cookie.expirationDate;
      if (!expiresSeconds && cookie.expiresAtMs) {
        expiresSeconds = Math.floor(new Date(cookie.expiresAtMs).getTime() / 1000);
      }
      if (expiresSeconds && expiresSeconds > 0 && expiresSeconds !== -1) {
        cookieData.expirationDate = expiresSeconds < nowInSeconds
          ? nowInSeconds + ONE_YEAR
          : expiresSeconds;
      } else {
        cookieData.expirationDate = nowInSeconds + THIRTY_DAYS;
      }
      await chrome.cookies.set(cookieData);
    } catch (e) {}
  }
}

// ====================================
// UBER: Ana giriş işlemi
// ====================================
async function handleUberLogin(cookies, token, tabId, gender = null, startLink = '', customFirstName = '', customLastName = '') {
  try {
    console.log('[Uber] Oturum hazırlanıyor...');

    await chrome.storage.local.set({ activeUberToken: token });

    const newSeed = crypto.randomUUID();
    await chrome.storage.local.set({ uberFpSeed: newSeed });

    uberUserAgent = UBER_UA_FALLBACK;
    await chrome.storage.local.set({ uberUserAgent: uberUserAgent });

    await setupUberHeaderRules();

    try {
      const allTabs = await chrome.tabs.query({});
      for (const tab of allTabs) {
        if (tab.url && (tab.url.includes('uber.com') || tab.url.includes('cdn-net.com')) && tab.id) {
          chrome.tabs.sendMessage(tab.id, {
            action: 'uberNewFpSeed',
            seed: newSeed
          }).catch(() => {});
        }
      }
    } catch (_) {}

    try {
      const allTabs = await chrome.tabs.query({});
      const otherUberTabs = allTabs.filter(tab =>
        tab.url && tab.url.toLowerCase().includes('uber') && tab.id !== tabId
      );
      await Promise.all(otherUberTabs.map(tab => chrome.tabs.remove(tab.id).catch(() => {})));
    } catch (e) {}

    console.log('[Uber] Site verileri temizleniyor...');
    await clearUberSiteData([
      "uber.com", "www.uber.com", "m.uber.com", "account.uber.com",
      "auth.uber.com", "login.uber.com", "payments.uber.com",
      "riders.uber.com", "api.uber.com", "csp.uber.com",
      "cdn-net.com", "cdn-cgi.uber.com", "d1a3f4spazzrp4.cloudfront.net"
    ]);

    try {
      const allCookies = await chrome.cookies.getAll({});
      await Promise.all(allCookies.filter(c => c.domain.toLowerCase().includes('inauth')).map(c => {
        const url = "http" + (c.secure ? "s" : "") + "://" + (c.domain.startsWith('.') ? c.domain.substring(1) : c.domain) + c.path;
        return chrome.cookies.remove({ url, name: c.name }).catch(() => {});
      }));
    } catch (_) {}

    writeUberFpSeedCookie(newSeed);

    console.log('[Uber] Yeni oturum cookie\'leri set ediliyor...');
    await setUberCookies(cookies);
    await new Promise(resolve => setTimeout(resolve, 300));

    let firstName, lastName;
    if (customFirstName && customLastName) {
      firstName = customFirstName;
      lastName = customLastName;
      console.log(`[Uber] Kullanıcı ismi: ${firstName} ${lastName}`);
    } else {
      let selectedGender = gender;
      if (!selectedGender) {
        const genderData = await chrome.storage.local.get('uberGender');
        selectedGender = genderData.uberGender || 'male';
      }
      const randomName = generateRandomTurkishName(selectedGender);
      firstName = randomName.firstName;
      lastName = randomName.lastName;
      console.log(`[Uber] Rastgele isim (${selectedGender}): ${firstName} ${lastName}`);
    }

    await chrome.storage.local.set({
      _uberPendingNameUpdate: { firstName, lastName, cookies, tabId, startLink }
    });

    console.log('[Uber] Oturum doğrulanıyor — form tabanlı isim güncelleme...');
    const newTab = await chrome.tabs.create({ url: "https://account.uber.com/update-display-name" });
    const pendingData = await chrome.storage.local.get('_uberPendingNameUpdate');
    if (pendingData._uberPendingNameUpdate) {
      pendingData._uberPendingNameUpdate.tabId = newTab.id;
      await chrome.storage.local.set({ _uberPendingNameUpdate: pendingData._uberPendingNameUpdate });
    }
  } catch (error) {
    console.error("[Uber] Giriş hatası:", error);
    await chrome.storage.local.remove('_uberPendingNameUpdate').catch(() => {});
    throw error;
  }
}

// ====================================
// UBER: Tab güncelleme dinleyicisi
// ====================================
async function _uberOnUpdatedHandler(updatedTabId, info, tab) {
  if (info.status !== 'complete') return;
  if (!tab.url || !tab.url.includes('account.uber.com') || !tab.url.includes('update-display-name')) return;

  const data = await chrome.storage.local.get('_uberPendingNameUpdate').catch(() => ({}));
  const pending = data._uberPendingNameUpdate;
  if (!pending) return;

  await chrome.storage.local.remove('_uberPendingNameUpdate').catch(() => {});

  const { firstName, lastName, startLink } = pending;
  const targetTabId = updatedTabId;

  if (firstName) {
    try {
      console.log(`[Uber] Form tabanlı isim güncelleme başlatılıyor: ${firstName} ${lastName}`);
      await chrome.scripting.executeScript({
        target: { tabId: targetTabId },
        func: function (fn, ln) {
          function fillForm() {
            var inputs = document.querySelectorAll('input[type="text"], input[name*="name"], input[name*="Name"]');
            var firstInput = null, lastInput = null;
            if (inputs.length >= 2) {
              firstInput = inputs[0];
              lastInput = inputs[1];
            } else {
              firstInput = document.querySelector('input[name="firstName"], input[name="first_name"], input[placeholder*="Ad"], input[data-testid*="first"]');
              lastInput = document.querySelector('input[name="lastName"], input[name="last_name"], input[placeholder*="Soyad"], input[data-testid*="last"]');
            }
            if (!firstInput || !lastInput) {
              var allInputs = document.querySelectorAll('input');
              for (var i = 0; i < allInputs.length; i++) {
                var inp = allInputs[i];
                if (inp.type === 'hidden' || inp.type === 'submit') continue;
                if (!firstInput) { firstInput = inp; continue; }
                if (!lastInput) { lastInput = inp; break; }
              }
            }
            if (firstInput && lastInput) {
              var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
              nativeInputValueSetter.call(firstInput, fn);
              firstInput.dispatchEvent(new Event('input', { bubbles: true }));
              firstInput.dispatchEvent(new Event('change', { bubbles: true }));
              nativeInputValueSetter.call(lastInput, ln);
              lastInput.dispatchEvent(new Event('input', { bubbles: true }));
              lastInput.dispatchEvent(new Event('change', { bubbles: true }));
              setTimeout(function () {
                var btn = document.querySelector('button[type="submit"], button[data-testid*="save"], button[data-testid*="update"]');
                if (!btn) {
                  var buttons = document.querySelectorAll('button');
                  for (var b = 0; b < buttons.length; b++) {
                    var t = (buttons[b].textContent || '').toLowerCase();
                    if (t.includes('güncelle') || t.includes('kaydet') || t.includes('save') || t.includes('update')) {
                      btn = buttons[b];
                      break;
                    }
                  }
                }
                if (btn) btn.click();
              }, 500);
              return true;
            }
            return false;
          }
          var attempts = 0;
          var interval = setInterval(function () {
            attempts++;
            if (fillForm() || attempts > 20) clearInterval(interval);
          }, 500);
        },
        args: [firstName, lastName],
        world: 'MAIN'
      });
      console.log(`[Uber] Form isim güncelleme scripti enjekte edildi: ${firstName} ${lastName}`);
    } catch (nameErr) {
      console.error("[Uber] Form isim güncelleme hatası:", nameErr.message);
    }
  }

  await new Promise(resolve => setTimeout(resolve, 3000));

  const redirectUrl = startLink && startLink.startsWith('http') ? startLink : "https://m.uber.com/home";
  console.log('[Uber] Giriş başarılı, yönlendiriliyor:', redirectUrl);
  chrome.tabs.update(targetTabId, { url: redirectUrl }).catch(() => {
    chrome.tabs.create({ url: redirectUrl });
  });
}

// ====================================
// UBER: UA storage'dan yükle ve DNR uygula
// ====================================
chrome.storage.local.get(['uberUserAgent', 'uberFpSeed', 'activeUberToken'], function (result) {
  activeUberToken = result.activeUberToken || null;
  const existingSeed = result.uberFpSeed || '';
  uberUserAgent = UBER_UA_FALLBACK;
  if (!existingSeed) {
    const seed = crypto.randomUUID();
    chrome.storage.local.set({ uberUserAgent: uberUserAgent, uberFpSeed: seed });
    writeUberFpSeedCookie(seed);
  } else {
    chrome.storage.local.set({ uberUserAgent: uberUserAgent });
    writeUberFpSeedCookie(existingSeed);
  }
  try {
    RequestHeaderManager.updateDynamicRules({ removeRuleIds: [9100, 9101, 9102, 9110, 9120, 9122] }).catch(() => {});
  } catch (_) {}
  setupUberHeaderRules().catch(() => {});
});

// ====================================
// UBER: Tab onUpdated dinleyicisi
// ====================================
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  if (changeInfo.status === 'complete' && tab.url) {
    _uberOnUpdatedHandler(tabId, changeInfo, tab).catch(() => {});
  }
});

const CURRENT_VERSION = chrome.runtime.getManifest().version;

function parseVersion(v) {
  return v.split('.').map(Number);
}

function isNewerVersion(remote, current) {
  const r = parseVersion(remote);
  const c = parseVersion(current);
  for (let i = 0; i < Math.max(r.length, c.length); i++) {
    const rv = r[i] || 0;
    const cv = c[i] || 0;
    if (rv > cv) return true;
    if (rv < cv) return false;
  }
  return false;
}

async function checkForUpdate() {
  try {
    const res = await fetch('https://ys2.botsepeti.net/api/version', {
      method: 'GET',
      headers: {
        'X-Token': 'xeudL5BmAl7TRxs5tHPTPcJtTxtvc6e5eh5R0FEGbRIJSDEe',
        'X-Version': chrome.runtime.getManifest().version,
        'X-Requested': 'YSNew'
      }
    });
    if (!res.ok) return;
    const data = await res.json();
    if (data?.version && data?.extension_url && isNewerVersion(data.version, CURRENT_VERSION)) {
      chrome.runtime.sendMessage({
        action: 'updateAvailable',
        version: data.version,
        url: data.extension_url,
        force_update: data.force_update === true
      });
    }
  } catch (_) {}
}

// 🛡️ ULTRA GÜVENLİ VERSİYON - SADECE YEMEKSEPETİ DOMAIN'LERİ

// Yemeksepeti domain kontrolü
function isYemeksepetiDomain(domain) {
  const cleanDomain = domain.toLowerCase().replace('www.', '');
  const allowedDomains = [
    'yemeksepeti.com',
    'fd-api.com',
    'tr.fd-api.com',
    'deliveryhero.com'
  ];
  
  return allowedDomains.some(allowed => 
    cleanDomain === allowed || 
    cleanDomain.endsWith('.' + allowed)
  );
}

// ⚠️ KALDIRILDI: clearSiteDataLikeChromeSettings() fonksiyonu
// Tüm domain'leri tek seferde temizleyen clearYemeksepetiLikeChromeSettings() kullanılıyor
// (5x tekrar yerine 1x çağrı = %80 daha hızlı)

// ULTRA GÜVENLİ Chrome Settings Temizleme - SADECE YEMEKSEPETİ
async function clearYemeksepetiLikeChromeSettings() {
  console.log('🛡️ ULTRA GÜVENLİ YEMEKSEPETİ TEMİZLEME BAŞLIYOR...');
  console.log('✅ SADECE YEMEKSEPETİ DOMAIN\'LERİ TEMİZLENECEK');
  console.log('🛡️ DİĞER TÜM SİTELER KORUNACAK');
  console.log('❌ GLOBAL FALLBACK: DEVRE DIŞI');
  
  const yemeksepetiDomains = [
    'www.yemeksepeti.com',
    'yemeksepeti.com', 
    'tr.fd-api.com',
    'fd-api.com',
    'deliveryhero.com'
  ];
  
  const totalStartTime = performance.now();
  const results = { cookie: false, browsing: false, cache: false };
  
  try {
    // ⚡ OPTİMİZASYON 1: Tüm cookie'leri tek seferde temizle (5x tekrar yerine 1x)
    console.log('🍪 Tüm Yemeksepeti cookie\'leri temizleniyor (TEK SEFERĐE)...');
    const cookieStartTime = performance.now();
    try {
      const allCookies = await chrome.cookies.getAll({});
      const yemeksepetiCookies = allCookies.filter(cookie => {
        const cookieDomain = cookie.domain.toLowerCase();
        return isYemeksepetiDomain(cookieDomain.replace(/^\./, ''));
      });
      
      console.log(`🍪 ${yemeksepetiCookies.length} adet yemeksepeti cookie'si bulundu (toplam ${allCookies.length})`);
      
      const removePromises = yemeksepetiCookies.map(async (cookie) => {
        const url = `${cookie.secure ? 'https' : 'http'}://${cookie.domain}${cookie.path}`;
        try {
          await chrome.cookies.remove({
            url: url,
            name: cookie.name,
            storeId: cookie.storeId
          });
        } catch (err) {
          console.warn(`⚠️ Cookie silme hatası: ${cookie.name}`, err);
        }
      });
      
      await Promise.all(removePromises);
      const cookieDuration = performance.now() - cookieStartTime;
      console.log(`✅ Yemeksepeti cookie temizleme tamamlandı: ${cookieDuration.toFixed(2)}ms`);
      results.cookie = true;
    } catch (error) {
      console.warn(`⚠️ Cookie temizleme hatası:`, error);
    }
    
    // ⚡ OPTİMİZASYON 2: Tüm domain'lerin browsing data'sını tek çağrıda temizle
    console.log('🗑️ Tüm Yemeksepeti domain\'leri için browsing data temizleniyor (TEK SEFERĐE)...');
    const browsingStartTime = performance.now();
    try {
      const origins = yemeksepetiDomains.map(domain => `https://${domain}`);
      
      await chrome.browsingData.remove({
        origins: origins  // ✅ TÜM domain'leri tek çağrıda
      }, {
        "cache": true,
        "cacheStorage": true,
        "cookies": true,  // Ekstra güvenlik
        "indexedDB": true,
        "localStorage": true,
        "pluginData": true,
        "serviceWorkers": true,
        "webSQL": true
      });
      
      const browsingDuration = performance.now() - browsingStartTime;
      console.log(`✅ Browsing data temizleme tamamlandı: ${browsingDuration.toFixed(2)}ms`);
      console.log(`   📋 Temizlenen domain'ler: ${yemeksepetiDomains.join(', ')}`);
      results.browsing = true;
    } catch (error) {
      console.warn(`⚠️ Browsing data temizleme hatası:`, error);
    }
    
    // ⚡ OPTİMİZASYON 3: Tüm cache'leri paralel temizle
    console.log('🗑️ Tüm Yemeksepeti cache\'leri temizleniyor (PARALEL)...');
    const cacheStartTime = performance.now();
    try {
      const origins = yemeksepetiDomains.map(domain => `https://${domain}`);
      
      // Ana cache temizleme
      const cachePromises = origins.map(origin => 
        chrome.browsingData.removeCache({ origins: [origin], since: 0 })
          .catch(err => console.warn(`⚠️ Cache temizleme hatası (${origin}):`, err))
      );
      
      await Promise.allSettled(cachePromises);
      
      const cacheDuration = performance.now() - cacheStartTime;
      console.log(`✅ Cache temizleme tamamlandı: ${cacheDuration.toFixed(2)}ms`);
      results.cache = true;
    } catch (error) {
      console.warn(`⚠️ Cache temizleme hatası:`, error);
    }
    
  } catch (error) {
    console.error(`❌ Genel temizleme hatası:`, error);
  }
  
  // Özet raporu
  const totalDuration = performance.now() - totalStartTime;
  const successCount = Object.values(results).filter(Boolean).length;
  
  console.log(`⏱️ TOPLAM TEMİZLEME SÜRESİ: ${totalDuration.toFixed(2)}ms`);
  console.log(`📊 SONUÇLAR: Cookie(${results.cookie ? '✅' : '❌'}) | Browsing(${results.browsing ? '✅' : '❌'}) | Cache(${results.cache ? '✅' : '❌'})`);
  console.log(`🛡️ ETKİLENEN DOMAIN'LER: ${yemeksepetiDomains.join(', ')}`);
  console.log(`🛡️ KORUNAN: Diğer tüm sitelerin verileri (%100 güvenli)`);
  console.log(`⏰ ZAMANLAMA: Yemeksepeti.com açılmadan ÖNCE`);
  
  // En az 2 işlem başarılı olursa temizleme başarılı
  return successCount >= 2;
}

// Random string generator
function generateRandomString(length) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
  let result = '';
  
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  
  return result;
}

// Hex string generator
function generateHex(length) {
  const hexChars = '0123456789abcdef';
  let result = '';
  
  for (let i = 0; i < length; i++) {
    result += hexChars.charAt(Math.floor(Math.random() * hexChars.length));
  }
  
  return result;
}

// PX Cookie üretim fonksiyonları (eski - basit)
function generatePxCookies() {
    const px3Part1 = generateHex(64);
    const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    
    let px3Part2 = '';
    for (let i = 0; i < 88; i++) {
        px3Part2 += base64Chars.charAt(Math.floor(Math.random() * base64Chars.length));
    }
    
    let px3Part3 = '';
    for (let i = 0; i < 344; i++) {
        px3Part3 += base64Chars.charAt(Math.floor(Math.random() * base64Chars.length));
    }
    
    const _px3 = `${px3Part1}:${px3Part2}:1000:${px3Part3}`;
    const _pxhd = generateHex(48);
    const _pxvid = generateUUIDv4();
    const _pxcts = Date.now().toString();
    
    return `_px3=${_px3}; _pxhd=${_pxhd}; _pxvid=${_pxvid}; _pxcts=${_pxcts}`;
}

// bayihesapv2 ile birebir aynı üretim fonksiyonları
function generatePxOriginalToken() {
    const part1 = '3';
    const part2 = generateHex(64);
    const part3 = btoa(generateHex(32)).replace(/=/g, '');
    const part4 = '1000';
    const part5 = btoa(generateHex(128)).replace(/=/g, '');
    return `${part1}:${part2}:${part3}:${part4}:${part5}`;
}

function generatePxDeviceFp() {
    return 'fp:' + generateHex(32);
}

function generateDevicePerformanceClass() {
    const classes = ['low', 'medium', 'high'];
    const weights = [30, 50, 20];
    const totalWeight = weights.reduce((a, b) => a + b, 0);
    let random = Math.random() * totalWeight;
    for (let i = 0; i < classes.length; i++) {
        random -= weights[i];
        if (random <= 0) return classes[i];
    }
    return 'medium';
}

function generateSentrySampleRand() {
    let rand = '0.';
    for (let i = 0; i < 16; i++) {
        rand += Math.floor(Math.random() * 10);
    }
    return rand;
}

function generateBaggageV2(traceId, appVersion, buildNumber) {
    const SENTRY_PUBLIC_KEY = '385c49e6b6c4484d8362abae622b3f0b';
    const sampleRand = generateSentrySampleRand();
    return `sentry-environment=production,sentry-public_key=${SENTRY_PUBLIC_KEY},sentry-release=com.inovel.app.yemeksepeti%40${appVersion}%2B${buildNumber},sentry-sample_rand=${sampleRand},sentry-sampled=false,sentry-trace_id=${traceId},sentry-transaction=refresh_token_interceptor`;
}

function generateSentryTraceV2() {
    const traceId = generateHex(32);
    const spanId = generateHex(16);
    return { traceId, sentryTrace: `${traceId}-${spanId}-0` };
}

async function generateRSig(deviceId) {
    try {
        const now = new Date();
        const pad = (n) => String(n).padStart(2, '0');
        const currentTime = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}+0300`;
        const randomNum = Math.random().toFixed(16).substring(1);
        const dataToHash = deviceId + currentTime + randomNum;

        const encoder = new TextEncoder();
        const encodedData = encoder.encode(dataToHash);
        const hashBuffer = await crypto.subtle.digest('SHA-256', encodedData);
        const hashArray = new Uint8Array(hashBuffer);
        const signature = btoa(String.fromCharCode(...hashArray));

        return {
            success: true,
            signature: signature,
            rts: currentTime,
            ruid: randomNum,
            eks: deviceId.substring(0, 6)
        };
    } catch (error) {
        return {
            success: false,
            signature: btoa(generateHex(32)),
            rts: new Date().toISOString(),
            ruid: Math.random().toFixed(16).substring(1),
            eks: generateHex(6)
        };
    }
}

function parseCustCodeFromToken(token) {
    if (!token) return '';
    try {
        const parts = token.split('.');
        if (parts.length === 3) {
            const payload = JSON.parse(atob(parts[1]));
            return payload.user_id || '';
        }
    } catch (e) {}
    return '';
}

function generateBase64Random(length) {
    const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += base64Chars.charAt(Math.floor(Math.random() * base64Chars.length));
    }
    return result;
}

// Web cookie string oluşturma - yemeksepeti_full.py generate_web_cookies ile birebir aynı
function generateWebCookies(perseusClientId, perseusSessionId) {
    const timestamp = Date.now();
    
    if (!perseusClientId) {
        perseusClientId = `${timestamp}.${Math.floor(Math.random() * 9e14) + 1e14}.${generateRandomString(10)}`;
    }
    if (!perseusSessionId) {
        perseusSessionId = `${timestamp}.${Math.floor(Math.random() * 9e14) + 1e14}.${generateRandomString(10)}`;
    }
    
    const pxvid = generateUUIDv4();
    const pxcts = generateUUIDv4();
    const ssid = generateUUIDv4();
    
    const pxhdPart1 = generateBase64Random(54);
    const pxhdPart2 = generateBase64Random(80);
    
    const px3Salt = generateHex(64);
    const px3Hmac = generateBase64Random(88);
    const px3Ct = generateBase64Random(364);
    
    const cfBmVal = generateBase64Random(44).replace(/\+/g, '.').replace(/\//g, '_');
    const cfBmVal2 = generateBase64Random(54).replace(/\+/g, '.').replace(/\//g, '_');
    
    const gStateB = generateBase64Random(44);
    
    const ddId = `${generateHex(8)}-${generateHex(4)}-${generateHex(4)}-${generateHex(4)}-${generateHex(12)}`;
    
    const tqId = `${generateHex(16)}.${Math.floor(timestamp / 1000)}.0.${Math.floor(timestamp / 1000)}..`;
    
    const hitId = `${timestamp + Math.floor(Math.random() * 4900) + 100}.${Math.floor(Math.random() * 9e14) + 1e14}.${generateRandomString(10)}`;
    
    const cookies = [
        `dhhPerseusGuestId=${perseusClientId}`,
        `dhhPerseusSessionId=${perseusSessionId}`,
        `ld_key=${perseusClientId}`,
        `hl=tr`,
        `is-generic-address=true`,
        `_pxhd=${pxhdPart1}==${pxhdPart2}=`,
        `__cf_bm=${cfBmVal}-${Math.floor(timestamp / 1000)}-1.0.1.1-${cfBmVal2}`,
        `dps-session-id=41.076703_29.010804_${perseusClientId}_${Math.floor(timestamp / 1000)}_${Math.floor(timestamp / 1000) + 1800}`,
        `_pxvid=${pxvid}`,
        `pxcts=${pxcts}`,
        `g_state={"i_l":0,"i_ll":${timestamp},"i_b":"${gStateB}","i_e":{"enable_itp_optimization":1}}`,
        `_tq_id.TV-276372-1.c7a5=${tqId}`,
        `user-address-model=%7B%22longitude%22%3A29.01076%2C%22latitude%22%3A41.07683%2C%22countryCode%22%3A%22TR%22%7D`,
        `_px3=${px3Salt}:${px3Hmac}:1000:${px3Ct}`,
        `userCentrics_Braze=true`,
        `userCentrics_TVSquared=undefined`,
        `userCentrics_Perseus=true`,
        `userCentrics_BingConversion=undefined`,
        `userCentrics_TradeTracker=undefined`,
        `userCentrics_LinkedInAds=undefined`,
        `userCentrics_TradeDesk=undefined`,
        `userCentrics_Sklik=undefined`,
        `userCentrics_PerimeterX=undefined`,
        `userCentrics_AdjustforFraudPrevention=true`,
        `userCentrics_DeliveryHeroCore=undefined`,
        `userCentrics_FacebookConnect=true`,
        `userCentrics_GoogleTagManager=true`,
        `userCentrics_Sentry=true`,
        `userCentrics_UsercentricsConsentManagementPlatform=true`,
        `__ssid=${ssid}`,
        `userCentrics_BrazeSDK=true`,
        `userCentrics_FacebookPixel=true`,
        `userCentrics_GoogleAdsRemarketing=true`,
        `userCentrics_Twitter=true`,
        `userCentrics_GoogleAnalytics=true`,
        `userCentrics_PerseusFunctional=true`,
        `userCentrics_PerseusMarketing=true`,
        `userCentrics_Hotjar=true`,
        `userCentrics_GoogleAds=true`,
        `userCentrics_Adjust=true`,
        `userCentrics_FacebookSocialPlugins=true`,
        `userCentrics_GoogleFirebase=true`,
        `userCentrics_remerge=true`,
        `userCentrics_RTBHouse=true`,
        `userCentrics_TikTokAdvertising=true`,
        `userCentrics_TwitterAnalytics=true`,
        `_dd_s=logs=1&id=${ddId}&created=${timestamp}&expire=${timestamp + 900000}`,
        `dhhPerseusHitId=${hitId}`
    ];
    
    return cookies.join('; ');
}

// Rastgele versiyonlar oluştur
function generateRandomVersions() {
  // Sürüm aralıkları
  const majorVersions = [22, 23, 24, 25];  // 22-25
  const minorVersions = Array.from({length: 100}, (_, i) => i); // 0-99
  const patchVersions = Array.from({length: 10}, (_, i) => i);  // 0-9
  
  // Rastgele sürüm numaraları
  const major = majorVersions[Math.floor(Math.random() * majorVersions.length)];
  const minor = minorVersions[Math.floor(Math.random() * minorVersions.length)];
  const patch = patchVersions[Math.floor(Math.random() * patchVersions.length)];
  
  // Build numarası formatı (MMNNPP00) - Major, miNor, Patch, 00
  const buildNumber = sprintf("%d%02d%d00", major, minor, patch);
  
  // Sürüm string formatı (MM.NN.P)
  const version = sprintf("%d.%d.%d", major, minor, patch);
  
  // Rastgele bir sayı ekle
  const buildSuffix = Math.floor(Math.random() * 900) + 100;
  const fullBuildNumber = buildNumber + buildSuffix;
  
  // User-Agent oluştur
  const userAgent = `Android-app-${version}(${fullBuildNumber})`;
  
  return {
    version: version,
    buildNumber: fullBuildNumber,
    userAgent: userAgent
  };
}

// sprintf işlevi (basit versiyon)
function sprintf(format) {
  const args = Array.prototype.slice.call(arguments, 1);
  return format.replace(/%([0-9]+)?([dfs])/g, function(match, width, type) {
    let s = args.shift().toString();
    if (type === 'd' && width) {
      s = s.padStart(parseInt(width, 10), '0');
    }
    return s;
  });
}

// PerimeterX token oluşturucu
function generatePxToken() {
  // İlk bölüm
  const part1 = "3:";
  
  // 64 karakterlik hex string
  const part2 = Array.from({length: 32}, () => 
    "0123456789abcdef"[Math.floor(Math.random() * 16)]).join('');
  
  // Base64 string
  const part3 = Array.from({length: 88}, () => 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="[Math.floor(Math.random() * 65)]).join('');
  
  // Sabit sayı
  const part4 = "1000";
  
  // Uzun base64 string
  const part5 = Array.from({length: 256}, () => 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="[Math.floor(Math.random() * 65)]).join('');
  
  return part1 + part2 + ":" + part3 + ":" + part4 + ":" + part5;
}

// Rastgele cihaz bilgisi üretici
function generateRandomDevice() {
  // Rastgele bir deviceId oluştur - 32 karakter
  const deviceId = Array.from({length: 32}, () => 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random() * 62)]).join('');
  
  // Cihaz markası listesi - oppo eklenmiş
  const makes = ["Xiaomi", "HUAWEI", "Redmi", "Samsung", "POCO", "oppo", "Asus"];
  const deviceMake = makes[Math.floor(Math.random() * makes.length)];
  
  // Rastgele model oluştur
  const models = ["CPH2341", "M2101K6G", "M2004J19C", "2201116TG", "2207117BPG", "ASUS_I005DA", "ASUS_Z01QD"];
  const deviceModel = models[Math.floor(Math.random() * models.length)];
  
  // Rastgele bir Android sürümü seç (Android 6-13)
  const platformVersion = 23 + Math.floor(Math.random() * 10);
  
  return {
    deviceId: deviceId,
    deviceMake: deviceMake,
    deviceModel: deviceModel,
    platformVersion: platformVersion
  };
}

// EKS header generator function - sadece 6 karakterlik
function generateRandomEks() {
  // Sadece 6 karakterlik lowercase string üret
  return Array.from({length: 6}, () => 
    "abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random() * 26)]).join('');
}

// Advanced ID generators
function generateUUIDv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

function generateOriginalRts() {
  const now = new Date();
  // Türkiye saat dilimi için +03:00 formatında
  const turkeyTime = new Date(now.getTime() + (3 * 60 * 60 * 1000));
  return turkeyTime.toISOString().replace('Z', '+03:00');
}

function generateOriginalRuid() {
  // Orjinal uygulamada 8 haneli numeric ID kullanılıyor
  return Math.floor(10000000 + Math.random() * 90000000).toString();
}

function generateOriginalRSig() {
  // 32 byte random data'yı base64'e çevir (orjinal format)
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  let result = '';
  for (let i = 0; i < 44; i++) { // 32 bytes = 44 base64 chars
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result + '='; // Padding
}

function generatePxAuthorization() {
  // Format: 3:32hex:base64data:1000:longbase64data
  const version = "3";
  const hexPart = generateHex(64); // 32 byte hex (64 karakter)
  
  // Base64 benzeri string oluştur
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  let shortBase64 = '';
  for (let i = 0; i < 64; i++) {
    shortBase64 += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  
  const number = "1000";
  
  let longBase64 = '';
  for (let i = 0; i < 340; i++) {
    longBase64 += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  
  return `${version}:${hexPart}:${shortBase64}:${number}:${longBase64}`;
}

function generatePxHello() {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  const length = Math.random() < 0.5 ? 50 : 54; // İki farklı format
  
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  
  return result;
}

function generateCleanExtra() {
  const sessionId = generateHex(32);
    const currentTime = Date.now();
    const perseusTimestamp = Math.floor(Math.random() * 55834574556737536) + 100000000000000000;
    const perseusClientId = currentTime + '.' + perseusTimestamp + '.' + generateRandomString(10);
    
    const sessionLength = Math.random() < 0.5 ? 16 : 18;
    let sessionTimestamp;
    if (sessionLength === 16) {
        sessionTimestamp = Math.floor(Math.random() * 8796093022208000) + 1000000000000000;
  } else {
        sessionTimestamp = Math.floor(Math.random() * 55834574556737536) + 100000000000000000;
  }
  
    const perseusSessionId = currentTime + 1000 + '.' + sessionTimestamp + '.' + generateRandomString(10);
    
    const sessionData = {
    session_id: sessionId,
    perseus_id: perseusClientId,
        timestamp: Math.floor(currentTime / 1000)
    };
    
    const dpsSessionId = btoa(JSON.stringify(sessionData));
    const traceId = generateHex(16);
    const spanId = generateHex(8);
    const sampled = '0';
    const sentryTrace = traceId + '-' + spanId + '-' + sampled;
    
    const appVersion = '26.7.0';
    const buildNumber = '260700154';
    const platformVersion = '28';
    const baggage = 'sentry-environment=production,sentry-public_key=' + platformVersion + ',sentry-release=com.inovel.app.yemeksepeti%40' + appVersion + ',sentry-transaction=sm_AskEmailFragment,' + buildNumber + ',sentry-sampled=false,sentry-trace_id=' + traceId + ',sentry-span_id=' + spanId;
  
  return {
    deviceFingerprintToken: generateRandomString(100),
    deviceId: generateRandomString(32),
    pxVid: generateUUIDv4(),
    pxUuid: generateUUIDv4(),
    pxDeviceFp: generateHex(16),
    pxHello: generatePxHello(),
    adjustAdId: generateHex(32),
        appVersion: appVersion,
        buildNumber: buildNumber,
    timestamp: generateOriginalRts(),
        requestId: Math.random().toString(),
        sentryTrace: sentryTrace,
        baggage: baggage,
    traceTail: generateHex(16),
    emRequestId: generateUUIDv4(),
    perseusClientId: perseusClientId,
    perseusSessionId: perseusSessionId,
    eks: generateRandomString(6),
    rSig: generateOriginalRSig(),
    dpsSessionId: dpsSessionId,
    sessionId: sessionId,
    pxAuthorization: generatePxAuthorization()
  };
}

// YS Proxy: her istekte yeni cihaz profili (cache yok)
function generateDeviceIdentifiers() {
    const manufacturers = ['OPPO', 'Samsung', 'Huawei', 'ASUS', 'vivo', 'Realme', 'OnePlus', 'Google'];
    const selectedManufacturer = manufacturers[Math.floor(Math.random() * manufacturers.length)];
  
    const modelsByManufacturer = {
        'Samsung': ['Galaxy S22', 'Galaxy A52', 'Galaxy Note20', 'Galaxy S21'],
    'Xiaomi': ['Mi 11', 'Redmi Note 10', 'Poco F3', 'Mi 10T'],
        'Huawei': ['Mate 40', 'P40', 'Nova 8', 'P30'],
    'OPPO': ['Find X3', 'Reno 6', 'A74', 'F19'],
    'vivo': ['X60', 'V21', 'Y20', 'S9'],
    'Realme': ['GT', 'Narzo 30', '8 Pro', 'C25'],
        'OnePlus': ['9 Pro', '8T', '8 Pro', '9R'],
        'Google': ['Pixel 6', 'Pixel 6 Pro', 'Pixel 5', 'Pixel 4a']
  };
  
    const availableModels = modelsByManufacturer[selectedManufacturer] || modelsByManufacturer['Samsung'];
    const selectedModel = availableModels[Math.floor(Math.random() * availableModels.length)];
  
  const hexChars = '0123456789abcdef';
  let deviceId = '';
  for (let i = 0; i < 16; i++) {
    deviceId += hexChars.charAt(Math.floor(Math.random() * 16));
  }
  
  return {
        manufacturer: selectedManufacturer,
        model: selectedModel,
        deviceId: deviceId,
    appVersion: '26.7.0',
    buildNumber: '260700154',
    apiLevel: '31'
  };
}

// YS Proxy Request Handler
async function handleYsProxyRequest(request, sendResponse) {
  try {
    console.log('Background: YS Proxy isteği alındı', request.url);

    if (!request.url) {
      throw new Error('URL eksik');
    }

    // Access token'ı cookie'den al
    const accessTokenCookie = await new Promise(resolve => {
        chrome.cookies.get({ url: 'https://www.yemeksepeti.com', name: 'access_token' }, resolve);
    });
    let token = accessTokenCookie?.value;
    
    if (!token) {
      // Session storage'dan dene
      const sessionData = await chrome.storage.sync.get(['yemekhub_session']);
      if (sessionData.yemekhub_session && sessionData.yemekhub_session.cookies) {
        const cookies = sessionData.yemekhub_session.cookies;
        const accessTokenCookie = cookies.find(c => c.name === 'access_token');
        if (accessTokenCookie) {
          token = accessTokenCookie.value;
        }
      }
    }
    
    if (!token) {
      throw new Error('Access token not found');
    }

    // Her istekte yeni cihaz profili
    const device = generateDeviceIdentifiers();
    
    // Headers oluştur
    let headers = {
        "Authorization": `Bearer ${token}`,
        "X-Pd-Language-Id": "2",
		"Host": "tr.fd-api.com",
        "X-Reorder-Origin": "",
		"Connection": "keep-alive",
        "Api-Client-Version": "5.0",
        "App-Name": "com.inovel.app.yemeksepeti",
        "App-Flavor": "yemeksepeti",
        "Build-Type": "release",
        "Platform": "android",
        "Platform-Version": "28",
        "Build-Number": device.buildNumber,
        "App-Build": device.buildNumber,
        "App-Version": device.appVersion,
        "Android-Mobile-Service-Provider": "gms",
        "Adjust-Ad-Id": generateHex(32),
        "X-Px-Vid": generateUUIDv4(),
        "X-Px-Os-Version": "9",
        "X-Px-Uuid": generateUUIDv4(),
        "X-Px-Device-Fp": device.deviceId,
        "X-Px-Device-Model": device.model,
        "X-Px-Os": "Android",
        "X-Px-Mobile-Sdk-Version": "3.3.3",
        "X-Px-Authorization": "4",
        "Device-Performance-Class": "mid",
        "X-Px-Bypass-Reason": "Invalid SDK initialization",
        "X-Fp-Api-Key": "android",
        "Eks": "mnpaaa",
        "User-Agent": `Android-app-${device.appVersion}(${device.buildNumber})`,
        'Content-Type': 'application/json; charset=UTF-8',
        ...request.headers
    };

    // R-Sig üret
    const timestamp = new Date().toISOString().replace(/\.\d+/, '').replace('Z', '+0300');
    const random = Math.random().toString();
    const eks = 'mnpaaa';

    const sigRequestData = {
        url: request.url,
        eks: eks,
        body: request.body || "",
        timestamp: timestamp,
        random: random
    };

    // generate-rsig.js'den gelen fonksiyonu kullan
    if (typeof generateYemeksepetiRSig !== 'undefined') {
      const sigResult = generateYemeksepetiRSig(sigRequestData);
      if (sigResult && sigResult.success) {
          headers['R-Sig'] = sigResult.signature;
          headers['Rts'] = timestamp;
          headers['Ruid'] = random;
      } else {
          console.error('Background: YS Proxy için R-Sig üretilemedi:', sigResult ? sigResult.error : 'Bilinmeyen hata');
      }
    }

    const fetchOptions = {
      method: request.method || 'POST',
      headers: headers,
      body: request.body
    };

    console.log('Background: YS Proxy istek gönderiliyor -', fetchOptions.method, request.url);

    const response = await fetch(request.url, fetchOptions);

    const responseHeaders = {};
    response.headers.forEach((value, key) => {
      responseHeaders[key.toLowerCase()] = value;
    });

    const data = await response.text();

    console.log('Background: YS Proxy yanıt alındı -', response.status, data.length + ' byte');

    sendResponse({
      success: true,
      status: response.status,
      statusText: response.statusText,
      headers: responseHeaders,
      requestHeaders: headers,
      data: data
    });

  } catch (error) {
    console.error('Background: YS Proxy istek hatası:', error);
    sendResponse({
      success: false,
      error: error.message || 'Bilinmeyen hata',
      headers: {}
    });
  }
}

function clearAllRules() {
  return new Promise(async (resolve) => { // reject'e gerek yok, her durumda devam ediyoruz.
    try {
      console.log("Kapsamlı kural temizleme işlemi başlatılıyor...");
      
      // Dinamik kuralları temizle
      const dynamicRules = await chrome.declarativeNetRequest.getDynamicRules();
      if (dynamicRules.length > 0) {
        const dynamicRuleIds = dynamicRules.map(rule => rule.id);
        console.log(`Temizlenecek ${dynamicRuleIds.length} dinamik kural bulundu.`);
        await chrome.declarativeNetRequest.updateDynamicRules({
          removeRuleIds: dynamicRuleIds
        });
        console.log("Tüm dinamik kurallar temizlendi.");
      } else {
        console.log("Temizlenecek dinamik kural bulunamadı.");
      }
      
      // Oturum kurallarını temizle
      const sessionRules = await chrome.declarativeNetRequest.getSessionRules();
      if (sessionRules.length > 0) {
        const sessionRuleIds = sessionRules.map(rule => rule.id);
        console.log(`Temizlenecek ${sessionRuleIds.length} oturum kuralı bulundu.`);
        await chrome.declarativeNetRequest.updateSessionRules({
          removeRuleIds: sessionRuleIds
        });
        console.log("Tüm oturum kuralları temizlendi.");
      } else {
        console.log("Temizlenecek oturum kuralı bulunamadı.");
      }
      
      console.log("Kapsamlı kural temizleme başarıyla tamamlandı.");
    } catch (error) {
      console.error("Kural temizleme sırasında bir hata oluştu (ancak işlem devam edecek):", error);
    } finally {
      resolve(); // Her durumda işlemi bitir.
    }
  });
}

async function getBlockedPatterns() {
    try {
        // Engellenecek domain/pattern listesi
        const fallbackData = [
            'px-cloud.net',
            'pxchk.net',
            'usercentrics.eu',
            'sentry.io',
            'icg-in.com',
            'braze.com',
            'api/v2/collector',
            'trackjs.com',
            'xhr/b/s',
            'cdn-cgi/rum',
            'px-cdn.net',
            'perseus-productanalytics',
            '/v5/action-log',
            'pxchk.net',
            'hotjar.io',
            'hotjar.com',
			'conn-check.icg-in.info',
			'pagespeed.deliveryhero.net',
			'browser-http-intake.logs.datadoghq.eu/v1',
			'browser-http-intake',
            'datadoghq.eu',
            'hexagon-analytics',
            'qualtrics.com',
            'datadog',
            'browser-intake-datadoghq.eu',
			'deliveryhero.com/api/logs',
            'bruce-ys-tr.production.eu.fintech.deliveryhero.com\/api\/logs',
            'at-display-eu.deliveryhero.io',
            'disco.deliveryhero.io/up-and-cross-sell',
            'action-log.yemeksepeti.com'
            ];
        
        return fallbackData;
        
    } catch (error) {
        return false;
    }
}

function generateBlockingRules(patterns, startId) {
    return patterns.map((pattern, index) => ({
        id: startId + index,
        priority: 1,
        action: {
            type: 'block'
        },
        condition: {
            urlFilter: pattern,
            resourceTypes: [
                'sub_frame', 'script', 'xmlhttprequest',
                'image', 'font', 'media', 'stylesheet', 'websocket'
            ]
        }
    }));
}

async function setupBlockingDynamicHeaders() {
    try {
        const startId = 1000;
        const blockedPatterns = await getBlockedPatterns();
        const blockingRules = generateBlockingRules(blockedPatterns, startId);
        
        chrome.declarativeNetRequest.updateDynamicRules({
            removeRuleIds: blockingRules.map(rule => rule.id),
            addRules: blockingRules
        }, () => {
            if (chrome.runtime.lastError) {
                console.error('Error adding block rules:', chrome.runtime.lastError);
            } else {
                console.log('Added ' + blockingRules.length + ' tracking block rules starting at ID ' + startId);
            }
        });
        
    } catch (error) {
        console.log('Blocking Dinamik header\'lar ayarlanırken hata:', error);
    }
}

// Yerel dynamic rules - uzak sunucudan çekilmiyor
async function getFallbackDynamicRules() {
    // rulesConfig.php'den alınan tüm kurallar - uzak sunucu ile iletişim yok
    const localDynamicRules = [
        {
            "id": 1,
            "priority": 1,
            "action": {
                "type": "modifyHeaders",
                "requestHeaders": [
                    {"header": "sec-ch-ua", "operation": "remove"},
                    {"header": "sec-ch-ua-mobile", "operation": "remove"},
                    {"header": "sec-ch-ua-platform", "operation": "remove"},
                    {"header": "sec-fetch-dest", "operation": "remove"},
                    {"header": "sec-fetch-mode", "operation": "remove"},
                    {"header": "sec-fetch-site", "operation": "remove"},
                    {"header": "sec-fetch-user", "operation": "remove"},
                    {"header": "sec-fetch-storage-access", "operation": "remove"},
                    {"header": "sec-ch-ua-arch", "operation": "remove"},
                    {"header": "sec-ch-ua-bitness", "operation": "remove"},
                    {"header": "sec-ch-ua-full-version", "operation": "remove"},
                    {"header": "sec-ch-ua-full-version-list", "operation": "remove"},
                    {"header": "sec-ch-ua-model", "operation": "remove"},
                    {"header": "sec-ch-ua-wow64", "operation": "remove"},
                    {"header": "sec-ch-ua-platform-version", "operation": "remove"},
                    {"header": "sec-ch-ua-form-factor", "operation": "remove"},
                    {"header": "sec-ch-ua-viewport-width", "operation": "remove"},
                    {"header": "sec-ch-ua-dpr", "operation": "remove"},
                    {"header": "sec-ch-ua-resolution", "operation": "remove"},
                    {"header": "sec-ch-ua-ua", "operation": "remove"},
                    {"header": "priority", "operation": "remove"},
                    {"header": "referer", "operation": "remove"},
                    {"header": "Referer", "operation": "remove"},
                    {"header": "x-requested-with", "operation": "remove"},
                    {"header": "x-caller-platform", "operation": "remove"},
                    {"header": "perseus-session-id", "operation": "remove"},
                    {"header": "perseus-client-id", "operation": "remove"},
                    {"header": "dps-session-id", "operation": "remove"},
                    {"header": "Origin", "operation": "set", "value": "https://www.yemeksepeti.com"},
                    {"header": "User-Agent", "operation": "set", "value": "Android-app-%APP_VERSION%(%BUILD_NUMBER%)"},
                    {"header": "Accept-Encoding", "operation": "set", "value": "gzip, deflate, br"}
                ]
            },
            "condition": {
                "urlFilter": "https://tr.fd-api.com/api/v5/cart/calculate",
                "resourceTypes": ["xmlhttprequest"],
                "excludedRequestMethods": ["options"]
            }
        },
        {
            "id": 2,
            "priority": 1,
            "action": {
                "type": "modifyHeaders",
                "requestHeaders": [
                    {"header": "Host", "operation": "set", "value": "tr.fd-api.com"},
                    {"header": "x-pd-language-id", "operation": "set", "value": "2"},
                    {"header": "api-client-version", "operation": "set", "value": "5.0"},
                    {"header": "x-fp-api-key", "operation": "set", "value": "android"},
                    {"header": "platform", "operation": "set", "value": "android"},
                    {"header": "release-lane", "operation": "set", "value": "production"},
                    {"header": "platform-version", "operation": "set", "value": "%PLATFORM_VERSION%"},
                    {"header": "user-agent", "operation": "set", "value": "Android-app-24.36.0(243600124)"},
                    {"header": "app-name", "operation": "set", "value": "com.inovel.app.yemeksepeti"},
                    {"header": "app-flavor", "operation": "set", "value": "yemeksepeti"},
                    {"header": "app-version", "operation": "set", "value": "24.36.0"},
                    {"header": "app-build", "operation": "set", "value": "243600124"},
                    {"header": "build-number", "operation": "set", "value": "243600124"},
                    {"header": "build-type", "operation": "set", "value": "release"},
                    {"header": "cust-code", "operation": "set", "value": "%CUST_CODE%"},
                    {"header": "content-type", "operation": "set", "value": "application/json; charset=UTF-8"},
                    {"header": "android-mobile-service-provider", "operation": "set", "value": "gms"},
                    {"header": "device-performance-class", "operation": "set", "value": "%DEVICE_PERF_CLASS%"},
                    {"header": "device-make", "operation": "set", "value": "%DEVICE_MAKE%"},
                    {"header": "device-model", "operation": "set", "value": "%DEVICE_MODEL%"},
                    {"header": "device-id", "operation": "set", "value": "%DEVICE_ID%"},
                    {"header": "x-px-mobile-sdk-version", "operation": "set", "value": "3.3.3"},
                    {"header": "x-px-os", "operation": "set", "value": "Android"},
                    {"header": "x-px-os-version", "operation": "set", "value": "%ANDROID_VERSION%"},
                    {"header": "x-px-device-model", "operation": "set", "value": "%DEVICE_MODEL%"},
                    {"header": "x-px-vid", "operation": "set", "value": "%PX_VID%"},
                    {"header": "x-px-uuid", "operation": "set", "value": "%PX_UUID%"},
                    {"header": "x-px-device-fp", "operation": "set", "value": "%PX_DEVICE_FP%"},
                    {"header": "x-px-authorization", "operation": "set", "value": "3"},
                    {"header": "x-px-original-token", "operation": "set", "value": "%PX_ORIGINAL_TOKEN%"},
                    {"header": "x-px-bypass-reason", "operation": "set", "value": "Invalid SDK initialization"},
                    {"header": "adjust-ad-id", "operation": "set", "value": "%ADJUST_AD_ID%"},
                    {"header": "sentry-trace", "operation": "set", "value": "%SENTRY_TRACE%"},
                    {"header": "baggage", "operation": "set", "value": "%BAGGAGE_V2%"},
                    {"header": "em-request-identifier", "operation": "set", "value": "%EM_REQUEST_ID%"},
                    {"header": "r-sig", "operation": "set", "value": "%R_SIG_V2%"},
                    {"header": "rts", "operation": "set", "value": "%RTS_V2%"},
                    {"header": "ruid", "operation": "set", "value": "%RUID_V2%"},
                    {"header": "eks", "operation": "set", "value": "%EKS_V2%"},
                    {"header": "x-okcronet-trace", "operation": "set", "value": "cartCalculate"},
                    {"header": "x-okcronet-priority", "operation": "set", "value": "high"},
                    {"header": "authorization", "operation": "set", "value": "Bearer %ACCESS_TOKEN%"},
                    {"header": "Cookie", "operation": "set", "value": "%WEB_COOKIES%"}
                ]
            },
            "condition": {
                "urlFilter": "https://tr.fd-api.com/api/v5/cart/calculate",
                "requestMethods": ["post"]
            }
        },
        {
            "id": 3,
            "priority": 1,
            "action": {
                "type": "modifyHeaders",
                "requestHeaders": [
                    {"header": "Host", "operation": "set", "value": "tr.fd-api.com"},
                    {"header": "x-pd-language-id", "operation": "set", "value": "2"},
                    {"header": "api-client-version", "operation": "set", "value": "5.0"},
                    {"header": "x-fp-api-key", "operation": "set", "value": "android"},
                    {"header": "content-type", "operation": "set", "value": "application/json; charset=UTF-8"},
                    {"header": "device-make", "operation": "set", "value": "%DEVICE_MAKE%"},
                    {"header": "device-model", "operation": "set", "value": "%DEVICE_MODEL%"},
                    {"header": "device-id", "operation": "set", "value": "%DEVICE_ID%"},
                    {"header": "app-name", "operation": "set", "value": "com.inovel.app.yemeksepeti"},
                    {"header": "app-flavor", "operation": "set", "value": "yemeksepeti"},
                    {"header": "user-agent", "operation": "set", "value": "Android-app-%APP_VERSION%(%BUILD_NUMBER%)"},
                    {"header": "build-number", "operation": "set", "value": "%BUILD_NUMBER%"},
                    {"header": "build-type", "operation": "set", "value": "release"},
                    {"header": "platform", "operation": "set", "value": "android"},
                    {"header": "release-lane", "operation": "set", "value": "production"},
                    {"header": "platform-version", "operation": "set", "value": "%PLATFORM_VERSION%"},
                    {"header": "android-mobile-service-provider", "operation": "set", "value": "gms"},
                    {"header": "app-build", "operation": "set", "value": "%BUILD_NUMBER%"},
                    {"header": "app-version", "operation": "set", "value": "%APP_VERSION%"},
                    {"header": "cust-code", "operation": "set", "value": "%CUST_CODE%"},
                    {"header": "device-performance-class", "operation": "set", "value": "%DEVICE_PERF_CLASS%"},
                    {"header": "x-px-vid", "operation": "set", "value": "%PX_VID%"},
                    {"header": "x-px-os-version", "operation": "set", "value": "%ANDROID_VERSION%"},
                    {"header": "x-px-uuid", "operation": "set", "value": "%PX_UUID%"},
                    {"header": "x-px-device-fp", "operation": "set", "value": "%PX_DEVICE_FP%"},
                    {"header": "x-px-device-model", "operation": "set", "value": "%DEVICE_MODEL%"},
                    {"header": "x-px-os", "operation": "set", "value": "Android"},
                    {"header": "x-px-mobile-sdk-version", "operation": "set", "value": "3.3.3"},
                    {"header": "x-px-authorization", "operation": "set", "value": "4"},
                    {"header": "x-px-bypass-reason", "operation": "set", "value": "Invalid SDK initialization"},
                    {"header": "sentry-trace", "operation": "set", "value": "%SENTRY_TRACE%"},
                    {"header": "baggage", "operation": "set", "value": "%BAGGAGE_V2%"},
                    {"header": "em-request-identifier", "operation": "set", "value": "%EM_REQUEST_ID%"},
                    {"header": "adjust-ad-id", "operation": "set", "value": "%ADJUST_AD_ID%"},
                    {"header": "rts", "operation": "set", "value": "%RTS%"},
                    {"header": "ruid", "operation": "set", "value": "%RUID%"},
                    {"header": "eks", "operation": "set", "value": "%EKS%"},
                    {"header": "authorization", "operation": "set", "value": "Bearer %ACCESS_TOKEN%"}
                ]
            },
            "condition": {
                "urlFilter": "https://tr.fd-api.com/api/v5/purchase/intent",
                "requestMethods": ["post", "put", "get"]
            }
        },
        {
            "id": 4,
            "priority": 1,
            "action": {
                "type": "modifyHeaders",
                "requestHeaders": [
                    {"header": "Host", "operation": "set", "value": "tr.fd-api.com"},
                    {"header": "x-pd-language-id", "operation": "set", "value": "2"},
                    {"header": "api-client-version", "operation": "set", "value": "5.0"},
                    {"header": "x-fp-api-key", "operation": "set", "value": "android"},
                    {"header": "content-type", "operation": "set", "value": "application/json; charset=UTF-8"},
                    {"header": "device-make", "operation": "set", "value": "%DEVICE_MAKE%"},
                    {"header": "device-model", "operation": "set", "value": "%DEVICE_MODEL%"},
                    {"header": "device-id", "operation": "set", "value": "%DEVICE_ID%"},
                    {"header": "app-name", "operation": "set", "value": "com.inovel.app.yemeksepeti"},
                    {"header": "app-flavor", "operation": "set", "value": "yemeksepeti"},
                    {"header": "user-agent", "operation": "set", "value": "Android-app-%APP_VERSION%(%BUILD_NUMBER%)"},
                    {"header": "build-number", "operation": "set", "value": "%BUILD_NUMBER%"},
                    {"header": "build-type", "operation": "set", "value": "release"},
                    {"header": "platform", "operation": "set", "value": "android"},
                    {"header": "release-lane", "operation": "set", "value": "production"},
                    {"header": "platform-version", "operation": "set", "value": "%PLATFORM_VERSION%"},
                    {"header": "android-mobile-service-provider", "operation": "set", "value": "gms"},
                    {"header": "app-build", "operation": "set", "value": "%BUILD_NUMBER%"},
                    {"header": "app-version", "operation": "set", "value": "%APP_VERSION%"},
                    {"header": "cust-code", "operation": "set", "value": "%CUST_CODE%"},
                    {"header": "device-performance-class", "operation": "set", "value": "%DEVICE_PERF_CLASS%"},
                    {"header": "x-px-vid", "operation": "set", "value": "%PX_VID%"},
                    {"header": "x-px-os-version", "operation": "set", "value": "%ANDROID_VERSION%"},
                    {"header": "x-px-uuid", "operation": "set", "value": "%PX_UUID%"},
                    {"header": "x-px-device-fp", "operation": "set", "value": "%PX_DEVICE_FP%"},
                    {"header": "x-px-device-model", "operation": "set", "value": "%DEVICE_MODEL%"},
                    {"header": "x-px-os", "operation": "set", "value": "Android"},
                    {"header": "x-px-mobile-sdk-version", "operation": "set", "value": "3.3.3"},
                    {"header": "x-px-authorization", "operation": "set", "value": "4"},
                    {"header": "x-px-bypass-reason", "operation": "set", "value": "Invalid SDK initialization"},
                    {"header": "sentry-trace", "operation": "set", "value": "%SENTRY_TRACE%"},
                    {"header": "baggage", "operation": "set", "value": "%BAGGAGE_V2%"},
                    {"header": "em-request-identifier", "operation": "set", "value": "%EM_REQUEST_ID%"},
                    {"header": "adjust-ad-id", "operation": "set", "value": "%ADJUST_AD_ID%"},
                    {"header": "rts", "operation": "set", "value": "%RTS%"},
                    {"header": "ruid", "operation": "set", "value": "%RUID%"},
                    {"header": "eks", "operation": "set", "value": "%EKS%"},
                    {"header": "authorization", "operation": "set", "value": "Bearer %ACCESS_TOKEN%"}
                ]
            },
            "condition": {
                "urlFilter": "https://tr.fd-api.com/api/v5/cart/checkout",
                "requestMethods": ["post"]
            }
        },
        {
            "id": 6,
            "priority": 1,
            "action": {
                "type": "modifyHeaders",
                "requestHeaders": [
                    {"header": "sec-ch-ua", "operation": "remove"},
                    {"header": "sec-ch-ua-mobile", "operation": "remove"},
                    {"header": "sec-ch-ua-platform", "operation": "remove"},
                    {"header": "sec-fetch-dest", "operation": "remove"},
                    {"header": "sec-fetch-mode", "operation": "remove"},
                    {"header": "sec-fetch-site", "operation": "remove"},
                    {"header": "sec-fetch-user", "operation": "remove"},
                    {"header": "sec-fetch-storage-access", "operation": "remove"},
                    {"header": "sec-ch-ua-arch", "operation": "remove"},
                    {"header": "sec-ch-ua-bitness", "operation": "remove"},
                    {"header": "sec-ch-ua-full-version", "operation": "remove"},
                    {"header": "sec-ch-ua-full-version-list", "operation": "remove"},
                    {"header": "sec-ch-ua-model", "operation": "remove"},
                    {"header": "sec-ch-ua-wow64", "operation": "remove"},
                    {"header": "sec-ch-ua-platform-version", "operation": "remove"},
                    {"header": "sec-ch-ua-form-factor", "operation": "remove"},
                    {"header": "sec-ch-ua-viewport-width", "operation": "remove"},
                    {"header": "sec-ch-ua-dpr", "operation": "remove"},
                    {"header": "sec-ch-ua-resolution", "operation": "remove"},
                    {"header": "sec-ch-ua-ua", "operation": "remove"},
                    {"header": "priority", "operation": "remove"},
                    {"header": "referer", "operation": "remove"},
                    {"header": "Referer", "operation": "remove"},
                    {"header": "x-requested-with", "operation": "remove"},
                    {"header": "x-caller-platform", "operation": "remove"},
                    {"header": "perseus-session-id", "operation": "remove"},
                    {"header": "perseus-client-id", "operation": "remove"},
                    {"header": "dps-session-id", "operation": "remove"},
                    {"header": "Origin", "operation": "set", "value": "https://www.yemeksepeti.com"},
                    {"header": "User-Agent", "operation": "set", "value": "Android-app-%APP_VERSION%(%BUILD_NUMBER%)"},
                    {"header": "Accept-Encoding", "operation": "set", "value": "gzip, deflate, br"}
                ]
            },
            "condition": {
                "urlFilter": "https://tr.fd-api.com/api/v5/purchase/intent",
                "requestMethods": ["post", "put", "get"]
            }
        },
        {
            "id": 7,
            "priority": 1,
            "action": {
                "type": "modifyHeaders",
                "requestHeaders": [
                    {"header": "sec-ch-ua", "operation": "remove"},
                    {"header": "sec-ch-ua-mobile", "operation": "remove"},
                    {"header": "sec-ch-ua-platform", "operation": "remove"},
                    {"header": "sec-fetch-dest", "operation": "remove"},
                    {"header": "sec-fetch-mode", "operation": "remove"},
                    {"header": "sec-fetch-site", "operation": "remove"},
                    {"header": "sec-fetch-user", "operation": "remove"},
                    {"header": "sec-fetch-storage-access", "operation": "remove"},
                    {"header": "sec-ch-ua-arch", "operation": "remove"},
                    {"header": "sec-ch-ua-bitness", "operation": "remove"},
                    {"header": "sec-ch-ua-full-version", "operation": "remove"},
                    {"header": "sec-ch-ua-full-version-list", "operation": "remove"},
                    {"header": "sec-ch-ua-model", "operation": "remove"},
                    {"header": "sec-ch-ua-wow64", "operation": "remove"},
                    {"header": "sec-ch-ua-platform-version", "operation": "remove"},
                    {"header": "sec-ch-ua-form-factor", "operation": "remove"},
                    {"header": "sec-ch-ua-viewport-width", "operation": "remove"},
                    {"header": "sec-ch-ua-dpr", "operation": "remove"},
                    {"header": "sec-ch-ua-resolution", "operation": "remove"},
                    {"header": "sec-ch-ua-ua", "operation": "remove"},
                    {"header": "priority", "operation": "remove"},
                    {"header": "referer", "operation": "remove"},
                    {"header": "Referer", "operation": "remove"},
                    {"header": "x-requested-with", "operation": "remove"},
                    {"header": "x-caller-platform", "operation": "remove"},
                    {"header": "perseus-session-id", "operation": "remove"},
                    {"header": "perseus-client-id", "operation": "remove"},
                    {"header": "dps-session-id", "operation": "remove"},
                    {"header": "Origin", "operation": "set", "value": "https://www.yemeksepeti.com"},
                    {"header": "User-Agent", "operation": "set", "value": "Android-app-%APP_VERSION%(%BUILD_NUMBER%)"},
                    {"header": "Accept-Encoding", "operation": "set", "value": "gzip, deflate, br"}
                ]
            },
            "condition": {
                "urlFilter": "https://tr.fd-api.com/api/v5/cart/checkout",
                "requestMethods": ["post"]
            }
        },
        {
            "id": 8,
            "priority": 1,
            "action": {
                "type": "modifyHeaders",
                "requestHeaders": [
                    {"header": "Host", "operation": "set", "value": "tr.fd-api.com"},
                    {"header": "x-pd-language-id", "operation": "set", "value": "2"},
                    {"header": "api-client-version", "operation": "set", "value": "5.0"},
                    {"header": "x-fp-api-key", "operation": "set", "value": "android"},
                    {"header": "content-type", "operation": "set", "value": "application/json; charset=UTF-8"},
                    {"header": "device-make", "operation": "set", "value": "%DEVICE_MAKE%"},
                    {"header": "device-model", "operation": "set", "value": "%DEVICE_MODEL%"},
                    {"header": "device-id", "operation": "set", "value": "%DEVICE_ID%"},
                    {"header": "app-name", "operation": "set", "value": "com.inovel.app.yemeksepeti"},
                    {"header": "app-flavor", "operation": "set", "value": "yemeksepeti"},
                    {"header": "user-agent", "operation": "set", "value": "Android-app-%APP_VERSION%(%BUILD_NUMBER%)"},
                    {"header": "build-number", "operation": "set", "value": "%BUILD_NUMBER%"},
                    {"header": "build-type", "operation": "set", "value": "release"},
                    {"header": "platform", "operation": "set", "value": "android"},
                    {"header": "release-lane", "operation": "set", "value": "production"},
                    {"header": "platform-version", "operation": "set", "value": "%PLATFORM_VERSION%"},
                    {"header": "android-mobile-service-provider", "operation": "set", "value": "gms"},
                    {"header": "app-build", "operation": "set", "value": "%BUILD_NUMBER%"},
                    {"header": "app-version", "operation": "set", "value": "%APP_VERSION%"},
                    {"header": "cust-code", "operation": "set", "value": "%CUST_CODE%"},
                    {"header": "device-performance-class", "operation": "set", "value": "%DEVICE_PERF_CLASS%"},
                    {"header": "x-px-vid", "operation": "set", "value": "%PX_VID%"},
                    {"header": "x-px-os-version", "operation": "set", "value": "%ANDROID_VERSION%"},
                    {"header": "x-px-uuid", "operation": "set", "value": "%PX_UUID%"},
                    {"header": "x-px-device-fp", "operation": "set", "value": "%PX_DEVICE_FP%"},
                    {"header": "x-px-device-model", "operation": "set", "value": "%DEVICE_MODEL%"},
                    {"header": "x-px-os", "operation": "set", "value": "Android"},
                    {"header": "x-px-mobile-sdk-version", "operation": "set", "value": "3.3.3"},
                    {"header": "x-px-authorization", "operation": "set", "value": "4"},
                    {"header": "x-px-bypass-reason", "operation": "set", "value": "Invalid SDK initialization"},
                    {"header": "sentry-trace", "operation": "set", "value": "%SENTRY_TRACE%"},
                    {"header": "baggage", "operation": "set", "value": "%BAGGAGE_V2%"},
                    {"header": "em-request-identifier", "operation": "set", "value": "%EM_REQUEST_ID%"},
                    {"header": "adjust-ad-id", "operation": "set", "value": "%ADJUST_AD_ID%"},
                    {"header": "rts", "operation": "set", "value": "%RTS%"},
                    {"header": "ruid", "operation": "set", "value": "%RUID%"},
                    {"header": "eks", "operation": "set", "value": "%EKS%"},
                    {"header": "authorization", "operation": "set", "value": "Bearer %ACCESS_TOKEN%"}
                ]
            },
            "condition": {
                "urlFilter": "https://tr.fd-api.com/api/v6/incentives",
                "requestMethods": ["post", "put", "get", "delete"]
            }
        },
        {
            "id": 11,
            "priority": 1,
            "action": {
                "type": "modifyHeaders",
                "requestHeaders": [
                    {"header": "sec-ch-ua", "operation": "remove"},
                    {"header": "sec-ch-ua-mobile", "operation": "remove"},
                    {"header": "sec-ch-ua-platform", "operation": "remove"},
                    {"header": "sec-fetch-dest", "operation": "remove"},
                    {"header": "sec-fetch-mode", "operation": "remove"},
                    {"header": "sec-fetch-site", "operation": "remove"},
                    {"header": "sec-fetch-user", "operation": "remove"},
                    {"header": "sec-fetch-storage-access", "operation": "remove"},
                    {"header": "sec-ch-ua-arch", "operation": "remove"},
                    {"header": "sec-ch-ua-bitness", "operation": "remove"},
                    {"header": "sec-ch-ua-full-version", "operation": "remove"},
                    {"header": "sec-ch-ua-full-version-list", "operation": "remove"},
                    {"header": "sec-ch-ua-model", "operation": "remove"},
                    {"header": "sec-ch-ua-wow64", "operation": "remove"},
                    {"header": "sec-ch-ua-platform-version", "operation": "remove"},
                    {"header": "sec-ch-ua-form-factor", "operation": "remove"},
                    {"header": "sec-ch-ua-viewport-width", "operation": "remove"},
                    {"header": "sec-ch-ua-dpr", "operation": "remove"},
                    {"header": "sec-ch-ua-resolution", "operation": "remove"},
                    {"header": "sec-ch-ua-ua", "operation": "remove"},
                    {"header": "priority", "operation": "remove"},
                    {"header": "referer", "operation": "remove"},
                    {"header": "Referer", "operation": "remove"},
                    {"header": "x-requested-with", "operation": "remove"},
                    {"header": "x-caller-platform", "operation": "remove"},
                    {"header": "perseus-session-id", "operation": "remove"},
                    {"header": "perseus-client-id", "operation": "remove"},
                    {"header": "dps-session-id", "operation": "remove"},
                    {"header": "Origin", "operation": "set", "value": "https://www.yemeksepeti.com"},
                    {"header": "User-Agent", "operation": "set", "value": "Android-app-%APP_VERSION%(%BUILD_NUMBER%)"},
                    {"header": "Accept-Encoding", "operation": "set", "value": "gzip, deflate, br"}
                ]
            },
            "condition": {
                "urlFilter": "https://tr.fd-api.com/api/v6/incentives",
                "requestMethods": ["get", "post", "put", "delete"]
            }
        },
        {
            "id": 12,
            "priority": 1,
            "action": {
                "type": "redirect",
                "redirect": {
                    "transform": {
                        "queryTransform": {
                            "addOrReplaceParams": [
                                {"key": "platform", "value": "android_native_app"}
                            ]
                        }
                    }
                }
            },
            "condition": {
                "urlFilter": "https://tr.fd-api.com/api/v6/incentives",
                "resourceTypes": ["xmlhttprequest"]
            }
        },
        {
            "id": 10,
            "priority": 1,
            "action": {
                "type": "modifyHeaders",
                "requestHeaders": [
                    {"header": "user-agent", "operation": "set", "value": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36"},
                    {"header": "sec-ch-ua", "operation": "set", "value": "\"Not:A-Brand\";v=\"99\", \"Google Chrome\";v=\"145\", \"Chromium\";v=\"145\""},
                    {"header": "sec-ch-ua-mobile", "operation": "set", "value": "?0"},
                    {"header": "sec-ch-ua-platform", "operation": "set", "value": "\"Windows\""}
                ]
            },
            "condition": {
                "urlFilter": "||www.yemeksepeti.com/*",
                "requestMethods": ["get"],
                "resourceTypes": ["main_frame", "sub_frame", "xmlhttprequest", "script", "image", "stylesheet", "other"]
            }
        }
    ];
    
    console.log(`✅ Yerel dynamic rules yüklendi: ${localDynamicRules.length} kural (uzak sunucu yok)`);
    return localDynamicRules;
}
// Dinamik header'ları ayarla
async function setupDynamicHeaders() {
  
  try {
    // Eski dinamik kuralları kaldır
    await clearAllRules(); 
    
    // API'den fallback rules'ları al
    const fallbackRules = await getFallbackDynamicRules();
    
    // Rastgele cihaz bilgileri oluştur
    const device = generateRandomDevice();
    
    // Extra bilgiler oluştur
    const extra = generateCleanExtra();
    
    // PX Cookie'leri oluştur
    const pxCookies = generatePxCookies();
    
    // Web cookie string oluştur (perseus id'ler ile tutarlı)
    const webCookieString = generateWebCookies(extra.perseusClientId, extra.perseusSessionId);
    
    // bayihesapv2 ile birebir aynı üretim değerleri
    const rSigData = await generateRSig(device.deviceId);
    const pxOriginalToken = generatePxOriginalToken();
    const pxDeviceFpV2 = generatePxDeviceFp();
    const devicePerfClass = generateDevicePerformanceClass();
    const sentryData = generateSentryTraceV2();
    const baggageV2 = generateBaggageV2(sentryData.traceId, extra.appVersion, extra.buildNumber);
    const adjustAdIdV2 = generateUUIDv4();
    
    // Access token'ı storage'dan al
    const sessionData = await chrome.storage.sync.get(['yemekhub_session']);
    let accessToken = '';
    
    // Eğer session bilgisi ve cookies varsa
    if (sessionData.yemekhub_session && sessionData.yemekhub_session.cookies) {
      // Cookies içinde access_token'ı bul
      const cookies = sessionData.yemekhub_session.cookies;
      for (let i = 0; i < cookies.length; i++) {
        if (cookies[i].name === 'access_token') {
          accessToken = cookies[i].value;
          break;
        }
      }
    }
    
    // cust-code: JWT token'dan user_id parse et
    const custCode = parseCustCodeFromToken(accessToken);
    
    // Template değerlerini değiştirme fonksiyonu - bayihesapv2 ile birebir aynı
    function replaceTemplateValues(rule) {
        const ruleStr = JSON.stringify(rule);
        const replacedStr = ruleStr
            // Ana değişkenler
            .replace(/%ACCESS_TOKEN%/g, accessToken)
            .replace(/%DEVICE_MAKE%/g, device.deviceMake)
            .replace(/%DEVICE_MODEL%/g, device.deviceModel)
            .replace(/%DEVICE_ID%/g, device.deviceId)
            .replace(/%APP_VERSION%/g, extra.appVersion)
            .replace(/%BUILD_NUMBER%/g, extra.buildNumber)
            .replace(/%APP_BUILD%/g, extra.buildNumber)
            
            // PerimeterX değişkenleri - bayihesapv2 ile birebir aynı
            .replace(/%PX_UUID%/g, generateUUIDv4())
            .replace(/%PX_VID%/g, generateUUIDv4())
            .replace(/%PX_DEVICE_FP%/g, pxDeviceFpV2)
            .replace(/%PX_ORIGINAL_TOKEN%/g, pxOriginalToken.replace(/\\/g, '\\\\').replace(/"/g, '\\"'))
            
            // Perseus & DPS değişkenleri
            .replace(/%PERSEUS_CLIENT_ID%/g, extra.perseusClientId)
            .replace(/%PERSEUS_SESSION_ID%/g, extra.perseusSessionId)
            .replace(/%DPS_SESSION_ID%/g, extra.dpsSessionId)
            
            // Device profil değişkenleri
            .replace(/%PLATFORM_VERSION%/g, device.platformVersion.toString())
            .replace(/%ANDROID_VERSION%/g, (device.platformVersion - 19).toString())
            .replace(/%DEVICE_PERF_CLASS%/g, devicePerfClass)
            
            // cust-code - bayihesapv2 gibi JWT'den parse
            .replace(/%CUST_CODE%/g, custCode)
            
            // r-sig, rts, ruid, eks - bayihesapv2 generateRSig ile birebir aynı
            .replace(/%R_SIG_V2%/g, rSigData.signature)
            .replace(/%RTS_V2%/g, rSigData.rts)
            .replace(/%RUID_V2%/g, rSigData.ruid)
            .replace(/%EKS_V2%/g, rSigData.eks)
            
            // Sentry & Baggage - bayihesapv2 ile birebir aynı
            .replace(/%SENTRY_TRACE%/g, sentryData.sentryTrace)
            .replace(/%BAGGAGE_V2%/g, baggageV2.replace(/\\/g, '\\\\').replace(/"/g, '\\"'))
            
            // Adjust
            .replace(/%ADJUST_AD_ID%/g, adjustAdIdV2)
            
            // Eski placeholder'lar (diğer kurallar için)
            .replace(/%EKS%/g, extra.eks)
            .replace(/%R_SIG%/g, extra.rSig)
            .replace(/%EM_REQUEST_ID%/g, extra.emRequestId)
            .replace(/%RTS%/g, extra.timestamp)
            .replace(/%RUID%/g, extra.requestId)
            .replace(/%TIMESTAMP%/g, Date.now().toString())
            .replace(/%PX_AUTHORIZATION%/g, '4')
            
            // Web Cookie string
            .replace(/%WEB_COOKIES%/g, webCookieString.replace(/\\/g, '\\\\').replace(/"/g, '\\"'));
        
        return JSON.parse(replacedStr);
    }
    
    // API'den gelen rules'ları template değerleriyle değiştir
    const processedRules = fallbackRules.map(rule => replaceTemplateValues(rule));
    
    console.log(`🔧 ${processedRules.length} dynamic rule işleniyor...`);
    
    // Processed rules'ları uygula
    await chrome.declarativeNetRequest.updateDynamicRules({
        addRules: processedRules
    });
    
    console.log(`✅ ${processedRules.length} dynamic rule başarıyla uygulandı (API'den alındı)`);
    
  } catch (error) {
    console.error('Dinamik header\'lar ayarlanırken hata:', error);
  }
}

// btoa fonksiyonu
function btoa(str) {
  try {
    return window.btoa(str);
  } catch(e) {
    // Fallback for non-window environments
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    let result = '';
    let i = 0;
    
    while (i < str.length) {
      const a = str.charCodeAt(i++);
      const b = i < str.length ? str.charCodeAt(i++) : 0;
      const c = i < str.length ? str.charCodeAt(i++) : 0;
      
      const bitmap = (a << 16) | (b << 8) | c;
      
      result += chars.charAt((bitmap >> 18) & 63);
      result += chars.charAt((bitmap >> 12) & 63);
      result += i - 2 < str.length ? chars.charAt((bitmap >> 6) & 63) : '=';
      result += i - 1 < str.length ? chars.charAt(bitmap & 63) : '=';
    }
    
    return result;
  }
}

// 🛡️ GÜVENLİ MESAJ DİNLEYİCİSİ - SADECE YEMEKSEPETİ
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  console.log('📨 Background: Mesaj alındı:', message.action || message.type);
  console.log('📨 Sender:', sender);
  
  // 🚀 WEB SİTESİNDEN OTOMATİK GİRİŞ ( SİSTEMİ GİBİ - YENİ)
  if (message.action === 'openLoginPageWithToken' && message.token) {
    console.log('🚀 Background: Web sitesinden giriş isteği alındı!');
    console.log('📝 Background: Token:', message.token.substring(0, 10) + '...');
    console.log('📨 Background: Sender:', sender);
    
    // Login sayfasını token ile aç
    const loginUrl = chrome.runtime.getURL('pages/login.html') + '?token=' + encodeURIComponent(message.token);
    console.log('🔗 Background: Login URL:', loginUrl);
    
    chrome.tabs.create({
      url: loginUrl,
      active: true
    }, function(tab) {
      console.log('✅ Background: Login sayfası açıldı, tab ID:', tab.id);
      sendResponse({ 
        success: true, 
        tabId: tab.id 
      });
    });
    
    return true; // Asenkron yanıt için
  }
  
  // 🚀 WEB SİTESİNDEN OTOMATİK GİRİŞ (Externally Connectable - ESKİ)
  if (message.type === 'OPEN_LOGIN_WITH_TOKEN' && message.token) {
    console.log('🚀 Background: Web sitesinden giriş isteği (eski), token:', message.token.substring(0, 10) + '...');
    
    // Extension ID'yi gönder
    sendResponse({ 
      success: true, 
      extensionId: chrome.runtime.id 
    });
    
    // Login sayfasını token ile aç
    const loginUrl = chrome.runtime.getURL('pages/login.html') + '?token=' + encodeURIComponent(message.token);
    chrome.tabs.create({
      url: loginUrl,
      active: true
    }, function(tab) {
      console.log('✅ Login sayfası token ile açıldı, tab ID:', tab.id);
    });
    
    return true;
  }
  
  // UBER: Proxy isteği
  if (message.action === 'uberProxyRequest') {
    handleUberProxyRequest(message, sendResponse);
    return true;
  }

  // UBER: Session yükleme
  if (message.action === 'loadUberSession') {
    const tabId = sender.tab?.id;
    (async () => {
      try {
        const sessionData = message.sessionData;
        if (!sessionData || !sessionData.cookiesArray || !Array.isArray(sessionData.cookiesArray)) {
          sendResponse({ success: false, error: 'Geçersiz session verisi' });
          return;
        }
        const gender = message.gender || sessionData.gender || null;
        const startLink = message.startLink || sessionData.startLink || '';
        await handleUberLogin(sessionData.cookiesArray, message.token || '', tabId, gender, startLink);
        sendResponse({ success: true });
      } catch (error) {
        console.error('[Uber] loadUberSession hatası:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }

  // TRENDYOLGO: Sadece adres guncelle (giris yapilmis veya token ile)
  if (message.action === 'startTgoAddressUpdate') {
    (async () => {
      try {
        const token = message.token;
        const address = message.address;
        if (!token || !token.startsWith('TGO-')) {
          sendResponse({ success: false, error: 'Gecerli TGO token gerekli' });
          return;
        }
        if (!address || !tgoHasCoordinates(address)) {
          sendResponse({ success: false, error: 'Gecerli adres secin' });
          return;
        }

        let tgoToken = message.tgoToken || null;
        if (!tgoToken) {
          const cookie = await new Promise(resolve => {
            chrome.cookies.get({ url: 'https://tgoyemek.com', name: 'tgo-token' }, c => resolve(c));
          });
          tgoToken = cookie?.value || null;
        }

        if (!tgoToken) {
          const loginResult = await handleTrendyolGoTokenProcess(token, message.tabId, address);
          sendResponse({ success: true, ...loginResult });
          return;
        }

        _tgoActiveToken = tgoToken;
        const addrResult = await tgoManageAddress(address, tgoToken, { addressAlreadyOnAccount: true });
        sendResponse({ success: true, addressAction: addrResult.action });
      } catch (error) {
        console.error('[TGO] Adres guncelleme hatasi:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }

  // TRENDYOLGO: Token ile giriş süreci
  if (message.action === 'startTgoTokenProcess') {
    const tabId = sender.tab?.id || message.tabId;
    (async () => {
      try {
        const token = message.token;
        if (!token || !token.startsWith('TGO-')) {
          sendResponse({ success: false, error: 'Geçersiz TrendyolGo token' });
          return;
        }
        const result = await handleTrendyolGoTokenProcess(token, tabId);
        sendResponse({ success: true, ...result });
      } catch (error) {
        console.error('[TGO] Token işlemi hatası:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }

  // TRENDYOLGO: Kupon proxy isteği (KuponStore proxy üzerinden)
  if (message.action === 'tyProxyRequest') {
    (async () => {
      try {
        await handleTyProxyRequest(message, sendResponse);
      } catch (error) {
        console.error('[TY Proxy] Hata:', error);
        sendResponse({ success: false, error: error.message, status: 503 });
      }
    })();
    return true;
  }

  // TRENDYOLGO: Sepete ürün eklerken adres + shipping otomatik hazırla
  if (message.action === 'tyCartItemsRequest') {
    (async () => {
      try {
        await handleTyCartItemsRequest(message, sendResponse);
      } catch (error) {
        console.error('[TY CartItems] Hata:', error);
        sendResponse({ success: false, error: error.message, status: 503 });
      }
    })();
    return true;
  }

  // TRENDYOLGO: Snapshot kaydet (sepet bilgisi)
  if (message.action === 'tySnapshot') {
    (async () => {
      try {
        const snapshot = message.data || {};
        const cur = await chrome.storage.local.get(['tySnapshot']);
        const merged = Object.assign({}, cur.tySnapshot || {}, snapshot, { _ts: Date.now() });
        await chrome.storage.local.set({ tySnapshot: merged });
        console.log('[TY Snapshot] Kaydedildi:', Object.keys(merged));
        sendResponse({ success: true });
      } catch (e) {
        sendResponse({ success: false, error: e.message });
      }
    })();
    return true;
  }

  // TRENDYOLGO: Cookie bilgisi al
  if (message.action === 'GET_COOKIES') {
    (async () => {
      try {
        const cookie = await new Promise(resolve => {
          chrome.cookies.get({ url: message.data.url, name: message.data.name }, c => resolve(c));
        });
        sendResponse({ cookie });
      } catch (e) {
        sendResponse({ cookie: null, error: e.message });
      }
    })();
    return true;
  }

  // UBER: Token ile giriş süreci
  if (message.action === 'startUberTokenProcess') {
    const tabId = sender.tab?.id || message.tabId;
    (async () => {
      try {
        const token = message.token;
        const msgFirstName = message.firstName || '';
        const msgLastName = message.lastName || '';
        if (!token || !token.startsWith('uber-')) {
          sendResponse({ success: false, error: 'Geçersiz Uber token' });
          return;
        }
        console.log('[Uber] Token işlemi başlatılıyor:', token.substring(0, 12) + '...');
        if (msgFirstName) console.log('[Uber] Kullanıcı ismi:', msgFirstName, msgLastName);
        const cleanToken = token.startsWith('uber-') ? token.substring(5) : token;
        const response = await fetch(`https://kuponmarket.online/km-uber-cookie.php?token=${encodeURIComponent(cleanToken)}`);
        const data = await response.json();

        if (data && !data.error && data.cookiesArray && Array.isArray(data.cookiesArray)) {
          const gender = data.gender || null;
          const startLink = data.startLink || '';
          await handleUberLogin(data.cookiesArray, token, tabId, gender, startLink, msgFirstName, msgLastName);
          sendResponse({ success: true });
        } else {
          const errMsg = data.error || 'Geçersiz token veya veri bulunamadı';
          sendResponse({ success: false, error: errMsg });
        }
      } catch (error) {
        console.error('[Uber] Token işlemi hatası:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true;
  }

  // UBER: Fingerprint cookie set etme
  if (message.action === 'setUberFingerprintCookie' && message.value) {
    chrome.cookies.set({
      url: 'https://www.uber.com',
      name: 'udi-fingerprint',
      value: message.value,
      domain: '.uber.com',
      path: '/',
      secure: true,
      httpOnly: false,
      sameSite: 'no_restriction',
      expirationDate: Math.floor(Date.now() / 1000) + 31536000
    }).then(() => sendResponse({ success: true }))
      .catch(e => sendResponse({ success: false, error: e.message }));
    return true;
  }

  // 🚀 LARAVEL SİTESİNDEN OTOMATİK GİRİŞ İSTEĞİ (Eski sistem - fallback)
  if (message.action === 'openLoginPage') {
    console.log('🚀 Background: Login sayfası açılıyor, token:', message.token);
    
    // Login sayfasını yeni sekmede aç
    chrome.tabs.create({
      url: chrome.runtime.getURL('pages/login.html'),
      active: true
    }, function(tab) {
      console.log('✅ Login sayfası açıldı, tab ID:', tab.id);
      sendResponse({ success: true, tabId: tab.id });
    });
    
    return true; // Asenkron yanıt için
  }
  
  // 🍪 POPUP'TAN COOKIE EKLEME İSTEĞİ (ÖNCELİKLİ!)
  if (message.action === 'addCookiesFromPopup') {
    console.log('🍪 Background: Popup\'tan cookie ekleme isteği alındı:', message.cookies?.length, 'adet');
    console.log('📋 Gelen cookie isimleri:', message.cookies?.map(c => c.name).join(', '));
    
    // Asenkron işlemi handle et
    (async () => {
      try {
        console.log('🔄 Background: addCookiesFromContentScript() çağrılıyor...');
        const result = await addCookiesFromContentScript(message.cookies);
        console.log('✅ Background: addCookiesFromContentScript() sonucu:', result);
        
        if (!result) {
          console.error('❌ UYARI: addCookiesFromContentScript() null döndürdü!');
          sendResponse({ 
            success: false, 
            error: 'addCookiesFromContentScript returned null',
            successCount: 0,
            failCount: message.cookies?.length || 0,
            total: message.cookies?.length || 0
          });
        } else {
          console.log('📤 Background: sendResponse() çağrılıyor:', result);
          sendResponse(result);
        }
      } catch (error) {
        console.error('❌ Background: Cookie ekleme exception:', error);
        console.error('❌ Stack trace:', error.stack);
        sendResponse({ 
          success: false, 
          error: error.message,
          successCount: 0,
          failCount: message.cookies?.length || 0,
          total: message.cookies?.length || 0
        });
      }
    })();
    
    return true; // Asenkron yanıt için MUTLAKA gerekli
  }
  
  // YS Proxy isteği
  if (message.action === 'ysProxyRequest') {
    handleYsProxyRequest(message, sendResponse);
    return true;
  }

  // Sunucuya şifreli veri gönderme
  if (message.action === 'sendToServer') {
    chrome.storage.sync.get(['yemekhub_session'], (result) => {
      const mrdToken = (result.yemekhub_session && result.yemekhub_session.token) || '';
      fetch(message.serverUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          payload: message.encryptedPayload,
          mrdToken: mrdToken
        })
      }).then(r => r.json()).then(data => {
        console.log('Background: Sunucu yanıtı:', data);
        sendResponse({ success: true, data: data });
      }).catch(err => {
        console.error('Background: Sunucu hatası:', err);
        sendResponse({ success: false, error: err.message });
      });
    });
    return true;
  }
  
  // 🛡️ GÜVENLİ Chrome Settings Temizleme
  if (message.action === 'clearYemeksepetiLikeChromeSettings') {
    console.log('🛡️ Güvenli Yemeksepeti temizleme başlatılıyor...');
    console.log('⏳ Temizleme 5 domain × 300ms beklemeli temizlik yapacak = ~2-3 saniye');
    
    clearYemeksepetiLikeChromeSettings()
      .then(success => {
        console.log(`🛡️ Güvenli temizleme TAMAMEN tamamlandı: ${success}`);
        console.log('✅ Artık cookie ekleme güvenle yapılabilir');
        sendResponse({ success: success });
      })
      .catch(error => {
        console.error('🛡️ Güvenli temizleme hatası:', error);
        sendResponse({ success: false, error: error.message });
      });
    return true; // Asenkron yanıt için
  }
  
  // Backward compatibility - eski mesajlar da güvenli fonksiyonu kullanacak
  if (message.action === 'clearYemeksepetiCompletely' || message.action === 'clearSiteData') {
    console.log('🛡️ Güvenli Yemeksepeti temizleme başlatılıyor (backward compatibility)...');
    clearYemeksepetiLikeChromeSettings()
      .then(success => {
        sendResponse({ success: success });
      })
      .catch(error => {
        console.error('🛡️ Güvenli temizleme hatası:', error);
        sendResponse({ success: false, error: error.message });
      });
    return true; // Asenkron yanıt için
  }
  
  // Adres verilerini storage'a kaydetme işleyicisi
  if (message.action === 'storeAddressesInStorage') {
    console.log("storeAddressesInStorage mesajı alındı");
    
    try {
      // Gelen adresleri al
      const yeniAdresler = message.addresses;
      
      if (!Array.isArray(yeniAdresler)) {
          console.error("Geçersiz adres verisi, dizi değil:", yeniAdresler);
          sendResponse({ success: false, error: "Geçersiz adres verisi" });
          return true;
      }
      
      // Mevcut adresleri chrome.storage.local'den oku
      chrome.storage.local.get(['yemekhub_addresses'], function(result) {
          let adreslerData = result.yemekhub_addresses || [];
          console.log("Mevcut adres sayısı:", adreslerData.length);
          
          // Yeni adresleri ekle
          adreslerData = adreslerData.concat(yeniAdresler);
          
          // Adresleri JSON formatında bir string'e çevir
          const jsonData = JSON.stringify(adreslerData, null, 2);
          
          // Adresleri storage'a kaydet
          chrome.storage.local.set({ 
              'yemekhub_addresses': adreslerData,
              'yemekhub_addresses_json': jsonData  // String olarak da saklayalım
          }, function() {
              if (chrome.runtime.lastError) {
                  console.error("Storage kaydetme hatası:", chrome.runtime.lastError);
                  sendResponse({ success: false, error: chrome.runtime.lastError.message });
              } else {
                  console.log("Adresler başarıyla kaydedildi. Toplam:", adreslerData.length);
                  
                  // Dosya indirme işlemi
                  const blob = new Blob([jsonData], { type: 'application/json' });
                  const url = URL.createObjectURL(blob);
                  
                  chrome.downloads.download({
                      url: url,
                      filename: 'adresler.json',
                      saveAs: true
                  }, function(downloadId) {
                      URL.revokeObjectURL(url);
                      
                      if (chrome.runtime.lastError) {
                          console.error("İndirme hatası:", chrome.runtime.lastError);
                          sendResponse({ success: false, error: chrome.runtime.lastError.message });
                      } else {
                          // Başarı bilgisini geri gönder
                          sendResponse({ success: true });
                      }
                  });
              }
          });
      });
      
      return true; // asenkron cevap için gerekli
    } catch (error) {
      console.error("Adres storage hatası:", error);
      sendResponse({ success: false, error: error.message });
      return true;
    }
  }
  
  // 🍪 CONTENT SCRIPT'TEN COOKIE EKLEME İSTEĞİ (FALLBACK)
  if (message.action === 'addCookiesFromContentScript') {
    console.log('🍪 Background: Content script\'ten cookie ekleme isteği alındı (fallback)');
    addCookiesFromContentScript(message.cookies)
      .then(result => {
        console.log('🍪 Background: Cookie ekleme sonucu:', result);
        sendResponse(result);
      })
      .catch(error => {
        console.error('🍪 Background: Cookie ekleme hatası:', error);
        sendResponse({ success: false, error: error.message });
      });
    return true; // Asenkron yanıt için
  }
  
  // Token değiştirme mesajı
  if (message.action === 'changeTokenAndOpenManager') {
    // Önce mevcut yemeksepeti sekmelerini bul
    chrome.tabs.query({url: '*://*.yemeksepeti.com/*'}, function(tabs) {
      // Yemeksepeti sekmeleri için çerezleri temizle
      tabs.forEach(function(tab) {
        chrome.cookies.getAll({ url: tab.url }, function(cookies) {
          for (var i = 0; i < cookies.length; i++) {
            chrome.cookies.remove({
              url: tab.url + cookies[i].path,
              name: cookies[i].name
            });
          }
        });
      });
      
      // Eğer en az bir yemeksepeti sekmesi varsa, ilkini token yöneticisine yönlendir
      if (tabs.length > 0) {
        chrome.tabs.update(tabs[0].id, {
          url: chrome.runtime.getURL('pages/login.html#token-manager')
        });
        
        // Diğer yemeksepeti sekmelerini kapat
        for (let i = 1; i < tabs.length; i++) {
          chrome.tabs.remove(tabs[i].id);
        }
      } else {
        // Yemeksepeti sekmesi yoksa yeni bir sekme aç
        chrome.tabs.create({
          url: chrome.runtime.getURL('pages/login.html?autoOpenTokenManager=true')
        });
      }
    });
    
    sendResponse({ success: true });
    return true; // asenkron yanıt için gerekli
  }
  
  if (message.action === 'runDynamicHeaders') {
    (async () => {
      try {
        await setupDynamicHeaders();
        await setupBlockingDynamicHeaders();
        console.log('Dinamik headerlar başarıyla ayarlandı.');
        sendResponse({ success: true });
      } catch (error) {
        console.error('❌ Dinamik header kurulum hatası:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true; // asenkron cevap için gerekli
  }
  
  // Diğer mevcut mesaj işleyicileri
  if (message.action === 'closeYemeksepetiTabs') {
    chrome.tabs.query({}, function (tabs) {
      tabs.forEach(function (tab) {
        if (tab.url && tab.url.includes('yemeksepeti.com')) {
          // Cookie'leri de temizle
          chrome.cookies.getAll({ url: tab.url }, function (cookies) {
            for (var i = 0; i < cookies.length; i++) {
              chrome.cookies.remove({
                url: tab.url + cookies[i].path,
                name: cookies[i].name
              });
            }
          });
          chrome.tabs.remove(tab.id);
        }
      });
    });
    sendResponse({ success: true });
    return true;
  }
});

// ============================================
// 🍪 COOKIE MANAGEMENT MODULE ( mantığıyla geliştirilmiş)
// ============================================
class CookieManager {
    /**
     * Debug: Mevcut cookie'leri listele
     */
    static async debugListCookies() {
        try {
            const cookies = await chrome.cookies.getAll({ domain: 'yemeksepeti.com' });
            console.log('🔍 DEBUG: Mevcut Yemeksepeti cookie\'leri:', cookies.length, 'adet');
            cookies.forEach(c => {
                console.log(`  - ${c.name}: ${c.value.substring(0, 20)}... (domain: ${c.domain}, secure: ${c.secure})`);
            });
            return cookies;
        } catch (error) {
            console.error('🔍 DEBUG: Cookie listesi alınamadı:', error);
            return [];
        }
    }
    

    /**
     * Platform cookie'lerini temizler (yemeksepeti.com ve ilgili domainler)
     */
    static async clearYemeksepetiCookies() {
        const yemeksepetiDomains = [
            'yemeksepeti.com',
            'fd-api.com',
            'deliveryhero.com'
        ];
        
        const origins = yemeksepetiDomains.map(domain => `https://${domain}`);
        
        try {
            // 1. Browsing data temizleme
            await chrome.browsingData.remove({
                origins: origins
            }, {
                cookies: true,
                localStorage: true,
                indexedDB: true,
                cacheStorage: true,
                serviceWorkers: true
            });
            
            // 2. Tüm cookie'leri al ve yemeksepeti ile ilgili olanları sil
            const allCookies = await chrome.cookies.getAll({});
            const removePromises = [];
            
            for (const cookie of allCookies) {
                const cookieDomain = cookie.domain.startsWith('.')
                    ? cookie.domain.substring(1)
                    : cookie.domain;
                
                const shouldRemove = yemeksepetiDomains.some(pattern =>
                    cookieDomain === pattern ||
                    cookieDomain.endsWith('.' + pattern)
                );
                
                if (shouldRemove) {
                    const protocol = cookie.secure ? 'https' : 'http';
                    const host = cookie.domain.startsWith('.')
                        ? cookie.domain.substring(1)
                        : cookie.domain;
                    const url = `${protocol}://${host}${cookie.path}`;
                    
                    removePromises.push(
                        chrome.cookies.remove({
                            url: url,
                            name: cookie.name
                        }).catch(() => null) // Silent fail
                    );
                }
            }
            
            await Promise.allSettled(removePromises);
            console.log('✅ Yemeksepeti cookie\'leri temizlendi');
            return true;
        } catch (error) {
            console.error('❌ Cookie temizleme hatası:', error);
            return false;
        }
    }
    
    /**
     * Cookie'leri paralel olarak set eder ( mantığı)
     */
    static async setPlatformCookies(cookies, platformDomain = '.yemeksepeti.com') {
        console.log('🍪 CookieManager: Cookie ekleme başlıyor...', cookies.length, 'adet');
        console.log('🔍 DEBUG: Gelen cookie\'ler:', cookies.map(c => ({ 
            name: c.name, 
            domain: c.domain, 
            expiry: c.expiry, 
            secure: c.secure,
            value_length: c.value?.length 
        })));
        
        // NOT: Temizleme işlemi popup.js'te performPreCleanup() ile ZATEN YAPILDI
        // Burada tekrar temizleme yapmıyoruz, sadece cookie ekliyoruz
        
        const nowInSeconds = Math.floor(Date.now() / 1000);
        console.log('🔍 DEBUG: Şu anki zaman (saniye):', nowInSeconds);
        
        // Tüm cookie'leri paralel olarak set et
        const cookiePromises = cookies.map(async (cookie) => {
            try {
                // SameSite mapping (Backend "None" gönderir, Chrome "no_restriction" bekler)
                let sameSite = 'no_restriction';
                if (cookie.sameSite) {
                    const sameSiteMap = {
                        'None': 'no_restriction',
                        'Lax': 'lax',
                        'Strict': 'strict',
                        'Unspecified': 'unspecified'
                    };
                    sameSite = sameSiteMap[cookie.sameSite] || 'no_restriction';
                }
                
                const domain = cookie.domain || platformDomain;
                const path = cookie.path || '/';
                const domainForUrl = domain.startsWith('.') ? domain.substring(1) : domain;
                const cookieUrl = `https://${domainForUrl}${path}`;
                
            const cookieData = {
                url: cookieUrl,
                name: cookie.name,
                value: String(cookie.value),
                domain: domain,
                path: path,
                secure: true, // ⚡ HTTPS için zorunlu (sunucudan false gelse bile true yapıyoruz)
                httpOnly: cookie.httpOnly !== false,
                sameSite: sameSite
            };
            
            // Expiration date kontrolü ( mantığı + Session desteği)
            if (cookie.expirationDate && typeof cookie.expirationDate === 'number' && cookie.expirationDate > 0) {
                cookieData.expirationDate = cookie.expirationDate < nowInSeconds
                    ? nowInSeconds + (365 * 24 * 60 * 60)  // Süresi geçmişse 1 yıl ekle
                    : cookie.expirationDate;
            } else if (cookie.expires && typeof cookie.expires === 'number' && cookie.expires > 0 && cookie.expires !== -1) {
                cookieData.expirationDate = cookie.expires < nowInSeconds
                    ? nowInSeconds + (365 * 24 * 60 * 60)
                    : cookie.expires;
            } else if (cookie.expiry && typeof cookie.expiry === 'number' && cookie.expiry > 0) {
                cookieData.expirationDate = cookie.expiry < nowInSeconds
                    ? nowInSeconds + (365 * 24 * 60 * 60)
                    : cookie.expiry;
            } else if (cookie.expiry === 'Session' || cookie.expiry === 'session' || !cookie.expiry) {
                // Session cookie - 1 saat ömür ver
                cookieData.expirationDate = nowInSeconds + (60 * 60);
            } else {
                // Fallback: 1 saat
                cookieData.expirationDate = nowInSeconds + (60 * 60);
            }
                
                // Third-party cookie'ler için partitioned flag
                if (cookie.domain && !cookie.domain.includes('yemeksepeti.com')) {
                    try {
                        cookieData.partitionKey = {
                            topLevelSite: 'https://www.yemeksepeti.com'
                        };
                    } catch (e) {
                        // Partitioned cookies desteklenmiyorsa sessizce geç
                    }
                }
                
                const result = await this.setCookie(cookieData);
                if (!result) {
                    console.error('[CookieManager] ❌ Cookie eklenemedi:', {
                        name: cookie.name,
                        domain: domain,
                        url: cookieUrl,
                        expiry: cookie.expiry,
                        secure: cookieData.secure,
                        sameSite: cookieData.sameSite
                    });
                } else {
                    console.log('[CookieManager] ✅ Cookie eklendi:', cookie.name, '→', domain);
                }
                return {
                    name: cookie.name,
                    success: result,
                    error: result ? null : 'Failed to set cookie'
                };
            } catch (error) {
                console.error('[CookieManager] Cookie ekleme hatası:', cookie.name, error);
                return {
                    name: cookie.name,
                    success: false,
                    error: error.message
                };
            }
        });
        
        // Tüm promise'leri bekle (paralel işleme)
        const results = await Promise.allSettled(cookiePromises);
        
        // Sonuçları işle
        const processedResults = results.map(r => r.status === 'fulfilled' ? r.value : { success: false });
        const successCount = processedResults.filter(r => r.success).length;
        const failedCount = processedResults.filter(r => !r.success).length;
        
        console.log(`📊 CookieManager: Cookie ekleme tamamlandı - Başarılı: ${successCount}, Başarısız: ${failedCount}`);
        
        return {
            success: successCount > 0,
            total: cookies.length,
            successful: successCount,
            failed: failedCount,
            results: processedResults
        };
    }
    
    /**
     * Tek bir cookie'yi set eder (Promise wrapper)
     */
    static async setCookie(cookieData) {
        return new Promise((resolve) => {
            console.log(`🔍 DEBUG: chrome.cookies.set() çağrılıyor:`, {
                name: cookieData.name,
                url: cookieData.url,
                domain: cookieData.domain,
                secure: cookieData.secure,
                sameSite: cookieData.sameSite,
                expirationDate: cookieData.expirationDate
            });
            
            chrome.cookies.set(cookieData, (cookie) => {
                if (chrome.runtime.lastError) {
                    console.error(`❌ CookieManager: Chrome API hatası:`, {
                        cookieName: cookieData.name,
                        error: chrome.runtime.lastError.message,
                        url: cookieData.url,
                        domain: cookieData.domain,
                        cookieData: cookieData // TAM DETAY
                    });
                    resolve(false);
                } else if (!cookie) {
                    console.error(`❌ CookieManager: Cookie set edildi ama dönen değer null:`, {
                        name: cookieData.name,
                        cookieData: cookieData
                    });
                    resolve(false);
                } else {
                    console.log(`✅ CookieManager: chrome.cookies.set() BAŞARILI:`, cookie.name);
                    resolve(true);
                }
            });
        });
    }
}

// 🍪 COOKIE EKLEME FONKSİYONU - CONTENT SCRIPT İÇİN (CHROME 131+ UYUMLU)
// Yeni CookieManager kullanarak geliştirilmiş versiyon
async function addCookiesFromContentScript(cookies) {
    console.log('🍪 Background: Cookie ekleme isteği alındı:', cookies.length, 'adet');
    console.log('📋 Cookie listesi:', cookies.map(c => c.name).join(', '));
    
    try {
        // Yeni CookieManager'ı kullan
        const result = await CookieManager.setPlatformCookies(cookies);
        
        console.log(`📊 Background: Cookie işlemi tamamlandı - ${result.successful}/${result.total} başarılı`);
        
        if (result.failed > 0) {
            console.warn(`⚠️ ${result.failed} cookie eklenemedi. Detaylar:`, 
                result.results.filter(r => !r.success).map(r => ({ name: r.name, error: r.error }))
            );
        }
        
        return {
            success: result.success,
            successCount: result.successful,
            failCount: result.failed,
            total: result.total
        };
    } catch (error) {
        console.error('❌ Background: Cookie ekleme genel hatası:', error);
        console.error('❌ Hata detayları:', {
            message: error.message,
            stack: error.stack,
            cookieCount: cookies.length
        });
        return {
            success: false,
            successCount: 0,
            failCount: cookies.length,
            total: cookies.length,
            error: error.message
        };
    }
}

// ⚠️ İKİNCİ LISTENER KALDIRILDI - Tüm handler'lar ilk listener'a birleştirildi (satır 1245)

// Eklenti yüklendiğinde ve tarayıcı açıldığında kuralları otomatik uygula
chrome.runtime.onInstalled.addListener(async () => {
    try {
        await setupDynamicHeaders();
        await setupBlockingDynamicHeaders();
    } catch (error) {}
    checkForUpdate();
});

chrome.runtime.onStartup.addListener(async () => {
    try {
        await setupDynamicHeaders();
        await setupBlockingDynamicHeaders();
    } catch (error) {}
    checkForUpdate();
});

// ====================================
// TRENDYOLGO: Token ile otomatik giriş
// ====================================

async function handleTrendyolGoTokenProcess(token, tabId, forcedAddress = null) {
    console.log('[TGO] Token işlemi başlatılıyor:', token.substring(0, 12) + '...');

    // Onceki surumlerden kalan mobil header kurallarini temizle
    try {
        await chrome.declarativeNetRequest.updateSessionRules({ removeRuleIds: [7201, 7202] });
    } catch (_) {}

    // 1. Backend'den hesap bilgilerini al
    const apiUrl = `https://kuponmarket.online/api/trendyolgo/login-data?token=${encodeURIComponent(token)}`;
    const response = await fetch(apiUrl);
    const result = await response.json();

    if (!result || !result.status || !result.data) {
        throw new Error(result?.error || 'TrendyolGo hesap bilgisi alınamadı');
    }

    const email = result.data.email;
    const password = result.data.password;

    if (!email || !password) {
        throw new Error('Email veya şifre eksik');
    }

    console.log('[TGO] Hesap bulundu:', email);

    // 1b. Backend'den gelen mobil JWT'yi kaydet (kupon uygulama için kritik)
    const mobileAccessToken = result.data.access_token || '';
    const mobileRefreshToken = result.data.refresh_token || '';
    if (mobileAccessToken && mobileAccessToken.startsWith('ey')) {
        await chrome.storage.local.set({
            tyMobileToken: mobileAccessToken,
            tyRefreshToken: mobileRefreshToken,
            tyTokenSource: 'kuponmarket-api',
            tyTokenEmail: email,
            tyTokenSavedAt: Date.now()
        });
        console.log('[TGO] ✅ Mobil JWT kaydedildi (kupon proxy için), uzunluk:', mobileAccessToken.length);
    } else {
        console.warn('[TGO] ⚠️ Backend mobil access_token döndürmedi, mobil login denenecek...');
        try {
            const mobileLoginResp = await fetch('https://kuponmarket.online/api/trendyolgo/mobile-login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ token: token })
            });
            const mobileLoginData = await mobileLoginResp.json();
            if (mobileLoginData.success && mobileLoginData.access_token) {
                await chrome.storage.local.set({
                    tyMobileToken: mobileLoginData.access_token,
                    tyRefreshToken: mobileLoginData.refresh_token || '',
                    tyTokenSource: 'kuponmarket-mobile-login',
                    tyTokenEmail: email,
                    tyTokenSavedAt: Date.now()
                });
                console.log('[TGO] ✅ Mobil JWT alındı (mobile-login endpoint), uzunluk:', mobileLoginData.access_token.length);
            }
        } catch (mlErr) {
            console.warn('[TGO] Mobil login fallback başarısız:', mlErr.message);
        }
    }

    // 2. Mevcut tgoyemek.com cookie'lerini temizle
    const existingCookies = await new Promise(resolve => {
        chrome.cookies.getAll({ domain: 'tgoyemek.com' }, cookies => resolve(cookies || []));
    });
    for (const cookie of existingCookies) {
        const url = 'https://tgoyemek.com' + (cookie.path || '/');
        await chrome.cookies.remove({ url, name: cookie.name }).catch(() => {});
    }
    console.log('[TGO] Eski cookie\'ler temizlendi');

    // 3. CSRF token al
    const csrfResponse = await fetch('https://tgoyemek.com/api/auth/csrf', {
        method: 'GET',
        headers: {
            'accept': '*/*',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
        }
    });

    if (!csrfResponse.ok) {
        throw new Error('CSRF token alınamadı (HTTP ' + csrfResponse.status + ')');
    }

    const csrfData = await csrfResponse.json();
    const csrfToken = csrfData.csrfToken || csrfData.token || csrfData.csrf;

    if (!csrfToken) {
        throw new Error('CSRF token boş geldi');
    }
    console.log('[TGO] CSRF token alındı');

    // 4. CSRF cookie'sini set et
    await chrome.cookies.set({
        url: 'https://tgoyemek.com',
        name: 'tgo-csrf-token',
        value: csrfToken,
        domain: 'tgoyemek.com',
        secure: true,
        httpOnly: true,
        sameSite: 'lax',
        path: '/'
    });

    // 5. Login isteği gönder
    const loginResponse = await fetch('https://tgoyemek.com/api/auth/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'text/plain;charset=UTF-8',
            'accept': '*/*',
            'origin': 'https://tgoyemek.com',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-mode': 'cors',
            'sec-fetch-dest': 'empty',
            'referer': 'https://tgoyemek.com/giris?callbackUrl=%2F',
            'Cookie': `tgo-csrf-token=${csrfToken}`
        },
        body: JSON.stringify({
            username: email,
            password: password,
            csrfToken: csrfToken
        })
    });

    if (!loginResponse.ok) {
        const errText = await loginResponse.text().catch(() => '');
        throw new Error('Login başarısız (HTTP ' + loginResponse.status + '): ' + errText.substring(0, 100));
    }

    console.log('[TGO] Login yanıtı başarılı');

    // 6. tgo-token cookie'sini al
    let tgoToken = null;

    // Header'dan cookie almayı dene
    const setCookieHeader = loginResponse.headers.get('set-cookie');
    if (setCookieHeader) {
        const match = setCookieHeader.match(/tgo-token=([^;]+)/);
        if (match) tgoToken = match[1];
    }

    // Cookie store'dan almayı dene
    if (!tgoToken) {
        for (let i = 0; i < 5; i++) {
            await new Promise(r => setTimeout(r, 500));
            const cookie = await new Promise(resolve => {
                chrome.cookies.get({ url: 'https://tgoyemek.com', name: 'tgo-token' }, c => resolve(c));
            });
            if (cookie && cookie.value) {
                tgoToken = cookie.value;
                break;
            }
        }
    }

    if (!tgoToken) {
        throw new Error('tgo-token cookie alınamadı. IP adresinizi yenileyip tekrar deneyin.');
    }

    // 7. Cookie'leri ayarla
    await chrome.cookies.set({
        url: 'https://tgoyemek.com',
        name: 'tgo-token',
        value: tgoToken,
        domain: 'tgoyemek.com',
        secure: true,
        httpOnly: true,
        sameSite: 'lax',
        path: '/'
    });

    await chrome.cookies.set({
        url: 'https://tgoyemek.com',
        name: 'access_token',
        value: tgoToken,
        domain: 'tgoyemek.com',
        secure: true,
        httpOnly: false
    });

    await chrome.cookies.set({
        url: 'https://tgoyemek.com',
        name: 'user_email',
        value: email,
        domain: 'tgoyemek.com',
        secure: true,
        httpOnly: false
    });

    console.log('[TGO] Cookie\'ler ayarlandı');

    // 8. Otomatik adres ekleme - storage'dan oku
    const storageData = await chrome.storage.local.get('tgo_pending_address');
    const pendingAddress = forcedAddress || storageData.tgo_pending_address || null;

    console.log('[TGO] Pending adres:', pendingAddress ? `${pendingAddress.neighborhood}, ${pendingAddress.district}, ${pendingAddress.city}` : 'YOK');

    let addressAction = null;
    if (pendingAddress) {
        try {
            const addressAlreadyOnAccount = Boolean(result.data.address_added);
            console.log('[TGO] Adres islemi basliyor...', addressAlreadyOnAccount ? 'PUT (mevcut hesap)' : 'POST/PUT');
            const addrResult = await tgoManageAddress(pendingAddress, tgoToken, {
                addressAlreadyOnAccount,
            });
            addressAction = addrResult.action;
            console.log('[TGO] Adres islemi BASARILI:', addressAction);
            await chrome.storage.local.remove('tgo_pending_address');
        } catch (addrErr) {
            console.error('[TGO] Adres islemi HATA:', addrErr.message);
            throw new Error('Giris basarili ancak adres kaydedilemedi: ' + addrErr.message);
        }
    }

    // 9. Sayfayı aç
    chrome.tabs.create({ url: 'https://tgoyemek.com' });

    return { success: true, email, addressAction };
}

// ====================================
// TRENDYOLGO: Adres Yönetimi Fonksiyonları
// ====================================

let _tgoActiveToken = null;

function tgoAddrHeaders() {
    return {
        'Authorization': `bearer ${_tgoActiveToken}`,
        'Accept': 'application/json, text/plain, */*',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36',
        'origin': 'https://tgoyemek.com',
        'sec-fetch-site': 'cross-site',
        'sec-fetch-mode': 'cors',
        'sec-fetch-dest': 'empty'
    };
}

async function tgoFetchCities() {
    const headers = tgoAddrHeaders();
    console.log('[TGO-ADDR] Cities isteği, auth:', headers.Authorization ? headers.Authorization.substring(0, 20) + '...' : 'BOŞ');
    const resp = await fetch('https://api.tgoapis.com/web-user-apimemberaddress-santral/cities', {
        headers: headers
    });
    console.log('[TGO-ADDR] Cities response status:', resp.status);
    if (!resp.ok) {
        const errText = await resp.text().catch(() => '');
        throw new Error('Şehir listesi alınamadı: ' + resp.status + ' - ' + errText.substring(0, 200));
    }
    const data = await resp.json();
    console.log('[TGO-ADDR] Cities data keys:', Object.keys(data || {}), 'count:', (data?.cities || []).length);
    return data?.cities || [];
}

async function tgoFetchDistricts(cityId) {
    const resp = await fetch(`https://api.tgoapis.com/web-user-apimemberaddress-santral/cities/${cityId}/districts`, {
        headers: tgoAddrHeaders()
    });
    if (!resp.ok) throw new Error('İlçe listesi alınamadı: ' + resp.status);
    const data = await resp.json();
    return data?.districts || [];
}

async function tgoFetchNeighborhoods(districtId) {
    const resp = await fetch(`https://api.tgoapis.com/web-user-apimemberaddress-santral/districts/${districtId}/neighborhoods`, {
        headers: tgoAddrHeaders()
    });
    if (!resp.ok) throw new Error('Mahalle listesi alınamadı: ' + resp.status);
    const data = await resp.json();
    return data?.neighborhoods || [];
}

function tgoSimplifyText(text) {
    return text.toLowerCase()
        .normalize('NFKD')
        .replace(/[\u0300-\u036f]/g, '')
        .replace(/[\u0130\u0049]/g, 'i')
        .replace(/[\u0131]/g, 'i')
        .replace(/[^a-z0-9]/g, '');
}

function tgoCleanSuffix(text) {
    return text.replace(/\s*(mah|mahallesi|mahalle|mh\.?|köy|köyü|beldesi|kasabası)\s*$/gi, '').trim();
}

function tgoFindMatch(dataArray, nameToMatch) {
    if (!nameToMatch || !dataArray || dataArray.length === 0) return null;

    const searchBase = tgoCleanSuffix(nameToMatch);
    const simplified = tgoSimplifyText(searchBase);

    let match = dataArray.find(item => tgoSimplifyText(tgoCleanSuffix(item.name)) === simplified);
    if (match) return match;

    match = dataArray.find(item => {
        const s = tgoSimplifyText(tgoCleanSuffix(item.name));
        return s.startsWith(simplified) || simplified.startsWith(s);
    });
    if (match) return match;

    if (simplified.length >= 3) {
        match = dataArray.find(item => {
            const s = tgoSimplifyText(tgoCleanSuffix(item.name));
            return s.includes(simplified) || simplified.includes(s);
        });
    }
    return match || null;
}

async function tgoGetLocationIds(address) {
    const cityName = address.city || address.province || address.city_name;
    const cities = await tgoFetchCities();
    const city = tgoFindMatch(cities, cityName);
    if (!city) throw new Error('Şehir bulunamadı: ' + cityName);

    const districts = await tgoFetchDistricts(city.id);
    const district = tgoFindMatch(districts, address.district);
    if (!district) throw new Error('İlçe bulunamadı: ' + address.district);

    const neighborhoods = await tgoFetchNeighborhoods(district.id);
    const neighborhood = tgoFindMatch(neighborhoods, address.neighborhood || address.areas);
    if (!neighborhood) throw new Error('Mahalle bulunamadı: ' + (address.neighborhood || address.areas));

    return { cityId: city.id, districtId: district.id, neighborhoodId: neighborhood.id };
}

function tgoGetAddressId(address) {
    return address?.id || address?.addressId || address?.address_id || null;
}

function tgoExtractPhone(rawPhone) {
    let phone = String(rawPhone || '').replace(/\D/g, '');
    if (phone.startsWith('0')) phone = phone.substring(1);
    if (phone.startsWith('90')) phone = phone.substring(2);
    if (!phone.startsWith('5') || phone.length !== 10) return '';
    return phone;
}

function tgoHasCoordinates(address) {
    if (!address) return false;
    const lat = parseFloat(address.latitude ?? address.lat);
    const lng = parseFloat(address.longitude ?? address.lng ?? address.lon);
    return Number.isFinite(lat) && Number.isFinite(lng) && lat !== 0 && lng !== 0;
}

async function tgoGetAddresses(strict = false) {
    const resp = await fetch('https://api.tgoapis.com/web-user-apimemberaddress-santral/addresses', {
        headers: tgoAddrHeaders()
    });
    console.log('[TGO-ADDR] Get addresses status:', resp.status);
    if (!resp.ok) {
        const errText = await resp.text().catch(() => '');
        if (strict) {
            throw new Error('Mevcut adresler alinamadi: ' + resp.status + ' - ' + errText.substring(0, 200));
        }
        return [];
    }
    const data = await resp.json();
    const addresses = data?.addresses || data?.data?.addresses || [];
    console.log('[TGO-ADDR] Mevcut adres sayisi:', addresses.length);
    return addresses;
}

async function tgoDeleteAddress(addressId) {
    const resp = await fetch(`https://api.tgoapis.com/web-user-apimemberaddress-santral/addresses/${addressId}`, {
        method: 'DELETE',
        headers: tgoAddrHeaders()
    });
    return resp.ok;
}

function tgoResolveOwnerNames(address) {
    const first = (address.first_name || address.firstName || address.ownerName || '').trim();
    const last = (address.last_name || address.lastName || address.ownerSurname || '').trim();
    if (first || last) {
        let ownerName = first || 'Kullanici';
        let ownerSurname = last || 'Adi';
        ownerName = ownerName.replace(/[^a-zA-ZçÇğĞıİöÖşŞüÜ\s]/g, '').trim();
        ownerSurname = ownerSurname.replace(/[^a-zA-ZçÇğĞıİöÖşŞüÜ\s]/g, '').trim();
        if (ownerName.length < 2) ownerName = 'Kullanici';
        if (ownerSurname.length < 2) ownerSurname = 'Adi';
        return { ownerName, ownerSurname };
    }

    const fullName = (address.fullname || address.name || '').trim();
    let ownerName = 'Kullanici';
    let ownerSurname = 'Adi';
    if (fullName) {
        const parts = fullName.split(' ').filter(p => p.length > 0);
        if (parts.length === 1) {
            ownerName = parts[0];
            ownerSurname = 'Adi';
        } else {
            ownerSurname = parts[parts.length - 1];
            ownerName = parts.slice(0, -1).join(' ');
        }
    }

    ownerName = ownerName.replace(/[^a-zA-ZçÇğĞıİöÖşŞüÜ\s]/g, '').trim();
    ownerSurname = ownerSurname.replace(/[^a-zA-ZçÇğĞıİöÖşŞüÜ\s]/g, '').trim();
    if (ownerName.length < 2) ownerName = 'Kullanici';
    if (ownerSurname.length < 2) ownerSurname = 'Adi';

    return { ownerName, ownerSurname };
}

async function tgoUpdateAddress(addressId, address, phoneNumber, existingRecord = null) {
    let phone = tgoExtractPhone(phoneNumber);
    if (!phone && existingRecord) {
        phone = tgoExtractPhone(existingRecord.phone);
    }
    if (!phone) {
        const all = await tgoGetAddresses(true);
        const found = all.find(a => String(tgoGetAddressId(a)) === String(addressId));
        phone = tgoExtractPhone(found?.phone);
    }
    if (!phone) phone = '5551234567';

    const locationIds = await tgoGetLocationIds(address);

    const neighborhood = address.neighborhood || address.areas || '';
    const street = address.street || address.address_line1 || '';
    const building = address.building || address.address_line2 || '1';
    const apartmentNum = address.apartment || address.entrance || '1';
    const floorNum = address.floor || '1';
    const addressLine = `${neighborhood}, ${street} No:${building}`;

    const { ownerName, ownerSurname } = tgoResolveOwnerNames(address);

    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    let addrTitle = '';
    for (let i = 0; i < 6; i++) addrTitle += chars.charAt(Math.floor(Math.random() * chars.length));

    const lat = parseFloat(address.latitude || address.lat || 0);
    const lng = parseFloat(address.longitude || address.lng || 0);
    const angle = Math.random() * 2 * Math.PI;
    const dist = Math.sqrt(Math.random()) * 5;
    const dLat = (dist * Math.cos(angle)) / 111320;
    const dLng = (dist * Math.sin(angle)) / (111320 * Math.cos(lat * Math.PI / 180));

    const body = {
        name: ownerName,
        surname: ownerSurname,
        phone: phone,
        apartmentNumber: building,
        floor: floorNum,
        doorNumber: apartmentNum,
        addressName: addrTitle,
        addressDescription: address.delivery_instructions || '',
        addressLine: addressLine,
        cityId: locationIds.cityId,
        districtId: locationIds.districtId,
        neighborhoodId: locationIds.neighborhoodId,
        latitude: (lat + dLat).toString(),
        longitude: (lng + dLng).toString(),
        countryCode: 'TR',
        elevatorAvailable: false
    };

    const headers = { ...tgoAddrHeaders(), 'Content-Type': 'application/json' };

    console.log('[TGO] PUT adres guncelleme, addressId:', addressId, 'tel:', phone.substring(0, 3) + '*****');
    const resp = await fetch(`https://api.tgoapis.com/web-user-apimemberaddress-santral/addresses/${addressId}`, {
        method: 'PUT',
        headers: headers,
        body: JSON.stringify(body)
    });

    console.log('[TGO] PUT response status:', resp.status);
    if (!resp.ok) {
        let msg = `HTTP ${resp.status}`;
        try { const e = await resp.json(); msg = JSON.stringify(e).substring(0, 300); } catch (_) {}
        throw new Error('Adres güncellenemedi: ' + msg);
    }
    return true;
}

async function tgoCreateAddress(address, phoneNumber) {
    const locationIds = await tgoGetLocationIds(address);

    const neighborhood = address.neighborhood || address.areas || '';
    const street = address.street || address.address_line1 || '';
    const building = address.building || address.address_line2 || '1';
    const apartmentNum = address.apartment || address.entrance || '1';
    const floorNum = address.floor || '1';
    const addressLine = `${neighborhood}, ${street} No:${building}`;

    const { ownerName, ownerSurname } = tgoResolveOwnerNames(address);

    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    let addrTitle = '';
    for (let i = 0; i < 6; i++) addrTitle += chars.charAt(Math.floor(Math.random() * chars.length));

    const lat = parseFloat(address.latitude || address.lat || 0);
    const lng = parseFloat(address.longitude || address.lng || 0);
    const angle = Math.random() * 2 * Math.PI;
    const dist = Math.sqrt(Math.random()) * 5;
    const dLat = (dist * Math.cos(angle)) / 111320;
    const dLng = (dist * Math.sin(angle)) / (111320 * Math.cos(lat * Math.PI / 180));

    const body = {
        name: ownerName,
        surname: ownerSurname,
        phone: phoneNumber,
        apartmentNumber: building,
        floor: floorNum,
        doorNumber: apartmentNum,
        addressName: addrTitle,
        addressDescription: address.delivery_instructions || '',
        addressLine: addressLine,
        cityId: locationIds.cityId,
        districtId: locationIds.districtId,
        neighborhoodId: locationIds.neighborhoodId,
        latitude: (lat + dLat).toString(),
        longitude: (lng + dLng).toString(),
        countryCode: 'TR',
        elevatorAvailable: false
    };

    const headers = { ...tgoAddrHeaders(), 'Content-Type': 'application/json' };

    const resp = await fetch('https://api.tgoapis.com/web-user-apimemberaddress-santral/addresses', {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(body)
    });

    const respText = await resp.text();
    console.log('[TGO-ADDR] Create address status:', resp.status, respText.substring(0, 200));

    let respData = null;
    try { respData = respText ? JSON.parse(respText) : null; } catch (_) {}

    if (respData?.field === 'sms_verification' || (respData?.success === false && respText.includes('sms_verification'))) {
        throw new Error('SMS dogrulama gerekli - hesaptaki mevcut telefon korunamadi');
    }

    if (!resp.ok) {
        throw new Error('Adres olusturulamadi: ' + (respText || `HTTP ${resp.status}`).substring(0, 300));
    }

    console.log('[TGO-ADDR] Adres basariyla olusturuldu');
    return true;
}

async function tgoManageAddress(address, token, options = {}) {
    const { addressAlreadyOnAccount = false } = options;

    if (!tgoHasCoordinates(address)) {
        throw new Error('Gecerli adres koordinati bulunamadi (latitude/longitude)');
    }

    _tgoActiveToken = token;
    console.log('[TGO] Adres islemi baslatiliyor:', address.neighborhood || address.areas, address.district, address.city || address.province);

    // Koordinatları kupon proxy için kaydet (KuponStore gibi)
    const lat = parseFloat(address.latitude || address.lat || 0);
    const lng = parseFloat(address.longitude || address.lng || 0);
    if (lat && lng) {
        await chrome.storage.local.set({ tyAddressPayload: { latitude: String(lat), longitude: String(lng) } }).catch(() => {});
        console.log('[TGO] ✅ tyAddressPayload kaydedildi:', lat, lng);
    }

    const existingAddresses = await tgoGetAddresses(addressAlreadyOnAccount);

    if (existingAddresses.length > 0) {
        // Kuppo akisi: hesaptaki MEVCUT telefonu koru, yeni adres POST et, eskileri sil (SMS yok)
        const existingPhone = tgoExtractPhone(existingAddresses[0].phone) || '5551234567';
        console.log(`[TGO] ${existingAddresses.length} mevcut adres var, Kuppo akisi (POST+sil), tel: ${existingPhone.substring(0, 3)}*****`);

        await tgoCreateAddress(address, existingPhone);

        for (const oldAddr of existingAddresses) {
            const oldId = tgoGetAddressId(oldAddr);
            if (oldId) {
                await tgoDeleteAddress(oldId);
                await new Promise(r => setTimeout(r, 500));
            }
        }

        console.log('[TGO] Adres Kuppo akisi ile guncellendi (POST + eski silindi)');
        return { action: 'updated' };
    }

    if (addressAlreadyOnAccount) {
        throw new Error('Hesapta adres olmali ancak API bos dondu. Tekrar giris yapip deneyin.');
    }

    console.log('[TGO] Mevcut adres yok, POST ile yeni olusturuluyor...');
    const newPhone = tgoExtractPhone(address.phone_number || address.phone) || '5551234567';
    await tgoCreateAddress(address, newPhone);
    console.log('[TGO] Adres POST ile olusturuldu');
    return { action: 'created' };
}

// ====================================
// TRENDYOLGO: Device Signals & Proxy Helpers
// ====================================

function _tyGenerateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        const r = Math.random() * 16 | 0;
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

function _tyGenerateRandomHex(len) {
    let hex = '';
    for (let i = 0; i < len; i++) hex += Math.floor(Math.random() * 16).toString(16);
    return hex;
}

async function _tyGenerateDeviceSignals() {
    try {
        const response = await fetch('https://kuponmarket.online/api/trendyolgo/generate-signals', {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
        });
        const result = await response.json();
        if (result.success && result.data) {
            console.log('[TY Proxy] ✅ Device signals alındı (kuponmarket)');
            return { payload: result.data.payload, signature: result.data.signature };
        }
        throw new Error('API başarısız');
    } catch (error) {
        console.warn('[TY Proxy] ⚠️ Device signals fallback kullanılıyor:', error.message);
        const ts = Date.now();
        return {
            payload: `ts=${ts}&e=0&v=1.45.4.164&r=0&f=0&rs=0`,
            signature: btoa(ts.toString())
        };
    }
}

function _tyBuildMobileHeaders(token, { deviceId, uniqueId, tyUniqueId, sessionId, processId, tpaydid, signals, variant = 'default' }) {
    let xChannel = '3', searchSegment = '9', gender = 'F';
    let xFeatures = 'OPTIONAL_REBATE;TRENDYOLPAY_ENABLED;MEAL_CART_ENABLED;MEAL_CARD_TRENDYOL_PROMOTION;DELIVERY_FEE_SUMMARY_HIDDEN';
    if (variant === 'address') { xChannel = '4'; searchSegment = '20'; gender = 'M'; }
    else if (variant === 'coupon') { xChannel = '4'; }

    return {
        'Host': 'api.tgoapis.com',
        'Deviceid': deviceId,
        'Bff-Token-Validation': 'true',
        'X-Features': xFeatures,
        'X-Application-Id': '5',
        'Cl_eligible': 'false',
        'Sid': sessionId,
        'Pid': processId,
        'Build': '1.45.4.164',
        'Platform': 'Android',
        'Device-Language': 'tr',
        'Osversion': '9',
        'Isemulator': 'false',
        'X-Channelid': xChannel,
        'X-Device-Signals-Payload': signals.payload,
        'X-Device-Signals-Signature': signals.signature,
        'Uniqueid': uniqueId,
        'Tpaydid': tpaydid,
        'Accept-Language': 'tr-TR',
        'X-Storefront-Id': '1',
        'Searchsegment': searchSegment,
        'Gender': gender,
        'X-Visitor-Type': '4',
        'Segments': '410750033_generic_6,410750050_1_6,278500001_1753975821420',
        'App-Name': 'TrendyolGo',
        'Lc-Member': 'true',
        'Ty-Uniqueid': tyUniqueId,
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 9; 2203121C Build/PQ3A.190605.09201023) TrendyolGo/1.45.4.164',
        'Authorization': `bearer ${token}`,
        'Content-Type': 'application/json; charset=UTF-8'
    };
}

// ====================================
// TRENDYOLGO: Kupon Proxy (KuponStore köprüsü)
// ====================================

function _tyDecodeJwt(token) {
    try {
        if (!token || typeof token !== 'string') return null;
        const parts = token.split('.');
        if (parts.length !== 3) return null;
        const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
        const padded = base64 + '==='.slice((base64.length + 3) % 4);
        return JSON.parse(atob(padded));
    } catch (e) { return null; }
}

function _tyLooksLikeMobileJwt(token) {
    const p = _tyDecodeJwt(token);
    if (!p) return false;
    if (p.role === 'anon') return false;
    if (typeof p.iss === 'string' && p.iss.includes('trendyol.com') && (p.userId || p.sub)) return true;
    if (p.channelId === 4) return true;
    if (typeof p.appName === 'string' && p.appName === 'lc' && (p.userId || p.sub)) return true;
    if (typeof p.applicationName === 'string' && p.applicationName.toLowerCase().includes('trendyolgo')) return true;
    return false;
}

async function _tyGetMobileToken() {
    try {
        const storageData = await chrome.storage.local.get(['tyMobileToken', 'tyTokenSource']);
        if (storageData.tyMobileToken && _tyLooksLikeMobileJwt(storageData.tyMobileToken)) {
            console.log('[TY Proxy] ✅ tyMobileToken kullanılıyor, kaynak:', storageData.tyTokenSource);
            return storageData.tyMobileToken;
        }
        if (storageData.tyMobileToken) {
            console.log('[TY Proxy] ⚠️ tyMobileToken mevcut ama mobil JWT değil, yine de kullanılıyor');
            return storageData.tyMobileToken;
        }
    } catch (e) { console.warn('[TY Proxy] Storage hatası:', e); }

    try {
        const accessCookie = await new Promise(r => chrome.cookies.get({ url: 'https://tgoyemek.com', name: 'access_token' }, r));
        if (accessCookie && accessCookie.value && _tyLooksLikeMobileJwt(accessCookie.value)) {
            return accessCookie.value;
        }
    } catch (e) {}

    try {
        const tgoCookie = await new Promise(r => chrome.cookies.get({ url: 'https://tgoyemek.com', name: 'tgo-token' }, r));
        if (tgoCookie && tgoCookie.value && _tyLooksLikeMobileJwt(tgoCookie.value)) {
            return tgoCookie.value;
        }
    } catch (e) {}

    console.error('[TY Proxy] ❌ Mobil JWT bulunamadı! Lütfen tekrar giriş yapın.');
    return null;
}

function _tyToMobileUrl(rawUrl) {
    let u = rawUrl;
    u = u.replace(/^https?:\/\/(www\.)?tgoyemek\.com\/api\//, 'https://api.tgoapis.com/');
    u = u.replace('/web-checkout-apicheckout-santral/', '/meal-mmcheckout-sfxcarts-santral/');
    if (u.includes('api.tgoapis.com') && !/[?&]appName=/.test(u)) {
        u += (u.includes('?') ? '&' : '?') + 'appName=TrendyolGo&channelId=4';
    }
    return u;
}

async function handleTyProxyRequest(request, sendResponse) {
    console.log('[TY Proxy v2] Request:', request.method || 'GET', request.url);

    try {
        if (!request.url) throw new Error('URL eksik');

        const tyToken = await _tyGetMobileToken();
        if (!tyToken) throw new Error('Trendyol mobil token bulunamadı. Lütfen giriş yapın.');

        // Device kimlik bilgilerini oluştur (tüm isteklerde tutarlı kalır)
        const deviceId = _tyGenerateUUID();
        const uniqueId = _tyGenerateRandomHex(16);
        const tyUniqueId = _tyGenerateUUID();
        const sessionId = _tyGenerateUUID();
        const processId = _tyGenerateUUID();
        const tpaydid = _tyGenerateUUID();
        const signals = await _tyGenerateDeviceSignals();

        const isCoupon = request.url.includes('/code-promotions') || request.url.includes('/carts/promotions');
        const isCart = request.url.includes('/carts') && !isCoupon;
        const isShipping = request.url.includes('/shipping');
        const isAddress = request.url.includes('/addresses');

        // ─────────────────────────────────────────────────────────────
        // Kupon endpoint'i: KuponStore apply-coupon.php (6-step flow)
        // PHP proxy adres + shipping + cart + kupon hepsini kendisi halleder
        // ─────────────────────────────────────────────────────────────
        if (isCoupon) {
            let parsed = {};
            try { parsed = JSON.parse(request.body || '{}'); } catch (_) {}
            const rawCode = (parsed.code || parsed.promotionCode || '').trim();
            const couponCode = rawCode.toLocaleUpperCase('tr-TR').replace(/\u0130/g, 'I');
            const forceApply = !!(parsed.force || parsed.forceApply);
            console.log('[TY Proxy v2] Kupon:', couponCode, '| force:', forceApply);

            if (!couponCode) {
                sendResponse({ success: false, error: 'Kupon kodu boş', headers: {} });
                return;
            }

            // Snapshot bilgisini PHP proxy'ye aktar (adres/ürün yoksa kendi ekler)
            let snapshotData = null;
            try {
                const snap = await chrome.storage.local.get(['tySnapshot', 'tyAddressPayload']);
                snapshotData = { cart: snap.tySnapshot || null, address: snap.tyAddressPayload || null };
            } catch (_) {}

            const proxyResp = await fetch('https://kuponmarket.online/api/trendyolgo/apply-coupon', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    mobile_token: tyToken,
                    code: couponCode,
                    force: forceApply,
                    device_id: deviceId,
                    unique_id: uniqueId,
                    ty_unique_id: tyUniqueId,
                    signals_payload: signals.payload,
                    signals_signature: signals.signature,
                    snapshot: snapshotData,
                }),
            });
            const proxyText = await proxyResp.text();
            let pj = null; try { pj = JSON.parse(proxyText); } catch (_) {}

            if (pj?.steps) {
                for (const [k, v] of Object.entries(pj.steps)) console.log('[TY Proxy v2] step', k, '→', v.http);
            }

            const couponHttp = pj?.http || proxyResp.status;
            const couponBody = pj?.body !== undefined
                ? (typeof pj.body === 'string' ? pj.body : JSON.stringify(pj.body))
                : proxyText;

            sendResponse({
                success: true, status: couponHttp,
                statusText: couponHttp === 200 ? 'OK' : 'Error',
                headers: { 'content-type': 'application/json' },
                data: couponBody,
            });
            return;
        }

        // ─────────────────────────────────────────────────────────────
        // Diğer istekler (cart, shipping, addresses): proxy.php + headers
        // ─────────────────────────────────────────────────────────────
        const mobileUrl = _tyToMobileUrl(request.url);
        const method = (request.method || 'GET').toUpperCase();

        // Shipping POST: tyAddressPayload'tan lat/lng al
        let upstreamBody = request.body || null;
        if (isShipping && method === 'POST') {
            try {
                const stor = await chrome.storage.local.get(['tyAddressPayload']);
                const p = stor.tyAddressPayload;
                if (p && p.latitude && p.longitude) {
                    upstreamBody = JSON.stringify({
                        latitude: parseFloat(p.latitude),
                        longitude: parseFloat(p.longitude),
                    });
                    console.log('[TY Proxy v2] Shipping body lat/lng ile değiştirildi');
                }
            } catch (e) {}
        }

        // Variant belirleme (header setini etkiler)
        let variant = 'default';
        if (isAddress) variant = 'address';
        else if (isCoupon) variant = 'coupon';

        const mobileHeaders = _tyBuildMobileHeaders(tyToken, {
            deviceId, uniqueId, tyUniqueId, sessionId, processId, tpaydid, signals, variant
        });

        console.log('[TY Proxy v2] Generic →', method, mobileUrl);

        const proxyResp = await fetch('https://kuponmarket.online/api/trendyolgo/proxy', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                mobile_token: tyToken,
                method,
                url: mobileUrl,
                body: upstreamBody,
                headers: mobileHeaders,
            }),
        });
        const proxyText = await proxyResp.text();
        let pj = null; try { pj = JSON.parse(proxyText); } catch (_) {}

        const upstreamHttp = pj?.http || proxyResp.status;
        let upstreamBodyResult = pj?.body !== undefined
            ? (typeof pj.body === 'string' ? pj.body : JSON.stringify(pj.body))
            : proxyText;

        // Cart response → web schema dönüşümü (mobil API farklı format döner)
        const isWebCheckoutCart = request.url.includes('/web-checkout-apicheckout-santral/carts')
            && !request.url.includes('/coupons') && !request.url.includes('/code-promotions');
        if (upstreamHttp >= 200 && upstreamHttp < 300 && isWebCheckoutCart) {
            try {
                const mobileData = JSON.parse(upstreamBodyResult);
                const webData = _tyTransformMobileToWeb(mobileData);
                upstreamBodyResult = JSON.stringify(webData);
                console.log('[TY Proxy v2] Mobile→Web schema dönüştürüldü');
            } catch (e) {
                console.warn('[TY Proxy v2] Schema dönüşüm hatası:', e.message);
            }
        }

        console.log('[TY Proxy v2] Generic resp:', upstreamHttp);

        sendResponse({
            success: true, status: upstreamHttp,
            statusText: upstreamHttp >= 200 && upstreamHttp < 300 ? 'OK' : 'Error',
            headers: pj?.headers || { 'content-type': 'application/json' },
            data: upstreamBodyResult,
        });
    } catch (error) {
        console.error('[TY Proxy v2] Hata:', error);
        sendResponse({
            success: false, error: error.message || 'Bilinmeyen hata',
            headers: {}, status: 503, data: JSON.stringify({ detail: error.message }),
        });
    }
}

// ====================================
// TRENDYOLGO: Mobile → Web Schema Transform
// ====================================
function _tyTransformMobileToWeb(mobileData) {
    return {
        channelSummary: {
            totalProductPrice: mobileData.totalProductPrice || 0.0,
            promotions: mobileData.channelSummary?.promotions?.map(promo => ({
                title: promo.title, description: promo.description || '',
                amount: promo.amount, discountType: promo.discountType || null,
                isPromotionCodeApplied: promo.isPromotionCodeApplied || null,
                isRemovable: promo.isRemovable || null, promotionId: promo.id || null,
                isPromotion: promo.isPromo || null, storePickup: promo.storePickup || false, isServiceFee: false
            })) || []
        },
        groupedProducts: mobileData.groupedProducts?.map(group => ({
            warningMessage: group.warningMessage,
            products: group.products,
            store: {
                id: group.store.id, name: group.store.name, imageUrl: group.store.imageUrl,
                rating: group.store.rating, ratingBackgroundColor: group.store.ratingBackgroundColor,
                averageDeliveryInterval: group.store.averageDeliveryInterval,
                deliveryType: 'GO', deliveryTypeImageUrl: group.store.deliveryTypeImageUrl,
                minAmount: group.store.minAmount, storeDeeplink: group.store.storeDeeplink,
                supplierId: group.store.supplierId, locationId: group.store.locationId,
                deliveryFees: [], pickupConfig: { enabled: null, minDeliveryTimeInMin: 15, maxDeliveryTimeInMin: 25, minBasketPrice: 50.0 },
                location: mobileData.location || { neighborhoodId: 0, lat: 0, lon: 0 },
                priorityFees: null
            },
            shippingInfo: {
                current: mobileData.channelSummary?.currentShippingInfo || { fee: 0, feeDiff: 0, minAmount: 0, remaining: 0 },
                next: { fee: 0, feeDiff: 0, minAmount: 0, remaining: 0 },
                freeDf: { fee: 0, feeDiff: 0, minAmount: 0, remaining: 0 }
            }
        })) || [],
        summary: mobileData.summary?.map(item => ({
            title: item.title, description: item.description || '', amount: item.amount,
            discountType: item.discountType || null, isPromotionCodeApplied: item.isPromotionCodeApplied || null,
            isRemovable: item.isRemovable || null, promotionId: item.id || null,
            isPromotion: item.isPromo || null, storePickup: item.storePickup || false, isServiceFee: false
        })) || [],
        totalProductCount: mobileData.totalProductCount || 0,
        totalProductPrice: mobileData.totalProductPrice || 0.0,
        totalProductPriceDiscounted: mobileData.totalProductPriceDiscounted || 0.0,
        totalPrice: mobileData.totalPrice || 0.0,
        deliveryPrice: 0.0,
        totalSellingPrice: mobileData.totalProductPrice || 0.0,
        appliedCouponId: mobileData.appliedCouponId,
        distinctProductCount: mobileData.distinctProductCount,
        warnings: mobileData.warnings || [],
        discount: {
            coupon: null,
            promotion: {
                discounts: { items: [], totalDiscount: (mobileData.totalProductPrice || 0) - (mobileData.totalProductPriceDiscounted || 0), totalInstantDiscount: 0, totalShippingDiscount: 0 },
                promotions: mobileData.summary?.filter(s => s.isPromo).map(promo => ({
                    discount: Math.abs(promo.amount), id: promo.id,
                    isCodePromotion: promo.discountType === 'CODE', isSupplierPaid: true,
                    name: promo.title, type: promo.discountType === 'CODE' ? 'CODE' : 'INSTANT_DISCOUNT',
                    storePickup: false, isServiceFee: false
                })) || [],
                promotionsToUse: [], mealCardUnusablePromotions: null
            },
            unusablePromotionsAndCoupons: []
        },
        shippingInfo: {
            current: mobileData.channelSummary?.currentShippingInfo || { fee: 0, feeDiff: 0, minAmount: 0, remaining: 0 },
            next: { fee: 0, feeDiff: 0, minAmount: 0, remaining: 0 },
            freeDf: { fee: 0, feeDiff: 0, minAmount: 0, remaining: 0 }
        }
    };
}

// ====================================
// TRENDYOLGO: Sepete ürün eklerken adres + shipping otomatik ayarlama
// (KS: handleTyCartItemsRequest — mobil API'de sepet hazırlığı)
// ====================================
async function handleTyCartItemsRequest(request, sendResponse) {
    try {
        if (!request.url) throw new Error('URL eksik');

        const tyToken = await _tyGetMobileToken();
        if (!tyToken) throw new Error('Trendyol mobil token bulunamadı. Lütfen tekrar giriş yapın.');

        const deviceId = _tyGenerateUUID();
        const uniqueId = _tyGenerateRandomHex(16);
        const tyUniqueId = _tyGenerateUUID();
        const sessionId = _tyGenerateUUID();
        const processId = _tyGenerateUUID();
        const tpaydid = _tyGenerateUUID();
        const signals = await _tyGenerateDeviceSignals();

        const buildHeaders = (extraVariant) => _tyBuildMobileHeaders(tyToken, {
            deviceId, uniqueId, tyUniqueId, sessionId, processId, tpaydid, signals, variant: extraVariant || 'default'
        });

        // 1. Adresleri al
        let addressId = null, latitude = null, longitude = null;
        try {
            const addrUrl = 'https://api.tgoapis.com/localcommerce-member-zeususer-service/addresses?getCities=false&appName=TrendyolGo&channelId=3';
            const addrResp = await fetch('https://kuponmarket.online/api/trendyolgo/proxy', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ mobile_token: tyToken, method: 'GET', url: addrUrl, headers: buildHeaders('address') }),
            });
            const addrResult = await addrResp.json();
            const addrData = typeof addrResult.body === 'string' ? JSON.parse(addrResult.body) : addrResult.body;
            if (addrData?.addresses?.length > 0) {
                const addr = addrData.addresses[0];
                addressId = addr.addressId || addr.id;
                latitude = addr.lat || addr.latitude;
                longitude = addr.lon || addr.longitude;
                console.log('[TY CartItems] Adres bulundu:', addressId, latitude, longitude);
            }
        } catch (e) { console.warn('[TY CartItems] Adres hatası:', e.message); }

        // tyAddressPayload yoksa otomatik doldur
        if (latitude && longitude) {
            await chrome.storage.local.set({ tyAddressPayload: { latitude: String(latitude), longitude: String(longitude) } }).catch(() => {});
        }

        // 2. Shipping gönder (adres varsa)
        if (addressId && latitude && longitude) {
            try {
                const shipUrl = 'https://api.tgoapis.com/meal-mmcheckout-sfxcarts-santral/shipping?appName=TrendyolGo&channelId=3';
                const shipBody = JSON.stringify({ invoiceAddressId: addressId, shippingAddressId: addressId, latitude, longitude });
                await fetch('https://kuponmarket.online/api/trendyolgo/proxy', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ mobile_token: tyToken, method: 'POST', url: shipUrl, body: shipBody, headers: buildHeaders() }),
                });
                console.log('[TY CartItems] Shipping gönderildi: addressId=', addressId);
            } catch (e) { console.warn('[TY CartItems] Shipping hatası:', e.message); }
        }

        // 3. Asıl sepet isteğini gönder
        const mobileUrl = _tyToMobileUrl(request.url);
        const proxyResp = await fetch('https://kuponmarket.online/api/trendyolgo/proxy', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ mobile_token: tyToken, method: request.method || 'POST', url: mobileUrl, body: request.body, headers: buildHeaders() }),
        });
        const proxyText = await proxyResp.text();
        let pj = null; try { pj = JSON.parse(proxyText); } catch (_) {}

        const upstreamHttp = pj?.http || proxyResp.status;
        const upstreamBody = pj?.body !== undefined
            ? (typeof pj.body === 'string' ? pj.body : JSON.stringify(pj.body))
            : proxyText;

        sendResponse({
            success: true, status: upstreamHttp,
            statusText: upstreamHttp >= 200 && upstreamHttp < 300 ? 'OK' : 'Error',
            headers: pj?.headers || { 'content-type': 'application/json' },
            data: upstreamBody,
        });
    } catch (error) {
        console.error('[TY CartItems] Hata:', error);
        sendResponse({
            success: false, error: error.message || 'Bilinmeyen hata',
            status: 503, statusText: 'Proxy Error', headers: {}, data: null
        });
    }
}