var PcName = ''
var AmazonUrl = ''
var MagazaAdi = ''
var AmzUrunList = [];
var zarar = 0
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)
    }
})
$(document).ready(function () {
    var host = window.location.host
    if (chrome?.storage?.sync) {
        chrome.storage.sync.get(
                [
                    'isStarted',
                    'UrunGetirildi',
                    'Durum',
                    'UrunFiyat',
                    'AmazonUrl',
                    'MagazaAdi',
                    'RequestTime',
                ],
                function (item) {
                    setTimeout(async function () {
                        if (item.isStarted === true) {
                            MagazaAdi = item.MagazaAdi
                            AmazonUrl = item.AmazonUrl
                            console.log(item.Durum)

                            // CAPTCHA kontrolü
                            if (isCaptchaPage()) {
                                console.log('CAPTCHA sayfası tespit edildi, geçiliyor...')
                                handleCaptchaPage()
                                return
                            }

                            var urll = window.location.href
                            if (item.Durum === 'FiyatKontrol' && urll == 'https://www.amazon.com/gp/cart/view.html?PgNm=Amz&Basket=True') {
                                chrome.storage.sync.set(
                                        {
                                            Durum: 'UrunAl',
                                        },
                                        function () {
                                            window.location.reload()
                                        }
                                )
                            }
                            if (item.Durum == 'AppStarted' && host === 'www.amazon.com') {
                                UrunGetir();
                            }
                            if (host === 'clinic.amazon.com' || host === 'health.amazon.com') {
                                UrunZararYaz()
                            }
                            if (host !== 'www.amazon.com') {
                                if (item.UrunGetirildi === false) {
                                    UrunGetir()
                                    SekmeBilgileriGonder()
                                } else if (item.Durum === 'FiyatKontrol') {
                                    if (host === 'www.jqueryscript.net') {
                                        UrunGetir()
                                    }
                                    console.log('Şuan yapılan işlem: ' + item.Durum)
                                } else {
                                    console.log('düşün')
                                    YanlisUrun()
                                }
                            } else {
                                if (item.Durum === 'FiyatKontrol') {
                                    HataKontrolYap(250)
                                    var Fiyat = parseFloat(item.UrunFiyat)
                                    var AmzPageCount = 0
                                    AmazonUrl = item.AmazonUrl
                                    function runFiyatKontrol() {
                                        AmazonFiyatKontrol(Fiyat, AmzPageCount, AmazonUrl)
                                        console.log('FiyatKontrolYap')
                                        if (isAmazonDogPage()) {
                                            UrunZararYaz()
                                        }
                                    }
                                    if (document.readyState === 'complete') {
                                        setTimeout(runFiyatKontrol, 2000)
                                    } else {
                                        window.addEventListener('load', function () {
                                            setTimeout(runFiyatKontrol, 2000)
                                        })
                                    }
                                } else if (item.Durum === 'UrunAl') {
                                    AmazonUrl = item.AmazonUrl
                                    var UrunSatinAlmaSayfasi = QueryStringOku('PgNm')
                                    var UrunSepetSayfasi = QueryStringOku('Basket')
                                    var AmzSepetBosalt = QueryStringOku('Sil')
                                    if (UrunSatinAlmaSayfasi != null && UrunSatinAlmaSayfasi.length > 0) {
                                        if (UrunSepetSayfasi != null && UrunSepetSayfasi.length > 0) {
                                            setTimeout(function () {
                                                AmzBasketPage()
                                            }, 500)
                                        } else if (AmzSepetBosalt != null && AmzSepetBosalt.length > 0) {
                                            setTimeout(function () {
                                                AmzBasketBosalt()
                                            }, 500)
                                        } else {
                                            if (document.querySelector('#submitOrderButtonId > span > input')) {
                                                AmzOrderComplete()
                                            } else {
                                                setTimeout(function () {
                                                    AmzUrunAl(item.UrunFiyat)
                                                }, 500)
                                            }
                                        }
                                    } else if (
                                            window.location.pathname === '/gp/huc/view.html' ||
                                            window.location.pathname.indexOf('/gp/cart/view.html') >= 0
                                            ) {
                                        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 {
                                                UrunZararYaz()
                                            }
                                        } else {
                                            UrunZararYaz()
                                        }
                                    } else if (window.location.pathname === '/gp/yourstore') {
                                        console.log('yourstore')
                                        if ($('.welcome-msg'))
                                            UrunZararYaz()
                                    } else {
                                        var path = window.location.pathname.toString()
                                        var NotAdded = 'item-dispatch'
                                        var NotAddedDurum = path.indexOf(NotAdded) !== -1
                                        if (NotAddedDurum) {
                                            AmzItemNotAdded()
                                        } else {
                                            if (window.location.pathname === '/gp/buy/spc/handlers/display.html') {
                                                AmzOrderComplete()
                                            } else if (window.location.pathname === '/checkout/entry/cart/amazon_business') {
                                                YanlisUrun()
                                            } else {
                                                if (document.querySelector('#submitOrderButtonId > span > input')) {
                                                    AmzOrderComplete()
                                                } else if (
                                                        document.querySelector('#orderSummaryPrimaryActionBtn > span > input')
                                                        ) {
                                                    AmzOrderComplete()
                                                } else if (window.location.pathname.indexOf('/checkout/p/p-') !== -1) {
                                                    AmzOrderComplete()
                                                } else if (window.location.pathname === '/errors/500') {
                                                    UrunZararYaz()
                                                } else if (
                                                        window.location.href.indexOf('https://www.amazon.com/checkout/byg') !== -1
                                                        ) {
                                                    document.querySelector('#checkout-byg-ptc-button > span > a').click()
                                                } else if (
                                                        window.location.pathname.indexOf('/cart/smart-wagon') >= 0 ||
                                                        window.location.pathname.indexOf('/cart') >= 0
                                                        ) {
                                                    if (document.querySelector('#sw-gtc > span > a')) {
                                                        document.querySelector('#sw-gtc > span > a').click()
                                                    } else {
                                                        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 {
                                                                UrunZararYaz()
                                                            }
                                                        } else {
                                                            UrunZararYaz()
                                                        }
                                                    }
                                                } else {
                                                    console.log('hiç biri')
                                                    UrunZararYaz();
                                                }
                                            }
                                        }
                                    }
                                } else if (item.Durum === 'SiparisTamamla') {
                                    if (window.location.pathname.indexOf('/gp/buy/thankyou/handlers/display.html') !== -1)
                                        AmzSiparisTamamla()
                                    else if (window.location.pathname === '/gp/css/order-history')
                                        AmzOrderInfoGet()
                                    else if (window.location.pathname.split('/')[3] === 'order-details')
                                        OrderViewPage()
                                    else if (window.location.pathname === '/gp/buy/duplicate-order/handlers/display.html')
                                        DuplicateOrderComplete()
                                    else if (window.location.pathname.indexOf('duplicateOrder') !== -1)
                                        DuplicateOrderComplete()
                                    else if (window.location.pathname === '/gp/buy/spc/handlers/static-submit-decoupled.html')
                                        YanlisUrun()
                                }
                            }
                        }
                    }, parseInt(item.RequestTime) * 1000)
                }
        )
    } else {
        window.location.reload()
    }
})
async function UrunGetir() {
    var host = window.location.host
    await clearAmazonCacheFromContent()
    console.log('Amazon cache ve cookie temizlendi.')
    setTimeout(function () {
        if (chrome?.storage?.sync) {
            chrome.storage.sync.get(['MagazaAdi', 'PcName', 'isStarted', 'ApiUrl'], function (item) {
                if (item.isStarted) {
                    console.log('Ürün Getirilecek!')
                    localStorage.clear()
                    localStorage.removeItem('LSAmazonUrunList')
                    var datam = {
                        magazaDeger: item.MagazaAdi,
                        tip: 'newOrderStartOtomatik',
                        PCAd: item.PcName,
                    }
                    console.log(datam)
                    console.log(datam.magazaDeger + ' için sipariş alınacak!')
                    $.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) {
                                setTimeout(function () {
                                    UrunGetir()
                                }, 5000)
                            } else {
                                if (cevap.result) {
                                    console.log(cevap.result)
                                    var data = cevap.result
                                    localStorage.clear()
                                    localStorage.removeItem('LSAmazonUrunList')
                                    if (chrome?.storage?.sync) {
                                        chrome.storage.sync.set(
                                                {
                                                    UrunID: data.ID,
                                                    UrunGetirildi: true,
                                                    Durum: 'FiyatKontrol',
                                                    UrunFiyat: data.Fiyat,
                                                    AmazonUrl: data.AmazonUrl,
                                                    UrunAdet: data.Adet,
                                                    Isbn: data.Isbn,
                                                    AdresEklendi: false,
                                                    AlinacakStok: data.AlinacakStok ? parseInt(data.AlinacakStok) : 1,
                                                },
                                                async function () {
                                                    localStorage.setItem('Isbn', data.Isbn);
                                                    console.table(data)
                                                    console.log(data.AmazonUrl)
                                                    console.log(data.Fiyat + 'Alış fiyatı!!!!!')
                                                    SekmeAc(data.AmazonUrl)
                                                    AmazonUrl = data.AmazonUrl
                                                    console.log('Sekmeler Açılacak!')
                                                    if (
                                                            data.AmazonUrl &&
                                                            (host == 'www.amazon.com')
                                                            ) {
                                                        SekmeKapat(2)
                                                    }
                                                }
                                        )
                                    } else {
                                        window.location.reload()
                                    }
                                }
                            }
                            console.log('UrunGetir() Response!')
                        },
                        error: function (req, textStatus, errorThrown) {
                            console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                            setTimeout(function () {
                                UrunGetir()
                            }, 5000)
                        },
                    })
                }
            })
        } else {
            window.location.reload()
        }
    }, 2000)
}
function YanlisUrun(fiyat = 0) {
    if (chrome?.storage?.sync) {
        chrome.storage.sync.get(['UrunID', 'ApiUrl'], function (item) {
            console.log('İstenilen ürüne  uygun fiyat ve diğer şartlar sağlanamadı!')
            $.ajax({
                type: 'post',
                url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                },
                cache: false,
                dataType: 'json',
                data: {
                    ID: item.UrunID,
                    tip: 'newOrderWrong',
                },
                success: function (cevap) {
                    console.log(cevap)
                    if (cevap.hata) {
                        console.log('Hata')
                    } else {
                        if (cevap.result) {
                            console.log(cevap.result)
                            console.log('YanlisUrun(' + fiyat + ')  çalıştı!')
                            UrunGetir()
                        }
                    }
                },
                error: function (req, textStatus, errorThrown) {
                    console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                    setTimeout(function () {
                        YanlisUrun()
                    }, 5000)
                },
            })
        })
    } else {
        window.location.reload()
}
}
async function AmazonFiyatKontrol(fiyat, AmzPageCount, AmazonUrl) {
    var Condition = QueryStringOku('condition')
    if (Condition?.indexOf(',') >= 0) {
        Condition = Condition.split(',')
    }

    waitForElement('#aod-container', function () {
        setTimeout(function () {
            var isArray = Array.isArray(Condition)
            if (isArray) {
                ;
                ['usedGood', 'usedVeryGood', 'usedAcceptable', 'usedLikeNew'].forEach(function (item) {
                    var checkbox = document.querySelector('#' + item + ' > div > label > input[type=checkbox]')
                    if (checkbox && checkbox.checked) {
                        document.querySelector('#' + item).click()
                    }
                })
                Condition.forEach(function (cond) {
                    var checkbox = document.querySelector('#' + cond + ' > div > label > input[type=checkbox]')
                    if (checkbox && !checkbox.checked) {
                        document.querySelector('#' + cond).click()
                    }
                })
            } else {
                if (Condition !== 'new') {
                    console.log(Condition)
                    if (document.querySelector('#usedGood > div > label > input[type=checkbox]').checked)
                        document.querySelector('#usedGood').click()
                    if (document.querySelector('#usedVeryGood > div > label > input[type=checkbox]').checked)
                        document.querySelector('#usedVeryGood').click()
                    if (document.querySelector('#usedAcceptable > div > label > input[type=checkbox]').checked)
                        document.querySelector('#usedAcceptable').click()
                    if (document.querySelector('#usedLikeNew > div > label > input[type=checkbox]').checked)
                        document.querySelector('#usedLikeNew').click()
                    var checkbox = document.querySelector('#' + Condition + ' > div > label > input[type=checkbox]')
                    if (checkbox && !checkbox.checked) {
                        document.querySelector('#' + Condition).click()
                    }
                }
            }
        }, 3000)
        setTimeout(async function () {
            if (
                    $(
                            '#rpi-attribute-book_details-isbn10  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                            ).length
                    ) {
                var Isbn10 = $(
                        '#rpi-attribute-book_details-isbn10  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                        )
                        .text()
                        .trim()
            }
            if (
                    $(
                            '#rpi-attribute-book_details-isbn13  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                            ).length
                    ) {
                var Isbn13 = $(
                        '#rpi-attribute-book_details-isbn13  div.a-section.a-spacing-none.a-text-center.rpi-attribute-value  span'
                        )
                        .text()
                        .trim()
            }
            var ASIN = 0
            if ($('#detailBulletsWrapper_feature_div')) {
                $('#detailBulletsWrapper_feature_div > ul').each(function () {
                    if ($(this).text().trim().indexOf('ASIN') != -1) {
                        var text = $(this).find('li > span').text()
                        var splitedText = text
                        if (splitedText.length > 1) {
                            var sText = splitedText.split('ASIN:')
                            if (sText.length >= 1 && typeof sText[1] !== 'undefined') {
                                ASIN = sText[1].trim().split('#')[1]
                            }
                        }
                    }
                })
            }
            if ($('#detailBullets_feature_div')) {
                $('#detailBullets_feature_div > ul').each(function () {
                    if ($(this).text().trim().indexOf('ASIN') != -1) {
                        var text = $(this).find('li > span').text()
                        var splitedText = text
                        if (splitedText.length > 1) {
                            var sText = splitedText.split('ASIN:')
                            if (sText.length >= 1 && typeof sText[1] !== 'undefined') {
                                ASIN = sText[1].trim()
                            }
                        }
                    }
                })
            }
            if (ASIN != 0) {
                Isbn10 = ASIN
            }
            console.log(
                    'Isbn10:' +
                    Isbn10 +
                    'Isbn13:' +
                    Isbn13
                    )
            var UrunList = localStorage.getItem('LSAmazonUrunList')
            if (UrunList != undefined) {
                AmzUrunList = JSON.parse(UrunList)
            }
            var liste = $('#aod-offer-list #aod-offer')
            var listeItemCount = parseInt($('#aod-offer-list #aod-offer').length) - 1
            if (chrome?.storage?.local) {
                try {
                    chrome.storage.local.set({Isbn10, Isbn13});
                } catch (e) {
                    window.location.reload();
                }
            } else {
                window.location.reload();
            }
            var FiyatKontrolTamamlandi = true
            liste.each(function (index) {
                var UrunFiyat = $(this)
                        .find('.a-price span[aria-hidden="true"]')
                        .text()
                        .trim()
                        .substr(1)
                        .replace(',', '')
                console.log(
                        $(this)
                        .find('#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE')
                        .find('span')
                        .attr('data-csa-c-delivery-price')
                        )
                if (
                        $(this)
                        .find('#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE')
                        .find('span')
                        .attr('data-csa-c-delivery-price')
                        ) {
                    var KargoFiyat = $(this)
                            .find('#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE')
                            .find('span')
                            .attr('data-csa-c-delivery-price')
                            .split('$')
                } else {
                    var KargoFiyat = 0.0
                }
                console.log('Kargo: ' + KargoFiyat)
                if (KargoFiyat.length > 1 || KargoFiyat[0] !== 'FREE')
                    KargoFiyat = KargoFiyat[1] ?? KargoFiyat
                var DFiyat = parseFloat(fiyat)
                var DUrunFiyat = parseFloat(UrunFiyat)
                var DKargoFiyat = KargoFiyat.length > 1 ? parseFloat(KargoFiyat) : 0
                if (isNaN(DKargoFiyat))
                    DKargoFiyat = 0.0
                var Price = DUrunFiyat + DKargoFiyat
                var Condition = $(this).find('#aod-offer-heading > h5').text().replace(/\s/g, '').trim()
                var ConditionDesc = $(this).find('#condition-text-block-title span.expandable-expanded-text').text()
                var Seller = $(this).find('#aod-offer-soldBy a').text().trim()
                var Positive = $(this).find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                if (Positive.length > 0)
                    Positive = Positive[0].split(')')[1]
                var r = $(this).find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                if (r.length > 0)
                    r = r[0].split(')')[0].split(' ')[0].split('(')[1]
                var Ratings = r != undefined ? r : '-'
                Price = Price.toFixed(2)
                var item = {
                    index,
                    Condition,
                    Seller,
                    Positive,
                    Ratings,
                    Price,
                    ConditionDesc,
                    Page: AmzPageCount,
                }
                AmzUrunList.push(item)
                console.log(listeItemCount + ' ' + index + ' ' + listeItemCount)
                if (listeItemCount === index && listeItemCount !== 0) {
                    FiyatKontrolTamamlandi = true
                    localStorage.setItem('LSAmazonUrunList', JSON.stringify(AmzUrunList))
                } else {
                    FiyatKontrolTamamlandi = true
                }
            })
            if (FiyatKontrolTamamlandi) {
                console.log('Verileri Gonder')
                console.table(AmzUrunList)
                if (chrome?.storage?.local) {
                    chrome.storage.local.set(
                            {
                                AmzUrunList: AmzUrunList,
                                AmazonUrl: AmazonUrl,
                                UrunFiyat: fiyat,
                            },
                            function () {
                                console.log('AmzUrunList kontrol edildi: ')
                                localStorage.removeItem('LSAmazonUrunList')
                                UrunListeleriniGonder()
                            }
                    )
                } else {
                    window.location.reload()
                }
            } else {
                console.log(AmzPageCount)
                var PaginationNext = parseInt(AmzPageCount) + 1
                if (chrome?.storage?.sync) {
                    chrome.storage.sync.set(
                            {
                                AmzPageCount: PaginationNext,
                            },
                            function () {
                                var amzlink = AmazonUrl
                                var params = '&PgNm=Amz&startIndex=' + PaginationNext * 10
                                var link = amzlink + params
                                console.log('diğer sayfaya gec')
                            }
                    )
                } else {
                    window.location.reload()
                }
            }
        }, 10000)
    }, 15000, function () {
        console.log('#aod-container bulunamadı (AmazonFiyatKontrol), YanlisUrun...')
        YanlisUrun()
    })
}
function AmzUrunAl(IstenilenFiyat, Condition) {
    waitForElement('#aod-container', function () {
        setTimeout(function () {
            if (chrome?.storage?.local) {
                chrome.storage.local.get(['AmzUrunList', 'ISBN'], function (item) {
                    console.log(item.AmzUrunList)
                    console.log('Amazon')
                    var AmzUrunList = item.AmzUrunList
                    var itemIndex = QueryStringOku('itemIndex') ?? 0
                    var NPrice = QueryStringOku('NPrice')
                    var Price = 0
                    var Seller = null
                    var LocaldekiUrun = AmzUrunList.find((item) => item.index == itemIndex)
                    console.log(LocaldekiUrun)
                    var AmzSeller = LocaldekiUrun.Seller
                    if (itemIndex == '-1') {
                        var Urun = $('#aod-pinned-offer')
                        var UrunFiyat = $('#aod-pinned-offer')
                                .find('.a-price span[aria-hidden="true"]')
                                .text()
                                .trim()
                                .substr(1)
                                .replace(',', '')
                        if (document.querySelector('#pinned-offer-top-id > div:nth-child(3) > span > span'))
                            var KargoFiyat = document
                                    .querySelector('#pinned-offer-top-id > div:nth-child(3) > span > span')
                                    .textContent.split(' ')
                        else
                            var KargoFiyat = 0
                        console.log(KargoFiyat.length)
                        if (KargoFiyat.length > 1)
                            KargoFiyat = KargoFiyat[1].trim().substr(1).replace(',', '')
                        console.log(KargoFiyat)
                        var DUrunFiyat = parseFloat(UrunFiyat)
                        var DKargoFiyat = KargoFiyat.length > 1 ? parseFloat(KargoFiyat.replace(',', '')) : 0
                        Price = DUrunFiyat + DKargoFiyat
                        var Condition = $('#aod-pinned-offer')
                                .find('#aod-offer-heading > h5')
                                .text()
                                .replace(/\s/g, '')
                                .trim()
                        Seller = $('#aod-pinned-offer')
                                .find('#aod-offer-soldBy > div > div > div.a-fixed-left-grid-col.a-col-right > a')
                                .text()
                                .trim()
                        var Positive = $('#aod-pinned-offer')
                                .find('#seller-rating-count-\\{iter\\} > span')
                                .text()
                                .split('%')
                        if (Positive.length > 0)
                            Positive = Positive[0].split(')')[1]
                        var r = $('#aod-pinned-offer').find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                        if (r.length > 0)
                            r = r[0].split(')')[0].split(' ')[0].split('(')[1]
                        var Ratings = r != undefined ? r : '0'
                        Price = Price.toFixed(2)
                    } else {
                        console.log(itemIndex)
                        var Urun = $('#aod-offer-list #aod-offer').eq(itemIndex)
                        var UrunFiyat = Urun.find('.a-price span[aria-hidden="true"]')
                                .text()
                                .trim()
                                .substr(1)
                                .replace(',', '')
                        var KargoFiyat = Urun.find(
                                '#aod-offer-price > div > div > div.a-fixed-left-grid-col.a-col-right > div > div > div.a-fixed-right-grid-col.aod-padding-right-10.a-col-left > span > span'
                                )
                                .text()
                                .split(' ')
                        if (KargoFiyat.length > 1)
                            KargoFiyat = KargoFiyat[1].trim().substr(1).replace(',', '')
                        var DUrunFiyat = parseFloat(UrunFiyat)
                        var DKargoFiyat = KargoFiyat.length > 1 ? parseFloat(KargoFiyat.replace(',', '')) : 0
                        if (DKargoFiyat === 0) {
                            if (
                                    document.querySelectorAll(
                                            '#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE > span'
                                            )[itemIndex]
                                    )
                                if (
                                        document
                                        .querySelectorAll(
                                                '#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE > span'
                                                )
                                [itemIndex].textContent.split(' ')[1] == 'FREE'
                                        )
                                    DKargoFiyat = 0
                                else
                                    DKargoFiyat = document
                                            .querySelectorAll(
                                                    '#mir-layout-DELIVERY_BLOCK-slot-PRIMARY_DELIVERY_MESSAGE_LARGE > span'
                                                    )
                                    [itemIndex].textContent.split(' ')[1]
                                            .split('$')[1]
                        }
                        console.log(DKargoFiyat)
                        Price = DUrunFiyat + parseFloat(DKargoFiyat)
                        var Condition = Urun.find('#aod-offer-heading > h5').text().replace(/\s/g, '').trim()
                        var Delivery = Urun.find('#delivery-message > b')
                                .text()
                                .split('\n')
                                .map((item) => item.trim())
                                .join(' ')
                                .trim()
                        Seller = Urun.find('#aod-offer-soldBy a').text().trim()
                        var Positive = Urun.find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                        if (Positive.length > 0)
                            Positive = Positive[0].split(')')[1]
                        var r = Urun.find('#seller-rating-count-\\{iter\\} > span').text().split('%')
                        if (r.length > 0)
                            r = r[0].split(')')[0].split(' ')[0].split('(')[1]
                        var Ratings = r != undefined ? r : '-'
                    }
                    console.log(
                            'Localdeki:' + LocaldekiUrun.Condition + ' ' + LocaldekiUrun.Seller + ' ' + LocaldekiUrun.Price
                            )
                    console.log('Sayfadaki:' + Condition + ' ' + Seller + ' ' + Price)
                    if (chrome?.storage?.sync) {
                        chrome.storage.sync.get(['LastPrice'], function (item33) {
                            console.log(item33.LastPrice)
                        })
                    } else {
                        window.location.reload()
                    }
                    NPrice = parseFloat(NPrice)
                    if (isNaN(NPrice) || NPrice == null || NPrice <= 0) {
                        NPrice = parseFloat(IstenilenFiyat)
                    }
                    if (LocaldekiUrun.Condition === Condition && LocaldekiUrun.Seller === Seller) {
                        console.log('İki ürün aynı. İşlemler devam edecek (Amazon)')
                        console.log(Urun)
                        var link = window.location.href
                        let beforeCount = parseInt($('#nav-cart-count').text()) || 0;
                        Urun.find("input[name='submit.addToCart']").click()
                        let checkCount = 0;
                        let cartCheckInterval = setInterval(function () {
                            checkCount++;
                            let afterCount = parseInt($('#nav-cart-count').text()) || 0;
                            if (afterCount > beforeCount) {
                                clearInterval(cartCheckInterval);
                                if (chrome?.storage?.sync) {
                                    chrome.storage.sync.set(
                                            {
                                                Durum: 'UrunAl',
                                                AmzSepetUrunLink: link,
                                                AmzSeller: AmzSeller,
                                                NextPrice: NPrice,
                                            },
                                            function () {
                                                window.location.href = 'https://www.amazon.com/gp/cart/view.html?PgNm=Amz&Basket=True'
                                            }
                                    )
                                } else {
                                    window.location.href = 'https://www.amazon.com/gp/cart/view.html?PgNm=Amz&Basket=True'
                                }
                            } else if (checkCount >= 8) {
                                clearInterval(cartCheckInterval);
                                UrunZararYaz();
                            }
                        }, 2000)
                    } else {
                        console.log('İki ürün aynı değil listedeki diğer ürüne geçilecek! (Amazon)')
                        UrunZararYaz(Price)
                    }
                })
            } else {
                window.location.reload()
            }
        }, 5000)
    }, 15000, function () {
        console.log('#aod-container bulunamadı (AmzUrunAl), YanlisUrun...')
        YanlisUrun()
    })
}
function UrunAl(tekrar) {
    var host = window.location.host
    if (chrome?.storage?.local) {
        chrome.storage.local.get(
                ['SiparisBilgileri', 'UrunFiyat', 'SiparisListesiLastIndex', 'SiparisIndex', 'AmazonUrl', 'ISBN'],
                function (item) {
                    var link = ''
                    var isbn = item.ISBN
                    var SiparisBilgileri = item.SiparisBilgileri
                    var SiparisIndex = item.SiparisIndex
                    var SiparisListesiLastIndex = item.SiparisListesiLastIndex - tekrar
                    console.log(SiparisListesiLastIndex)
                    console.log(SiparisIndex)
                    console.log(host)
                    if (SiparisIndex < SiparisListesiLastIndex || SiparisIndex === SiparisListesiLastIndex) {
                        var NPrice = parseFloat(SiparisBilgileri[item.SiparisIndex]['SecondPrice'])
                        console.log('Nprice type: ' + typeof NPrice + ' value: ' + NPrice)
                        if (isNaN(NPrice) || NPrice == null || NPrice <= 0) {
                            NPrice = parseFloat(item.UrunFiyat)
                        }
                        var SiparisIndexNext = parseInt(SiparisIndex) + 1 - tekrar
                        if (chrome?.storage?.local) {
                            chrome.storage.local.set(
                                    {
                                        SiparisIndex: SiparisIndexNext,
                                    },
                                    function () {
                                        AmzUrunAl(NPrice, 'usedLikeNew');
                                    }
                            )
                        } else {
                            window.location.reload()
                        }
                    } else {
                        console.log('Sipariş Listesinde Uygun Sipariş Kalmadı!')
                    }
                }
        )
    } else {
        window.location.reload()
    }
}
function UrunListeleriniGonder() {
    console.log(' UrunListeleriniGonder()')
    var host = window.location.host
    let OurPrice = 0
    let MagazaAdi = ''
    if (chrome?.storage?.sync) {
        chrome.storage.sync.get(['UrunID', 'PcName', 'UrunFiyat', 'ApiUrl', 'MagazaAdi'], function (item) {
            UrunID = item.UrunID
            PcName = item.PcName
            OurPrice = item.UrunFiyat
            ApiUrl = item.ApiUrl
            MagazaAdi = item.MagazaAdi
        })
    } else {
        window.location.reload()
        return
    }
    if (chrome?.storage?.local) {
        chrome.storage.local.get(
                [
                    'AmzUrunList',
                    'PcName',
                    'UrunFiyat',
                    'Rank',
                    'SellerCount',
                    'newPrice',
                    'Isbn10',
                    'Isbn13',
                    'buyBoxNew',
                    'buyBoxNewPrice',
                ],
                function (item) {
                    var Amazon = item.AmzUrunList
                    var orderArray = [[...Amazon]]
                    var stringArray = JSON.stringify(orderArray)
                    console.log(stringArray)
                    var datam = {
                        ID: UrunID,
                        price: 0,
                        magazaDeger: MagazaAdi,
                        orderArray: stringArray,
                        tip: 'newOrderFiltreOtomatik',
                        PCAd: PcName,
                        OurPrice: OurPrice,
                        Rank: item.Rank,
                        SaticiSayisi: item.SellerCount,
                        NewPrice: item.newPrice,
                        Isbn10: item.Isbn10,
                        Isbn13: item.Isbn13,
                        buyBoxNew: item.buyBoxNew,
                        buyBoxNewPrice: item.buyBoxNewPrice,
                    }
                    console.log(datam)
                    $.ajax({
                        type: 'post',
                        url: ApiUrl + 'ExtensionWebServis/ajaxCall',
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                        },
                        cache: false,
                        dataType: 'json',
                        timeout: 500000,
                        data: datam,
                        success: function (cevap) {
                            console.log(cevap)
                            if (cevap.hata) {
                                console.log('Hata')
                            } else {
                                if (cevap.result) {
                                    console.log('Sipariş listesi başarıyla alındı! UrunListeleriniGonder()')
                                    var gelenJson = cevap.result
                                    console.log(gelenJson)
                                    if (gelenJson['1'] != null && gelenJson['1'] != undefined) {
                                        console.log('Sipariş Alınacak')
                                        console.log(gelenJson[0])
                                        console.log(gelenJson[1])
                                        var SiparisListesiLastIndex = parseInt(gelenJson['1'].length) - 1
                                        var SiparisIndex = 0
                                        if (chrome?.storage?.sync) {
                                            chrome.storage.sync.set(
                                                    {
                                                        Durum: 'UrunAl',
                                                        AdresEklendi: false,
                                                    },
                                                    function () {
                                                        if (chrome?.storage?.sync) {
                                                            chrome.storage.sync.set(
                                                                    {
                                                                        LastPrice: gelenJson[1][SiparisIndex]['LastPrice'],
                                                                    },
                                                                    function () {}
                                                            )
                                                        } else {
                                                            setTimeout(function () {
                                                                console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                                                UrunGetir()
                                                            }, 2000)
                                                        }
                                                        if (chrome?.storage?.local) {
                                                            chrome.storage.local.set(
                                                                    {
                                                                        AdresBilgileri: gelenJson[0],
                                                                        SiparisBilgileri: gelenJson[1],
                                                                        SiparisListesiLastIndex: SiparisListesiLastIndex,
                                                                        SiparisIndex: SiparisIndex,
                                                                        UrunFiyat: item.buyBoxNewPrice,
                                                                        LastPrice: gelenJson[1][SiparisIndex]['LastPrice'],
                                                                    },
                                                                    function () {
                                                                        console.log('Siparişler alınacak. ')
                                                                        UrunAl(0)
                                                                    }
                                                            )
                                                        } else {
                                                            setTimeout(function () {
                                                                console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                                                UrunGetir()
                                                            }, 2000)
                                                        }
                                                    }
                                            )
                                        } else {
                                            setTimeout(function () {
                                                console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                                UrunGetir()
                                            }, 2000)
                                        }
                                    } else {
                                        setTimeout(function () {
                                            console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                            UrunGetir()
                                        }, 2000)
                                    }
                                } else {
                                    setTimeout(function () {
                                        console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                        UrunGetir()
                                    }, 2000)
                                }
                            }
                            console.log('Gönderildi')
                        },
                        error: function (req, textStatus, errorThrown) {
                            console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                            setTimeout(function () {
                                console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                                UrunListeleriniGonder()
                            }, 5000)
                        },
                    })
                }
        )
    } else {
        setTimeout(function () {
            console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
            UrunGetir()
        }, 2000)
    }
}
function UrunZararYaz(fiyat = 0) {
    if (chrome?.storage?.sync) {
        chrome.storage.sync.get(['UrunID', 'ApiUrl'], function (item) {
            console.log('İstenilen ürüne  uygun fiyat ve diğer şartlar sağlanamadı!')
            $.ajax({
                type: 'post',
                url: item.ApiUrl + 'ExtensionWebServis/ajaxCall',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                },
                cache: false,
                dataType: 'json',
                data: {
                    ID: item.UrunID,
                    price: fiyat,
                    orderArray: [],
                    tip: 'newOrderFiltreOtomatik',
                },
                success: function (cevap) {
                    console.log(cevap)
                    if (cevap.hata) {
                        console.log('Hata')
                    } else {
                        if (cevap.result == null || cevap.result.length == 0) {
                            console.log(cevap.result)
                            console.log('UrunZararYaz(' + fiyat + ')  çalıştı!')
                            UrunGetir()
                        }
                    }
                },
                error: function (req, textStatus, errorThrown) {
                    console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                    setTimeout(function () {
                        console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                        UrunZararYaz()
                    }, 2000)
                },
            })
        })
    } else {
        window.location.reload()
}
}
function AmzBasketPage() {
    console.log('AmzBasketPage()')
    var SepetCount = $('#nav-cart-count').text()
    console.log(SepetCount)
    if (SepetCount != undefined && SepetCount.length > 0) {
        if (parseInt(SepetCount) == 1) {
            console.log('Sepetteki ürün adeti: 1 Sipariş işlemleri devam edecek! AmzBasketPage()')
            if (chrome?.storage?.sync) {
                chrome.storage.sync.get(['AlinacakStok'], function (stokItem) {
                    var alinacakStok = stokItem.AlinacakStok ? parseInt(stokItem.AlinacakStok) : 1
                    console.log('AlinacakStok: ' + alinacakStok)
                    if (alinacakStok > 1) {
                        AmzSepetAdetArttir(alinacakStok, function () {
                            if (!$('#sc-buy-box-ptc-button'))
                                window.location.reload()
                            var gercekAdet2 = parseInt($('#nav-cart-count').text()) || 1
                            chrome.storage.sync.set({ GercekAlinacakStok: gercekAdet2 })
                            $('#sc-buy-box-ptc-button').click()
                            $('#sc-buy-box-ptc-button').trigger('click')
                            $('#sc-buy-box-ptc-button > span').click()
                            $('#sc-buy-box-ptc-button > span').trigger('click')
                            $('#sc-buy-box-ptc-button > span > input').click()
                            $('#sc-buy-box-ptc-button > span > input').trigger('click')
                            console.log('proceedToCheckout tıklandı AmzBasketPage()')
                        })
                    } else {
                        if (!$('#sc-buy-box-ptc-button'))
                            window.location.reload()
                        var gercekAdet1 = parseInt($('#nav-cart-count').text()) || 1
                        chrome.storage.sync.set({ GercekAlinacakStok: gercekAdet1 })
                        $('#sc-buy-box-ptc-button').click()
                        $('#sc-buy-box-ptc-button').trigger('click')
                        $('#sc-buy-box-ptc-button > span').click()
                        $('#sc-buy-box-ptc-button > span').trigger('click')
                        $('#sc-buy-box-ptc-button > span > input').click()
                        $('#sc-buy-box-ptc-button > span > input').trigger('click')
                        console.log('proceedToCheckout tıklandı AmzBasketPage()')
                    }
                })
            } else {
                window.location.reload()
            }
            // dummy comment to preserve structure
        } else {
            if (parseInt(SepetCount) == 0)
                console.log(SepetCount + " Sepetteki ürün 1'den fazla sepet boşaltılacak!  AmzBasketPage() ")
            // AlinacakStok > 1 ise AranacakCount'a bak: bizim ürün kaldıysa adet artır, yoksa temizle
            if (chrome?.storage?.sync) {
                chrome.storage.sync.get(['AlinacakStok'], function (stokItem) {
                    var alinacakStok = stokItem.AlinacakStok ? parseInt(stokItem.AlinacakStok) : 1
                    if (alinacakStok > 1) {
                        var aranacakCount = $('[data-itemtype="active"]').length
                        console.log('AlinacakStok > 1, AranacakCount: ' + aranacakCount + ' AmzBasketPage()')
                        if (aranacakCount == 1) {
                            // Bizim ürün kaldı, SepetCount'a bakmadan adet artır ve checkout yap
                            AmzSepetAdetArttir(alinacakStok, function () {
                                if (!$('#sc-buy-box-ptc-button'))
                                    window.location.reload()
                                var gercekAdet3 = parseInt($('#nav-cart-count').text()) || 1
                                chrome.storage.sync.set({ GercekAlinacakStok: gercekAdet3 })
                                $('#sc-buy-box-ptc-button').click()
                                $('#sc-buy-box-ptc-button').trigger('click')
                                $('#sc-buy-box-ptc-button > span').click()
                                $('#sc-buy-box-ptc-button > span').trigger('click')
                                $('#sc-buy-box-ptc-button > span > input').click()
                                $('#sc-buy-box-ptc-button > span > input').trigger('click')
                                console.log('proceedToCheckout tıklandı AmzBasketPage() AlinacakStok>1')
                            })
                        } else {
                            // Başka ürün satırı var, temizle
                            var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
                            var params = 'PgNm=Amz&Sil=True'
                            var link = amzlink + params
                            SayfaGit(link, 1)
                        }
                    } else {
                        // AlinacakStok == 1: eski akış
                        var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
                        var params = 'PgNm=Amz&Sil=True'
                        var link = amzlink + params
                        SayfaGit(link, 1)
                    }
                })
            } else {
                window.location.reload()
            }
        }
    } else {
        console.log('Sepet Boş! Ürün tekrar sepete atılacak. AmzBasketPage()')
        if (chrome?.storage?.sync) {
            chrome.storage.sync.get(['AmzSepetUrunLink'], function (item) {
                console.log(item.AmzSepetUrunLink)
            })
        } else {
            window.location.reload()
        }
    }
}
function AmzBasketBosalt() {
    if (chrome?.storage?.sync) {
        chrome.storage.sync.get(['Isbn'], function (item) {
            let isbn = null
            isbn = item.Isbn;
            console.log('AmzBasketBosalt()')
            var Listeler = []
            var liste1 = $('.sc-batch-items').children()
            var liste1Count = liste1.length
            Listeler.push({
                liste: '.sc-batch-items',
                count: liste1Count,
            })
            var liste2 = $('.sc-batches-list-body').children()
            var liste2Count = liste2.length
            Listeler.push({
                liste: '.sc-batches-list-body',
                count: liste2Count,
            })
            var liste3 = $('.sc-list-body').children()
            var liste3Count = liste3.length
            Listeler.push({
                liste: '.sc-list-body',
                count: liste3Count,
            })
            console.log(liste1Count)
            console.log(liste2Count)
            console.log(liste3Count)
            var HangiListe = Listeler.find((item) => item.count > 0)
            var AranacakListe = ''
            var AranacakCount = ''
            if (HangiListe != null && HangiListe != undefined) {
                AranacakListe = HangiListe.liste
                AranacakCount = HangiListe.count
            } else {
                AranacakListe = '.sc-batch-items'
                AranacakCount = '0'
            }
            AranacakListe = "#activeCartViewForm ul  div[data-csa-c-type='item']";
            console.log(AranacakListe, $(AranacakListe).length);
            var headerText = $('.sc-cart-header').text().trim()
            if (document.querySelector('#sc-active-cart > div > h3')) {
                headerText = document.querySelector('#sc-active-cart > div > h3').textContent.trim()
            }
            console.log(parseInt(AranacakCount), headerText)
            if (parseInt(AranacakCount) > 1 && headerText !== 'Your Amazon Cart is empty') {
                console.log("Sepetteki ürün 1'dan fazla AmzBasketBosalt()")
                const delay = 1000;
                const items = $(AranacakListe).toArray();
                var isbnKepte = false; // İlk eşleşen ürün tutuldu mu?
                async function processItems() {
                    for (let i = 0; i < items.length; i++) {
                        const item = $(items[i]);
                        const currentIsbn = item
                                .find('.sc-product-isbn-10')
                                .text()
                                .trim()
                                .split('ISBN-10: ')[1];
                        const currentQuantity = item
                                .find('.sc-action-quantity input');
                        if (parseInt(currentQuantity.val()) > 1) {
                            updateQuantity(currentQuantity)
                        }
                        console.log(`(${i + 1}/${items.length}) Karşılaştırılıyor:`, isbn, currentIsbn, parseInt(currentQuantity.val()));
                        if (isbn === currentIsbn && parseInt(currentQuantity.val()) == 1 && !isbnKepte) {
                            console.log('Eşleşti, ilk kopya tutuluyor, atlanıyor...');
                            isbnKepte = true;
                            await new Promise((r) => setTimeout(r, delay));
                            continue;
                        }
                        console.log('Farklı, siliniyor...');
                        item.find('.sc-action-delete > span > input').trigger('click');
                        item.find('.sc-action-delete-active > span > input').trigger('click');
                        item.find('.sc-action-delete > span').trigger('click');
                        item.find('.sc-action-delete-active > span').trigger('click');
                        await new Promise((r) => setTimeout(r, 500));
                        const target = $(AranacakListe).find('div').eq(i);
                        target.find('.sc-action-delete-active > span > input').trigger('click');
                        target.find('.sc-action-delete-active > span').trigger('click');
                        target.find('.sc-action-delete > span > input').trigger('click');
                        target.find('.sc-action-delete > span').trigger('click');
                        await new Promise((r) => setTimeout(r, delay));
                    }
                    console.log('✅ Tüm işlemler tamamlandı, sayfa yenileniyor...');
                    setTimeout(() => window.location.href = "https://www.amazon.com/gp/cart/view.html?PgNm=Amz&Basket=True", 2000);
                }
                processItems();
            } else if (parseInt(AranacakCount) === 1) {
                if (chrome?.storage?.sync) {
                    chrome.storage.sync.get(['AlinacakStok'], function (stokItem) {
                        var alinacakStok = stokItem.AlinacakStok ? parseInt(stokItem.AlinacakStok) : 1
                        console.log('AmzBasketBosalt() AlinacakStok: ' + alinacakStok)
                        if (alinacakStok > 1) {
                            AmzSepetAdetArttir(alinacakStok, function () {
                                var gercekAdet4 = parseInt($('#nav-cart-count').text()) || 1
                                chrome.storage.sync.set({ GercekAlinacakStok: gercekAdet4 })
                                $('#sc-buy-box-ptc-button').click()
                                $('#sc-buy-box-ptc-button').trigger('click')
                                $('#sc-buy-box-ptc-button > span').click()
                                $('#sc-buy-box-ptc-button > span').trigger('click')
                                $('#sc-buy-box-ptc-button > span > input').click()
                                $('#sc-buy-box-ptc-button > span > input').trigger('click')
                            })
                        } else {
                            var gercekAdet5 = parseInt($('#nav-cart-count').text()) || 1
                            chrome.storage.sync.set({ GercekAlinacakStok: gercekAdet5 })
                            $('#sc-buy-box-ptc-button').click()
                            $('#sc-buy-box-ptc-button').trigger('click')
                            $('#sc-buy-box-ptc-button > span').click()
                            $('#sc-buy-box-ptc-button > span').trigger('click')
                            $('#sc-buy-box-ptc-button > span > input').click()
                            $('#sc-buy-box-ptc-button > span > input').trigger('click')
                        }
                    })
                } else {
                    var gercekAdet5b = parseInt($('#nav-cart-count').text()) || 1
                    chrome.storage.sync.set({ GercekAlinacakStok: gercekAdet5b })
                    $('#sc-buy-box-ptc-button').click()
                    $('#sc-buy-box-ptc-button').trigger('click')
                    $('#sc-buy-box-ptc-button > span').click()
                    $('#sc-buy-box-ptc-button > span').trigger('click')
                    $('#sc-buy-box-ptc-button > span > input').click()
                    $('#sc-buy-box-ptc-button > span > input').trigger('click')
                }
            } else {
                console.log('Sepet Boş. Ürün sepete tekrar atılacak. AmzBasketBosalt()')
                if (chrome?.storage?.sync) {
                    chrome.storage.sync.get(['AmzSepetUrunLink'], function (item) {
                        console.log(item.AmzSepetUrunLink)
                        SayfaGit(item.AmzSepetUrunLink, 1)
                    })
                } else {
                    window.location.reload()
                }
            }
        });
    } else {
        window.location.reload()
    }
}
async function updateQuantity(el) {
    if (!el)
        return console.warn('element yok');
    try {
        const desc = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
        desc && typeof desc.set === "function" && desc.set.call(el, "1");
    } catch (e) {
        try {
            el.value = "1";
        } catch (err) {
        }
    }
    el.dispatchEvent(new Event("input", {bubbles: true}));
    el.dispatchEvent(new Event("change", {bubbles: true}));
    try {
        el.dispatchEvent(new CustomEvent("a-input", {bubbles: true}));
    } catch (e) {
    }
    try {
        el.dispatchEvent(new CustomEvent("a-change", {bubbles: true}));
    } catch (e) {
    }
    try {
        el.focus();
        await new Promise(r => setTimeout(r, 40));
        el.blur();
        el.dispatchEvent(new Event("focusout", {bubbles: true}));
    } catch (e) {
    }
}
function OrderViewPage() {
    var orderCount = $(
            '#orderDetails div.a-box.shipment div.a-fixed-right-grid.a-spacing-top-medium div.a-fixed-right-grid-col.a-col-left div.a-fixed-left-grid'
            ).length
    $(
            '#orderDetails div.a-box.shipment div.a-fixed-right-grid.a-spacing-top-medium div.a-fixed-right-grid-col.a-col-left div.a-fixed-left-grid'
            ).each(function () {
        var title = $(this)
                .find('div.a-fixed-left-grid-col.yohtmlc-item.a-col-right div:nth-child(1) a.a-link-normal')
                .text()
                .trim()
        var seller = $(this)
                .find(
                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(3) span  a.a-link-normal:nth-child(1)'
                        )
                .text()
                .trim()
        var condition = $(this)
                .find('div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(6) span.a-text-bold')
                .text()
                .trim()
                .split('Condition:')[1]
        if (condition == '' || condition == undefined) {
            condition = $(this)
                    .find('div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(6) span:nth-child(2)')
                    .text()
                    .trim()
        }
        if (condition == '' || condition == undefined) {
            condition = $(this)
                    .find('div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(7) span.a-text-bold')
                    .text()
                    .trim()
        }
        if (condition)
            var lastChar = condition[condition.length - 1]
        if (lastChar == '-') {
            condition = condition.trim().slice(0, -2)
        }
        var grandTotal = $('#od-subtotals > div:nth-child(8) > div.a-column.a-span5.a-text-right.a-span-last > span')
                .text()
                .trim()
                .split('$')[1]
        var fee = $('#od-subtotals > div:nth-child(6) > div.a-column.a-span5.a-text-right.a-span-last > span')
                .text()
                .trim()
                .split('$')[1]
        var shipping = $('#od-subtotals > div:nth-child(3) > div.a-column.a-span5.a-text-right.a-span-last > span')
                .text()
                .trim()
                .split('$')[1]
        var orderId = $(
                '#orderDetails > div:nth-child(3) > div.a-column.a-span9.a-spacing-top-mini > div > span:nth-child(2) > bdi'
                )
                .text()
                .trim()
        if (!orderId)
            orderId = $(
                    '#orderDetails > div > div.a-cardui > div > div:nth-child(1) > div:nth-child(10) > div > div > div:nth-child(1) > div > div > div:nth-child(5) > span'
                    )
                    .text()
                    .trim()
        var trackingUrl = $('.actions .track-package-button a').attr('href')
        var isbn = $(this)
                .find('div.a-fixed-left-grid-col.a-col-right div:nth-child(1) a')
                .attr('href')
                .split('/')[3]
                .trim()
        if (isbn === undefined) {
            var isbn = $(this)
                    .find('div.a-fixed-right-grid-col.a-col-left div:nth-child(1) a')
                    .attr('href')
                    .split('/')[3]
                    .trim()
        }
        var qty = '1'
        // od-item-view-qty varsa oku, yoksa 1
        var odQty = $(this).find('div.od-item-view-qty span').text().trim()
        if (odQty !== '' && !isNaN(parseInt(odQty))) {
            qty = odQty
            console.log('qty od-item-view-qty dan okundu: ' + qty)
        } else {
            console.log('od-item-view-qty bulunamadı, qty=1 kullanılıyor')
        }
        var OrderItemData = JSON.parse(localStorage.getItem('OrderItemData'))
        console.log(OrderItemData)
        console.log(
                'title: ' +
                title +
                ' tracking: ' +
                trackingUrl +
                ' isbn: ' +
                isbn +
                ' seller: ' +
                seller +
                ' condition: ' +
                condition +
                ' grandTotal:' +
                grandTotal +
                ' fee:' +
                fee +
                ' shipping:' +
                shipping +
                ' qty: ' +
                qty
                )
        for (var i in OrderItemData) {
            console.log(title, qty, condition, seller)
            console.log(OrderItemData[i])
            console.log('name: ' + title == OrderItemData[i].name)
            console.log('qty: ' + qty == OrderItemData[i].quantity)
            console.log('condition: ' + OrderItemData[i].condition == condition)
            console.log('seller: ' + OrderItemData[i].seller == seller)
            console.log('orderId: ' + OrderItemData[i].orderId == undefined)
            if (
                    title == OrderItemData[i].name &&
                    qty == OrderItemData[i].quantity &&
                    OrderItemData[i].condition == condition &&
                    OrderItemData[i].seller == seller &&
                    OrderItemData[i].orderId == undefined
                    ) {
                console.log(orderId)
                OrderItemData[i].orderId = orderId
                OrderItemData[i].totalPrice = grandTotal
                OrderItemData[i].fee = fee
                OrderItemData[i].shipping = shipping
                OrderItemData[i].trackingUrl = trackingUrl
                OrderItemData[i].isbn = isbn
                OrderItemData[i].mAd = seller
                OrderItemData[i].adet = qty
                OrderItemData[i].conditionType = condition
                OrderItemData[i].orderCount = orderCount
                localStorage.setItem('OrderItemData', JSON.stringify(OrderItemData))
            }
        }
    });
}
function AmzOrderInfoGet() {
    waitForElement('#orderIdField > span > div', function () {
        if (chrome?.storage?.sync) {
            chrome.storage.sync.get(['OrderItemCount'], function (item) {
                var OrderItemData = JSON.parse(localStorage.getItem('OrderItemData'))
                console.log(OrderItemData)
                console.log(Object.keys(OrderItemData).length)
                let loader = dialogModal(`Loading...`)
                count = 0
                insideCount = 0
                insideCount2 = 0
                insideCount3 = 0
                orderArray = {}
                var istek = []
                $('.order-card .a-box.shipment').each(function () {
                    if (insideCount < Object.keys(OrderItemData).length) {
                        var orderDetailLink = $(this)
                                .parent()
                                .find(
                                        'div.a-box.a-color-offset-background.order-info  div.a-fixed-right-grid-col.actions.a-col-right  div.a-row.a-size-base.yohtmlc-order-level-connections  ul  a.a-link-normal.yohtmlc-order-details-link'
                                        )
                                .attr('href')
                        localStorage.setItem('checkOrder', false)
                        console.log('https://www.amazon.com' + orderDetailLink)
                        if (orderDetailLink !== undefined) {
                            istek.push(
                                    new Promise((resolve, reject) => {
                                        axios
                                                .get(
                                                        'https://www.amazon.com' + orderDetailLink,
                                                        {},
                                                        {
                                                            headers: {
                                                                cookie: document.cookie,
                                                            },
                                                        }
                                                )
                                                .then((response) => {
                                                    const dataHtml = response.data
                                                    html = $.parseHTML(dataHtml)
                                                    var orderCount = $(
                                                            '#orderDetails div.a-box.shipment div.a-fixed-right-grid.a-spacing-top-medium div.a-fixed-right-grid-col.a-col-left div.a-fixed-left-grid',
                                                            html
                                                            ).length
                                                    $(
                                                            '#orderDetails div.a-box.shipment div.a-fixed-right-grid.a-spacing-top-medium div.a-fixed-right-grid-col.a-col-left div.a-fixed-left-grid',
                                                            html
                                                            ).each(function () {
                                                        var title = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right div:nth-child(1) a.a-link-normal'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        var seller = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(3) span  a.a-link-normal:nth-child(1)'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        if (seller === '' || seller === undefined) {
                                                            seller = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(3) > span'
                                                                            )
                                                                    .text()
                                                                    .split('Sold by:')[1]
                                                        }
                                                        var condition = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(6) span.a-text-bold'
                                                                        )
                                                                .text()
                                                                .trim()
                                                                .split('Condition:')[1]
                                                        if (condition)
                                                            var lastChar = condition[condition.length - 1]
                                                        if (lastChar == '-') {
                                                            condition = condition.trim().slice(0, -2)
                                                        }
                                                        if (condition == '') {
                                                            condition = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(6) span:nth-child(2)'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var basePrice = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(5) span'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        var grandTotal = $(
                                                                '#od-subtotals > div:nth-child(8) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        var fee = $(
                                                                '#od-subtotals > div:nth-child(6) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        var shipping = $(
                                                                '#od-subtotals > div:nth-child(3) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        var orderId = $(
                                                                '#orderDetails > div:nth-child(3) > div.a-column.a-span9.a-spacing-top-mini > div > span:nth-child(2) > bdi',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                        console.log('orderId1->' + orderId)
                                                        var trackingUrl = $('.actions .track-package-button a', html).attr('href')
                                                        var isbn = $(this, html)
                                                                .find('div.a-fixed-left-grid-col.a-col-right div:nth-child(1) a')
                                                                .attr('href')
                                                                .split('/')[3]
                                                                .trim()
                                                        if (isbn === undefined) {
                                                            var isbn = $(this, html)
                                                                    .find('div.a-fixed-right-grid-col.a-col-left div:nth-child(1) a')
                                                                    .attr('href')
                                                                    .split('/')[3]
                                                                    .trim()
                                                        }
                                                        var qty = '1'
                                                        if (
                                                                $(this, html)
                                                                .find(
                                                                        'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                        )
                                                                .text()
                                                                .trim() !== ''
                                                                ) {
                                                            var qty = $(this, html)
                                                                    .find(
                                                                            'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var OrderItemData = JSON.parse(localStorage.getItem('OrderItemData'))
                                                        console.log(OrderItemData)
                                                        console.log(
                                                                'title: ' +
                                                                title +
                                                                ' tracking: ' +
                                                                trackingUrl +
                                                                ' isbn: ' +
                                                                isbn +
                                                                ' seller: ' +
                                                                seller +
                                                                ' condition: ' +
                                                                condition +
                                                                ' grandTotal:' +
                                                                grandTotal +
                                                                ' fee:' +
                                                                fee +
                                                                ' shipping:' +
                                                                shipping +
                                                                ' qty: ' +
                                                                qty
                                                                )
                                                        for (var i in OrderItemData) {
                                                            console.log(title, qty, condition, seller)
                                                            if (
                                                                    title == OrderItemData[i].name &&
                                                                    qty == OrderItemData[i].quantity &&
                                                                    OrderItemData[i].condition == condition &&
                                                                    OrderItemData[i].seller == seller &&
                                                                    OrderItemData[i].orderId == undefined
                                                                    ) {
                                                                OrderItemData[i].orderId = orderId
                                                                OrderItemData[i].totalPrice = grandTotal
                                                                OrderItemData[i].fee = fee
                                                                OrderItemData[i].shipping = shipping
                                                                OrderItemData[i].trackingUrl = trackingUrl
                                                                OrderItemData[i].isbn = isbn
                                                                OrderItemData[i].mAd = seller
                                                                OrderItemData[i].adet = qty
                                                                OrderItemData[i].conditionType = condition
                                                                OrderItemData[i].orderCount = orderCount
                                                                localStorage.setItem('OrderItemData', JSON.stringify(OrderItemData))
                                                            }
                                                        }
                                                    })
                                                    $(loader).html(
                                                            `İşleniyor : ${insideCount + '/' + Object.keys(OrderItemData).length}`
                                                            )
                                                    resolve()
                                                })
                                                .catch((e) => {
                                                    reject(e)
                                                })
                                    })
                                    )
                        }
                        insideCount++
                    }
                })
                $('.order-card .a-box.delivery-box').each(function () {
                    if (insideCount < Object.keys(OrderItemData).length) {
                        var orderDetailLink = $(this)
                                .parent()
                                .find(
                                        'div.a-box.a-color-offset-background.order-header div.a-text-right.a-fixed-right-grid-col.a-col-right a'
                                        )
                                .attr('href')
                        localStorage.setItem('checkOrder', false)
                        console.log('https://www.amazon.com' + orderDetailLink)
                        if (orderDetailLink !== undefined) {
                            istek.push(
                                    new Promise((resolve, reject) => {
                                        axios
                                                .get(
                                                        'https://www.amazon.com' + orderDetailLink,
                                                        {},
                                                        {
                                                            headers: {
                                                                cookie: document.cookie,
                                                            },
                                                        }
                                                )
                                                .then((response) => {
                                                    const dataHtml = response.data
                                                    html = $.parseHTML(dataHtml)
                                                    var orderCount = $(
                                                            '#orderDetails div[data-component="shipments"] div.a-fixed-left-grid',
                                                            html
                                                            ).length
                                                    $(
                                                            '#orderDetails div[data-component="shipments"] div.a-fixed-left-grid',
                                                            html
                                                            ).each(function () {
                                                        var title = $(this, html)
                                                                .find(
                                                                        'div[data-component="purchasedItemsRightGrid"] div[data-component="itemTitle"] a'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        var seller = $(this, html)
                                                                .find(
                                                                        'div[data-component="purchasedItemsRightGrid"] div[data-component="orderedMerchant"] a'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        if (seller === '' || seller === undefined) {
                                                            seller = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(3) > span'
                                                                            )
                                                                    .text()
                                                                    .split('Sold by:')[1]
                                                        }
                                                        var condition = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(6) span.a-text-bold'
                                                                        )
                                                                .text()
                                                        if (condition)
                                                            var lastChar = condition[condition.length - 1]
                                                        if (lastChar == '-') {
                                                            condition = condition.trim().slice(0, -2)
                                                        }
                                                        if (condition == '') {
                                                            condition = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(6) span:nth-child(2)'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var grandTotal = undefined
                                                        if (
                                                                $(
                                                                        '#od-subtotals > div:nth-child(8) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                        html
                                                                        )
                                                                ) {
                                                            var grandTotal = $(
                                                                    '#od-subtotals > div:nth-child(8) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        if (grandTotal == undefined) {
                                                            var grandTotal = $(
                                                                    '#od-subtotals > div:nth-child(9) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        var fee = $(
                                                                '#od-subtotals > div:nth-child(6) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        var shipping = $(
                                                                '#od-subtotals > div:nth-child(3) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        var orderId = $('div[data-component="orderDateInvoice"] bdi', html)
                                                                .text()
                                                                .trim()
                                                        console.log('orderId2->' + orderId)
                                                        var trackingUrl = $('#a-autoid-3-announce', html).attr('href')
                                                        var isbn = $(this, html)
                                                                .find("div[data-component='itemImage'] a")
                                                                .attr('href')
                                                                .split('/')
                                                        if (isbn.length > 3) {
                                                            isbn = isbn[2].split('?')[0]
                                                        } else if (isbn.length > 4) {
                                                            isbn = isbn[3].trim()
                                                        }
                                                        if (isbn === undefined) {
                                                            var isbn = $(this, html)
                                                                    .find('div.a-fixed-right-grid-col.a-col-left div:nth-child(1) a')
                                                                    .attr('href')
                                                                    .split('/')[3]
                                                                    .trim()
                                                        }
                                                        var qty = '1'
                                                        if (
                                                                $(this, html)
                                                                .find(
                                                                        'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                        )
                                                                .text()
                                                                .trim() !== ''
                                                                ) {
                                                            var qty = $(this, html)
                                                                    .find(
                                                                            'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var OrderItemData = JSON.parse(localStorage.getItem('OrderItemData'))
                                                        console.log(OrderItemData)
                                                        console.log(
                                                                'orderid: ' +
                                                                orderId +
                                                                'title: ' +
                                                                title +
                                                                ' tracking: ' +
                                                                trackingUrl +
                                                                ' isbn: ' +
                                                                isbn +
                                                                ' seller: ' +
                                                                seller +
                                                                ' condition: ' +
                                                                condition +
                                                                ' grandTotal:' +
                                                                grandTotal +
                                                                ' fee:' +
                                                                fee +
                                                                ' shipping:' +
                                                                shipping +
                                                                ' qty: ' +
                                                                qty
                                                                )
                                                        for (var i in OrderItemData) {
                                                            console.log(title, qty, condition, seller)
                                                            if (
                                                                    title == OrderItemData[i].name &&
                                                                    qty == OrderItemData[i].quantity &&
                                                                    OrderItemData[i].seller == seller &&
                                                                    OrderItemData[i].orderId == undefined
                                                                    ) {
                                                                OrderItemData[i].orderId = orderId
                                                                OrderItemData[i].totalPrice = grandTotal
                                                                OrderItemData[i].fee = fee
                                                                OrderItemData[i].shipping = shipping
                                                                OrderItemData[i].trackingUrl = trackingUrl
                                                                OrderItemData[i].isbn = isbn
                                                                OrderItemData[i].mAd = seller
                                                                OrderItemData[i].adet = qty
                                                                OrderItemData[i].conditionType =
                                                                        OrderItemData[i].condition ?? 'Used - Like New'
                                                                OrderItemData[i].orderCount = orderCount
                                                                console.log(OrderItemData[i])
                                                                localStorage.setItem('OrderItemData', JSON.stringify(OrderItemData))
                                                            }
                                                        }
                                                    })
                                                    $(loader).html(
                                                            `İşleniyor : ${insideCount3 + '/' + Object.keys(OrderItemData).length}`
                                                            )
                                                    resolve()
                                                })
                                                .catch((e) => {
                                                    reject(e)
                                                })
                                    })
                                    )
                        }
                        insideCount++
                    }
                })
                $('div#orderCard').each(function () {
                    if (insideCount2 < Object.keys(OrderItemData).length) {
                        var orderDetailLink = $(this)
                                .find('#orderCardHeader div.a-span-last ul li:nth-child(2)  span  a')
                                .attr('href')
                        localStorage.setItem('checkOrder', false)
                        console.log('https://www.amazon.com' + orderDetailLink)
                        if (orderDetailLink !== undefined) {
                            istek.push(
                                    new Promise((resolve, reject) => {
                                        axios
                                                .get(
                                                        'https://www.amazon.com' + orderDetailLink,
                                                        {},
                                                        {
                                                            headers: {
                                                                cookie: document.cookie,
                                                            },
                                                        }
                                                )
                                                .then((response) => {
                                                    const dataHtml = response.data
                                                    html = $.parseHTML(dataHtml)
                                                    var orderCount = $(
                                                            "#orderDetails div.a-cardui div[data-component='orderCard']  div.a-fixed-left-grid",
                                                            html
                                                            ).length
                                                    console.log(orderCount)
                                                    $(
                                                            "#orderDetails div.a-cardui div[data-component='orderCard'] div.a-fixed-left-grid",
                                                            html
                                                            ).each(function () {
                                                        var orderId = undefined
                                                        var title = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right div:nth-child(1) a.a-link-normal'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        if (title === '' || title === undefined) {
                                                            title = $(this, html)
                                                                    .find('div[data-component="itemTitle"] a')
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var seller = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(3) span  a.a-link-normal:nth-child(1)'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        if (seller === '' || seller === undefined) {
                                                            if (
                                                                    $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(3) > span'
                                                                            )
                                                                    .text()
                                                                    ) {
                                                                seller = $(this, html)
                                                                        .find(
                                                                                'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(3) > span'
                                                                                )
                                                                        .text()
                                                                        .split('Sold by:')[1]
                                                            }
                                                        }
                                                        if (seller === '' || seller === undefined) {
                                                            if (
                                                                    $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(2) > span'
                                                                            )
                                                                    .text()
                                                                    ) {
                                                                seller = $(this, html)
                                                                        .find(
                                                                                'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(2) > span'
                                                                                )
                                                                        .text()
                                                                        .split('Sold by:')[1]
                                                                        .trim()
                                                            }
                                                            seller = $(this, html)
                                                                    .find("div[data-component='orderedMerchant'] a")
                                                                    .text()
                                                        }
                                                        if (seller === '' || seller === undefined) {
                                                            seller = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(2) > span > a'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var condition = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(6) span.a-text-bold'
                                                                        )
                                                                .text()
                                                                .trim()
                                                                .split('Condition:')[1]
                                                        if (condition == '' || condition == undefined) {
                                                            condition = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(6) span:nth-child(2)'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                            if (condition.indexOf('Condition:') > -1) {
                                                                condition = condition.split('Condition:')[1]
                                                            }
                                                        }
                                                        if (condition == '' || condition == undefined) {
                                                            condition = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(7) span.a-text-bold'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                            if (condition.indexOf('Condition:') > -1) {
                                                                condition = condition.split('Condition:')[1]
                                                            }
                                                        }
                                                        if (condition == '' || condition == undefined) {
                                                            condition = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(7) span:nth-child(2)'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                            if (condition.indexOf('Condition:') > -1) {
                                                                condition = condition.split('Condition:')[1]
                                                            }
                                                        }
                                                        if (condition)
                                                            var lastChar = condition[condition.length - 1]
                                                        if (lastChar == '-') {
                                                            condition = condition.trim().slice(0, -2)
                                                        }
                                                        if (condition == '' || condition == undefined) {
                                                            condition = $(this, html)
                                                                    .find('div[data-component="itemCondition"] span:nth-child(2)')
                                                                    .text()
                                                            console.log('Condition2:' + condition)
                                                        }
                                                        var basePrice = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(5) span'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        var grandTotal = $(
                                                                '#od-subtotals > div:nth-child(8) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        if (grandTotal === undefined) {
                                                            grandTotal = $(
                                                                    '#od-subtotals > div:nth-child(1) > div ul li:nth-child(6) span  div  div.a-column.a-span5.od-line-item-row-content.a-span-last span',
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        if (grandTotal === undefined) {
                                                            grandTotal = $("#od-subtotals  div:nth-child(1)  div  ul  li:nth-child(5)  span  div  div.a-column.a-span5.od-line-item-row-content.a-span-last span",
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        console.log('grandTotal->' + grandTotal)
                                                        var fee = $(
                                                                '#od-subtotals > div:nth-child(6) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        if (fee == undefined) {
                                                            fee = $(
                                                                    '#od-subtotals > div:nth-child(1) > div > div:nth-child(5) > div.a-column.a-span5.od-line-item-row-content.a-span-last > span',
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        if (fee == undefined) {
                                                            fee = $("#od-subtotals > div:nth-child(1) > div > ul > li:nth-child(4) > span > div > div.a-column.a-span5.od-line-item-row-content.a-span-last > span", html)
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        console.log('fee->' + fee)
                                                        var shipping = $(
                                                                '#od-subtotals > div:nth-child(3) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        if (shipping == undefined) {
                                                            shipping = $(
                                                                    '#od-subtotals > div:nth-child(1) > div > div:nth-child(3) > div.a-column.a-span5.od-line-item-row-content.a-span-last > span',
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        if (shipping == undefined) {
                                                            shipping = $("#od-subtotals > div:nth-child(1) > div > ul > li:nth-child(2) > span > div > div.a-column.a-span5.od-line-item-row-content.a-span-last > span", html)
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        console.log('shipping->' + shipping)
                                                        orderId = $(
                                                                '#orderDetails > div:nth-child(3) > div.a-column.a-span9.a-spacing-top-mini > div > span:nth-child(2) > bdi',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                        var trackingUrl = $('.actions .track-package-button a', html).attr('href')
                                                        let isbn = undefined
                                                        try {
                                                            if (isbn === undefined) {
                                                                let href
                                                                href = $(this, html)
                                                                        .find(
                                                                                'div.a-fixed-right-grid-col.a-col-left div:nth-child(1) a'
                                                                                )
                                                                        .attr('href')
                                                                if (href) {
                                                                    let match = href.match(
                                                                            /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                            )
                                                                    if (match && match[1]) {
                                                                        isbn = match[1].trim()
                                                                    }
                                                                }
                                                                if (href == undefined) {
                                                                    href = $(this, html)
                                                                            .find(
                                                                                    'div.a-fixed-right-grid.a-spacing-top-medium > div > div.a-fixed-right-grid-col.a-col-left > div > div > div > div.a-text-center.a-fixed-left-grid-col.a-col-left > div > a'
                                                                                    )
                                                                            .attr('href')
                                                                    if (href) {
                                                                        let match = href.match(
                                                                                /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                                )
                                                                        if (match && match[1]) {
                                                                            isbn = match[1].trim()
                                                                        }
                                                                    }
                                                                }
                                                                if (href == undefined) {
                                                                    href = $(this, html)
                                                                            .find('div.item-view-left-col-inner a')
                                                                            .attr('href')
                                                                    console.log('href:' + href)
                                                                    if (href) {
                                                                        let match = href.match(
                                                                                /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                                )
                                                                        if (match && match[1]) {
                                                                            isbn = match[1].trim()
                                                                        }
                                                                    }
                                                                }
                                                                if (isbn === undefined) {
                                                                    href = $(this, html)
                                                                            .find(
                                                                                    'div.a-fixed-left-grid-col.a-col-right div:nth-child(1) a'
                                                                                    )
                                                                            .attr('href')
                                                                    if (href) {
                                                                        let match = href.match(
                                                                                /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                                )
                                                                        if (match && match[1]) {
                                                                            isbn = match[1].trim()
                                                                        }
                                                                    }
                                                                }
                                                                if (isbn === undefined) {
                                                                    href = $(this, html)
                                                                            .find(
                                                                                    "div[data-component='itemTitle'] div:nth-child(1) a",
                                                                                    html
                                                                                    )
                                                                            .attr('href')
                                                                    if (href) {
                                                                        let match = href.match(
                                                                                /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                                )
                                                                        if (match && match[1]) {
                                                                            isbn = match[1].trim()
                                                                        }
                                                                    }
                                                                }
                                                                if (isbn === undefined) {
                                                                    href = $(this, html)
                                                                            .find(
                                                                                    "div[data-component='itemImage'] div:nth-child(1) a",
                                                                                    html
                                                                                    )
                                                                            .attr('href')
                                                                    console.log('href:' + href)
                                                                    if (href) {
                                                                        let match = href.match(
                                                                                /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                                )
                                                                        if (match && match[1]) {
                                                                            isbn = match[1].trim()
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        } catch (error) {
                                                        }
                                                        console.log('Isbn->' + isbn)
                                                        var qty = '1'
                                                        if (
                                                                $(this, html)
                                                                .find(
                                                                        'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                        )
                                                                .text()
                                                                .trim() !== ''
                                                                ) {
                                                            var qty = $(this, html)
                                                                    .find(
                                                                            'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var OrderItemData = JSON.parse(localStorage.getItem('OrderItemData'))
                                                        if (orderId == '' || orderId == undefined) {
                                                            orderId = $(
                                                                    "#orderDetails div.a-cardui  div[data-component='orderId']",
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                            console.log('OrderID->' + orderId)
                                                        }
                                                        for (var i in OrderItemData) {
                                                            console.log(title, qty, condition, seller, orderId, isbn)
                                                            console.log(OrderItemData[i])
                                                            if (condition == 'Used - Mint')
                                                                condition = 'Used - Like New'
                                                            if (
                                                                    title == OrderItemData[i].name &&
                                                                    orderId != undefined &&
                                                                    isbn != undefined
                                                                    ) {
                                                                if (condition == '' || condition == undefined) {
                                                                    condition = 'Used - Like New'
                                                                }
                                                                OrderItemData[i].orderId = orderId
                                                                OrderItemData[i].totalPrice = grandTotal
                                                                OrderItemData[i].fee = fee
                                                                OrderItemData[i].shipping = shipping
                                                                OrderItemData[i].trackingUrl = trackingUrl
                                                                OrderItemData[i].isbn = isbn
                                                                OrderItemData[i].mAd = OrderItemData[i].seller
                                                                OrderItemData[i].adet = 1
                                                                OrderItemData[i].conditionType = condition ?? 'Used - Like New'
                                                                OrderItemData[i].orderCount = orderCount
                                                                console.log(OrderItemData[i])
                                                                localStorage.setItem('OrderItemData', JSON.stringify(OrderItemData))
                                                            }
                                                        }
                                                    })
                                                    $(loader).html(
                                                            `İşleniyor : ${insideCount2 + '/' + Object.keys(OrderItemData).length}`
                                                            )
                                                    resolve()
                                                })
                                                .catch((e) => {
                                                    reject(e)
                                                })
                                    })
                                    )
                        }
                        insideCount2++
                    }
                })
                Promise.all(istek)
                        .then((values) => {
                            $(loader).html('Kayıt ediliyor!')
                            var OrderItemData = JSON.parse(localStorage.getItem('OrderItemData'))
                            console.table(OrderItemData)
                            console.table(values)
                            chrome.storage.sync.get(['AmzSeller', 'DLastPrice'], function (item) {
                                var MagazaAdi = item.AmzSeller
                                var AbeOrAmazon = 0
                                var SiparisNo = QueryStringOku('purchaseId')
                                var hasInv = hasInvalidRecord(OrderItemData)
                                if (!hasInv) {
                                    console.log('Sipariş Tamamla')
                                    SiparisTamamla(MagazaAdi, SiparisNo, AbeOrAmazon, OrderItemData)
                                }
                                console.log(
                                        'MagazaAdi:' +
                                        MagazaAdi +
                                        ' OrderArray:' +
                                        OrderItemData +
                                        ' SiparisNo:' +
                                        SiparisNo +
                                        ' AbeSaticiNo: ' +
                                        '-' +
                                        'Son Fiyat:' +
                                        item.DLastPrice
                                        )
                            })
                        })
                        .catch((e) => {
                            console.log(e, 'Axios Hatası! Yeni ürüne geçiliyor...')
                            $(loader).remove()
                            setTimeout(function () {
                                UrunGetir()
                            }, 3000)
                        })
            })
        } else {
            window.location.reload();
        }
    })
    waitForElement('.your-orders-content-container', function () {
        if (chrome?.storage?.sync) {
            chrome.storage.sync.get(['OrderItemCount'], function (item) {
                var OrderItemData = JSON.parse(localStorage.getItem('OrderItemData'))
                console.log(OrderItemData)
                console.log(Object.keys(OrderItemData).length)
                let loader = dialogModal(`Loading...`)
                count = 0
                insideCount = 0
                insideCount2 = 0
                insideCount3 = 0
                orderArray = {}
                var istek = []
                $('.order-card .a-box.shipment').each(function () {
                    if (insideCount < Object.keys(OrderItemData).length) {
                        var orderDetailLink = $(this)
                                .parent()
                                .find(
                                        'div.a-box.a-color-offset-background.order-info  div.a-fixed-right-grid-col.actions.a-col-right  div.a-row.a-size-base.yohtmlc-order-level-connections  ul  a.a-link-normal.yohtmlc-order-details-link'
                                        )
                                .attr('href')
                        localStorage.setItem('checkOrder', false)
                        console.log('https://www.amazon.com' + orderDetailLink)
                        if (orderDetailLink !== undefined) {
                            istek.push(
                                    new Promise((resolve, reject) => {
                                        axios
                                                .get(
                                                        'https://www.amazon.com' + orderDetailLink,
                                                        {},
                                                        {
                                                            headers: {
                                                                cookie: document.cookie,
                                                            },
                                                        }
                                                )
                                                .then((response) => {
                                                    const dataHtml = response.data
                                                    html = $.parseHTML(dataHtml)
                                                    var orderCount = $(
                                                            '#orderDetails div.a-box.shipment div.a-fixed-right-grid.a-spacing-top-medium div.a-fixed-right-grid-col.a-col-left div.a-fixed-left-grid',
                                                            html
                                                            ).length
                                                    $(
                                                            '#orderDetails div.a-box.shipment div.a-fixed-right-grid.a-spacing-top-medium div.a-fixed-right-grid-col.a-col-left div.a-fixed-left-grid',
                                                            html
                                                            ).each(function () {
                                                        var title = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right div:nth-child(1) a.a-link-normal'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        var seller = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(3) span  a.a-link-normal:nth-child(1)'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        if (seller === '' || seller === undefined) {
                                                            seller = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(3) > span'
                                                                            )
                                                                    .text()
                                                                    .split('Sold by:')[1]
                                                        }
                                                        var condition = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(6) span.a-text-bold'
                                                                        )
                                                                .text()
                                                                .trim()
                                                                .split('Condition:')[1]
                                                        if (condition)
                                                            var lastChar = condition[condition.length - 1]
                                                        if (lastChar == '-') {
                                                            condition = condition.trim().slice(0, -2)
                                                        }
                                                        if (condition == '') {
                                                            condition = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(6) span:nth-child(2)'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var basePrice = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(5) span'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        var grandTotal = $(
                                                                '#od-subtotals > div:nth-child(8) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        var fee = $(
                                                                '#od-subtotals > div:nth-child(6) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        var shipping = $(
                                                                '#od-subtotals > div:nth-child(3) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        var orderId = $(
                                                                '#orderDetails > div:nth-child(3) > div.a-column.a-span9.a-spacing-top-mini > div > span:nth-child(2) > bdi',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                        console.log('orderId1->' + orderId)
                                                        var trackingUrl = $('.actions .track-package-button a', html).attr('href')
                                                        var isbn = $(this, html)
                                                                .find('div.a-fixed-left-grid-col.a-col-right div:nth-child(1) a')
                                                                .attr('href')
                                                                .split('/')[3]
                                                                .trim()
                                                        if (isbn === undefined) {
                                                            var isbn = $(this, html)
                                                                    .find('div.a-fixed-right-grid-col.a-col-left div:nth-child(1) a')
                                                                    .attr('href')
                                                                    .split('/')[3]
                                                                    .trim()
                                                        }
                                                        var qty = '1'
                                                        if (
                                                                $(this, html)
                                                                .find(
                                                                        'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                        )
                                                                .text()
                                                                .trim() !== ''
                                                                ) {
                                                            var qty = $(this, html)
                                                                    .find(
                                                                            'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var OrderItemData = JSON.parse(localStorage.getItem('OrderItemData'))
                                                        console.log(OrderItemData)
                                                        console.log(
                                                                'title: ' +
                                                                title +
                                                                ' tracking: ' +
                                                                trackingUrl +
                                                                ' isbn: ' +
                                                                isbn +
                                                                ' seller: ' +
                                                                seller +
                                                                ' condition: ' +
                                                                condition +
                                                                ' grandTotal:' +
                                                                grandTotal +
                                                                ' fee:' +
                                                                fee +
                                                                ' shipping:' +
                                                                shipping +
                                                                ' qty: ' +
                                                                qty
                                                                )
                                                        for (var i in OrderItemData) {
                                                            console.log(title, qty, condition, seller)
                                                            if (
                                                                    title == OrderItemData[i].name &&
                                                                    qty == OrderItemData[i].quantity &&
                                                                    OrderItemData[i].condition == condition &&
                                                                    OrderItemData[i].seller == seller &&
                                                                    OrderItemData[i].orderId == undefined
                                                                    ) {
                                                                OrderItemData[i].orderId = orderId
                                                                OrderItemData[i].totalPrice = grandTotal
                                                                OrderItemData[i].fee = fee
                                                                OrderItemData[i].shipping = shipping
                                                                OrderItemData[i].trackingUrl = trackingUrl
                                                                OrderItemData[i].isbn = isbn
                                                                OrderItemData[i].mAd = seller
                                                                OrderItemData[i].adet = qty
                                                                OrderItemData[i].conditionType = condition
                                                                OrderItemData[i].orderCount = orderCount
                                                                localStorage.setItem('OrderItemData', JSON.stringify(OrderItemData))
                                                            }
                                                        }
                                                    })
                                                    $(loader).html(
                                                            `İşleniyor : ${insideCount + '/' + Object.keys(OrderItemData).length}`
                                                            )
                                                    resolve()
                                                })
                                                .catch((e) => {
                                                    reject(e)
                                                })
                                    })
                                    )
                        }
                        insideCount++
                    }
                })
                $('.order-card .a-box.delivery-box').each(function () {
                    if (insideCount < Object.keys(OrderItemData).length) {
                        var orderDetailLink = $(this)
                                .parent()
                                .find(
                                        'div.a-box.a-color-offset-background.order-header div.a-text-right.a-fixed-right-grid-col.a-col-right a'
                                        )
                                .attr('href')
                        localStorage.setItem('checkOrder', false)
                        console.log('https://www.amazon.com' + orderDetailLink)
                        if (orderDetailLink !== undefined) {
                            istek.push(
                                    new Promise((resolve, reject) => {
                                        axios
                                                .get(
                                                        'https://www.amazon.com' + orderDetailLink,
                                                        {},
                                                        {
                                                            headers: {
                                                                cookie: document.cookie,
                                                            },
                                                        }
                                                )
                                                .then((response) => {
                                                    const dataHtml = response.data
                                                    html = $.parseHTML(dataHtml)
                                                    var orderCount = $(
                                                            '#orderDetails div[data-component="shipments"] div.a-fixed-left-grid',
                                                            html
                                                            ).length
                                                    $(
                                                            '#orderDetails div[data-component="shipments"] div.a-fixed-left-grid',
                                                            html
                                                            ).each(function () {
                                                        var title = $(this, html)
                                                                .find(
                                                                        'div[data-component="purchasedItemsRightGrid"] div[data-component="itemTitle"] a'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        var seller = $(this, html)
                                                                .find(
                                                                        'div[data-component="purchasedItemsRightGrid"] div[data-component="orderedMerchant"] a'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        if (seller === '' || seller === undefined) {
                                                            seller = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(3) > span'
                                                                            )
                                                                    .text()
                                                                    .split('Sold by:')[1]
                                                        }
                                                        var condition = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(6) span.a-text-bold'
                                                                        )
                                                                .text()
                                                        if (condition)
                                                            var lastChar = condition[condition.length - 1]
                                                        if (lastChar == '-') {
                                                            condition = condition.trim().slice(0, -2)
                                                        }
                                                        if (condition == '') {
                                                            condition = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(6) span:nth-child(2)'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var grandTotal = undefined
                                                        if (
                                                                $(
                                                                        '#od-subtotals > div:nth-child(8) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                        html
                                                                        )
                                                                ) {
                                                            var grandTotal = $(
                                                                    '#od-subtotals > div:nth-child(8) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        if (grandTotal == undefined) {
                                                            var grandTotal = $(
                                                                    '#od-subtotals > div:nth-child(9) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        var fee = $(
                                                                '#od-subtotals > div:nth-child(6) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        var shipping = $(
                                                                '#od-subtotals > div:nth-child(3) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        var orderId = $('div[data-component="orderDateInvoice"] bdi', html)
                                                                .text()
                                                                .trim()
                                                        if (!orderId)
                                                            orderId = $(
                                                                    '#orderDetails > div > div.a-cardui > div > div:nth-child(1) > div:nth-child(10) > div > div > div:nth-child(1) > div > div > div:nth-child(5) > span',
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                        console.log('orderId2->' + orderId)
                                                        var trackingUrl = $('#a-autoid-3-announce', html).attr('href')
                                                        var isbn = $(this, html)
                                                                .find("div[data-component='itemImage'] a")
                                                                .attr('href')
                                                                .split('/')
                                                        console.log(isbn.length, isbn)
                                                        if (isbn.length > 2) {
                                                            isbn = isbn[2].split('?')[0]
                                                        } else if (isbn.length > 3) {
                                                            isbn = isbn[2].split('?')[0]
                                                        } else if (isbn.length > 4) {
                                                            isbn = isbn[3].trim()
                                                        }
                                                        if (isbn === undefined) {
                                                            var isbn = $(this, html)
                                                                    .find('div.a-fixed-right-grid-col.a-col-left div:nth-child(1) a')
                                                                    .attr('href')
                                                                    .split('/')[3]
                                                                    .trim()
                                                        }
                                                        if (isbn === undefined) {
                                                            isbn = $(
                                                                    '#orderDetails > div > div.a-cardui > div > div:nth-child(1) > div:nth-child(13) > div > div > div > div > div > div > div:nth-child(1) > div > div:nth-child(2) > div > div > div > div:nth-child(1) > div > div > div > a',
                                                                    html
                                                                    )
                                                                    .attr('href')
                                                                    .split('/')
                                                            console.log(isbn.length, isbn)
                                                            if (isbn.length > 2) {
                                                                isbn = isbn[2].split('?')[0]
                                                            } else if (isbn.length > 3) {
                                                                isbn = isbn[2].split('?')[0]
                                                            } else if (isbn.length > 4) {
                                                                isbn = isbn[3].trim()
                                                            }
                                                        }
                                                        var qty = '1'
                                                        if (
                                                                $(this, html)
                                                                .find(
                                                                        'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                        )
                                                                .text()
                                                                .trim() !== ''
                                                                ) {
                                                            var qty = $(this, html)
                                                                    .find(
                                                                            'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var OrderItemData = JSON.parse(localStorage.getItem('OrderItemData'))
                                                        console.log(OrderItemData)
                                                        console.log(
                                                                'orderid: ' +
                                                                orderId +
                                                                'title: ' +
                                                                title +
                                                                ' tracking: ' +
                                                                trackingUrl +
                                                                ' isbn: ' +
                                                                isbn +
                                                                ' seller: ' +
                                                                seller +
                                                                ' condition: ' +
                                                                condition +
                                                                ' grandTotal:' +
                                                                grandTotal +
                                                                ' fee:' +
                                                                fee +
                                                                ' shipping:' +
                                                                shipping +
                                                                ' qty: ' +
                                                                qty
                                                                )
                                                        for (var i in OrderItemData) {
                                                            console.log(title, qty, condition, seller)
                                                            if (
                                                                    title == OrderItemData[i].name &&
                                                                    OrderItemData[i].seller == seller &&
                                                                    OrderItemData[i].orderId == undefined
                                                                    ) {
                                                                OrderItemData[i].orderId = orderId
                                                                OrderItemData[i].totalPrice = grandTotal
                                                                OrderItemData[i].fee = fee
                                                                OrderItemData[i].shipping = shipping
                                                                OrderItemData[i].trackingUrl = trackingUrl
                                                                OrderItemData[i].isbn = isbn
                                                                OrderItemData[i].mAd = seller
                                                                OrderItemData[i].adet = qty
                                                                OrderItemData[i].conditionType =
                                                                        OrderItemData[i].condition ?? 'Used - Like New'
                                                                OrderItemData[i].orderCount = orderCount
                                                                console.log(OrderItemData[i])
                                                                localStorage.setItem('OrderItemData', JSON.stringify(OrderItemData))
                                                            }
                                                        }
                                                    })
                                                    $(loader).html(
                                                            `İşleniyor : ${insideCount3 + '/' + Object.keys(OrderItemData).length}`
                                                            )
                                                    resolve()
                                                })
                                                .catch((e) => {
                                                    reject(e)
                                                })
                                    })
                                    )
                        }
                        insideCount++
                    }
                })
                $('div#orderCard').each(function () {
                    if (insideCount2 < Object.keys(OrderItemData).length) {
                        var orderDetailLink = $(this)
                                .find('#orderCardHeader div.a-span-last ul li:nth-child(2)  span  a')
                                .attr('href')
                        localStorage.setItem('checkOrder', false)
                        console.log('https://www.amazon.com' + orderDetailLink)
                        if (orderDetailLink !== undefined) {
                            istek.push(
                                    new Promise((resolve, reject) => {
                                        axios
                                                .get(
                                                        'https://www.amazon.com' + orderDetailLink,
                                                        {},
                                                        {
                                                            headers: {
                                                                cookie: document.cookie,
                                                            },
                                                        }
                                                )
                                                .then((response) => {
                                                    const dataHtml = response.data
                                                    html = $.parseHTML(dataHtml)
                                                    var orderCount = $(
                                                            "#orderDetails div.a-cardui div[data-component='orderCard']  div.a-fixed-left-grid",
                                                            html
                                                            ).length
                                                    console.log(orderCount)
                                                    $(
                                                            "#orderDetails div.a-cardui div[data-component='orderCard'] div.a-fixed-left-grid",
                                                            html
                                                            ).each(function () {
                                                        var orderId = undefined
                                                        var title = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right div:nth-child(1) a.a-link-normal'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        if (title === '' || title === undefined) {
                                                            title = $(this, html)
                                                                    .find('div[data-component="itemTitle"] a')
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var seller = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(3) span  a.a-link-normal:nth-child(1)'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        if (seller === '' || seller === undefined) {
                                                            if (
                                                                    $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(3) > span'
                                                                            )
                                                                    .text()
                                                                    ) {
                                                                seller = $(this, html)
                                                                        .find(
                                                                                'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(3) > span'
                                                                                )
                                                                        .text()
                                                                        .split('Sold by:')[1]
                                                            }
                                                        }
                                                        if (seller === '' || seller === undefined) {
                                                            if (
                                                                    $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(2) > span'
                                                                            )
                                                                    .text()
                                                                    ) {
                                                                seller = $(this, html)
                                                                        .find(
                                                                                'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(2) > span'
                                                                                )
                                                                        .text()
                                                                        .split('Sold by:')[1]
                                                                        .trim()
                                                            }
                                                            seller = $(this, html)
                                                                    .find("div[data-component='orderedMerchant'] a")
                                                                    .text()
                                                        }
                                                        if (seller === '' || seller === undefined) {
                                                            seller = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(2) > span > a'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var condition = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(6) span.a-text-bold'
                                                                        )
                                                                .text()
                                                                .trim()
                                                                .split('Condition:')[1]
                                                        if (condition == '' || condition == undefined) {
                                                            condition = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(6) span:nth-child(2)'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                            if (condition.indexOf('Condition:') > -1) {
                                                                condition = condition.split('Condition:')[1]
                                                            }
                                                        }
                                                        if (condition == '' || condition == undefined) {
                                                            condition = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(7) span.a-text-bold'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                            if (condition.indexOf('Condition:') > -1) {
                                                                condition = condition.split('Condition:')[1]
                                                            }
                                                        }
                                                        if (condition == '' || condition == undefined) {
                                                            condition = $(this, html)
                                                                    .find(
                                                                            'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right  div:nth-child(7) span:nth-child(2)'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                            if (condition.indexOf('Condition:') > -1) {
                                                                condition = condition.split('Condition:')[1]
                                                            }
                                                        }
                                                        if (condition)
                                                            var lastChar = condition[condition.length - 1]
                                                        if (lastChar == '-') {
                                                            condition = condition.trim().slice(0, -2)
                                                        }
                                                        if (condition == '' || condition == undefined) {
                                                            condition = $(this, html)
                                                                    .find('div[data-component="itemCondition"] span:nth-child(2)')
                                                                    .text()
                                                            console.log('Condition2:' + condition)
                                                        }
                                                        var basePrice = $(this, html)
                                                                .find(
                                                                        'div.a-fixed-left-grid-col.yohtmlc-item.a-col-right > div:nth-child(5) span'
                                                                        )
                                                                .text()
                                                                .trim()
                                                        var grandTotal = $(
                                                                '#od-subtotals > div:nth-child(8) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        if (grandTotal === undefined) {
                                                            grandTotal = $(
                                                                    '#od-subtotals > div:nth-child(1) > div > div:nth-child(6) > div.a-column.a-span5.od-line-item-row-content.a-span-last > span',
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        console.log('grandTotal->' + grandTotal)
                                                        var fee = $(
                                                                '#od-subtotals > div:nth-child(6) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        if (fee == undefined) {
                                                            fee = $(
                                                                    '#od-subtotals > div:nth-child(1) > div > div:nth-child(5) > div.a-column.a-span5.od-line-item-row-content.a-span-last > span',
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        console.log('fee->' + fee)
                                                        var shipping = $(
                                                                '#od-subtotals > div:nth-child(3) > div.a-column.a-span5.a-text-right.a-span-last > span',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                                .split('$')[1]
                                                        if (shipping == undefined) {
                                                            shipping = $(
                                                                    '#od-subtotals > div:nth-child(1) > div > div:nth-child(3) > div.a-column.a-span5.od-line-item-row-content.a-span-last > span',
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                                    .split('$')[1]
                                                        }
                                                        console.log('shipping->' + shipping)
                                                        orderId = $(
                                                                '#orderDetails > div:nth-child(3) > div.a-column.a-span9.a-spacing-top-mini > div > span:nth-child(2) > bdi',
                                                                html
                                                                )
                                                                .text()
                                                                .trim()
                                                        var trackingUrl = $('.actions .track-package-button a', html).attr('href')
                                                        let isbn = undefined
                                                        try {
                                                            if (isbn === undefined) {
                                                                let href
                                                                href = $(this, html)
                                                                        .find(
                                                                                'div.a-fixed-right-grid-col.a-col-left div:nth-child(1) a'
                                                                                )
                                                                        .attr('href')
                                                                if (href) {
                                                                    let match = href.match(
                                                                            /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                            )
                                                                    if (match && match[1]) {
                                                                        isbn = match[1].trim()
                                                                    }
                                                                }
                                                                if (href == undefined) {
                                                                    href = $(this, html)
                                                                            .find(
                                                                                    'div.a-fixed-right-grid.a-spacing-top-medium > div > div.a-fixed-right-grid-col.a-col-left > div > div > div > div.a-text-center.a-fixed-left-grid-col.a-col-left > div > a'
                                                                                    )
                                                                            .attr('href')
                                                                    if (href) {
                                                                        let match = href.match(
                                                                                /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                                )
                                                                        if (match && match[1]) {
                                                                            isbn = match[1].trim()
                                                                        }
                                                                    }
                                                                }
                                                                if (href == undefined) {
                                                                    href = $(this, html)
                                                                            .find('div.item-view-left-col-inner a')
                                                                            .attr('href')
                                                                    console.log('href:' + href)
                                                                    if (href) {
                                                                        let match = href.match(
                                                                                /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                                )
                                                                        if (match && match[1]) {
                                                                            isbn = match[1].trim()
                                                                        }
                                                                    }
                                                                }
                                                                if (isbn === undefined) {
                                                                    href = $(this, html)
                                                                            .find(
                                                                                    'div.a-fixed-left-grid-col.a-col-right div:nth-child(1) a'
                                                                                    )
                                                                            .attr('href')
                                                                    if (href) {
                                                                        let match = href.match(
                                                                                /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                                )
                                                                        if (match && match[1]) {
                                                                            isbn = match[1].trim()
                                                                        }
                                                                    }
                                                                }
                                                                if (isbn === undefined) {
                                                                    href = $(this, html)
                                                                            .find(
                                                                                    "div[data-component='itemTitle'] div:nth-child(1) a",
                                                                                    html
                                                                                    )
                                                                            .attr('href')
                                                                    if (href) {
                                                                        let match = href.match(
                                                                                /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                                )
                                                                        if (match && match[1]) {
                                                                            isbn = match[1].trim()
                                                                        }
                                                                    }
                                                                }
                                                                if (isbn === undefined) {
                                                                    href = $(this, html)
                                                                            .find(
                                                                                    "div[data-component='itemImage'] div:nth-child(1) a",
                                                                                    html
                                                                                    )
                                                                            .attr('href')
                                                                    console.log('href:' + href)
                                                                    if (href) {
                                                                        let match = href.match(
                                                                                /\/(?:dp|gp\/product)\/([A-Z0-9]{10,13})/i
                                                                                )
                                                                        if (match && match[1]) {
                                                                            isbn = match[1].trim()
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        } catch (error) {
                                                        }
                                                        console.log('Isbn->' + isbn)
                                                        var qty = '1'
                                                        if (
                                                                $(this, html)
                                                                .find(
                                                                        'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                        )
                                                                .text()
                                                                .trim() !== ''
                                                                ) {
                                                            var qty = $(this, html)
                                                                    .find(
                                                                            'div.a-text-center.a-fixed-left-grid-col.a-col-left > div > span.item-view-qty'
                                                                            )
                                                                    .text()
                                                                    .trim()
                                                        }
                                                        var OrderItemData = JSON.parse(localStorage.getItem('OrderItemData'))
                                                        if (orderId == '' || orderId == undefined) {
                                                            orderId = $(
                                                                    "#orderDetails div.a-cardui  div[data-component='orderId']",
                                                                    html
                                                                    )
                                                                    .text()
                                                                    .trim()
                                                            console.log('OrderID->' + orderId)
                                                        }
                                                        for (var i in OrderItemData) {
                                                            console.log(title, qty, condition, seller, orderId, isbn)
                                                            console.log(OrderItemData[i])
                                                            if (condition == 'Used - Mint')
                                                                condition = 'Used - Like New'
                                                            if (
                                                                    title == OrderItemData[i].name &&
                                                                    orderId != undefined &&
                                                                    isbn != undefined
                                                                    ) {
                                                                if (condition == '' || condition == undefined) {
                                                                    condition = 'Used - Like New'
                                                                }
                                                                OrderItemData[i].orderId = orderId
                                                                OrderItemData[i].totalPrice = grandTotal
                                                                OrderItemData[i].fee = fee
                                                                OrderItemData[i].shipping = shipping
                                                                OrderItemData[i].trackingUrl = trackingUrl
                                                                OrderItemData[i].isbn = isbn
                                                                OrderItemData[i].mAd = OrderItemData[i].seller
                                                                OrderItemData[i].adet = 1
                                                                OrderItemData[i].conditionType = condition ?? 'Used - Like New'
                                                                OrderItemData[i].orderCount = orderCount
                                                                console.log(OrderItemData[i])
                                                                localStorage.setItem('OrderItemData', JSON.stringify(OrderItemData))
                                                            }
                                                        }
                                                    })
                                                    $(loader).html(
                                                            `İşleniyor : ${insideCount2 + '/' + Object.keys(OrderItemData).length}`
                                                            )
                                                    resolve()
                                                })
                                                .catch((e) => {
                                                    reject(e)
                                                })
                                    })
                                    )
                        }
                        insideCount2++
                    }
                })
                Promise.all(istek)
                        .then((values) => {
                            $(loader).html('Kayıt ediliyor!')
                            var OrderItemData = JSON.parse(localStorage.getItem('OrderItemData'))
                            console.table(OrderItemData)
                            console.table(values)
                            chrome.storage.sync.get(['AmzSeller', 'DLastPrice'], function (item) {
                                var MagazaAdi = item.AmzSeller
                                var AbeOrAmazon = 0
                                var SiparisNo = QueryStringOku('purchaseId')
                                var hasInv = hasInvalidRecord(OrderItemData)
                                if (!hasInv) {
                                    console.log('Sipariş Tamamla')
                                    SiparisTamamla(MagazaAdi, SiparisNo, AbeOrAmazon, OrderItemData)
                                }
                                console.log(
                                        'MagazaAdi:' +
                                        MagazaAdi +
                                        ' OrderArray:' +
                                        OrderItemData +
                                        ' SiparisNo:' +
                                        SiparisNo +
                                        ' AbeSaticiNo: ' +
                                        '-' +
                                        'Son Fiyat:' +
                                        item.DLastPrice
                                        )
                            })
                        })
                        .catch((e) => {
                            console.log(e, 'Axios Hatası! Yeni ürüne geçiliyor...')
                            $(loader).remove()
                            setTimeout(function () {
                                UrunGetir()
                            }, 3000)
                        })
            })
        } else {
            window.location.reload();
        }
    });
}
function selectDeliveryOptionIfNeeded() {
    // Delivery option seçilmesi gerekiyor mu kontrol et
    var needsDeliverySelection = false;

    // Hata mesajı kontrolü
    var alertBoxes = document.querySelectorAll('.a-alert-inline-error, .a-alert-error, .a-box.a-alert-error');
    alertBoxes.forEach(function (box) {
        if (box.textContent.indexOf('delivery option') !== -1 ||
                box.textContent.indexOf('select a new delivery') !== -1 ||
                box.textContent.indexOf('delivery options have changed') !== -1) {
            needsDeliverySelection = true;
        }
    });

    // Place your order butonu disabled mi kontrol et
    var placeOrderBtn = document.querySelector('#submitOrderButtonId > span > input');
    var blockerVisible = document.querySelector('#review-order-continue-blocker-tooltip-trigger');
    if (blockerVisible && !blockerVisible.classList.contains('aok-hidden')) {
        needsDeliverySelection = true;
    }

    if (needsDeliverySelection) {
        console.log('Delivery option seçilmesi gerekiyor, ilk seçenek seçiliyor...');

        // İlk checked olmayan veya checked olan radio'yu bul ve seç
        var radioOptions = document.querySelectorAll('.edg-option-in-tango input[type="radio"]');
        if (radioOptions.length > 0) {
            var firstOption = radioOptions[0];
            if (!firstOption.checked) {
                firstOption.click();
                firstOption.dispatchEvent(new Event('change', {bubbles: true}));
                console.log('İlk delivery option seçildi:', firstOption.value);
            } else {
                console.log('Delivery option zaten seçili:', firstOption.value);
            }
        }

        // Alternatif: a-radio div'ini tıkla
        var radioContainers = document.querySelectorAll('.edg-option-in-tango');
        if (radioContainers.length > 0 && radioOptions.length === 0) {
            radioContainers[0].click();
            console.log('Radio container tıklandı');
        }

        return true; // seçim yapıldı, biraz bekle
    }
    return false; // seçim gerekmiyordu
}

function getCheckoutTotalPrice() {
    // 1. Yeni Chewbacca checkout - data-shimmer-target ile fiyat span'i
    // HTML: <span data-shimmer-target="ordertotals-amount">$9.11</span>
    // Bu span hem spc-form içinde hem pyo-block'ta var, son li > order-summary-line-definition altında
    var shimmerVal = null
    // Son li'deki (Order total satırı) shimmer span'i bul
    $('#subtotals-marketplace-table > li:last-child [data-shimmer-target="ordertotals-amount"]').each(function () {
        var txt = $(this).text().trim().replace(/[^0-9.]/g, '')
        var val = parseFloat(parseFloat(txt).toFixed(2))
        if (!isNaN(val) && val > 0) {
            shimmerVal = val
        }
    })
    if (shimmerVal !== null) {
        console.log('getCheckoutTotalPrice: shimmer-target ile bulundu=' + shimmerVal)
        return shimmerVal
    }

    // 2. order-summary-grid içindeki order-summary-line-definition
    var gridVal = null
    $('#subtotals-marketplace-table > li:last-child .order-summary-line-definition').each(function () {
        var txt = $(this).text().trim().replace(/[^0-9.]/g, '')
        var val = parseFloat(parseFloat(txt).toFixed(2))
        if (!isNaN(val) && val > 0) {
            gridVal = val
        }
    })
    if (gridVal !== null) {
        console.log('getCheckoutTotalPrice: order-summary-line-definition ile bulundu=' + gridVal)
        return gridVal
    }

    // 3. grand-total-cell (PYO block alt satır)
    var grandVal = null
    $('.grand-total-cell [data-shimmer-target="ordertotals-amount"]').each(function () {
        var txt = $(this).text().trim().replace(/[^0-9.]/g, '')
        var val = parseFloat(parseFloat(txt).toFixed(2))
        if (!isNaN(val) && val > 0) {
            grandVal = val
        }
    })
    if (grandVal !== null) {
        console.log('getCheckoutTotalPrice: grand-total-cell ile bulundu=' + grandVal)
        return grandVal
    }

    // 4. "Order total" içeren bold satırı tara
    var found = 0
    $('#subtotals-marketplace-table li, #subtotals-marketplace-tango-bottom li').each(function () {
        var row = $(this)
        if (row.find('.order-summary-line-term').text().indexOf('Order total') !== -1 ||
                row.find('.grand-total-cell').length > 0 ||
                row.text().indexOf('Order total') !== -1) {
            var txt = row.find('[data-shimmer-target], .order-summary-line-definition, .grand-total-cell').text().trim().replace(/[^0-9.]/g, '')
            var val = parseFloat(parseFloat(txt).toFixed(2))
            if (!isNaN(val) && val > 0) {
                found = val
            }
        }
    })
    if (found > 0) {
        console.log('getCheckoutTotalPrice: Order total satırı taramayla bulundu=' + found)
        return found
    }

    console.log('getCheckoutTotalPrice: Fiyat okunamadı!')
    return NaN
}

function AmzOrderComplete() {
    var i = 0
    var LastPrice = 0;
    chrome.storage.sync.get(['UrunID', 'UrunFiyat', 'NextPrice', 'CardNumber', 'LastPrice', 'AlinacakStok', 'GercekAlinacakStok'], function (item) {
        setInterval(function () {
            console.log('AmzOrderComplete()' + i + zarar)
            i++

            // Her iterasyonda delivery option kontrolü yap
            if (selectDeliveryOptionIfNeeded()) {
                console.log('Delivery option seçimi yapıldı, bir sonraki iterasyonda devam edilecek...');
                return; // Bu iterasyonu atla, bir sonrakinde devam et
            }

            chrome.storage.local.get(['AdresBilgileri'], function (item) {
                var data = item.AdresBilgileri
            })
            var AdresError = 'An error occurred setting your shipping address. Please try again.'
            var ErrorText = $('.a-alert-content').text()
            var AdresErrorDurum = ErrorText.indexOf(AdresError) !== -1
            if (AdresErrorDurum) {
                $('input[type=submit][aria-labelledby=orderSummaryPrimaryActionBtn-announce]').click()
                $('input[type=submit][aria-labelledby=orderSummaryPrimaryActionBtn-announce]').trigger('click')
            }
            if (document.querySelector("#purchase-level-messages")) {
                let error = document.querySelector("#purchase-level-messages").textContent.trim().indexOf('There was a problem with some of the items in your order');
                if (error > 10 && zarar == 0) {
                    zarar = 1;
                    UrunZararYaz();
                }
            }
            var AdresError1 =
                    'There was a problem with some of the items in your order (see below for more information):'
            var AdresError2 =
                    'Sorry, the quantity you requested is no longer available. We updated your quantity to the maximum available.'
            var ErrorText1 = null
            var AdresErrorDurum1 = false
            if (document.querySelector('.a-color-error')) {
                ErrorText1 = document.querySelector('.a-color-error').textContent
                AdresErrorDurum1 = ErrorText1.indexOf(AdresError1) !== -1
            }
            if (document.querySelector('#changeQuantityFormId span.break-word')) {
                ErrorText1 = document.querySelector('#changeQuantityFormId span.break-word').textContent
                AdresErrorDurum1 = ErrorText1.indexOf(AdresError2) !== -1
            }
            if (AdresErrorDurum1 && zarar == 0) {
                zarar = 1;
                UrunZararYaz()
            }
            if (i == 5 || i == 15 || i == 25) {
                var DLastPrice = getCheckoutTotalPrice()
                var DUrunFiyat = parseFloat(item.LastPrice)
                var DNextPrice = parseFloat(item.NextPrice)
                var limitFiyat = (!isNaN(DUrunFiyat) && DUrunFiyat > 0) ? DUrunFiyat : DNextPrice
                var birimFiyat = DLastPrice / (item.GercekAlinacakStok ? parseInt(item.GercekAlinacakStok) : 1)
                console.log(DLastPrice)
                console.log('birimFiyat: ' + birimFiyat)
                console.log(DUrunFiyat)
                console.log(DNextPrice)
                if (isNaN(DLastPrice)) {
                    console.log('Fiyat okunamadı (NaN), bu iterasyon atlanıyor...')
                } else if (birimFiyat <= limitFiyat) {
                    setOrderItemData()
                } else if (zarar == 0) {
                    zarar = 1;
                    UrunZararYaz();
                }
                $('input[type=submit][aria-labelledby=orderSummaryPrimaryActionBtn-announce]').click()
                $('input[type=submit][aria-labelledby=orderSummaryPrimaryActionBtn-announce]').trigger('click')
                waitForElement('#orderSummaryPrimaryActionBtn', function () {
                    $('#orderSummaryPrimaryActionBtn > span > input').click()
                    $('#orderSummaryPrimaryActionBtn > span > input').trigger('click')
                    $('#orderSummaryPrimaryActionBtn > span > span').click()
                    $('#orderSummaryPrimaryActionBtn > span > span').trigger('click')
                    console.log('continue-top tıkladım!')
                })
                waitForElement('#checkout-secondary-continue-button-id', function () {
                    $('#checkout-secondary-continue-button-id > span > input').click()
                    $('#checkout-secondary-continue-button-id > span > input').trigger('click')
                    $('#checkout-secondary-continue-button-id > span > input').click()
                    $('#checkout-secondary-continue-button-id > span > input').trigger('click')
                    console.log('continue-top tıkladım!')
                })
            }
            if ((i == 10 || i == 20 || i == 30) && zarar == 0) {
                var DLastPrice = getCheckoutTotalPrice()
                var DUrunFiyat = parseFloat(item.LastPrice)
                var DNextPrice = parseFloat(item.NextPrice)
                var limitFiyat = (!isNaN(DUrunFiyat) && DUrunFiyat > 0) ? DUrunFiyat : DNextPrice
                var birimFiyat = DLastPrice / (item.GercekAlinacakStok ? parseInt(item.GercekAlinacakStok) : 1)
                console.log(DLastPrice)
                console.log('birimFiyat: ' + birimFiyat)
                console.log(DUrunFiyat)
                console.log(DNextPrice)
                if (isNaN(DLastPrice)) {
                    console.log('Fiyat okunamadı (NaN), bu iterasyon atlanıyor...')
                } else if (birimFiyat <= limitFiyat) {
                    setOrderItemData()
                    console.log('girdim1')
                    if (document.querySelector('#placeOrder')) {
                        console.log('girdim2')
                        document.querySelector('#placeOrder').click()
                    } else {
                        document.querySelector('#submitOrderButtonId > span > input').click()
                    }
                } else if (zarar == 0) {
                    zarar = 1;
                    UrunZararYaz();
                }
            }
        }, 3000)
        setTimeout(function () {
            waitForElement('#checkout-item-block-panel', function () {

                // Önce delivery option kontrolü yap
                if (selectDeliveryOptionIfNeeded()) {
                    console.log('Delivery option seçimi yapıldı, 3 saniye bekleniyor...');
                    setTimeout(function () {
                        // Seçimden sonra tekrar fiyat kontrolü ve sipariş işlemini başlat
                        AmzOrderComplete();
                    }, 3000);
                    return;
                }

                var DLastPrice = getCheckoutTotalPrice()
                var DUrunFiyat = parseFloat(item.LastPrice)
                var DNextPrice = parseFloat(item.NextPrice)
                var limitFiyat = (!isNaN(DUrunFiyat) && DUrunFiyat > 0) ? DUrunFiyat : DNextPrice
                var birimFiyat = DLastPrice / (item.GercekAlinacakStok ? parseInt(item.GercekAlinacakStok) : 1)
                console.log(DLastPrice)
                console.log('birimFiyat: ' + birimFiyat)
                console.log(DUrunFiyat)
                console.log(DNextPrice)
                if (isNaN(DLastPrice)) {
                    console.log('Fiyat okunamadı (NaN), bu iterasyon atlanıyor...')
                    return
                }
                if (birimFiyat <= limitFiyat && zarar == 0) {
                    setOrderItemData()
                    chrome.storage.sync.set(
                            {
                                Durum: 'SiparisTamamla',
                                DLastPrice: DLastPrice,
                                OrderItemCount: 1,
                            },
                            function () {
                                $('#submitOrderButtonId > span > input').addClass('tikladim1')
                                $('#submitOrderButtonId > span > input').click()
                                $('#submitOrderButtonId > span > input').trigger('click')
                                waitForElement('#placeYourOrder > span > input', function () {
                                    var AdresError1 =
                                            'There was a problem with some of the items in your order (see below for more information):'
                                    var AdresError2 =
                                            'Sorry, the quantity you requested is no longer available. We updated your quantity to the maximum available.'
                                    var ErrorText1 = null
                                    var AdresErrorDurum1 = false
                                    if (document.querySelector('.a-color-error')) {
                                        ErrorText1 = document.querySelector('.a-color-error').textContent
                                        AdresErrorDurum1 = ErrorText1.indexOf(AdresError1) !== -1
                                    }
                                    if (document.querySelector('#changeQuantityFormId span.break-word')) {
                                        ErrorText1 = document.querySelector(
                                                '#changeQuantityFormId span.break-word'
                                                ).textContent
                                        AdresErrorDurum1 = ErrorText1.indexOf(AdresError2) !== -1
                                    }
                                    if (AdresErrorDurum && zarar == 0) {
                                        zarar = 1;
                                        UrunZararYaz();
                                    } else {
                                        $('input[name=placeYourOrder1]').click()
                                        $('input[name=placeYourOrder1]').trigger('click')
                                        $('#submitOrderButtonId').addClass('isa1')
                                        $('#submitOrderButtonId').trigger('click')
                                        $('#submitOrderButtonId > span').click()
                                        $('#submitOrderButtonId > span').trigger('click')
                                        $('#submitOrderButtonId > span > input').click()
                                        $('#submitOrderButtonId > span > input').trigger('click')
                                        $('#submitOrderButtonId > span > input').addClass('tikladim2')
                                        console.log('AmzOrderComplete Button tıkladım')
                                        setTimeout(function () {
                                            $('.tikladim2').click()
                                            $('.tikladim2').trigger('click')
                                            $('.tikladim1').click()
                                            $('.tikladim1').trigger('click')
                                        }, 10000)
                                    }
                                })
                                console.log('AmzOrderComplete Button tıklanacak')
                            }
                    )
                } else {
                    console.log('AmzOrderComplete() son fiyat ile istenilen fiyattan fazla')
                    if (zarar == 0) {
                        zarar++
                        UrunZararYaz(DLastPrice)
                    }
                }
            })
        }, 3000)
    })
}
function AmzSiparisTamamla() {
    chrome.storage.sync.get(['AmzSeller', 'DLastPrice'], function (item) {
        console.log('AmzSiparisTamamla()')
        var urlu = window.location.href
        if (urlu === 'https://www.amazon.com/gp/buy/duplicate-order/handlers/display.html?hasWorkingJavascript=1') {
            $('input[name=forcePlaceOrder]').click()
            $('input[name=forcePlaceOrder]').trigger('click')
        } else {
            var MagazaAdi = item.AmzSeller
            var AbeOrAmazon = 0
            var SiparisNo = QueryStringOku('purchaseId')
            SayfaGit('https://www.amazon.com/gp/css/order-history', 1)
        }
    })
}
function SiparisTamamla(MagazaAdi, SiparisNo, AbeOrAmazon, orderArray) {
    chrome.storage.sync.get(['MagazaAdi', 'UrunID', 'PcName', 'DLastPrice', 'UrunFiyat', 'ApiUrl'], function (item) {
        PcName = item.PcName
        if (MagazaAdi == '')
            MagazaAdi = 'ThriftBooks'
        var datam = {
            ID: item.UrunID,
            magazaDeger: item.MagazaAdi,
            tip: 'newOrderManuelEnd',
            MAd: MagazaAdi,
            SipNo: SiparisNo,
            MTip: 0,
            PCAd: PcName,
            Price: item.DLastPrice,
            OurPrice: item.UrunFiyat,
            OrderArray: orderArray,
        }
        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,
            timeout: 500000,
            success: function (cevap) {
                console.log(cevap)
                if (cevap.hata === '0') {
                    console.log('Hata: Sipariş Bilgileri Gönderilemedi!')
                } else {
                    if (cevap.result === 1) {
                        $('.extDialog').remove()
                        dialogModal('Kayıt tamamlandı!. Yeni siparişe geçiliyor.')
                        console.log(cevap.result)
                        console.log('Sipariş bilgileri gönderildi')
                        setTimeout(function () {
                            UrunGetir()
                        }, 2000)
                    } else {
                        setTimeout(function () {
                            console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                            window.location.reload()
                        }, 5000)
                    }
                }
                console.log('Sipariş Tamamla Response!')
            },
            error: function (req, textStatus, errorThrown) {
                console.log('Ooops, something happened: ' + textStatus + ' ' + errorThrown)
                setTimeout(function () {
                    console.log('Yeni Ürüne Geçilecek! UrunListeleriniGonder()')
                    window.location.reload()
                }, 5000)
            },
        })
    })
}
function DuplicateOrderComplete() {
    if (document.querySelector('input[name=forcePlaceOrder]'))
        document.querySelector('input[name=forcePlaceOrder]').click()
    if (document.querySelector('#placeOrder'))
        document.querySelector('#placeOrder').click()
}
function AmzItemNotAdded() {
    console.log('AmzItemNotAdded()')
    var SepetCount = $('#nav-cart-count').text()
    console.log(SepetCount)
    if (SepetCount != undefined && SepetCount.length > 0) {
        if (parseInt(SepetCount) == 1) {
            AmzBasketPage()
        }
    }
    var isNotAdded = $('#huc-v2-order-row-confirm-text').text().trim()
    var CartIsEmpty = ''
    if (document.querySelector('#sc-active-cart h1'))
        var CartIsEmpty = document.querySelector('#sc-active-cart h1').textContent.trim()
    if (document.querySelector('#activeCartViewForm > div > h2.a-spacing-mini.a-spacing-top-base.sc-empty-cart-header'))
        var CartIsEmpty = document
                .querySelector('#activeCartViewForm > div > h2.a-spacing-mini.a-spacing-top-base.sc-empty-cart-header')
                .textContent.trim()
    if (
            document.querySelector(
                    '#sc-active-cart > div > div.a-column.a-span8.a-span-last > div.a-row.sc-your-amazon-cart-is-empty > h2'
                    )
            )
        var CartIsEmpty = document
                .querySelector(
                        '#sc-active-cart > div > div.a-column.a-span8.a-span-last > div.a-row.sc-your-amazon-cart-is-empty > h2'
                        )
                .textContent.trim()
    console.log(CartIsEmpty)
    if (isNotAdded == 'Not added') {
        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 (CartIsEmpty === 'Your Amazon Cart is empty.') {
        var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
        var params = 'PgNm=Amz&Sil=True'
        var link = amzlink + params
        console.log(link)
        SayfaGit(link, 1)
    } else if (CartIsEmpty == 'Your Amazon Cart is empty') {
        var amzlink = 'https://www.amazon.com/gp/cart/view.html?'
        var params = 'PgNm=Amz&Sil=True'
        var link = amzlink + params
        SayfaGit(link, 1)
    }
}
async function HataKontrolYap(time, msj2) {
    HataKontrol = setTimeout(async function () {
        chrome.storage.local.get(['isStarted', 'PcName', 'Durum', 'UrunID', 'MagazaAdi'], function (item) {
            chrome.storage.sync.get(['Durum'], function (itemSync) {
                try {
                    if (itemSync.Durum == 'SiparisTamamla') {
                        chrome.storage.sync.set({Durum: 'FiyatKontrol'})
                    }
                    var aciklama = ''
                    if (msj2 == undefined) {
                        aciklama = ''
                    } else {
                        aciklama = 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)
                    var host = window.location.host
                    chrome.runtime.sendMessage({
                        HataYenile: true,
                    })
                } catch (e) {
                    if (itemSync.Durum == 'SiparisTamamla') {
                        chrome.storage.sync.set({Durum: 'FiyatKontrol'})
                    }
                    window.location.reload();
                }
            })
        })
    }, parseInt(time) * 1000)
}
function SekmeBilgileriGonder() {
    chrome.runtime.sendMessage({
        AktifSekmeBilgileri: true,
    })
}
function isAmazonDogPage() {
    const title = document.title.toLowerCase()
    return title.includes('page not found') || title.includes('sorry') || title.includes('went wrong')
}
function isCaptchaPage() {
    return document.querySelector('form[action="/errors/validateCaptcha"]') !== null
            || document.querySelector('#captchacharacters') !== null
            || document.title.toLowerCase().includes('robot check')
            || window.location.pathname.startsWith('/challenge/captcha')
            || document.querySelector('form[action="/challenge/validateCaptcha"]') !== null
}
function handleCaptchaPage() {
    console.log('CAPTCHA sayfası tespit edildi, Continue shopping butonuna tıklanıyor...')

    var challengeBtn = document.querySelector('#a-autoid-0-announce')
            || document.querySelector('button[alt="Continue shopping"]')
            || document.querySelector('form#captchaForm button[type="submit"]')

    if (challengeBtn) {
        console.log('Continue shopping butonu bulundu, tıklanıyor...')
        challengeBtn.click()
        setTimeout(function () {
            if (isCaptchaPage()) {
                console.log('Hâlâ CAPTCHA sayfasında, tekrar deneniyor...')
                handleCaptchaPage()
            } else {
                console.log('CAPTCHA geçildi, UrunGetir çağrılıyor...')
                UrunGetir()
            }
        }, 8000)
    } else {
        console.log('CAPTCHA butonu bulunamadı, 5 saniye sonra tekrar denenecek...')
        setTimeout(function () {
            if (isCaptchaPage()) {
                handleCaptchaPage()
            } else {
                UrunGetir()
            }
        }, 5000)
    }
}
function setOrderItemData() {
    var orderItemData = {}
    var orderItemCount = 0
    var newD = false
    if (document.querySelector('#header > div > div.a-column.a-span8 > h1 > span > span > span > span')) {
        orderItemCount = parseInt(
                document
                .querySelector('#header > div > div.a-column.a-span8 > h1 > span > span > span > span')
                .textContent.split(' ')[0]
                )
    }
    console.log(orderItemCount)
    if (orderItemCount == 0) {
        newD = true
        orderItemCount = $('.lineitem-container').length
    }
    if (orderItemCount > 10) {
        alert(
                'Lütfen sepeti içerisindeki ürün adeti 10 veya daha küçük olmalıdır aksi takdirde hata oluşacaktır. Sepet içerisinde ürün sayısını azaltıp sayfayı yenileyiniz.'
                )
    }
    var cnt = 0
    if (!newD) {
        $('#spc-orders div.a-box-inner .item-row').each(function () {
            var seller = $(this)
                    .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(5) > span')
                    .text()
                    .trim()
                    .split('Sold by:')[1]
            if (seller == undefined) {
                seller = $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(6) > span')
                        .text()
                        .trim()
                        .split('Sold by:')[1]
            }
            if (seller == undefined) {
                seller = $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(4) > span')
                        .text()
                        .trim()
                        .split('Sold by:')[1]
            }
            console.log(seller)
            if (seller !== undefined) {
                var condition = undefined
                if (
                        $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(6) span')
                        .text()
                        .trim() != '' &&
                        condition == undefined
                        )
                    condition = $(this)
                            .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(6) span')
                            .text()
                            .trim()
                            .split('Condition:')[1]
                if (
                        $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(7) span')
                        .text()
                        .trim() != '' &&
                        condition == undefined
                        )
                    condition = $(this)
                            .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(7) span')
                            .text()
                            .trim()
                            .split('Condition:')[1]
                if (
                        $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(8) span')
                        .text()
                        .trim() != '' &&
                        condition == undefined
                        )
                    condition = $(this)
                            .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right  div:nth-child(8) span')
                            .text()
                            .trim()
                            .split('Condition:')[1]
                var title = $(this)
                        .find(
                                'div.a-fixed-left-grid-col.item-details-right-column.a-col-right > div.a-row.breakword > span'
                                )
                        .text()
                var price = $(this)
                        .find('div.a-fixed-left-grid-col.item-details-right-column.a-col-right span.a-color-price span')
                        .text()
                var quantity = $(this).find('span.a-dropdown-prompt').text().trim()
                orderItemData[cnt] = {}
                orderItemData[cnt].seller = seller
                orderItemData[cnt].condition = condition
                orderItemData[cnt].quantity = quantity
                orderItemData[cnt].name = title.trim()
                orderItemData[cnt].price = price.trim().split('$')[1]
                cnt++
            }
        })
        console.table(orderItemData)
        localStorage.setItem('OrderItemData', JSON.stringify(orderItemData))
        chrome.storage.local.set(
                {
                    OrderItemData: JSON.stringify(orderItemData),
                },
                function () {}
        )
        document.querySelector('#submitOrderButtonId-announce').textContent = 'Siparişi Tamamla'
        chrome.storage.local.get('OrderItemData', function (itemm) {
            'OrderItemData'
            console.log(itemm.OrderItemData)
        })
    } else {
        $('.lineitem-container').each(function () {
            var seller = removeRepeatingSubstring($(this).find('.lineitem-seller-section a span').text().trim())
            var quantity = $(this).find('.a-box-inner .a-row:nth-child(2) div span:nth-child(2)').text().trim()
            var title = $(this).find('.lineitem-title-text').text().trim()
            var price = $(this).find('.lineitem-price-text').text().trim().split('$')[1]
            var condition = 'Used - Like New'
            orderItemData[cnt] = {}
            orderItemData[cnt].seller = seller
            orderItemData[cnt].condition = condition
            orderItemData[cnt].quantity = quantity
            orderItemData[cnt].name = title
            orderItemData[cnt].price = price
            cnt++
            console.table(orderItemData)
            localStorage.setItem('OrderItemData', JSON.stringify(orderItemData))
            chrome.storage.local.set(
                    {
                        OrderItemData: JSON.stringify(orderItemData),
                    },
                    function () {}
            )
            document.querySelector('#submitOrderButtonId-announce').textContent = 'Siparişi Tamamla'
            chrome.storage.local.get('OrderItemData', function (itemm) {
                'OrderItemData'
                console.log(itemm.OrderItemData)
            })
        })
    }
}
function SayfaGit(adres, time) {
    setTimeout(function () {
        window.location.href = adres
    }, parseInt(time) * 1000)
}
function clearAmazonCacheFromContent() {
    return new Promise((resolve) => {
        chrome.runtime.sendMessage({action: 'clearAmazonCache'}, (response) => {
            if (response && response.success) {
                console.log('Amazon cache temizliği content.js tarafından tetiklendi.')
            }
            resolve()
        })
    })
}
function SekmeAc(link) {
    setTimeout(function () {
        console.log('Sekme Açılıyor: ' + link)
        chrome.runtime.sendMessage({
            YeniSekme: true,
            Url: link,
        })
    }, 200)
}
function SekmeKapat(sure) {
    setTimeout(function () {
        chrome.runtime.sendMessage({
            SekmeKapat: true,
        })
    }, sure * 1000)
}
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 waitForElement(elementPath, callBack, timeout, onTimeout) {
    var start = timeout ? Date.now() : null
    function check() {
        if ($(elementPath).text().length > 0) {
            callBack(elementPath, $(elementPath))
        } else if (timeout && (Date.now() - start) >= timeout) {
            console.log('waitForElement timeout: ' + elementPath)
            if (typeof onTimeout === 'function')
                onTimeout()
        } else {
            window.setTimeout(check, 100)
        }
    }
    window.setTimeout(check, 100)
}
function removeRepeatingSubstring(str) {
    let match = str.match(/^(.+?)\1+$/)
    if (match) {
        return match[1]
    }
    return str
}
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).css('padding', '10px 10px 10px 10px')
    $(loader).html(message)
    document.body.append(loader)
    return loader
}
function hasInvalidRecord(data) {
    const dataArray = Object.values(data)
    return dataArray.some(
            (item) => !('orderId' in item) || item.orderId === null || item.orderId === undefined || item.orderId === ''
    )
}
function AmzSepetAdetArttir(hedefAdet, callback) {
    console.log('AmzSepetAdetArttir() hedef adet: ' + hedefAdet)

    var aktifItem = document.querySelector('[data-itemtype="active"]')
    if (!aktifItem) {
        console.log('Aktif sepet item bulunamadı, devam ediyor.')
        callback()
        return
    }

    // Stok kısıtı kontrolü — sc-product-scarcity içindeki rakamı oku
    var scarcityEl = aktifItem.querySelector('span.sc-product-scarcity')
    if (scarcityEl) {
        var scarcityText = scarcityEl.textContent.trim()
        console.log('sc-product-scarcity bulundu: "' + scarcityText + '"')
        var scarcityMatch = scarcityText.match(/Only (\d+) left/i)
        if (scarcityMatch) {
            var scarcityAdet = parseInt(scarcityMatch[1])
            console.log('Stokta ' + scarcityAdet + ' adet var')
            if (scarcityAdet < hedefAdet) {
                console.log('Hedef adet (' + hedefAdet + ') stoktan (' + scarcityAdet + ') fazla, hedef ' + scarcityAdet + ' olarak güncellendi.')
                hedefAdet = scarcityAdet
            } else {
                console.log('Stok yeterli (' + scarcityAdet + ' >= ' + hedefAdet + '), devam ediyor.')
            }
        } else {
            console.log('Stok metni sayısal değil, devam ediyor: "' + scarcityText + '"')
        }
    }

    // Mevcut adeti oku
    var innerValueEl = aktifItem.querySelector('span[data-a-selector="inner-value"]')
    var mevcutAdet = innerValueEl ? parseInt(innerValueEl.textContent.trim()) : 1
    console.log('Mevcut adet: ' + mevcutAdet + ' Hedef: ' + hedefAdet)

    if (mevcutAdet >= hedefAdet) {
        console.log('Adet zaten yeterli, devam ediyor.')
        callback()
        return
    }

    var tiklanacakSayisi = hedefAdet - mevcutAdet
    var tiklanandi = 0

    function tikla() {
        // Döngü içinde scarcity kontrolü — tıklama sonrası stok limitine ulaşıldı mı
        var itemCheck = document.querySelector('[data-itemtype="active"]')
        var scarcityCheck = itemCheck ? itemCheck.querySelector('span.sc-product-scarcity') : null
        if (scarcityCheck) {
            var scarcityTextLoop = scarcityCheck.textContent.trim()
            var matchLoop = scarcityTextLoop.match(/Only (\d+) left/i)
            if (matchLoop) {
                var scarcityAdetLoop = parseInt(matchLoop[1])
                var innerNow = itemCheck.querySelector('span[data-a-selector="inner-value"]')
                var mevcutNow = innerNow ? parseInt(innerNow.textContent.trim()) : 0
                if (mevcutNow >= scarcityAdetLoop) {
                    console.log('Stok limitine ulaşıldı (' + scarcityAdetLoop + ' adet). Devam ediyor.')
                    setTimeout(callback, 1000)
                    return
                }
            }
        }

        // Amazon limit uyarısı — kesin selector: input[name="imb-type"][value="quantityUnavailable"]
        var limitMsg = document.querySelector('input[name="imb-type"][value="quantityUnavailable"]')
        if (limitMsg) {
            console.log('Amazon quantityUnavailable uyarısı geldi, maksimuma ulaşıldı. Devam ediyor.')
            setTimeout(callback, 1000)
            return
        }

        if (tiklanandi >= tiklanacakSayisi) {
            console.log('Adet artırma tamamlandı (' + hedefAdet + ' adet). Devam ediyor.')
            setTimeout(callback, 1500)
            return
        }

        var item = document.querySelector('[data-itemtype="active"]')
        if (!item) {
            console.log('Aktif item kayboldu, devam ediyor.')
            setTimeout(callback, 1000)
            return
        }

        var btn = item.querySelector('button[data-action="a-stepper-increment"]')
        if (!btn) {
            console.log('+ butonu bulunamadı, devam ediyor.')
            setTimeout(callback, 1000)
            return
        }

        if (btn.disabled || btn.getAttribute('aria-disabled') === 'true') {
            console.log('+ butonu disabled, limite ulaşıldı. Devam ediyor.')
            setTimeout(callback, 1000)
            return
        }

        btn.click()
        tiklanandi++
        console.log('+ butonuna tıklandı (' + tiklanandi + '/' + tiklanacakSayisi + ')')
        setTimeout(tikla, 2000)
    }

    tikla()
}