function createStore(reducer){
    let state = reducer(undefined, {})
    let callbacks = []
    const getState = () => state
    const dispatch = (action) => {
        const newState = reducer(state, action)
        if(newState !== state) {
            state = newState
        }
        for(let cb of callbacks) {
            cb()
        }
    }

    const subscribe = (callback) => (callbacks.push(callback),
        () => callbacks = callbacks.filter(c => c !== callback))
    return {
        getState,
        dispatch,
        subscribe
    }
}

function reducer(state, {type, item, number, price}){ //объект action деструктуризируется на три переменных
    if (!state){ //начальная уборка в ларьке:
        return {
            items :
                [
                     {
                        name: 'beer',
                        price: 35,
                        number: 100
                     },
                    {
                        name: 'chips',
                        price: 50,
                        number: 100
                    },
                    {
                        name: 'cigarettes',
                        price: 45,
                        number: 100
                    },
                    {
                        name: 'gum',
                        price: 15,
                        number: 100
                    }
                ],
            money: 0
        }
    }
    if (type === 'BUY'){ //если тип action - КУПИТЬ, то:
        console.log(state.items)
        return {
            ...state, //берем все что было из ассортимента

            items: state.items.filter(i => i.name === item), //и уменьшаем то, что покупается на количество
            money: state.money += state.items.filter(i => i.price === price)
        }
    }
    return state //если мы не поняли, что от нас просят в `action` - оставляем все как есть
}

const store = createStore(reducer)
// console.log(store.getState())

let $select = document.createElement('select')
let $table = document.createElement('table');
let $num = document.createElement('input')
$num.type = 'number'
let btn = document.createElement('button')
$num.min = '1';
console.log(store.getState().items)
let money = document.createElement('div')
for(let item of store.getState().items) {
    let $tr = document.createElement('tr')
    let $td = document.createElement('td')
    let $td2 = document.createElement('td')
    let $td3 = document.createElement('td')
    $td.innerText = item.name
    $td2.innerText = item.price
    $td3.innerText = item.number
    let $option = document.createElement('option')
    $option.innerHTML = item.name
    $select.append($option)
    btn.innerHTML = 'buy'
    $tr.append($td, $td2, $td3)
    $table.append($tr)
    btn.onclick = (e) => {
        // console.log(store.getState().items, item)
        // console.log(item.number - +$num.value >= 0 )
            if(item.number - +$num.value >= 0 ) {
                // console.log(+$num.value, item.number)
                let [selected] = store.getState().items.filter(i => i.name === $select.value)
                selected.number = item.number - +$num.value
                // console.log(selected.number)
                if(item.number > 0) {
                    console.log(store.getState())
                    store.dispatch({type: 'BUY', item: selected.name, number: item.number - +$num.value})
                    console.log(store.getState())
                }
            }

    }
    console.log(store.getState())
    store.subscribe(() => money.innerHTML = `Cashbox: ${+store.getState().money}`)
    store.subscribe(() => $td3.innerHTML = `${item.number}`)
    document.body.append($select, $num, btn, $table)
}
document.body.appendChild(money)
