// AutistMask content script — bridges between inpage (window.ethereum)
// and the background service worker via extension messaging.

const {
    hasBrowserNamespace,
    runtimeApi,
    sendMessage,
    storageGet,
    storageSet,
} = require("../shared/browserApi");

// In Chrome (MV3), inpage.js runs as a MAIN-world content script declared
// in the manifest, so no injection is needed here.  In Firefox (MV2), the
// "world" key is not supported, so we inject via a <script> tag.
if (hasBrowserNamespace()) {
    const script = document.createElement("script");
    script.src = runtimeApi().getURL("src/content/inpage.js");
    script.onload = function () {
        this.remove();
    };
    (document.head || document.documentElement).appendChild(script);
}

// Send the persisted EIP-6963 provider UUID to the inpage script.
// Generated once at install time and stored in extension storage.
(async function sendProviderUuid() {
    let uuid = null;
    try {
        const items = await storageGet("eip6963Uuid");
        uuid = items?.eip6963Uuid;
        if (!uuid) {
            uuid = crypto.randomUUID();
            await storageSet({ eip6963Uuid: uuid });
        }
    } catch {
        // Storage was unavailable or refused the write. The announcement
        // still has to go out — a provider that never announces is invisible
        // to every EIP-6963 dApp — so it goes under a fresh uuid that this
        // page load will not outlive.
        if (!uuid) uuid = crypto.randomUUID();
    }
    window.postMessage(
        { type: "AUTISTMASK_PROVIDER_UUID", uuid },
        location.origin,
    );
})();

// Relay requests from the page to the background script
window.addEventListener("message", (event) => {
    if (event.source !== window) return;
    if (event.data?.type !== "AUTISTMASK_REQUEST") return;
    const { id, method, params } = event.data;

    sendMessage({
        type: "AUTISTMASK_RPC",
        id,
        method,
        params,
        origin: location.origin,
    })
        .then((response) => {
            if (response) {
                window.postMessage(
                    { type: "AUTISTMASK_RESPONSE", id, ...response },
                    "*",
                );
            }
        })
        .catch(() => {
            // No receiver: the background context is gone. The page's promise
            // stays pending, which is what it did before this was a promise
            // at all; turning it into a rejection here is a change to what
            // dApps see and belongs to its own issue.
        });
});

// Listen for events pushed from the background (e.g. accountsChanged)
runtimeApi().onMessage.addListener((msg) => {
    if (msg.type === "AUTISTMASK_EVENT") {
        window.postMessage(
            {
                type: "AUTISTMASK_EVENT",
                eventName: msg.eventName,
                data: msg.data,
            },
            "*",
        );
    }
});
