// ─── BookOutlet a.js (popup) ───────────────────────────────────────────────────
var logs = []
var sizes = ['1', '2', '3', '5', '10', '15', '20', '25', '30']

var AramaZamani = 5
$(document).ready(function () {
    chrome.storage.onChanged.addListener(function (changes, namespace) {
        if (changes.LastIndex) {
            Dashboard()
        }
    })

    Dashboard()
    chrome.runtime.sendMessage(
            {method: 'Dashboard'},
            function (response) {
                var logsDiv = $('.applogs')
                if (response != undefined) {
                    if (response.AppLog) {
                        logsDiv.html('')
                        logs = response.AppLog
                        var uzunluk = logs.length
                        var logsHTML = ''
                        for (index = 0; index < uzunluk; index++) {
                            logsHTML += `<p>⚡ ${logs[index].split('-')[0].trim()}   <i>(${logs[index].split('-')[1].trim()})</i></p>`
                        }
                        logsDiv.html(logsHTML)
                    }
                    if (response.HataDurum == true) {
                        $('.hatavar').show()
                    } else {
                        $('.hatavar').hide()
                    }
                } else {
                    logsDiv.html('')
                }
            }
    )

    $('.slider').slider({
        min: 0,
        max: sizes.length - 1,
        value: 0,
        step: 1,
        slide: function (event, ui) {
            $('.range').text(sizes[ui.value])
            var reqTime = sizes[ui.value]
            chrome.storage.sync.set({RequestTime: reqTime}, function () {})
            AramaZamani = reqTime
        },
    })

    $('.menu-item').click(function () {
        var index = $(this).index()
        var aktif = $(this).hasClass('active')
        if (!aktif) {
            TabAcKapa(index)
        }
    })

    var StartButton = document.getElementById('StartButton')
    StartButton.disabled = false

    // ─── RESET ───────────────────────────────────────────────────────────────
    var ResetButton = document.getElementById('ResetButton')
    ResetButton.addEventListener('click', function () {
        chrome.storage.sync.set({isStarted: false}, function () {
            chrome.storage.sync.remove([
                'isStarted', 'RequestTime',
                'CurrentSectionIndex', 'LastIndex',
                'CategoryList', 'CurrentCategoryIndex'
            ], function () {})
            chrome.storage.sync.set({LastIndex: 1}, function () {
                console.log('Sıfırlandı.')
            })
            localStorage.clear()
            $('.uygulamabaslat').hide()
            StartButton.disabled = false
            $('.applogs').html('')
            Dashboard()
            console.log('Tüm datalar temizlendi.')
        })
    })

    // ─── STOP ────────────────────────────────────────────────────────────────
    var CancelButton = document.getElementById('CancelButton')
    CancelButton.addEventListener('click', function () {
        // Sadece isStarted false yap, konum bilgilerini koru
        chrome.storage.sync.set({isStarted: false}, function () {
            StartButton.disabled = false
            $('.uygulamabaslat').hide()
            $('.applogs').html('')
            Dashboard()
            console.log('İşlemler İptal Edildi')
            chrome.runtime.sendMessage({UygulamaKapatildi: true})
        })
    })

    // ─── START ───────────────────────────────────────────────────────────────
    StartButton.addEventListener('click', function () {
        $('.uygulamabaslat').hide()
        chrome.storage.sync.get(['isStarted', 'LastIndex', 'SearchUrl'], function (item) {
            if (item.isStarted == true) {
                alert('Uygulamayı tekrar başlatmak için önce durdurmalısınız!')
            } else {
                var MagazaAdi = $('#txtMagazaAdi').val()
                var PcName = $('#txtPcName').val()
                var ApiUrl = $('#txtApiUrl').val()
                var LastIndex = $('#txtLastIndex').val() || 1
                var SearchUrl = $('#txtSearchUrl').val()

                if (MagazaAdi.length > 0 && PcName.length > 0 && ApiUrl.length > 0 && SearchUrl.length > 0) {
                    // Section ve page'den başlangıç URL'ini hesapla
                    var ALL_SECTION_URLS_BTN = [
                        'https://bookoutlet.com/books',
                        'https://bookoutlet.com/books?qs=%24filters%24section%3Dadult',
                        'https://bookoutlet.com/books?qs=%24filters%24section%3Dadult-teens-young-adult',
                        'https://bookoutlet.com/books?qs=%24filters%24section%3Dteens-young-adult',
                        'https://bookoutlet.com/books?qs=%24filters%24section%3Dkids'
                    ]
                    var secIdx = getSectionIndexFromUrl(SearchUrl)
                    var startPg = parseInt(LastIndex) || 1
                    var baseUrlBtn = ALL_SECTION_URLS_BTN[secIdx]
                    var startUrlBtn
                    if (startPg <= 1) {
                        startUrlBtn = baseUrlBtn
                    } else if (secIdx === 0) {
                        startUrlBtn = baseUrlBtn + '?page=' + startPg
                    } else {
                        startUrlBtn = baseUrlBtn + '&page=' + startPg
                    }

                    Start(AramaZamani, PcName, MagazaAdi, '', ApiUrl, LastIndex, SearchUrl)

                    // Başlangıç URL'ini aç
                    chrome.tabs.create({url: startUrlBtn}, function (tab) {
                        setTimeout(function () {
                            chrome.tabs.sendMessage(tab.id, {
                                Link: startUrlBtn,
                                UygulamaBaslatildi: true,
                            })
                        }, 2000)
                    })

                    setTimeout(function () {
                        Dashboard()
                    }, 1000)
                    StartButton.disabled = false
                    TabAcKapa(0)
                } else {
                    alert('Lütfen tüm alanları doldurun!')
                    TabAcKapa(1)
                }
            }
        })
    }, false)

    // ─── Kayıtlı ayarları yükle ───────────────────────────────────────────────
    chrome.storage.sync.get(
            ['PcName', 'RequestTime', 'MagazaAdi', 'ApiUrl', 'LastIndex', 'SearchUrl'],
            function (item) {
                if (item.RequestTime) {
                    AramaZamani = item.RequestTime
                }
                if (item.PcName && item.ApiUrl) {
                    $('#txtPcName').val(item.PcName)
                    $('#txtMagazaAdi').val(item.MagazaAdi)
                    $('#txtApiUrl').val(item.ApiUrl)
                    $('#txtLastIndex').val(item.LastIndex)
                    $('#txtSearchUrl').val(item.SearchUrl)
                }
            }
    )
})

