var HataDurum = false;
var logs = ['Loglar'];
var log = '';
var isRefreshed = false;
var SekmeKapatildi = false;
var PcName = '';
var AmazonUrl = '';
var AbeUrl = '';
var UrunID = '';
var MagazaAdi = '';
var kayitEdilsinDurumu = true; // Varsayılan olarak aktif

// Listen for messages from background script
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.Link) {
        window.location.reload();
        setTimeout(function () {
            window.location.reload();
        }, 1000);
    }
    if (message.UygulamaBaslatildi) {
        SekmeBilgileriGonder();
    }
    if (message.PageReload) {
        window.location.reload();
        setTimeout(function () {
            window.location.reload();
        }, 1000);
    }
    if (message.SekmeBulunamadi) {
        var text = "Extension'un çalıştığı sekme açık sekmeler arasında bulunamadı!";
        HataKontrolYap(1, text);
        console.log('Hata var:' + text);
    }
    if (message.action === 'setKayitDurumu') {
        kayitEdilsinDurumu = message.kayitEdilsin;
        console.log('Kayıt durumu güncellendi: ' + kayitEdilsinDurumu);
        sendResponse({status: "Kayıt durumu başarıyla güncellendi"});
    }
    return true;
});

var linkKontrolCount = 0;
var urunKontrolCount = 0;

// Listen for storage changes
chrome.storage.onChanged.addListener(function (changes, namespace) {
    var storageChange;

    for (key in changes) {
        if (key == 'KontrolUrl1' || key == 'KontrolUrl2') {
            storageChange = changes[key];
            if (storageChange.newValue.length > 0) {
                linkKontrolCount++;
                if (linkKontrolCount == 2) {
                    setTimeout(function () {
                        SiparisTamamla();
                    }, 2000);
                }
            }
        } else if (key == 'AmzUrunList' || key == 'AbeUrunList') {
            storageChange = changes[key];
            if (storageChange.newValue != undefined && storageChange.newValue != null) {
                urunKontrolCount++;
                if (urunKontrolCount == 2) {
                    setTimeout(function () {
                        console.log('UrunListeleriniGonder(); onchanged çağrıldı');
                        UrunListeleriniGonder();
                    }, 2000);
                }
            }
        }
    }
});

