(() => {
  const REQUEST_TYPE = 'MAZEXCHAIN_PROVIDER_REQUEST';
  const RESPONSE_TYPE = 'MAZEXCHAIN_PROVIDER_RESPONSE';

  function injectProvider() {
    const script = document.createElement('script');
    script.src = chrome.runtime.getURL('inpage.js');
    script.onload = () => script.remove();
    (document.documentElement || document.head).appendChild(script);
  }

  window.addEventListener('message', (event) => {
    if (event.source !== window) return;
    const message = event.data;
    if (!message || message.type !== REQUEST_TYPE || !message.id) return;

    chrome.runtime.sendMessage(
      {
        type: 'MAZEXCHAIN_WALLET_RPC',
        id: message.id,
        method: message.method,
        params: message.params || {},
      },
      (response) => {
        if (chrome.runtime.lastError) {
          window.postMessage(
            {
              type: RESPONSE_TYPE,
              id: message.id,
              ok: false,
              error: {
                code: 'EXTENSION_RUNTIME_ERROR',
                message: chrome.runtime.lastError.message,
              },
            },
            window.location.origin,
          );
          return;
        }
        window.postMessage(
          {
            type: RESPONSE_TYPE,
            id: message.id,
            ok: Boolean(response?.ok),
            result: response?.result,
            error: response?.error,
          },
          window.location.origin,
        );
      },
    );
  });

  injectProvider();
})();
