// ─── BookDepot content.js ─────────────────────────────────────────────────────
var HataDurum = false
var isStarted
var logs = ['Loglar']
var log = ''
var MagazaAdi = ''

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if (message.Link) {
        window.location.reload();
        setTimeout(function () {
            window.location.reload()
        }, 1000)
    }
    if (message.UygulamaBaslatildi) {
        SekmeBilgileriGonder()
    }
    if (message.PageReload) {
        window.location.reload();
        setTimeout(function () {
            window.location.reload()
        }, 1000)
    }
    if (message.SekmeBulunamadi) {
        HataKontrolYap(1, "Extension sekmesi bulunamadı!")
    }
})

$(document).ready(function () {
    chrome.storage.sync.get(
            ['isStarted', 'UrunGetirildi', 'Durum', 'MagazaAdi', 'RequestTime'],
            function (item) {
                setTimeout(async function () {
                    if (item.isStarted == true) {
                        MagazaAdi = item.MagazaAdi
                        if (item.UrunGetirildi == false) {
                            chrome.storage.sync.set(
                                    {UrunGetirildi: true, Durum: 'TypeKontrol'},
                                    function () {
                                        BirinciLinkKontrol()
                                    }
                            )
                            SekmeBilgileriGonder()
                        } else {
                            if (item.Durum == 'TypeKontrol') {
                                BirinciLinkKontrol()
                            }
                        }
                    }
                }, parseInt(item.RequestTime) * 1000)
            }
    )
})

// ─── Fiyat Aralıkları: $1-$10, $11-$20, $21-$30, $31-$40, $41-$120 ──────────
// BookDepot URL'de cent: Np=100-1000 → $1-$10
var PRICE_RANGES = [
    { label: '$1-$10',  urlParam: '100-1000'  },
    { label: '$11-$15', urlParam: '1100-1500' },
    { label: '$15-$100',urlParam: '1500-10000' }
]

// ─── Tüm Kategoriler (HTML'den çıkarılan sabit liste, value=Nc parametresi) ───
var ALL_CATEGORIES = [
    {id: '5', name: 'Biography & Autobiography'},
    {id: '12', name: 'Children Fiction'},
    {id: '13', name: 'Children Nonfiction'},
    {id: '31', name: 'Fiction'},
    {id: '39', name: 'History & Geography'},
    {id: '71', name: 'Religion & Spirituality'},
    {id: '73', name: 'Self-Help'},
    {id: '84', name: 'Tweens Fiction'},
    {id: '85', name: 'Tweens Nonfiction'},
    {id: '88', name: 'Young Adult Fiction'},
    {id: '1', name: 'Antiques & Collectibles'},
    {id: '2', name: 'Architecture'},
    {id: '3', name: 'Art'},
    {id: '6', name: 'Body, Mind & Spirit'},
    {id: '9', name: 'Business & Economics'},
    {id: '10', name: 'Calendars'},
    {id: '17', name: 'Comics & Graphic Novels'},
    {id: '18', name: 'Computers & Internet'},
    {id: '21', name: 'Cooking, Food & Wine'},
    {id: '22', name: 'Crafts & Hobbies'},
    {id: '92', name: 'Design'},
    {id: '24', name: 'Drama'},
    {id: '26', name: 'Education'},
    {id: '29', name: 'Family & Relationships'},
    {id: '32', name: 'Foreign Language Study'},
    {id: '33', name: 'Games'},
    {id: '34', name: 'Gardening'},
    {id: '37', name: 'Health & Fitness'},
    {id: '41', name: 'House & Home'},
    {id: '42', name: 'Humor'},
    {id: '43', name: 'Language Arts & Disciplines'},
    {id: '45', name: 'Law'},
    {id: '47', name: 'Literary Collections'},
    {id: '48', name: 'Literary Criticism'},
    {id: '51', name: 'Mathematics'},
    {id: '52', name: 'Medical'},
    {id: '53', name: 'Music'},
    {id: '55', name: 'Nature & Outdoors'},
    {id: '60', name: 'Performing Arts'},
    {id: '62', name: 'Pets'},
    {id: '63', name: 'Philosophy'},
    {id: '64', name: 'Photography'},
    {id: '66', name: 'Poetry'},
    {id: '67', name: 'Political Science'},
    {id: '68', name: 'Psychology'},
    {id: '70', name: 'Reference'},
    {id: '72', name: 'Science'},
    {id: '74', name: 'Social Science'},
    {id: '76', name: 'Sports & Recreation'},
    {id: '77', name: 'Stationery'},
    {id: '78', name: 'Study Aids'},
    {id: '79', name: 'Technology'},
    {id: '95', name: 'Toys & Activities'},
    {id: '81', name: 'Transportation'},
    {id: '82', name: 'Travel'},
    {id: '83', name: 'True Crime'},
    {id: '89', name: 'Young Adult Nonfiction'}
]

