(() => {
  const GUARDED = new Set([
    "eth_requestAccounts", "wallet_requestPermissions", "wallet_switchEthereumChain", "wallet_addEthereumChain",
    "eth_sendTransaction", "eth_signTransaction", "personal_sign", "eth_sign",
    "eth_signTypedData", "eth_signTypedData_v3", "eth_signTypedData_v4", "wallet_sendCalls"
  ]);
  const wrapped = new WeakSet();
  let sequence = 0;

  const askVeerSec = async (provider, method, params) => {
    let chainId = null;
    try {
      chainId = method === "eth_chainId" ? null : await provider.request({ method: "eth_chainId", params: [] });
    } catch {
      chainId = null;
    }
    const requestId = `veersec-${Date.now()}-${++sequence}`;
    const response = new Promise((resolve) => {
      const timeout = setTimeout(() => {
        window.removeEventListener("veersec:analysis-response", handler);
        resolve({ allow: window.confirm("VeerSec could not refresh trust evidence. Continue with this wallet request?") });
      }, 10000);
      const handler = (event) => {
        if (event.detail?.requestId !== requestId) return;
        clearTimeout(timeout);
        window.removeEventListener("veersec:analysis-response", handler);
        resolve(event.detail);
      };
      window.addEventListener("veersec:analysis-response", handler);
    });
    window.dispatchEvent(new CustomEvent("veersec:analyze-request", {
      detail: { requestId, method, params, chainId, origin: location.origin }
    }));
    return response;
  };

  const wrap = (provider) => {
    if (!provider || wrapped.has(provider) || typeof provider.request !== "function") return provider;
    const original = provider.request;
    provider.request = async function veersecGuardedRequest(args) {
      const method = String(args?.method || "");
      if (!GUARDED.has(method)) return original.call(this, args);
      const analysis = await askVeerSec(this, method, Array.isArray(args?.params) ? args.params : []);
      if (!analysis?.allow) {
        const error = new Error("VeerSec blocked or the user cancelled this wallet request.");
        error.code = 4001;
        throw error;
      }
      return original.call(this, args);
    };
    wrapped.add(provider);
    return provider;
  };

  const announceVeerSecProvider = () => {
    const info = {
      uuid: "7e91197e-01a2-44f4-a0e0-b07f1da3eb14",
      name: "VeerSec Protected Provider",
      icon: "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='48' height='48'><path fill='%2306b6d4' d='M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z'/></svg>",
      rdns: "com.veersec.protected"
    };

    const protectedProvider = {
      request: async (args) => {
        const underlying = window.ethereum;
        const method = String(args?.method || "");
        if (!GUARDED.has(method)) {
          return underlying ? underlying.request(args) : Promise.reject(new Error("No underlying provider connected."));
        }

        const analysis = await askVeerSec(underlying || protectedProvider, method, Array.isArray(args?.params) ? args.params : []);
        if (!analysis?.allow) {
          const error = new Error("VeerSec blocked or the user cancelled this wallet request.");
          error.code = 4001;
          throw error;
        }

        return underlying ? underlying.request(args) : Promise.reject(new Error("No underlying provider connected."));
      },
      on: (event, handler) => {
        if (window.ethereum && typeof window.ethereum.on === "function") {
          window.ethereum.on(event, handler);
        }
      },
      removeListener: (event, handler) => {
        if (window.ethereum && typeof window.ethereum.removeListener === "function") {
          window.ethereum.removeListener(event, handler);
        }
      }
    };

    window.dispatchEvent(new CustomEvent("eip6963:announceProvider", {
      detail: { info, provider: protectedProvider }
    }));
  };

  const wrapCurrentProvider = () => {
    try { wrap(window.ethereum); } catch { /* Provider may expose a non-writable request property. */ }
    try { (window.ethereum?.providers || []).forEach(wrap); } catch { /* Multi-provider list is optional. */ }
  };

  window.addEventListener("eip6963:announceProvider", (event) => {
    if (event.detail?.info?.rdns !== "com.veersec.protected") {
      wrap(event.detail?.provider);
    }
  });

  window.addEventListener("eip6963:requestProvider", () => {
    announceVeerSecProvider();
  });

  wrapCurrentProvider();
  window.addEventListener("DOMContentLoaded", wrapCurrentProvider, { once: true });
  window.dispatchEvent(new Event("eip6963:requestProvider"));
  announceVeerSecProvider();
})();