// Main execution when document is ready
$(document).ready(function () {
    var host = window.location.host;
    var href = window.location.href;
    chrome.storage.sync.get(
        [
            'isStarted',
            'UrunGetirildi',
            'Durum',
            'KontrolUrl1',
            'KontrolUrl1Hata',
            'KontrolUrl2Hata',
            'KontrolUrl2',
            'UrunFiyat',
            'AmzPageCount',
            'AbePageCount',
            'AmazonUrl',
            'AbeUrl',
            'UrunFiyat',
            'MagazaAdi',
            'RequestTime',
        ],
        function (item) {
            setTimeout(async function () {
                if (item.isStarted == true) {
                    MagazaAdi = item.MagazaAdi;
                    AmazonUrl = item.AmazonUrl;
                    console.log(item.Durum);
                    AbeUrl = item.AbeUrl;
                    var urll = window.location.href;
                    
                    if (urll == 'https://www.amazon.com/gp/errors/404.html') {
                        UrunZararYaz();
                    }
                    if (href == 'https://sellercentral.amazon.com/home') {
                        if (item.UrunGetirildi == false) {
                            UrunGetir();
                            SekmeBilgileriGonder();
                        } else {
                            console.log('düşün');
                        }
                    } else {
                        console.log(item.Durum + 'TypeKontrol');
                        if (item.Durum == 'TypeKontrol') {
                            console.log('TypeKontrol');
                            BirinciLinkKontrol();
                        } else if (item.Durum == 'FiyatKontrol') {
                            var Fiyat = item.UrunFiyat;
                            var AmzPageCount = 0;
                            var AbePageCount = 0;
                            AmazonUrl = item.AmazonUrl;
                            AbeUrl = item.AbeUrl;
                            var FiyatKontrolSayfasi = QueryStringOku('PgNm');
                            if (FiyatKontrolSayfasi != null && FiyatKontrolSayfasi.length > 0) {
                                setTimeout(function () {
                                    var FiyatKontrolYap =
                                        FiyatKontrolSayfasi == 'Abe'
                                            ? AbeFiyatKontrol(Fiyat, AbePageCount, AbeUrl)
                                            : AmazonFiyatKontrol(Fiyat, AmzPageCount, AmazonUrl);
                                    console.log('FiyatKontrolYap');
                                }, 500);
                            }
                        } else if (item.Durum == 'UrunAl') {
                            AmazonUrl = item.AmazonUrl;
                            AbeUrl = item.AbeUrl;
                            var UrunSatinAlmaSayfasi = QueryStringOku('PgNm');
                            var UrunSepetSayfasi = QueryStringOku('Basket');
                            var AddAdres = QueryStringOku('AddAdres');
                            var AmzSepetBosalt = QueryStringOku('Sil');
                            var AbeBilling = QueryStringOku('Billing');
                            var isAbePlaceOrder = QueryStringOku('Complete');
                            
                            if (UrunSatinAlmaSayfasi != null && UrunSatinAlmaSayfasi.length > 0) {
                                if (UrunSepetSayfasi != null && UrunSepetSayfasi.length > 0) {
                                    setTimeout(function () {
                                        var HangiSayfa =
                                            UrunSatinAlmaSayfasi == 'Abe' ? AbeBasketPage() : AmzBasketPage();
                                    }, 500);
                                } else if (AddAdres != null && AddAdres.length > 0) {
                                    setTimeout(function () {
                                        var HangiSayfa =
                                            UrunSatinAlmaSayfasi == 'Abe' ? AbeAdresSilme() : 'AmzAdresEkle()';
                                    }, 500);
                                } else if (AmzSepetBosalt != null && AmzSepetBosalt.length > 0) {
                                    setTimeout(function () {
                                        AmzBasketBosalt();
                                    }, 500);
                                } else if (AbeBilling != null && AbeBilling != 'false' && AbeBilling.length > 0) {
                                    setTimeout(function () {
                                        AbeEditBilling();
                                    }, 500);
                                } else if (isAbePlaceOrder != null && isAbePlaceOrder.length > 0) {
                                    setTimeout(function () {
                                        AbeOrderComplete();
                                    }, 500);
                                } else {
                                    setTimeout(function () {
                                        var HangiSayfa =
                                            UrunSatinAlmaSayfasi == 'Abe'
                                                ? AbeUrunAl(item.UrunFiyat)
                                                : AmzUrunAl(item.UrunFiyat);
                                    }, 500);
                                }
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/ShoppingBasket') {
                                AbeBasketBosalt();
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/PaymentDetail?ac=f') {
                                AbeSaveBilling();
                            } else if (
                                window.location.href == 'https://www.abebooks.com/servlet/OrderSummary' &&
                                document.referrer == 'https://www.abebooks.com/servlet/PaymentDetail?ac=f'
                            ) {
                                AbeOrderComplete();
                            } else if (window.location.href == 'https://www.abebooks.com/servlet/ShippingAddress') {
                                var textMessage = $('.errorMessage').text();
                                if (textMessage.length > 0) {
                                    HataKontrolYap(1, textMessage.trim());
                                    console.log('Hata var:' + textMessage.trim());
                                    UrunZararYaz();
                                } else {
                                    chrome.storage.sync.get(['AdresEklendi'], function (item) {
                                        console.log(item.AdresEklendi);
                                        if (!item.AdresEklendi) {
                                            var url =
                                                'https://www.abebooks.com/servlet/ShippingAddress?AddAdres=true&PgNm=Abe';
                                            SayfaGit(url, 1);
                                        } else {
                                            var link =
                                                'https://www.abebooks.com/servlet/OrderSummary?Billing=false&PgNm=Abe&Complete=true';
                                            SayfaGit(link, 1);
                                            console.log('Adres Eklendi && Sayfa Yenilendi');
                                        }
                                    });
                                }
                            } else if (window.location.pathname == '/gp/huc/view.html') {
                                var SepetCount = $('#nav-cart-count').text();
                                if (SepetCount != undefined && SepetCount.length > 0) {
                                    if (parseInt(SepetCount) > 1) {
                                        var amzlink = 'https://www.amazon.com/gp/cart/view.html?';
                                        var params = 'PgNm=Amz&Sil=True';
                                        var link = amzlink + params;
                                        SayfaGit(link, 1);
                                    } else if (parseInt(SepetCount) == 1) {
                                        console.log('Sepetteki ürün 0');
                                        var amzlink = 'https://www.amazon.com/gp/cart/view.html?';
                                        var params = 'PgNm=Amz&Basket=True';
                                        var link = amzlink + params;
                                        SayfaGit(link, 1);
                                    }
                                }
                            } else if (window.location.pathname == '/gp/buy/addressselect/handlers/display.html') {
                                if ($('.address-book-title').length > 0) {
                                    location.reload();
                                }
                                AmzAdresEkle();
                            } else if (window.location.pathname == '/gp/yourstore') {
                                var SepetKargoAdres =
                                    'https://www.amazon.com/gp/buy/addressselect/handlers/display.html';
                                console.log('yourstore');
                            } else {
                                var path = window.location.pathname.toString();
                                var NotAdded = 'item-dispatch';
                                var NotAddedDurum = path.indexOf(NotAdded) !== -1;
                                if (NotAddedDurum) {
                                    AmzItemNotAdded();
                                } else {
                                    var pass =
                                        $('.auth-text-truncate:first-child').text().trim().toLowerCase() + '478965';
                                    $('#ap_password').val(pass);
                                    if ($('#signInSubmit').length > 0) {
                                        $('#signInSubmit').click();
                                        $('#signInSubmit').trigger('click');
                                    } else UrunAl(1);
                                    console.log('hiç biri');
                                }
                            }
                        } else if (item.Durum == 'SiparisTamamla') {
                            var Sayfa = QueryStringOku('PgNm');
                            var SiparisTamamla = QueryStringOku('SiparisTamamla');
                            if (Sayfa != null && Sayfa.length > 0) {
                                if (SiparisTamamla != null && SiparisTamamla.length > 0) {
                                    setTimeout(function () {
                                        var HangiSayfa = Sayfa == 'Abe' ? AbeSiparisTamamla() : 'AmzSiparisTamamla()';
                                    }, 500);
                                }
                            } else if (window.location.pathname == '/servlet/ThankYou') {
                                if ($('.mfa-failure').length > 0) {
                                    chrome.storage.sync.set(
                                        {
                                            Durum: 'UrunAl',
                                            AdresEklendi: true,
                                        },
                                        function () {
                                            console.log('Siparişler alınacak. ');
                                            UrunAl(0);
                                        }
                                    );
                                } else {
                                    AbeSiparisTamamla();
                                }
                            } else if (window.location.pathname == '/gp/buy/thankyou/handlers/display.html')
                                AmzSiparisTamamla();
                        }
                    }
                }
            }, parseInt(item.RequestTime) * 1000);
        }
    );
});