// ─── UI ───────────────────────────────────────────────────────────────────────
function dialogModal(message, background) {
    background = background || 'limegreen'
    $('.extDialog').remove()
    var loader = document.createElement('div')
    $(loader).addClass('extDialog')
    $(loader).css({
        position: 'fixed', width: '220px', height: 'auto', minHeight: '120px',
        background: background, color: '#fff', overflowWrap: 'anywhere',
        fontWeight: 'bold', bottom: '10px', right: '10px', zIndex: '9999',
        display: 'flex', justifyContent: 'center', alignItems: 'center',
        textAlign: 'center', borderRadius: '12px', padding: '10px',
        fontSize: '13px', lineHeight: '1.5', boxShadow: '0 4px 12px rgba(0,0,0,0.3)'
    })
    $(loader).html(message)
    document.body.append(loader)
    return loader
}

// ─── Scroll ───────────────────────────────────────────────────────────────────
async function scrollSayfayiYukle() {
    return new Promise(function (resolve) {
        var distance = 400
        var scrolled = 0
        var maxScroll = Math.max(document.body.scrollHeight, 3000)
        var done = false

        function finish() {
            if (done)
                return
            done = true
            clearInterval(timer)
            clearTimeout(safety)
            window.scrollTo(0, 0)
            setTimeout(function () {
                resolve()
            }, 4000)
        }

        var timer = setInterval(function () {
            window.scrollBy(0, distance)
            scrolled += distance
            if (scrolled >= maxScroll) {
                finish()
            }
        }, 200)

        var safety = setTimeout(function () {
            finish()
        }, 15000)
    })
}

// ─── URL Yardımcıları ─────────────────────────────────────────────────────────
// BookDepot URL formatı: /Store/Browse?Nc=5&Np=100-1000&size=96&sort=arrival_1&page=2

function buildUrl(categoryId, priceUrlParam, pageNum) {
    var base = 'https://www.bookdepot.com/Store/Browse'
    var url = base + '?Nc=' + categoryId
    url += '&Np=' + priceUrlParam
    url += '&size=96&sort=arrival_1'
    if (pageNum > 1) {
        url += '&page=' + pageNum
    }
    return url
}

function getCurrentPageFromUrl(url) {
    var m = url.match(/[?&]page=(\d+)/)
    return m ? parseInt(m[1]) : 1
}

function getTotalPages() {
    var strong = document.querySelector("div.col-md-12 strong")
    if (strong) {
        var m = strong.textContent.match(/Page\s+\d+\s+of\s+(\d+)/)
        if (m)
            return parseInt(m[1])
    }
    return 9999
}

function isPageBeyondTotal() {
    var current = getCurrentPageFromUrl(window.location.href)
    var total = getTotalPages()
    return current > total
}

function hasNextPage() {
    // 1. Mevcut sayfa toplam sayfadan büyükse → son sayfa aşıldı
    if (isPageBeyondTotal())
        return false

    // 2. "No refinements available." varsa kesinlikle son sayfa
    var facets = document.querySelector('div#facets')
    if (facets && facets.innerText.includes('No refinements available'))
        return false

    // 3. "Page X of 0 - 0 results" → boş sayfa
    var strong = document.querySelector('div.col-md-12 strong')
    if (strong && /of\s+0\s*-\s*0\s+results/i.test(strong.textContent))
        return false

    // 4. Pagination'da » (Next) linki var mı?
    var found = false
    document.querySelectorAll('ul.pagination li a').forEach(function (a) {
        var label = a.getAttribute('aria-label') || ''
        var span = a.querySelector('span')
        if (label === 'Next' || (span && span.textContent.trim() === '»')) {
            if (!$(a).parent().hasClass('disabled'))
                found = true
        }
    })
    return found
}

