const DAILY_ECO_REWARDS = [100, 250, 500, 1000, 2500, 3500, 5000]



PlayerEvents.loggedIn(event => {
    const player = event.player
    const server = event.server

    const data = player.persistentData
    const today = getLocalDayNumber()

    const lastRewardDay = Number(data.dailyEcoLastRewardDay || 0)
    let streak = Number(data.dailyEcoStreak || 0)

    if (lastRewardDay === today) return

    if (lastRewardDay === today - 1 && streak < DAILY_ECO_REWARDS.length) {
        streak++
    } else {
        streak = 1
    }

    const amount = getDailyEcoReward(streak)
    const playerName = player.name.string

    data.dailyEcoLastRewardDay = today
    data.dailyEcoStreak = streak

    server.runCommandSilent(`execute as ${playerName} run eco give ${playerName} ${amount}`)
    server.runCommandSilent(`execute at ${playerName} run playsound minecraft:entity.player.levelup player ${playerName} ~ ~ ~ 1 1`)
    server.runCommandSilent(`execute at ${playerName} run particle minecraft:happy_villager ~ ~1 ~ 0.8 0.8 0.8 0.05 35 force ${playerName}`)
    server.runCommandSilent(`execute at ${playerName} run particle minecraft:totem_of_undying ~ ~1 ~ 0.5 0.8 0.5 0.02 25 force ${playerName}`)

    player.tell(Text.of(`Ежедневный бонус: ${amount} монет. День серии: ${streak}.`).gold())
})



function getLocalDayNumber() {
    const now = new Date()
    const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    return Math.floor(startOfToday.getTime() / 86400000)
}

function getDailyEcoReward(streak) {
    return DAILY_ECO_REWARDS[Math.min(streak, DAILY_ECO_REWARDS.length) - 1]
}