// Creates a dialog modal with a message
function dialogModal(message, background = 'limegreen') {
    let loader = document.createElement('div');
    $(loader).addClass('extDialog');
    $(loader).css('position', 'fixed');
    $(loader).css('min-height', '200px');
    $(loader).css('height', 'auto');
    $(loader).css('width', '200px');
    $(loader).css('background', background);
    $(loader).css('color', '#fff');
    $(loader).css('overflow-wrap', 'anywhere');
    $(loader).css('border-radius', '50%');
    $(loader).css('font-weight', 'bold');
    $(loader).css('bottom', '10px');
    $(loader).css('right', '0');
    $(loader).css('z-index', '9999');
    $(loader).css('display', 'flex');
    $(loader).css('justify-content', 'center');
    $(loader).css('align-items', 'center');

    $(loader).html(message);
    document.body.append(loader);
    return loader;
}

// Completes the order process
function SiparisTamamla(dataArray, lastShipmentId, createdDate, lastUpdatedDate) {
    if (!kayitEdilsinDurumu) {
        console.log('Siparişler kaydedilmiyor - ayarlarda devre dışı bırakıldı');
        $('.extDialog').remove();
        dialogModal('Sipariş kaydedilmedi (Ayarlarda devre dışı). Yeni siparişe geçiliyor.');
        return;
    }
    
    chrome.storage.sync.get(['MagazaAdi', 'UrunID', 'tracking', 'kargoFirma', 'ApiUrl'], function (item) {
        var datam = {
            magazaDeger: item.MagazaAdi,
            ShipmentLogArray: dataArray,
            lastShipmentId: lastShipmentId,
            createdDate: createdDate,
            lastUpdatedDate: lastUpdatedDate,
            tip: 'newShipmentLogEnd',
        };
        
        console.log(datam);
        $.ajax({
            type: 'post',
            url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            },
            cache: false,
            dataType: 'json',
            data: datam,
            success: function (cevap) {
                console.log(cevap);
                if (cevap.hata == '0') {
                    console.log('Hata: ShipmentLog Bilgileri Gönderilemedi!');
                } else {
                    if (cevap.result) {
                        console.log(cevap.result);
                        console.log('ShipmentLog bilgileri gönderildi');
                        setTimeout(function () {
                            SekmeKapat(1);
                            chrome.storage.local.set({ isStarted: false }, function () {
                                chrome.storage.sync.remove(['isStarted'], function () {});
                            });
                        }, 2000);
                    } else {
                        console.log('else girdi');
                    }
                }
            },
            error: function (req, textStatus, errorThrown) {
                console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown);
            },
        });
    });
}

