const shippingMethods = {
    toNPDepartment: {
        id: "65da6a84af3fb0fbf3f54124",
        name: "Доставка до нової пошти",
        class: ".np-postal_office",
        fields: ["apx-ecom-email", "apx-ecom-phone", "apx-ecom-surname", "apx-ecom-name", "apx-np-postal-office-city", "apx-np-postal-office-pickup-point"]
    },
    toNPAddress: {
        id: "65dc4c0ba59763361539cd3e",
        name: "Доставка до адреси",
        class: ".np-address_delivery",
        fields: ["apx-ecom-email", "apx-ecom-phone", "apx-ecom-surname", "apx-ecom-name", "apx-np-address-delivery-city", "apx-np-address-delivery-street", "apx-np-address-delivery-house", "apx-np-address-delivery-flat"]
    },
    pickup: {
        id: "671699fdbbd80ad39bf5c961",
        name: "Самовивіз",
        class: ".nothing",
        fields: ["apx-ecom-email", "apx-ecom-phone", "apx-ecom-surname", "apx-ecom-name"]
    },
};
let shippingMethod = localStorage.getItem('shippingMethod') || "toNPDepartment";

function updateShippingMethod(event) {
    if (event.target.name === "shipping-method-choice") {
        let selectedValue = event.target.value;
        for (const [key, value] of Object.entries(shippingMethods)) {
            document.querySelector(value.class).style.display = "none";
            if (value.id === selectedValue) {
                shippingMethod = key;
                document.querySelector(value.class).style.display = "block";
                localStorage.setItem('shippingMethod', shippingMethod);
                updateRequiredFields();
                attachFieldListeners();
            }
        }
    }
}
function setInitialShippingMethod() {
    const selectedShippingMethod = localStorage.getItem('shippingMethod') || "toNPDepartment";

    for (const [key, value] of Object.entries(shippingMethods)) {
        if (key === selectedShippingMethod) {
            document.querySelector(value.class).style.display = "block";
            document.querySelector(`input[name="shipping-method-choice"][value="${value.id}"]`).checked = true;
        } else {
            document.querySelector(value.class).style.display = "none";
        }
    }
}

let requiredFields = [];
const submitButton = document.getElementById("apx-submit_button");
function updateRequiredFields() {
    const method = shippingMethods[shippingMethod];
    requiredFields = method.fields.map((selector) =>
        document.querySelector('#'+selector)
    );
    checkRequiredFields();
}
function checkRequiredFields() {
    let allFilled = requiredFields.every((field) => field && field.value.trim());
    submitButton.disabled = !allFilled;
}
function attachFieldListeners() {
    requiredFields.forEach((field) => {
        if (field) {
            field.addEventListener("input", checkRequiredFields);
        }
    });
}

function collectShippingData() {
    const selectedMethod = shippingMethods[shippingMethod];
    const data = {};

    selectedMethod.fields.forEach((field) => {
        const inputElement = document.querySelector(`#"${field}`);
        if (inputElement) {
            data[field] = inputElement.value;
        }
    });

    return data;
}

function fetchCities(cityName, inputId, selectId) {
    fetch("https://api.topb.pp.ua/novapost/cities", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ cityName }),
    })
    .then((response) => response.json())
    .then((data) => {
        const cities = data.data || [];
        updateCityList(cities, inputId, selectId);
    })
    .catch((error) => {
        console.error("request error:", error);
    });
}
function updateCityList(cities, inputId, selectId) {
    const citySelectElement = document.getElementById(selectId);

    citySelectElement.innerHTML = "";

    const limitedCities = cities.slice(0, 3);

    limitedCities.forEach((city) => {
        const cityItem = document.createElement("div");
        cityItem.className = "apx-searchbox_list_item";

        const cityText = document.createElement("div");
        cityText.className = "apx-searchbox_list_item_text";
        cityText.textContent = city.SettlementTypeDescription + " " + city.Description + ", " + city.AreaDescription + " область";
        cityText.setAttribute("data-city-description", city.Description);

        cityItem.appendChild(cityText);
        citySelectElement.appendChild(cityItem);

        cityItem.addEventListener('click', function() {
            document.getElementById(inputId).value = city.SettlementTypeDescription + " " + city.Description + ", " + city.AreaDescription + " область";
            document.getElementById(inputId).setAttribute("data-city-description", city.Description);
            citySelectElement.innerHTML = '';
        });
    });

    if (limitedCities.length === 0) {
        const noResult = document.createElement("div");
        noResult.className = "apx-searchbox_list_item";
        noResult.style.color = "red";
        noResult.textContent = "Місто не знайдене";
        citySelectElement.appendChild(noResult);
    }
}
function setupCityInputListener(inputId, selectId) {
    document.getElementById(inputId).addEventListener("input", function () {
        let debounceTimer;
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(function () {
            const cityName = document.getElementById(inputId).value;
            if (cityName.length > 2) {
                fetchCities(cityName, inputId, selectId);
            } else {
                document.getElementById(selectId).innerHTML = '';
            }
        }, 500);
    });
}

