document.addEventListener("DOMContentLoaded", () => {
    if (sessionStorage.getItem("window_id")) {
        sessionStorage.removeItem("window_id");
    }
    sessionStorage.setItem(
        "window_id",
        document.querySelector('meta[name="x-window-id"]')?.content,
    );
});

document.addEventListener("turbo:before-fetch-request", (event) => {
    const windowId = sessionStorage.getItem("window_id");
    if (windowId) {
        event.detail.fetchOptions.headers["X-Window-Id"] = windowId;
    }
});
const originalFetch = window.fetch;

window.fetch = async function (input, init = {}) {
    const windowId = sessionStorage.getItem("window_id");
    const headers = new Headers(init.headers || {});

    if (windowId) {
        headers.set('X-Window-Id', windowId);
    }

    const modifiedInit = {
        ...init,
        headers,
    };

    return originalFetch(input, modifiedInit);
};

document.addEventListener("turbo:before-visit", (event) => {
    sessionStorage.setItem('previousUrl', window.location.pathname);
});
