// ─── BookDepot 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',
                'CurrentCategoryIndex', 'CurrentPriceIndex', 'LastIndex'
            ], 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 () {
        chrome.storage.sync.set({isStarted: false}, function () {
            chrome.storage.sync.remove(['isStarted', 'AppLog'], 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) {
                    Start(AramaZamani, PcName, MagazaAdi, '', ApiUrl, LastIndex, SearchUrl)

                    // Başlangıç URL'ini aç
                    chrome.tabs.create({url: SearchUrl}, function (tab) {
                        setTimeout(function () {
                            chrome.tabs.sendMessage(tab.id, {
                                Link: SearchUrl,
                                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() {
    chrome.storage.sync.get(
            ['isStarted', 'RequestTime', 'PcName', 'MagazaAdi', 'ApiUrl',
                'LastIndex', 'CurrentCategoryIndex', 'CurrentPriceIndex'],
            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' : '-')

                // Fiyat aralığı
                var PRICE_RANGES = [
                    {label: '$1-$10'},
                    {label: '$11-$15'},
                    {label: '$15-$100'}
                ]
                var priceIdx = parseInt(item.CurrentPriceIndex) || 0
                var priceLabel = PRICE_RANGES[priceIdx] ? PRICE_RANGES[priceIdx].label : '-'

                // Kategori
                var ALL_CATEGORIES_NAMES = [
                    'Biography & Autobiography', 'Children Fiction', 'Children Nonfiction', 'Fiction',
                    'History & Geography', 'Religion & Spirituality', 'Self-Help', 'Tweens Fiction',
                    'Tweens Nonfiction', 'Young Adult Fiction', 'Antiques & Collectibles', 'Architecture',
                    'Art', 'Body, Mind & Spirit', 'Business & Economics', 'Calendars',
                    'Comics & Graphic Novels', 'Computers & Internet', 'Cooking, Food & Wine',
                    'Crafts & Hobbies', 'Design', 'Drama', 'Education', 'Family & Relationships',
                    'Foreign Language Study', 'Games', 'Gardening', 'Health & Fitness', 'House & Home',
                    'Humor', 'Language Arts & Disciplines', 'Law', 'Literary Collections',
                    'Literary Criticism', 'Mathematics', 'Medical', 'Music', 'Nature & Outdoors',
                    'Performing Arts', 'Pets', 'Philosophy', 'Photography', 'Poetry', 'Political Science',
                    'Psychology', 'Reference', 'Science', 'Social Science', 'Sports & Recreation',
                    'Stationery', 'Study Aids', 'Technology', 'Toys & Activities', 'Transportation',
                    'Travel', 'True Crime', 'Young Adult Nonfiction'
                ]
                var catIdx = parseInt(item.CurrentCategoryIndex) || 0
                var catName = ALL_CATEGORIES_NAMES[catIdx] || '-'

                $('.lastindex').text(
                        'Sayfa: ' + (item.LastIndex || 1) + '\n' +
                        '💰 ' + priceLabel + '\n' +
                        '📂 ' + (catIdx + 1) + '/' + ALL_CATEGORIES_NAMES.length + ' - ' + catName
                        )

                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 Start(RequestTime, PcName, MagazaAdi, Applog, ApiUrl, LastIndex, SearchUrl) {
    chrome.storage.local.clear()
    chrome.storage.sync.set({
        RequestTime: RequestTime,
        isStarted: true,
        LastIndex: LastIndex || 1,
        SearchUrl: SearchUrl,
        UrunID: undefined,
        PcName: PcName,
        MagazaAdi: MagazaAdi,
        ApiUrl: ApiUrl,
        UrunGetirildi: false,
        Durum: 'AppStarted',
        CurrentCategoryIndex: 0,
        CurrentPriceIndex: 0,
        UygulamaAdi: 'BookDepot Sipariş',
    }, function () {
        console.log('BookDepot ayarları kaydedildi...')
    })
}