/**
 * Injects Provider Vault identity into pages this extension can see so the
 * RHA Wrapper app can detect install / version mismatch, and relays
 * folder-sync messages (localhost) to the background service worker.
 */
(() => {
  const version = chrome.runtime.getManifest().version;
  const extensionId = chrome.runtime.id;
  const payload = { version, extensionId, source: 'rha-provider-vault' };
  try {
    document.documentElement.dataset.rhaExt = JSON.stringify({ version, extensionId });
  } catch { /* document not ready */ }
  const post = () => {
    try { window.postMessage({ ...payload, type: 'rha-ext-meta' }, '*'); } catch { /* ignore */ }
  };
  post();
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', post, { once: true });
  }

  // Page → content script → background (localhost / same-tab bridge).
  window.addEventListener('message', (ev) => {
    const d = ev.data;
    if (!d || d.source !== 'rha-web' || d.type !== 'rha-deploy-req' || !d.id) return;
    chrome.runtime.sendMessage(d.payload, (response) => {
      const err = chrome.runtime.lastError;
      window.postMessage({
        type: 'rha-deploy-res',
        id: d.id,
        response: err ? { error: err.message } : response,
      }, '*');
    });
  });
})();
