/* ═══════════════════════════════════════════════════════════════════════════
   WCAHT Wallet – Content Script
   ═══════════════════════════════════════════════════════════════════════════
   Bridge between injected page provider (inject.js) and background service
   worker. Injects inject.js into the page and relays messages.
*/

// ── Inject the provider script ──────────────────────────────────────────────
const script = document.createElement('script');
script.src = chrome.runtime.getURL('content/inject.js');
script.onload = () => script.remove();
(document.head || document.documentElement).appendChild(script);

// ── Relay: page → background ────────────────────────────────────────────────
window.addEventListener('message', async (event) => {
  if (event.source !== window) return;
  if (!event.data || event.data.source !== 'wcaht-dapp') return;

  const { id, method, params } = event.data;

  let bgMsg;
  switch (method) {
    case 'connect':
      bgMsg = { type: 'DAPP_CONNECT' };
      break;
    case 'disconnect':
      bgMsg = { type: 'DAPP_DISCONNECT' };
      break;
    case 'getBalance':
      bgMsg = { type: 'GET_BALANCE', address: params.address };
      break;
    case 'sendTransaction':
      bgMsg = { type: 'DAPP_SIGN_TX', to: params.to, amount: params.amount };
      break;
    case 'getNodeStatus':
      bgMsg = { type: 'GET_STATUS' };
      break;
    default:
      window.postMessage({ source: 'wcaht-extension', id, result: { error: 'Unknown method: ' + method } }, '*');
      return;
  }

  try {
    const result = await chrome.runtime.sendMessage(bgMsg);
    window.postMessage({ source: 'wcaht-extension', id, result }, '*');
  } catch (e) {
    window.postMessage({ source: 'wcaht-extension', id, result: { error: e.message } }, '*');
  }
});
