import "./js/lazyImage";
import "./js/Recaptcha";

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", () => {
    sessionStorage.setItem("previousUrl", window.location.pathname);
});

const focusCheckoutField = (event) => {
    const selector = event?.detail?.selector;

    if (!selector) {
        return;
    }

    const field = document.querySelector(selector);

    if (!field) {
        return;
    }

    const top = Math.max(
        field.getBoundingClientRect().top + window.scrollY - 120,
        0,
    );

    window.scrollTo({ top, behavior: "smooth" });

    window.setTimeout(() => {
        field.focus({ preventScroll: true });

        if (
            typeof field.select === "function"
            && (field.tagName === "INPUT" || field.tagName === "TEXTAREA")
        ) {
            field.select();
        }
    }, 250);
};

const submitCheckoutPayment = (event) => {
    const detail = event?.detail ?? {};

    if (detail.mode === "redirect" && detail.url) {
        window.location.assign(detail.url);
        return;
    }

    if (detail.mode !== "form" || !detail.action) {
        return;
    }

    const form = document.createElement("form");
    form.method = (detail.method || "POST").toUpperCase();
    form.action = detail.action;
    form.style.display = "none";
    form.acceptCharset = "UTF-8";

    const fields = detail.fields || {};

    Object.entries(fields).forEach(([name, value]) => {
        const input = document.createElement("input");
        input.type = "hidden";
        input.name = name;
        input.value = value == null ? "" : String(value);
        form.appendChild(input);
    });

    document.body.appendChild(form);
    form.submit();
};

const scrollToCartRules = () => {
    const cart = document.getElementById("cart");

    if (!cart) {
        return;
    }

    const scrollContainer = cart.querySelector("[data-cart-scroll-container]");

    if (!scrollContainer) {
        return;
    }

    scrollContainer.scrollTo({ top: 0, behavior: "smooth" });
};

window.addEventListener("checkout:focus-field", focusCheckoutField);
document.addEventListener("checkout:focus-field", focusCheckoutField);
window.addEventListener("checkout:submit-payment", submitCheckoutPayment);
document.addEventListener("checkout:submit-payment", submitCheckoutPayment);

if (!window.__cartRulesScrollHandlerRegistered) {
    window.__cartRulesScrollHandlerRegistered = true;

    window.addEventListener("cart:scroll-to-rules", scrollToCartRules);
    document.addEventListener("cart:scroll-to-rules", scrollToCartRules);
}

const dismissPaymentReturnAlerts = () => {
    const alerts = document.querySelectorAll("[data-payment-return-alert]");
    const container = document.querySelector("[data-payment-return-container]");

    alerts.forEach((alert) => {
        window.setTimeout(() => {
            alert.classList.add("opacity-0");

            window.setTimeout(() => {
                alert.remove();

                if (
                    container
                    && container.querySelectorAll("[data-payment-return-alert]").length === 0
                ) {
                    container.classList.add("opacity-0");

                    window.setTimeout(() => {
                        container.remove();
                    }, 300);
                }
            }, 300);
        }, 15000);
    });
};

document.addEventListener("turbo:load", dismissPaymentReturnAlerts);
document.addEventListener("DOMContentLoaded", dismissPaymentReturnAlerts);