function noBooksFound() {
    // 1. Mevcut sayfa toplam sayfadan büyükse → geç
    if (isPageBeyondTotal())
        return true

    // 2. "No refinements available." — sayfa tamamen boş
    var facets = document.querySelector('div#facets')
    if (facets && facets.innerText.includes('No refinements available'))
        return true

    // 3. "0 - 0 results"
    var strong = document.querySelector('div.col-md-12 strong')
    if (strong && /of\s+0\s*-\s*0\s+results/i.test(strong.textContent))
        return true

    // 4. Hiç ISBN yoksa
    var isbns = document.querySelectorAll('span.small')
    for (var i = 0; i < isbns.length; i++) {
        if (isbns[i].textContent.includes('ISBN:'))
            return false
    }
    return true
}

// ─── ISBN & Fiyat Parse ───────────────────────────────────────────────────────
// BookDepot HTML: <span class="small">ISBN: 9781645196198</span>
// Fiyat:  <strike>$4.00</strike> <strong>$2.13</strong>  veya  sadece $2.50
// Her kitap bloğu: div#addwf-{ISBN} ile ayrılmış

function extractIsbnDataFromDOM() {
    var results = []
    var seen = {}

    // ISBN içeren span'ları bul
    document.querySelectorAll('span.small').forEach(function (span) {
        var text = span.textContent.trim()
        if (!text.startsWith('ISBN:'))
            return

        var isbn = text.replace('ISBN:', '').trim()
        if (!isbn || seen[isbn])
            return
        seen[isbn] = true

        // Bu span'ın ata kart elementini bul (genel olarak ortak parent div)
        var card = span
        for (var i = 0; i < 6; i++) {
            card = card.parentElement
            if (!card)
                break
            if (card.tagName === 'DIV' && (card.classList.contains('col-xs-6') ||
                    card.classList.contains('col-sm-4') || card.classList.contains('col-md-3') ||
                    card.classList.contains('item')))
                break
        }

        // Fiyat çek — önce kırmızı indirimli fiyat (color:#d1282f), yoksa normal span
        var price = null
        if (card) {
            var strongEl = card.querySelector('strong')
            if (strongEl) {
                // İndirimli fiyat: <span style="color:#d1282f">$1.75</span>
                var redSpan = strongEl.querySelector('span[style*="d1282f"]')
                if (redSpan) {
                    var m = redSpan.textContent.match(/\$([0-9.]+)/)
                    if (m)
                        price = parseFloat(m[1])
                }
                // Normal fiyat: tek span içinde
                if (price === null) {
                    var m2 = strongEl.textContent.match(/\$([0-9.]+)/)
                    if (m2)
                        price = parseFloat(m2[1])
                }
            }
        }

        results.push({asin: isbn, price: price, condition: 'New'})
    })

    console.log('[BookDepot] ' + results.length + ' ISBN bulundu')
    return results
}

// ─── Servise Gönder ───────────────────────────────────────────────────────────
async function SiparisTamamla(dataArray) {
    if (dataArray.length === 0) {
        console.log('[BookDepot] Bu sayfada ISBN yok, devam...')
        return
    }
    chrome.storage.sync.get(["MagazaAdi", "UrunID", "ApiUrl"], function (item) {
        var datam = {
            AsinArray: dataArray.map(function (x) {
                return x.asin
            }),
            FiyatArray: dataArray.map(function (x) {
                return x.price
            }),
            ConditionArray: dataArray.map(function (x) {
                return x.condition
            }),
            magazaDeger: item.MagazaAdi,
            tip: "newAsinEnd"
        }
        $.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) {
                if (cevap.hata == 0 || cevap.hata === "0") {
                    console.log('[BookDepot] Servis OK: ' + cevap.hatatext)
                } else {
                    console.log('[BookDepot] Servis cevap: ' + JSON.stringify(cevap))
                }
            },
            error: function (req, textStatus, errorThrown) {
                console.log('[BookDepot] Ajax hata:', textStatus, errorThrown)
            }
        })
    })
}