function TabAcKapa(index) {
    $('.settings').each(function () {
        $(this).slideUp()
    })
    $('.menu-item').each(function () {
        $(this).removeClass('active')
    })
    $('.menu-item').eq(index).addClass('active')
    $('.settings').eq(index).slideDown()
    setTimeout(function () {
        Dashboard()
    }, 500)
}

function Dashboard() {
    var ALL_SECTION_NAMES = ['All', 'Adult', 'Adult and Teens & YA', 'Teens & YA', 'Kids']

    chrome.storage.sync.get(
            ['isStarted', 'RequestTime', 'PcName', 'MagazaAdi', 'ApiUrl',
                'LastIndex', 'CurrentSectionIndex', 'CategoryList', 'CurrentCategoryIndex'],
            function (item) {
                $('.durum').text(item.isStarted == true ? 'Çalışıyor' : 'Devre Dışı')
                $('.bilgisayaradi').text(item.PcName || '-')
                $('.magazaadi').text(item.MagazaAdi || '-')
                $('.apiurl').text(item.ApiUrl || '-')
                $('.durum').removeClass('started cancelled')
                $('.durum').addClass(item.isStarted == true ? 'durum started' : 'durum cancelled')
                $('.aramasuresi').text(item.RequestTime ? item.RequestTime + ' Saniye' : '-')

                // Section
                var secIdx = parseInt(item.CurrentSectionIndex) || 0
                var secName = ALL_SECTION_NAMES[secIdx] || '-'

                var catList = item.CategoryList || []
                var catIdx2 = parseInt(item.CurrentCategoryIndex) || 0
                var catName2 = catList[catIdx2] || '-'
                var catInfo = catList.length > 0
                        ? '\n🏷️ ' + (catIdx2 + 1) + '/' + catList.length + ' - ' + catName2
                        : ''

                $('.lastindex').text(
                        'Sayfa: ' + (item.LastIndex || 1) + '\n' +
                        '📂 ' + (secIdx + 1) + '/' + ALL_SECTION_NAMES.length + ' - ' + secName +
                        catInfo
                        )

                var RequestTimeIndex = 0
                if (item.RequestTime) {
                    var sizes = ['1', '2', '3', '5', '10', '15', '20', '25', '30']
                    var idx = sizes.findIndex(function (x) {
                        return x == item.RequestTime
                    })
                    RequestTimeIndex = idx >= 0 ? idx : 0
                }
                $('.range').text(['1', '2', '3', '5', '10', '15', '20', '25', '30'][RequestTimeIndex])
                $('.slider').slider({min: 0, max: 8, value: RequestTimeIndex, step: 1})
            }
    )
}

