(function() {
  'use strict';

  console.log('[KM-TGO] Trendyol interceptor loaded');

  const serviceType = window.location.hostname.includes('tgoyemek') ? 'yemek' : 'market';

  function shouldInterceptTrendyol(url) {
    if (typeof url !== 'string') return false;

    // SADECE kupon endpoint'lerini intercept et
    // apply-coupon.php kendi içinde 6-step flow yapıyor (adres+shipping+cart+kupon)
    // Diğer istekleri (cart, items, shipping) web frontend'in kendi halletsin
    if (url.includes('/carts/code-promotions') || url.includes('/carts/promotions')) return true;

    return false;
  }

  function shouldSnapshot(url) {
    if (typeof url !== 'string') return false;
    return (
      url.includes('/web-checkout-apicheckout-santral/carts') ||
      url.includes('/web-user-apimemberaddress-santral/addresses') ||
      url.includes('/web-user-apimemberaddress-santral/user-addresses')
    );
  }

  function trySnapshotPayload(url, responseText) {
    try {
      if (!responseText) return;
      const j = JSON.parse(responseText);
      const snapshot = {};

      if (url.includes('/carts') && !url.includes('code-promotions') && !url.includes('promotions')) {
        const gp = j.groupedProducts || j.channelSummary?.groupedProducts;
        if (Array.isArray(gp) && gp.length > 0) {
          const grp = gp[0];
          const store = grp.store || {};
          const prod = (grp.products || [])[0];
          if (store.id && prod && prod.productId) {
            snapshot.restaurantId = store.id;
            snapshot.productId = prod.productId;
            snapshot.quantity = prod.quantity || 1;
            const loc = j.location || {};
            if (loc.lat) snapshot.latitude = loc.lat;
            if (loc.lon) snapshot.longitude = loc.lon;
          }
        }
        if (j.shippingAddressId) snapshot.addressId = j.shippingAddressId;
        if (j.invoiceAddressId) snapshot.invoiceAddressId = j.invoiceAddressId;
      }

      if (url.includes('/addresses') || url.includes('/user-addresses')) {
        if (j.id && !Array.isArray(j.addresses)) {
          snapshot.addressId = j.id;
        } else if (Array.isArray(j.addresses) && j.addresses.length > 0) {
          const a = j.addresses[0];
          snapshot.addressId = a.id;
          if (a.latitude) snapshot.latitude = parseFloat(a.latitude);
          if (a.longitude) snapshot.longitude = parseFloat(a.longitude);
        }
      }

      if (Object.keys(snapshot).length > 0) {
        window.postMessage({
          source: 'KM_TGO_INJECT',
          action: 'tySnapshotUpdate',
          snapshot
        }, '*');
      }
    } catch (e) {}
  }

  function isZeusUserEndpoint(url) {
    return typeof url === 'string' && url.includes('api.tgoapis.com') &&
      url.includes('web-user-apizeus-santral/user');
  }

  async function sendProxyRequest(requestData) {
    return new Promise((resolve, reject) => {
      const messageId = `proxy_${Date.now()}_${Math.random()}`;

      const messageHandler = (event) => {
        if (event.source !== window) return;
        if (!event.data || event.data.source !== 'KM_TGO_CONTENT') return;
        if (event.data.messageId !== messageId) return;

        window.removeEventListener('message', messageHandler);

        if (event.data.success) {
          resolve(event.data);
        } else {
          reject(new Error(event.data.error || 'Proxy failed'));
        }
      };

      window.addEventListener('message', messageHandler);

      setTimeout(() => {
        window.removeEventListener('message', messageHandler);
        reject(new Error('Proxy request timeout'));
      }, 15000);

      window.postMessage({
        source: 'KM_TGO_INJECT',
        messageId: messageId,
        action: 'tyProxyRequest',
        url: requestData.url,
        method: requestData.method,
        headers: requestData.headers,
        body: requestData.body
      }, '*');
    });
  }

  // Zeus profil doğrulama fake response
  function fakeZeusResponse() {
    return JSON.stringify({
      isVerified: true,
      isPhoneVerified: true,
      isEmailVerified: true,
      shouldShowVerification: false
    });
  }

  const originalFetch = window.fetch;
  window.fetch = async function(...args) {
    const [url, options = {}] = args;
    const urlString = url instanceof Request ? url.url : String(url);

    if (isZeusUserEndpoint(urlString)) {
      console.log('[KM-TGO] Zeus profil doğrulama engellendi (fetch):', urlString);
      return new Response(fakeZeusResponse(), {
        status: 200, statusText: 'OK',
        headers: { 'Content-Type': 'application/json' }
      });
    }

    if (shouldSnapshot(urlString)) {
      try {
        const resp = await originalFetch(...args);
        resp.clone().text().then(t => trySnapshotPayload(urlString, t)).catch(() => {});
        return resp;
      } catch (e) { return originalFetch(...args); }
    }

    if (shouldInterceptTrendyol(urlString)) {
      console.log('[KM-TGO] Intercepting fetch (proxy):', urlString);

      try {
        const proxyResponse = await sendProxyRequest({
          url: urlString,
          method: (options && options.method) || 'POST',
          headers: (options && options.headers) || {},
          body: (options && options.body) || null
        });

        return new Response(proxyResponse.data, {
          status: proxyResponse.status,
          statusText: proxyResponse.statusText || '',
          headers: proxyResponse.headers || {}
        });
      } catch (error) {
        console.error('[KM-TGO] Fetch proxy error:', error);
        return new Response(JSON.stringify({ message: error.message }), {
          status: 503, statusText: 'Proxy Error',
          headers: { 'content-type': 'application/json' }
        });
      }
    }

    return originalFetch(...args);
  };

  const originalXHROpen = XMLHttpRequest.prototype.open;
  const originalXHRSend = XMLHttpRequest.prototype.send;

  XMLHttpRequest.prototype.open = function(method, url, ...rest) {
    this._kmTgoUrl = url;
    this._kmTgoMethod = method;
    return originalXHROpen.call(this, method, url, ...rest);
  };

  XMLHttpRequest.prototype.send = function(body) {
    const url = this._kmTgoUrl;

    if (isZeusUserEndpoint(url)) {
      console.log('[KM-TGO] Zeus profil doğrulama engellendi (XHR):', url);
      const xhr = this;
      try { xhr.abort(); } catch (e) {}
      const fakeData = fakeZeusResponse();
      Object.defineProperty(xhr, 'readyState', { value: 4, writable: false, configurable: true });
      Object.defineProperty(xhr, 'status', { value: 200, writable: false, configurable: true });
      Object.defineProperty(xhr, 'statusText', { value: 'OK', writable: false, configurable: true });
      Object.defineProperty(xhr, 'responseText', { value: fakeData, writable: false, configurable: true });
      Object.defineProperty(xhr, 'response', { value: fakeData, writable: false, configurable: true });
      setTimeout(() => {
        if (xhr.onreadystatechange) xhr.onreadystatechange();
        if (xhr.onload) xhr.onload();
        if (xhr.onloadend) xhr.onloadend();
        try { xhr.dispatchEvent(new Event('readystatechange')); } catch(e) {}
        try { xhr.dispatchEvent(new Event('load')); } catch(e) {}
        try { xhr.dispatchEvent(new Event('loadend')); } catch(e) {}
      }, 10);
      return;
    }

    if (!shouldInterceptTrendyol(url)) {
      if (shouldSnapshot(url)) {
        this.addEventListener('load', () => {
          try { trySnapshotPayload(url, this.responseText); } catch(e) {}
        });
      }
      return originalXHRSend.call(this, body);
    }

    console.log('[KM-TGO] Intercepting XHR (proxy):', url);

    const xhr = this;
    xhr.abort();

    sendProxyRequest({
      url: this._kmTgoUrl,
      method: this._kmTgoMethod || 'GET',
      headers: {},
      body: body
    }).then(response => {
      Object.defineProperty(xhr, 'readyState', { configurable: true, get: () => 4 });
      Object.defineProperty(xhr, 'status', { configurable: true, get: () => response.status });
      Object.defineProperty(xhr, 'statusText', { configurable: true, get: () => response.statusText || '' });
      Object.defineProperty(xhr, 'responseText', { configurable: true, get: () => response.data });
      Object.defineProperty(xhr, 'response', { configurable: true, get: () => response.data });

      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'));
      }, 0);
    }).catch(error => {
      console.error('[KM-TGO] XHR proxy error:', error);
      Object.defineProperty(xhr, 'readyState', { configurable: true, get: () => 4 });
      Object.defineProperty(xhr, 'status', { configurable: true, get: () => 0 });

      setTimeout(() => {
        if (typeof xhr.onerror === 'function') xhr.onerror();
        if (typeof xhr.onreadystatechange === 'function') xhr.onreadystatechange();
        xhr.dispatchEvent(new Event('error'));
        xhr.dispatchEvent(new Event('readystatechange'));
        xhr.dispatchEvent(new Event('loadend'));
      }, 50);
    });
  };

  console.log('[KM-TGO] Trendyol interception active');
})();