// Gets product information
function UrunGetir() {
    chrome.storage.sync.set({
        KontrolUrl1: '',
        KontrolUrl2: '',
        Titles: '',
        tracking: '',
        kargoFirma: '',
    });
    
    var host = window.location.host;
    setTimeout(function () {
        chrome.storage.sync.get(['MagazaAdi', 'PcName', 'ApiUrl'], function (item) {
            clearTimeout(HataKontrol);
            console.log('Ürün Getirilecek!');
            localStorage.clear();
            localStorage.removeItem('LSAmazonUrunList');
            
            var datam = {
                magazaDeger: item.MagazaAdi,
                pcAd: item.PcName,
                tip: 'newShipmentLogStart',
            };
            
            console.log(datam);
            console.log('Ürün getirilecek!');
            $.ajax({
                type: 'post',
                url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                },
                cache: false,
                dataType: 'json',
                data: datam,
                timeout: 5000,
                success: function (cevap) {
                    console.log(cevap);
                    if (cevap) {
                        if (cevap.hata) {
                            chrome.storage.local.set({ isStarted: false }, function () {
                                chrome.storage.sync.remove(['isStarted'], function () {});
                            });
                        }

                        if (Array.isArray(cevap.result)) {
                            chrome.storage.sync.set(
                                {
                                    ShipID: cevap.result[0].ShipmentId,
                                    createdDate: cevap.result[0].ShipmentCreatedDate,
                                    lastUpdatedDate: cevap.result[0].ShipmentLastUpdateDate,
                                    ShipDate: cevap.result[0].ShipDate,
                                    UrunGetirildi: true,
                                    Durum: 'TypeKontrol',
                                    KontrolUrl1: '',
                                    KontrolUrl2: '',
                                },
                                function () {
                                    linkKontrolCount = 0;
                                    urunKontrolCount = 0;
                                    SekmeAc('https://sellercentral.amazon.com/gp/ssof/shipping-queue.html');
                                    console.log('Sekmeler Açılacak!');
                                    if (host == 'sellercentral.amazon.com' || host == 'www.abebooks.com') {
                                        SekmeKapat(2);
                                    }
                                }
                            );
                        } else {
                            chrome.storage.local.set({ isStarted: false }, function () {
                                chrome.storage.sync.remove(['isStarted'], function () {});
                            });
                        }
                    }
                },
                error: function (req, textStatus, errorThrown) {
                    console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown);
                    UrunGetir();
                },
            });
        });
    }, 2000);
}