function fetchWarehouses(warehouseName, cityName, inputId, selectId) {
    fetch("https://api.topb.pp.ua/novapost/warehouses", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ warehouseName, cityName }),
    })
    .then((response) => response.json())
    .then((data) => {
    const warehouses = data.data || [];
        updateWarehouseList(warehouses, inputId, selectId);
    })
    .catch((error) => {
        console.error("request error:", error);
    });
}
function updateWarehouseList(warehouses, inputId, selectId) {
    const warehouseSelectElement = document.getElementById(selectId);
  
    warehouseSelectElement.innerHTML = "";
  
    const limitedWarehouses = warehouses.slice(0, 3);
  
    limitedWarehouses.forEach((warehouse) => {
        const warehouseItem = document.createElement("div");
        warehouseItem.className = "apx-searchbox_list_item";
    
        const warehouseText = document.createElement("div");
        warehouseText.className = "apx-searchbox_list_item_text";
        warehouseText.textContent = warehouse.Description;

        const warehouseDescription = document.createElement("div");
        warehouseDescription.className = "apx-searchbox_list_item_description";
        warehouseDescription.textContent = warehouse.ShortAddress;
    
        warehouseItem.appendChild(warehouseText);
        warehouseItem.appendChild(warehouseDescription);
        warehouseSelectElement.appendChild(warehouseItem);
    
        warehouseItem.addEventListener('click', function() {
            document.getElementById(inputId).value = warehouse.Description;
            warehouseSelectElement.innerHTML = '';
      });
    });
  
    if (limitedWarehouses.length === 0) {
        const noResult = document.createElement("div");
        noResult.className = "apx-searchbox_list_item";
        noResult.style.color = "red";
        noResult.textContent = "Пункт отримання не знайдено";
        warehouseSelectElement.appendChild(noResult);
    }
}
function setupWarehouseInputListener(inputId, selectId, cityId) {
    document.getElementById(inputId).addEventListener("input", function () {
        let debounceTimer;
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(function () {
            const warehouseName = document.getElementById(inputId).value;
            const cityName = document.getElementById("apx-np-postal-office-city").getAttribute("data-city-description");
            if (warehouseName.length > 0) {
                fetchWarehouses(warehouseName, cityName, inputId, selectId);
            } else {
                document.getElementById(selectId).innerHTML = '';
            }
        }, 1000);
    });
}
// MARK: DOM loaded
document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("apx-np-postal-office-city-select").innerHTML = "";
    document.getElementById("apx-np-postal-office-pickup-point-select").innerHTML = "";

    setTimeout(function() {
        const fullNameInput = document.querySelector(".w-commerce-commercecheckoutshippingfullname");
        const countrySelector = document.querySelector(".w-commerce-commercecheckoutshippingcountryselector");

        if (fullNameInput && countrySelector) {
            fullNameInput.focus();
            fullNameInput.value = "Текст";
            fullNameInput.dispatchEvent(new Event('input', { bubbles: true }));
            fullNameInput.dispatchEvent(new Event('blur', { bubbles: true }));

            countrySelector.focus();
            countrySelector.value = "UA";
            countrySelector.dispatchEvent(new Event('input', { bubbles: true }));
            countrySelector.dispatchEvent(new Event('change', { bubbles: true }));
            countrySelector.dispatchEvent(new Event('blur', { bubbles: true }));
        } else {
            console.log("Элементы не найдены. Убедитесь, что они загружаются на странице.");
        }
    }, 1000);
    
    setTimeout(() => {
        if (document.querySelector("#apx-delivery-title") != null) {
            setInitialShippingMethod();
        } else {
            console.log("no shipping methods")
        }
    }, 5000);
    
    document.body.addEventListener("change", updateShippingMethod);
    updateRequiredFields();
    attachFieldListeners();
    checkRequiredFields();

    document.querySelectorAll('.apx-clear_icon').forEach(clearIcon => {
        clearIcon.addEventListener('click', function() {
            const inputBlock = this.closest('.apx-input_block');
            
            const inputField = inputBlock.querySelector('input[type="text"]');
            
            if (inputField) {
                inputField.value = '';
            }

            const citySelect = document.querySelector('#apx-np-postal-office-city-select');
            if (citySelect) {
                citySelect.innerHTML = '';
            }
            const warehouseSelect = document.querySelector('#apx-np-postal-office-pickup-point-select');
            if (warehouseSelect) {
                warehouseSelect.innerHTML = '';
            }
        });
    });

    setupCityInputListener("apx-np-postal-office-city", "apx-np-postal-office-city-select");
    setupWarehouseInputListener("apx-np-postal-office-pickup-point", "apx-np-postal-office-pickup-point-select", "apx-np-postal-office-city");
    
});
// MARK: button
document.getElementById("apx-submit_button").addEventListener("click", function () {
    if (document.getElementById("apx-submit_button").disabled) {
        const errorButton = document.getElementById("error-text");
        errorButton.style.color = "red";
        errorButton.innerHTML = "Введіть всі обов'язкові поля.";
        setTimeout(() => {
            errorButton.innerHTML = "";
        }, 5000);
        return;
    } 

    const emailInput = document.getElementById('apx-ecom-email');
    if (!emailInput.checkValidity()) {
        const errorButton = document.getElementById("error-text");
        errorButton.style.color = "red";
        errorButton.innerHTML = "Невірна електронна адреса.";
        setTimeout(() => {
            errorButton.innerHTML = "";
        }, 5000);
        return;
    }

    const isOnlinePayment = document.getElementById("payment-online").checked;
    const isOnReceiptPayment = document.getElementById("payment-on-receipt").checked;

    const secretKey = "6db8f124249a3341eb47a2fcd3f83af7a01a7648";
    const merchantAccount = "www_firanka_top";
    const merchantDomainName = "www.firanka.top";
    const orderReference = "ORDER-" + new Date().toISOString().replace(/[^\d]/g, "");
    const orderDate = Math.floor(new Date().getTime() / 1000);
    const currency = "UAH";

    const items = document.querySelectorAll(".w-commerce-commercecheckoutorderitem");

    let totalAmount = document.querySelector('#apx-total-amount-price').innerText;
    totalAmount = parseFloat(totalAmount.replace(/\D+/g, ""));

    let productNames = [];
    let productPrices = [];
    let productCounts = [];

    items.forEach((item) => {
        const productName = item.querySelector(".w-commerce-commercecheckoutorderitemdescriptionwrapper a").innerText.trim();
        const productCount = parseInt(item.querySelector('[data-wf-bindings*="count"]').innerText.trim());
        let productPrice = item.querySelector('[data-wf-bindings*="rowTotal"]').innerText;
        productPrice = parseFloat(productPrice.replace(/\D+/g, ""));

        productNames.push(productName);
        productPrices.push(productPrice);
        productCounts.push(productCount);
    });

    const selectedShippingMethod = shippingMethod;
    const shippingFields = shippingMethods[selectedShippingMethod].fields;
    const shippingData = {};

    shippingFields.forEach((field) => {
        const inputElement = document.querySelector(`#${field}`);
        if (inputElement) {
            shippingData[field] = inputElement.value;
        }
    });
    const customerFirstname = document.querySelector('#apx-ecom-name').value;
    const customerSurname = document.querySelector('#apx-ecom-surname').value;
    const customerNote = document.querySelector('#wf-ecom-notes').value;
    const customDontCallMe = document.querySelector('#wf-ecom-dontcall').value;
    let paymentType = "online";
    let status = "waiting";
    if (isOnReceiptPayment) {
        paymentType = "on-receipt";
        status = "confirmed";
    }

    const orderData = {
        source: "site",
        merchantAccount: merchantAccount,
        orderReference: orderReference,
        amount: totalAmount,
        currency: currency,
        products: productNames.map((name, index) => ({
            name: name,
            price: productPrices[index],
            count: productCounts[index],
        })),
        shippingMethod: shippingMethods[selectedShippingMethod].name,
        shippingData: shippingData,
        customerFirstname: customerFirstname,
        customerSurname: customerSurname,
        customerNote: customerNote,
        customDontCallMe: customDontCallMe,
        paymentType: paymentType,
        status: status
    };

    if (isOnReceiptPayment) {
        fetch("https://api.topb.pp.ua/wayforpay", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(orderData),
        })
        .then((response) => response.json())
        .then((data) => {
            console.log("Data successfully sent to API:", data);
        })
        .catch((error) => {
            console.error("Error sending data to API:", error);
        });
        window.location.href = "https://www.firanka.top/successful-payment";
        return;
    }

    fetch("https://api.topb.pp.ua/wayforpay", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(orderData),
    })
    .then((response) => response.json())
    .then((data) => {
        console.log("Data successfully sent to API:", data);
        sendToWayForPay(
            orderReference,
            orderDate,
            totalAmount,
            currency,
            productNames,
            productCounts,
            productPrices
        );
    })
    .catch((error) => {
        console.error("Error sending data to API:", error);
    });

    function sendToWayForPay(
        orderReference,
        orderDate,
        totalAmount,
        currency,
        productNames,
        productCounts,
        productPrices
    ) {
        const form = document.createElement("form");
        form.action = "https://secure.wayforpay.com/pay";
        form.method = "POST";
        form.style.display = "none";
        form.accept_charset = "UTF-8";

        const hiddenFields = {
            merchantAccount: merchantAccount,
            merchantAuthType: "SimpleSignature",
            merchantDomainName: merchantDomainName,
            orderReference: orderReference,
            orderDate: orderDate,
            currency: currency,
        };

        for (let key in hiddenFields) {
            let input = document.createElement("input");
            input.type = "hidden";
            input.name = key;
            input.value = hiddenFields[key];
            form.appendChild(input);
        }

        const signatureString = `${merchantAccount};${merchantDomainName};${orderReference};${orderDate};${totalAmount};${currency};${productNames.join(";")};${productCounts.join(";")};${productPrices.join(";")}`;
        const signature = CryptoJS.HmacMD5(signatureString, secretKey).toString();

        let amountInput = document.createElement("input");
        amountInput.type = "hidden";
        amountInput.name = "amount";
        amountInput.value = totalAmount;
        form.appendChild(amountInput);

        productNames.forEach((name, index) => {
            let productNameInput = document.createElement("input");
            productNameInput.type = "hidden";
            productNameInput.name = "productName[]";
            productNameInput.value = name;
            form.appendChild(productNameInput);
        
            let productCountInput = document.createElement("input");
            productCountInput.type = "hidden";
            productCountInput.name = "productCount[]";
            productCountInput.value = productCounts[index];
            form.appendChild(productCountInput);
        
            let productPriceInput = document.createElement("input");
            productPriceInput.type = "hidden";
            productPriceInput.name = "productPrice[]";
            productPriceInput.value = productPrices[index];
            form.appendChild(productPriceInput);
        });

        let returnUrlInput = document.createElement("input");
        returnUrlInput.type = "hidden";
        returnUrlInput.name = "returnUrl";
        returnUrlInput.value = `https://api.topb.pp.ua/wayforpay/redirect`;
        form.appendChild(returnUrlInput);

        let serviceUrlInput = document.createElement("input");
        serviceUrlInput.type = "hidden";
        serviceUrlInput.name = "serviceUrl";
        serviceUrlInput.value = `https://api.topb.pp.ua/wayforpay/receive`;
        form.appendChild(serviceUrlInput);

        let signatureInput = document.createElement("input");
        signatureInput.type = "hidden";
        signatureInput.name = "merchantSignature";
        signatureInput.value = signature;
        form.appendChild(signatureInput);

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