// ─── Sonraki Geçişi Hesapla ───────────────────────────────────────────────────
function hesaplaGecis(catIdx, priceIdx) {
    var nextCat = catIdx + 1
    var nextPrice = priceIdx

    if (nextCat >= ALL_CATEGORIES.length) {
        nextCat = 0
        nextPrice = priceIdx + 1
        if (nextPrice >= PRICE_RANGES.length) {
            nextPrice = 0
            console.log('[BookDepot] Tüm fiyat ve kategoriler tamamlandı, başa dönülüyor...')
        }
    }
    return {catIdx: nextCat, priceIdx: nextPrice}
}

// ─── Ana Döngü ────────────────────────────────────────────────────────────────
async function BirinciLinkKontrol() {
    chrome.storage.sync.get(
            ['LastIndex', 'SearchUrl', 'CurrentCategoryIndex', 'CurrentPriceIndex'],
            async function (item) {

                var categoryIndex = parseInt(item.CurrentCategoryIndex) || 0
                var priceIndex = parseInt(item.CurrentPriceIndex) || 0

                // Sınır kontrolü
                if (categoryIndex >= ALL_CATEGORIES.length)
                    categoryIndex = 0
                if (priceIndex >= PRICE_RANGES.length)
                    priceIndex = 0

                var currentCategory = ALL_CATEGORIES[categoryIndex]
                var currentPrice = PRICE_RANGES[priceIndex]
                var currentPage = getCurrentPageFromUrl(window.location.href)
                if (currentPage < 1)
                    currentPage = 1

                var loader = dialogModal('Başlatılıyor...')

                console.log('[BookDepot] Kat: ' + currentCategory.name +
                        ' (' + (categoryIndex + 1) + '/' + ALL_CATEGORIES.length + ')' +
                        ' | Fiyat: ' + currentPrice.label +
                        ' | Sayfa: ' + currentPage)

                $(loader).html(
                        '💰 ' + currentPrice.label + '<br>' +
                        '📂 ' + currentCategory.name + '<br>' +
                        'Kat: ' + (categoryIndex + 1) + '/' + ALL_CATEGORIES.length + '<br>' +
                        'Sayfa: ' + currentPage + '<br>' +
                        'Scroll yapılıyor...'
                        )

                // ── 1. Kitap yok kontrolü ─────────────────────────────────────────────
                if (noBooksFound()) {
                    console.log('[BookDepot] Kitap yok, sonraki kategoriye...')
                    var next = hesaplaGecis(categoryIndex, priceIndex)
                    var reqTime = Math.floor(Math.random() * 9) + 6

                    $(loader).html(
                            '⚠️ Kitap yok!<br>' +
                            currentCategory.name + '<br>' +
                            'Sonraki: ' + ALL_CATEGORIES[next.catIdx].name + '<br>' +
                            reqTime + 's bekleniyor...'
                            )

                    chrome.storage.sync.set({
                        LastIndex: 1,
                        CurrentCategoryIndex: next.catIdx,
                        CurrentPriceIndex: next.priceIdx
                    })
                    await new Promise(function (r) {
                        setTimeout(r, reqTime * 1000)
                    })
                    window.location.href = buildUrl(
                            ALL_CATEGORIES[next.catIdx].id,
                            PRICE_RANGES[next.priceIdx].urlParam,
                            1
                            )
                    return
                }

                // ── 2. Scroll ─────────────────────────────────────────────────────────
                await scrollSayfayiYukle()

                $(loader).html(
                        '💰 ' + currentPrice.label + '<br>' +
                        '📂 ' + currentCategory.name + '<br>' +
                        'Kat: ' + (categoryIndex + 1) + '/' + ALL_CATEGORIES.length + '<br>' +
                        'Sayfa: ' + currentPage + '<br>' +
                        'ISBN çekiliyor...'
                        )

                // ── 3. ISBN & Fiyat çek ───────────────────────────────────────────────
                var results = extractIsbnDataFromDOM()

                $(loader).html(
                        '💰 ' + currentPrice.label + '<br>' +
                        '📂 ' + currentCategory.name + '<br>' +
                        'Kat: ' + (categoryIndex + 1) + '/' + ALL_CATEGORIES.length + '<br>' +
                        'Sayfa: ' + currentPage + ' | ' + results.length + ' ISBN'
                        )

                // ── 4. Servise gönder ─────────────────────────────────────────────────
                await SiparisTamamla(results)

                // ── 5. Sonraki adımı hesapla ──────────────────────────────────────────
                var reqTime = Math.floor(Math.random() * 9) + 6
                var nextPage = currentPage
                var nextCatIdx = categoryIndex
                var nextPriceIdx = priceIndex

                if (hasNextPage()) {
                    nextPage = currentPage + 1
                    var nextUrl = buildUrl(currentCategory.id, currentPrice.urlParam, nextPage)
                    $(loader).html(
                            '💰 ' + currentPrice.label + '<br>' +
                            '📂 ' + currentCategory.name + '<br>' +
                            'Kat: ' + (categoryIndex + 1) + '/' + ALL_CATEGORIES.length + '<br>' +
                            'Sayfa ' + currentPage + ' bitti | ' + reqTime + 's → Sayfa ' + nextPage
                            )
                    chrome.storage.sync.set({LastIndex: nextPage, CurrentCategoryIndex: nextCatIdx, CurrentPriceIndex: nextPriceIdx})
                    await new Promise(function (r) {
                        setTimeout(r, reqTime * 1000)
                    })
                    window.location.href = nextUrl
                } else {
                    var next = hesaplaGecis(categoryIndex, priceIndex)
                    nextCatIdx = next.catIdx
                    nextPriceIdx = next.priceIdx
                    nextPage = 1
                    var nextUrl = buildUrl(ALL_CATEGORIES[nextCatIdx].id, PRICE_RANGES[nextPriceIdx].urlParam, 1)

                    $(loader).html(
                            '✅ ' + currentCategory.name + ' bitti!<br>' +
                            '💰 ' + PRICE_RANGES[nextPriceIdx].label + '<br>' +
                            '📂 ' + ALL_CATEGORIES[nextCatIdx].name + '<br>' +
                            reqTime + 's sonra başlıyor...'
                            )
                    chrome.storage.sync.set({LastIndex: 1, CurrentCategoryIndex: nextCatIdx, CurrentPriceIndex: nextPriceIdx})
                    await new Promise(function (r) {
                        setTimeout(r, reqTime * 1000)
                    })
                    window.location.href = nextUrl
                }
            })
}