function getSectionIndexFromUrl(url) {
    // URL decode ederek section= değerini bul
    var decoded = decodeURIComponent(url)
    if (decoded.indexOf('section=') === -1)
        return 0
    var m = decoded.match(/section=([^&]+)/)
    if (!m)
        return 0
    var val = m[1]
    var sections = ['all', 'adult', 'adult-teens-young-adult', 'teens-young-adult', 'kids']
    for (var i = 1; i < sections.length; i++) {
        if (sections[i] === val)
            return i
    }
    return 0
}

function Start(RequestTime, PcName, MagazaAdi, Applog, ApiUrl, LastIndex, SearchUrl) {
    chrome.storage.local.clear()
    // SearchUrl'den section index'i türet
    var sectionIdx = getSectionIndexFromUrl(SearchUrl || '')
    var startPage = parseInt(LastIndex) || 1
    // SearchUrl'i section+page olarak yeniden oluştur
    var ALL_SECTION_URLS = [
        'https://bookoutlet.com/books',
        'https://bookoutlet.com/books?qs=%24filters%24section%3Dadult',
        'https://bookoutlet.com/books?qs=%24filters%24section%3Dadult-teens-young-adult',
        'https://bookoutlet.com/books?qs=%24filters%24section%3Dteens-young-adult',
        'https://bookoutlet.com/books?qs=%24filters%24section%3Dkids'
    ]
    var baseUrl = ALL_SECTION_URLS[sectionIdx]
    var startUrl
    if (startPage <= 1) {
        startUrl = baseUrl
    } else if (sectionIdx === 0) {
        startUrl = baseUrl + '?page=' + startPage
    } else {
        startUrl = baseUrl + '&page=' + startPage
    }

    // CategoryList ve CurrentCategoryIndex sıfırlanır çünkü yeni bir konum seçildi
    // CurrentSectionIndex form'daki SearchUrl'den hesaplanır
    chrome.storage.sync.set({
        RequestTime: RequestTime,
        isStarted: true,
        LastIndex: startPage,
        SearchUrl: startUrl,
        UrunID: undefined,
        PcName: PcName,
        MagazaAdi: MagazaAdi,
        ApiUrl: ApiUrl,
        UrunGetirildi: false,
        Durum: 'AppStarted',
        CurrentSectionIndex: sectionIdx,
        CurrentCategoryIndex: 0,
        CategoryList: [],
        UygulamaAdi: 'BookOutlet Sipariş',
    }, function () {
        console.log('BookOutlet başlatıldı. Section: ' + sectionIdx + ' Sayfa: ' + startPage + ' URL: ' + startUrl)
    })
}