(() => {
  const SESSION_STORAGE_KEY = 'cc_session';
  const SUPERVISOR_REALTIME_PATH = '/proxy/supervisor/supervisor/realtime';

  function currentRole() {
    try {
      const raw = window.localStorage.getItem(SESSION_STORAGE_KEY);
      if (!raw) {
        return '';
      }
      const payload = JSON.parse(raw);
      return String(payload?.role || '').toLowerCase();
    } catch {
      return '';
    }
  }

  function roleFromRequest(input, init) {
    try {
      const headers = new Headers((init && init.headers) || (input && input.headers) || undefined);
      return String(headers.get('X-Role') || '').toLowerCase();
    } catch {
      return '';
    }
  }

  function urlFromRequest(input) {
    if (typeof input === 'string') {
      return input;
    }
    if (input && typeof input.url === 'string') {
      return input.url;
    }
    return '';
  }

  function isRestrictedSupervisorRealtime(input, init) {
    const url = urlFromRequest(input);
    if (!url.includes(SUPERVISOR_REALTIME_PATH)) {
      return false;
    }
    const role = roleFromRequest(input, init) || currentRole();
    return role === 'operator';
  }

  function restrictedSupervisorResponse() {
    return new Response(
      JSON.stringify({
        agents: { total: 0, by_state: {}, items: [] },
        queues: [],
        timestamp: new Date().toISOString(),
        restricted: true,
      }),
      {
        status: 200,
        headers: {
          'Content-Type': 'application/json',
        },
      },
    );
  }

  const originalFetch = window.fetch.bind(window);
  window.fetch = function patchedFetch(input, init) {
    if (isRestrictedSupervisorRealtime(input, init)) {
      return Promise.resolve(restrictedSupervisorResponse());
    }
    return originalFetch(input, init);
  };
})();