// API request utility functions
const MAX_RETRY_COUNT = 3;
let retryCount = 0;

const getInfoTab = async (shipID) => {
    let totalCostEstimate = undefined;
    try {
        const response = await axios.get(
            'https://sellercentral.amazon.com/fba/inbound-shipment/summary/shipment-info/' + shipID,
            {
                withCredentials: true,
            }
        );

        if (response.data && response.data.carrierShipmentInfo && response.data.carrierShipmentInfo.totalCostEstimate) {
            totalCostEstimate = response.data.carrierShipmentInfo.totalCostEstimate.amount ?? undefined;
        }
    } catch (error) {
        console.error('Hata oluştu:', error.message);
        retryCount++;
    }

    return totalCostEstimate;
};

let retryCount2 = 0;
const getItems = async (shipID) => {
    let discrepancies = null;

    try {
        const response = await axios.get(
            'https://sellercentral.amazon.com/fba/wmsr/eligibilities/' +
                shipID +
                '?withInquiry=true&withDiscrepancies=true',
            {
                withCredentials: true,
            }
        );

        discrepancies = response.data.discrepancies;
    } catch (error) {
        console.error('Hata oluştu:', error.message);
        retryCount2++;
    }

    return discrepancies;
};

let retryCount3 = 0;
const getItemTracking = async (shipID) => {
    let trackingId = null;

    try {
        const response = await axios.get(
            'https://sellercentral.amazon.com/fba/inbound/arest/addressbook/tracking/' +
                shipID +
                '/summary?pageSize=20&lastEntry=0',
            {
                withCredentials: true,
            }
        );

        trackingId = response.data.trackingItemsPage.trackingItems[0].trackingId;
    } catch (error) {
        console.error('Hata oluştu:', error.message);
        retryCount3++;
    }

    return trackingId;
};

let shipingData = [];
async function BirinciLinkKontrol() {
    chrome.storage.sync.get(['ShipID', 'createdDate', 'lastUpdatedDate'], async function (item) {
        let loader = dialogModal(`Loading...`);
        
        let url = `https://sellercentral.amazon.com/fba/shippingqueue/api/v1/shipment/listShipments?pageSize=250&&&orderBy=SHIPMENT_CREATE_DATE&isOrderAscending=false&&t2pLaunched=true`;

        // if (item.ShipID != '0' && item.ShipID != undefined) {
        //     url = `https://sellercentral.amazon.com/fba/shippingqueue/api/v1/shipment/listShipments?pageSize=250&&&orderBy=SHIPMENT_CREATE_DATE&isOrderAscending=false&&t2pLaunched=true&lastShipmentId=${item.ShipID}&createdDate=${item.createdDate}&lastUpdatedDate=${item.lastUpdatedDate}`;
        //     console.log(url);
        // }
        
        let total = 0;
        await axios
            .get(
                url,
                {},
                {
                    headers: {
                        cookie: document.cookie,
                    },
                }
            )
            .then((response) => {
                let responseData = response.data;
                console.log(responseData);
                let promises = Promise.all(
                    responseData.map(async (element) => {
                        let shipId = element.shipmentId;
                        console.log('1', shipId);
                        let _amount = await getInfoTab(shipId);
                        console.log('2', _amount);
                        let _discrepancies = await getItems(shipId);
                        console.log('3', _discrepancies);
                        let _trackingId = await getItemTracking(shipId);
                        console.log('4', 'aşama');
                        console.log(_discrepancies);
                        
                        let items = [];
                        if (_discrepancies && _discrepancies !== undefined && _discrepancies.items) {
                            await _discrepancies.items.forEach((item) => {
                                let data = {};
                                data.shipDate = element.createdDate;
                                data.status = element.shipmentStatus;
                                data.shipID = shipId;
                                data.asin = item.asin;
                                data.itemCondition = item.itemCondition;
                                data.quantity = item.expectedQuantity;
                                data.merchantSKU = item.merchantSKU;
                                data.trackNumber = _trackingId;
                                data.shipping = _amount / _discrepancies.totalRecords;
                                if (data.asin) {
                                    items.push(data);
                                }
                            });
                        }
                        
                        if (!isNaN(_amount)) total += _amount;
                        console.log(items);
                        return items;
                    })
                );

                promises
                    .then((values) => {
                        values = values.filter((v) => {
                            if (v.length > 0) {
                                return v;
                            }
                        });
                        
                        if (responseData.length >= 250) {
                            lastShipID = responseData[248].shipmentId;
                            lastUpdatedDate = responseData[248].lastUpdatedDate;
                            createdDate = responseData[248].createdDate;
                        } else {
                            lastShipID = '';
                            lastUpdatedDate = '';
                            createdDate = '';
                        }
                        
                        console.log('Result:', values.flat(), 'Total:' + total);
                        SiparisTamamla(values.flat(), lastShipID, createdDate, lastUpdatedDate);
                    })
                    .catch((e) => {
                        console.log(e);
                    });
            });
    });
}

