// injected.js - Hook fetch to intercept API requests
(function () {
  const CATEGORY_KEYWORD = '/api/v1/pop/product_growth/category/authorized';

  // 获取 shopRegion（从 localStorage 或 URL 参数）
  function getShopRegion() {
    // 优先从 localStorage 读取
    const shopRegion = localStorage.getItem('shopRegion');
    if (shopRegion) {
      return shopRegion;
    }
    
    // 如果 localStorage 中没有，尝试从 URL 参数读取
    const urlParams = new URLSearchParams(window.location.search);
    const urlShopRegion = urlParams.get('shop_region');
    if (urlShopRegion) {
      // 保存到 localStorage 以便后续使用
      localStorage.setItem('shopRegion', urlShopRegion);
      return urlShopRegion;
    }
    
    // 默认返回 null
    return null;
  }

  // 根据 shopRegion 获取 API base URL
  function getApiBaseUrl() {
    const shopRegion = getShopRegion();
    
    // 如果 shopRegion 是 US，使用当前域名
    if (shopRegion === 'US') {
      return window.location.origin;
    }
    
    // 如果 shopRegion 是东南亚区域，使用对应的 API 域名
    const seaRegions = ['MY', 'PH', 'SG', 'TH', 'VN'];
    if (shopRegion && seaRegions.includes(shopRegion)) {
      return 'https://api16-normal-sg.tiktokshopglobalselling.com';
    }
    
    // 默认使用当前域名
    return window.location.origin;
  }

  function handleCategoryResponse(data) {
    try {
      window.postMessage({
          type: 'TT_CATEGORY_DATA',
          payload: data
        },
        '*'
      );
      console.log('[TT Category injected] postMessage data:', data);
    } catch (e) {
      console.warn('[TT Category injected] handle error:', e);
    }
  }

  // 监听来自插件的请求消息
  window.addEventListener('message', function (event) {
    if (event.source !== window) return;

    // 处理榜单数据请求
    if (event.data && event.data.type === 'TT_FETCH_TOP_SELLING_DATA') {
      const { apiUrl, requestParams, requestId } = event.data;

      // 获取必要的参数（从 localStorage 或环境变量）
      const locale = localStorage.getItem('locale') || 'zh-CN';
      const tkShopData = JSON.parse(localStorage.getItem('tk_shop_data') || '{}');
      const fp = document.querySelector('input[name="fp"]')?.value || 
                 document.cookie.match(/s_v_web_id=([^;]+)/)?.[1] || '';

      // 构建 query parameters
      const params = new URLSearchParams({
        locale: locale,
        language: locale,
        oec_seller_id: tkShopData.oec_seller_id || '',
        aid: tkShopData.app_id || '6556',
        app_name: 'i18n_ecom_shop',
        fp: fp,
        device_platform: 'web',
        cookie_enabled: 'true',
        screen_width: window.screen.width.toString(),
        screen_height: window.screen.height.toString(),
        browser_language: navigator.language,
        browser_platform: navigator.platform,
        browser_name: navigator.appCodeName,
        browser_version: encodeURIComponent(navigator.appVersion),
        browser_online: navigator.onLine.toString(),
        timezone_name: 'America/Los_Angeles'
      });

      // 根据 shopRegion 动态获取 base URL
      const baseUrl = getApiBaseUrl();
      const url = `${baseUrl}${apiUrl}?${params.toString()}`;

      console.log('[TT TopSelling injected] Fetching data (POST):', url);
      console.log('[TT TopSelling injected] shopRegion:', getShopRegion(), 'baseUrl:', baseUrl);
      console.log('[TT TopSelling injected] Request params:', requestParams);

      // 使用 POST 请求，body 为 JSON
      fetch(url, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache'
          },
          body: JSON.stringify(requestParams)
        })
        .then(function (response) {
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
          }
          return response.json();
        })
        .then(function (data) {
          window.postMessage({
              type: 'TT_TOP_SELLING_DATA_RESPONSE',
              payload: data,
              requestId: requestId
            },
            '*'
          );
          console.log('[TT TopSelling injected] Data fetched:', data);
        })
        .catch(function (error) {
          window.postMessage({
              type: 'TT_TOP_SELLING_DATA_ERROR',
              error: error.message,
              requestId: requestId
            },
            '*'
          );
          console.error('[TT TopSelling injected] Fetch error:', error);
        });
    }

    // 处理获取类目数据的请求
    if (event.data && event.data.type === 'TT_FETCH_CATEGORY_DATA') {
      const scenario = event.data.scenario || 1;

      // 获取必要的参数（从 localStorage 或环境变量）
      const locale = localStorage.getItem('locale') || 'zh-CN';
      const tkShopData = JSON.parse(localStorage.getItem('tk_shop_data') || '{}');
      const fp = document.querySelector('input[name="fp"]')?.value || 
                 document.cookie.match(/s_v_web_id=([^;]+)/)?.[1] || '';

      // 构建 query parameters
      const params = new URLSearchParams({
        locale: locale,
        language: locale,
        oec_seller_id: tkShopData.oec_seller_id || '',
        aid: tkShopData.app_id || '6556',
        app_name: 'i18n_ecom_shop',
        fp: fp,
        device_platform: 'web',
        cookie_enabled: 'true',
        screen_width: window.screen.width.toString(),
        screen_height: window.screen.height.toString(),
        browser_language: navigator.language,
        browser_platform: navigator.platform,
        browser_name: navigator.appCodeName,
        browser_version: encodeURIComponent(navigator.appVersion),
        browser_online: navigator.onLine.toString(),
        timezone_name: 'America/Los_Angeles'
      });

      // 根据 shopRegion 动态获取 base URL
      const baseUrl = getApiBaseUrl();
      const url = `${baseUrl}/api/v1/pop/product_growth/category/authorized?${params.toString()}`;

      console.log('[TT Category injected] Fetching category data (POST):', url);
      console.log('[TT Category injected] shopRegion:', getShopRegion(), 'baseUrl:', baseUrl);

      // 使用 POST 请求，body 为 JSON
      fetch(url, {
          method: 'POST',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache'
          },
          body: JSON.stringify({ scenario: scenario })
        })
        .then(function (response) {
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
          }
          return response.json();
        })
        .then(function (data) {
          window.postMessage({
              type: 'TT_CATEGORY_DATA_RESPONSE',
              payload: data,
              requestId: event.data.requestId
            },
            '*'
          );
          console.log('[TT Category injected] Category data fetched:', data);
        })
        .catch(function (error) {
          window.postMessage({
              type: 'TT_CATEGORY_DATA_ERROR',
              error: error.message,
              requestId: event.data.requestId
            },
            '*'
          );
          console.error('[TT Category injected] Fetch error:', error);
        });
    }
  });

  (function hookFetch() {
    if (!window.fetch) return;
    const originalFetch = window.fetch;
    if (originalFetch.__tt_hooked__) return;

    function wrappedFetch(input, init) {
      let url = '';
      try {
        if (typeof input === 'string') {
          url = input;
        } else if (input && input.url) {
          url = input.url;
        }
      } catch (e) {}

      const isCategory = url && url.indexOf(CATEGORY_KEYWORD) !== -1;

      if (!isCategory) {
        return originalFetch.call(this, input, init);
      }

      return originalFetch.call(this, input, init).then(function (res) {
        try {
          const clone = res.clone();
          const ct = clone.headers && clone.headers.get ?
            (clone.headers.get('content-type') || '') :
            '';
          if (ct.indexOf('application/json') !== -1 || ct.indexOf('text/json') !== -1) {
            clone.json().then(handleCategoryResponse).catch(function () {});
          }
        } catch (e) {
          console.warn('[TT injected] fetch clone/json error:', e);
        }
        return res;
      });
    }

    wrappedFetch.__tt_hooked__ = true;
    window.fetch = wrappedFetch;
    console.log('[TT Plugin] fetch hooked');
  })();

  console.log('[TT Plugin] injected script loaded');
})();