import gsap from "gsap"

export function marketUI(game, stageData) {
    document.getElementById("market-container").addEventListener('click', () => {
        closeMarketUI(game, stageData)
    })

    document.getElementById('market-panel').addEventListener('click', (event) => {
        event.stopPropagation()
    })

    document.getElementById('buy-ingredients').addEventListener('click', (event) => {
        stageData.buyIngredients()
    })
}

let cartTotal = 0

export function populateMarketIngredients(game, stageData) {
    const ingredientList = document.getElementById("ingredients-list")
    ingredientList.innerHTML = ''

    const groupedIngredientCount = stageData.ingredientInventory.groupCount()

    for(let ingredientName in stageData.ingredientInfo) {
        const info = stageData.ingredientInfo[ingredientName]

        const sellContainer = document.createElement('div')
        sellContainer.className = "ingredient-sell-container"
        sellContainer.setAttribute('data-ingredient', ingredientName)

        const iconContainer = document.createElement('div')
        iconContainer.className = "ingredient-icon-container"

        const ingredientIcon = document.createElement('img')
        ingredientIcon.src = info.image

        const inventoryCount = document.createElement('div')
        inventoryCount.className = 'ingredient-inventory-count'
        inventoryCount.innerHTML = groupedIngredientCount[ingredientName] ?? 0

        iconContainer.appendChild(ingredientIcon)
        iconContainer.appendChild(inventoryCount)

        const descriptionContainer = document.createElement('div')
        descriptionContainer.className = 'ingredient-description'
        const title = document.createElement('h2')
        title.innerHTML = info.title

        const ingredientPrice = document.createElement('div')
        ingredientPrice.className = "ingredient-price"

        const coinImage = document.createElement('img')
        coinImage.src = "./images/coin.svg"

        const priceValue = document.createElement('div')
        priceValue.className = 'ingredient-price-value'
        priceValue.innerHTML = info.cost

        ingredientPrice.appendChild(coinImage)
        ingredientPrice.appendChild(priceValue)

        const callToAction = document.createElement('div')
        callToAction.className = 'call-to-action'
        callToAction.innerHTML = "Click to add to order"

        descriptionContainer.appendChild(title)
        descriptionContainer.appendChild(ingredientPrice)
        descriptionContainer.appendChild(callToAction)

        const inCartContainer = document.createElement('div')
        inCartContainer.className = 'ingredient-in-cart-container'

        const inCartAmount = document.createElement('div')
        inCartAmount.className = 'ingredient-in-cart-amount'
        inCartAmount.innerHTML = 0

        inCartContainer.appendChild(inCartAmount)

        sellContainer.appendChild(iconContainer)

        iconContainer.addEventListener('click', () => {

            const ingredientToAdd = sellContainer.getAttribute('data-ingredient')

            const infoToAdd = stageData.ingredientInfo[ingredientToAdd]
            if(infoToAdd.cost + cartTotal > stageData.currency) {
                stageData.soundEffects['audio/witch_cackle1.ogg'].play()
                return
            }

            stageData.soundEffects['audio/click1.ogg'].play()
            stageData.cartItems.push(ingredientToAdd)
            inCartAmount.innerHTML = stageData.cartItems.filter(item => item == ingredientName).length
            updateCartTotal(game, stageData)
        })

        inCartContainer.addEventListener('click', () => {
            const ingredientToRemove = sellContainer.getAttribute('data-ingredient')
            if(stageData.cartItems.indexOf(ingredientToRemove) != -1) {
                stageData.soundEffects['audio/click1.ogg'].play()
                stageData.cartItems.splice(stageData.cartItems.indexOf(ingredientToRemove), 1)
                inCartAmount.innerHTML = stageData.cartItems.filter(item => item == ingredientName).length
                updateCartTotal(game, stageData)
            }
        })
        sellContainer.appendChild(descriptionContainer)
        sellContainer.appendChild(inCartContainer)

        ingredientList.appendChild(sellContainer)

        
    }
    updateCartTotal(game, stageData)
}

export function updateCartTotal(game, stageData) {
    cartTotal = 0
    stageData.cartItems.forEach((ingredientName) => {
        const info = stageData.ingredientInfo[ingredientName]
        cartTotal += info.cost
    })

    document.getElementById("total-amount-value").innerHTML = cartTotal

 
}

export function openMarketUI(game, stageData) {
    if(stageData.sellingSkeleton.marketMenuOpen) {
        return
    }
    const marketContainer = document.getElementById("market-container")
    marketContainer.style.display = "block"

    populateMarketIngredients(game, stageData)

    stageData.soundEffects['audio/drawKnife2.ogg'].play()
    const marketPanel = document.getElementById("market-panel")
    gsap.to(marketPanel, {
        x: 0, duration: 0.8, onComplete: () => {
            stageData.sellingSkeleton.marketMenuOpen = true
        }
    })
}

export function closeMarketUI(game, stageData) {
    if(!stageData.sellingSkeleton.marketMenuOpen) {
        return
    }
    stageData.sellingSkeleton.marketMenuOpen = false

    stageData.cartItems = []

    stageData.soundEffects['audio/drawKnife2.ogg'].play()
    const marketPanel = document.getElementById("market-panel")
    gsap.to(marketPanel, {
        x: 1024, duration: 0.8, onComplete: () => {
            const marketContainer = document.getElementById("market-container")
            marketContainer.style.display = "none"

        }
    })
}