// Utility functions
function QueryStringOku(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function SekmeKapat(sure) {
    setTimeout(function () {
        chrome.runtime.sendMessage({
            SekmeKapat: true,
        });
    }, sure * 1000);
}

function SekmeBilgileriGonder() {
    chrome.runtime.sendMessage({
        AktifSekmeBilgileri: true,
    });
}

function waitForElement(elementPath, callBack) {
    window.setTimeout(function () {
        if ($(elementPath).text().length > 0) {
            callBack(elementPath, $(elementPath));
        } else {
            waitForElement(elementPath, callBack);
        }
    }, 100);
}

function AppLogGonder() {
    chrome.runtime.sendMessage({
        HataDurum: HataDurum,
        AppLog: logs,
    });
}

function AppLog(log) {
    var time = new Date().toLocaleString();
    var test = log + ' - ' + time;
    var loglar = logs;
    if (loglar.length < 6) {
        loglar.push(test);
    } else {
        loglar.splice(0, 1);
        loglar.push(test);
    }
    logs = loglar;
    localStorage.setItem('LocalStorageAppLog', JSON.stringify(logs));
    chrome.storage.sync.set(
        {
            AppLog: test,
        },
        function () {}
    );
}

function SayfaGit(adres, time) {
    setTimeout(function () {
        window.location.href = adres;
    }, parseInt(time) * 1000);
}

var HataKontrol;
function HataKontrolYap(time, msj2) {
    HataKontrol = setTimeout(function () {
        chrome.storage.sync.get(
            ['isStarted', 'PcName', 'UygulamaAdi', 'Durum', 'UrunID', 'MagazaAdi'],
            function (item) {
                var aciklama = msj2 ? msj2 : '';
                var msj = `Bilgisayar: ${item.PcName} Mağaza Adı: ${item.MagazaAdi}  Durum: ${item.Durum} iken extension çalışmayı durdurdu! ${aciklama}`;
                var datam = {
                    ID: item.UrunID,
                    tip: 'newOrderBreak',
                    mesaj: msj,
                };
                console.log(msj);

                $.ajax({
                    type: 'post',
                    url: 'https://www.andromedaworkspace.com/Extension/ajaxCall',
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                    },
                    cache: false,
                    dataType: 'json',
                    data: datam,
                    success: function (cevap) {
                        if (cevap.hata == 0) {
                            console.log('Hata: Hata Bilgisi Gönderilemedi!');
                        } else {
                            if (cevap.result) {
                                console.log(cevap.result);
                            }
                        }
                        console.log('Hata Bilgisi Gönder Response!');
                    },
                    error: function (req, textStatus, errorThrown) {
                        console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown);
                    },
                });
            }
        );
    }, parseInt(time) * 1000);
}

function SekmeAc(link) {
    setTimeout(function () {
        console.log('Sekme Açılıyor: ' + link);
        chrome.runtime.sendMessage({
            YeniSekme: true,
            Url: link,
        });
    }, 1000);
}
