;(function () {
  const COMMON_PARAMS = 'aid=253642&app_name=i18n_ecom_alliance&device_platform=web&user_language=pt-BR&locale=pt-BR';
  const API_PREFIX = '/api/v1/streamer_desktop/';

  function buildUrl(path) {
    const rawPath = String(path || '');
    if (/^https:\/\/[a-z0-9.-]+\.tiktok\.com\//i.test(rawPath)) return rawPath;
    
    const isAbsolute = /^\/api\//.test(rawPath);
    const fullPath = isAbsolute ? rawPath : API_PREFIX + rawPath.replace(/^\/+/, '');
    const separator = fullPath.indexOf('?') >= 0 ? '&' : '?';
    
    return location.origin + fullPath + separator + COMMON_PARAMS;
  }

  async function executeApiCall(path, method = 'GET', body = null) {
    const options = { 
      method, 
      credentials: 'include' 
    };

    if (method === 'POST' || method === 'PUT') {
      options.headers = { 'content-type': 'application/json' };
      options.body = JSON.stringify(body || {});
    }

    try {
      const res = await fetch(buildUrl(path), options);
      if (!res || typeof res.status !== 'number') return { status: 0, data: null };
      
      let data = null;
      try { data = await res.json(); } catch (_) { data = null; }
      return { status: res.status, data };
    } catch (err) {
      console.error('[LiveCam Bridge] Erro na requisição:', err);
      return { status: 0, data: null, error: String(err.message || err) };
    }
  }

  window.addEventListener('message', async (ev) => {
    if (ev.source !== window || !ev.data || !ev.data.__livecam_apireq) return;
    
    const { id, path, method, body } = ev.data;
    const result = await executeApiCall(path, method, body);

    window.postMessage({
      __livecam_apires: true,
      id,
      payload: result
    }, location.origin);
  });
})();