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

// 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 (typeof browser !== "undefined") {
    const script = document.createElement("script");
    script.src = browser.runtime.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 chrome.storage.local.
(function sendProviderUuid() {
    const storage =
        typeof browser !== "undefined"
            ? browser.storage.local
            : chrome.storage.local;
    storage.get("eip6963Uuid", (items) => {
        let uuid = items?.eip6963Uuid;
        if (!uuid) {
            uuid = crypto.randomUUID();
            storage.set({ eip6963Uuid: uuid });
        }
        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;

    const runtime =
        typeof browser !== "undefined" ? browser.runtime : chrome.runtime;

    runtime.sendMessage(
        { type: "AUTISTMASK_RPC", id, method, params, origin: location.origin },
        (response) => {
            if (response) {
                window.postMessage(
                    { type: "AUTISTMASK_RESPONSE", id, ...response },
                    "*",
                );
            }
        },
    );
});

// Listen for events pushed from the background (e.g. accountsChanged)
const runtime =
    typeof browser !== "undefined" ? browser.runtime : chrome.runtime;

runtime.onMessage.addListener((msg) => {
    if (msg.type === "AUTISTMASK_EVENT") {
        window.postMessage(
            {
                type: "AUTISTMASK_EVENT",
                eventName: msg.eventName,
                data: msg.data,
            },
            "*",
        );
    }
});