// ─── Yardımcı Fonksiyonlar ────────────────────────────────────────────────────
function SekmeBilgileriGonder() {
    chrome.runtime.sendMessage({AktifSekmeBilgileri: true})
}
function AppLog(log) {
    var time = new Date().toLocaleString()
    var test = log + ' - ' + time
    if (logs.length < 6) {
        logs.push(test)
    } else {
        logs.splice(0, 1);
        logs.push(test)
    }
    localStorage.setItem('LocalStorageAppLog', JSON.stringify(logs))
    chrome.storage.sync.set({AppLog: test}, function () {})
}
function AppLogGonder() {
    chrome.runtime.sendMessage({HataDurum: HataDurum, isStarted: isStarted, AppLog: logs})
}
var HataKontrol
function HataKontrolYap(time, msj2) {
    HataKontrol = setTimeout(function () {
        chrome.storage.sync.get(['isStarted', 'PcName', 'UygulamaAdi', 'Durum', 'UrunID', 'MagazaAdi'], function (item) {
            var msj = 'Bilgisayar: ' + item.PcName + ' Mağaza: ' + item.MagazaAdi + ' Durum: ' + item.Durum + ' iken durdu! ' + (msj2 || '')
            $.ajax({
                type: 'post', url: 'https://www.andromedaworkspace.com/Extension/ajaxCall',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
                },
                cache: false, dataType: 'json', data: {ID: item.UrunID, tip: 'newOrderBreak', mesaj: msj},
                success: function () {
                    console.log('Hata bilgisi gönderildi')
                },
                error: function (r, s, e) {
                    console.log('Ooops: ' + s + ' ' + e)
                }
            })
        })
    }, parseInt(time) * 1000)
}