;(() => {
  const root = global.cloudIslandBarnMission
  if (!root || typeof root.registerLogic !== 'function' || typeof root.registerSubmit !== 'function') return

  const REQUIRED = 16
  const DEBUG = !!(root.config && root.config.debug)

  const TASKS = [
    { logicKey: 'submit_wheat', itemId: 'minecraft:wheat', doneKey: 'barn_submit_wheat_done_round_' },
    { logicKey: 'submit_beetroot', itemId: 'minecraft:beetroot', doneKey: 'barn_submit_beetroot_done_round_' },
    { logicKey: 'submit_carrot', itemId: 'minecraft:carrot', doneKey: 'barn_submit_carrot_done_round_' },
    { logicKey: 'submit_potato', itemId: 'minecraft:potato', doneKey: 'barn_submit_potato_done_round_' },
    { logicKey: 'submit_cabbage', itemId: 'farmersdelight:cabbage', doneKey: 'barn_submit_cabbage_done_round_' },
    { logicKey: 'submit_tomato', itemId: 'farmersdelight:tomato', doneKey: 'barn_submit_tomato_done_round_' },
    { logicKey: 'submit_onion', itemId: 'farmersdelight:onion', doneKey: 'barn_submit_onion_done_round_' },
    { logicKey: 'submit_rice_panicle', itemId: 'farmersdelight:rice_panicle', doneKey: 'barn_submit_rice_panicle_done_round_' },
  ]

  function getTaskId() {
    const cfg = root.config || {}
    return String(cfg.rotationTaskId || '')
  }

  TASKS.forEach(function(task) {
    root.registerLogic(task.logicKey, player => {
      const taskId = getTaskId()
      if (!taskId) return false

      const data = player.persistentData
      const round = data.getLong(`barn_rot_round_${taskId}`)
      const doneRound = data.getLong(`${task.doneKey}${taskId}`)
      return round > 0 && doneRound === round
    })

    root.registerSubmit(task.logicKey, player => {
      const taskId = getTaskId()
      if (!taskId) {
        if (DEBUG) player.tell(`§8[BarnDebug] ${task.logicKey}: 0 taskId§r`)
        return 'failed'
      }

      const data = player.persistentData
      const round = data.getLong(`barn_rot_round_${taskId}`)
      const doneRoundKey = `${task.doneKey}${taskId}`

      if (DEBUG) player.tell(`§8[BarnDebug] ${task.logicKey}: round=${round}, done=${data.getLong(doneRoundKey)}§r`)
      if (round > 0 && data.getLong(doneRoundKey) === round) {
        if (DEBUG) player.tell(`§8[BarnDebug] ${task.logicKey}: already done this round§r`)
        return 'failed'
      }

      const server = player.server
      if (!server) return 'failed'
      const removed = Number(server.runCommandSilent(`clear ${player.username} ${task.itemId} ${REQUIRED}`))
      if (DEBUG) player.tell(`§8[BarnDebug] ${task.logicKey}: removed=${removed}§r`)
      if (!isFinite(removed) || removed < REQUIRED) return 'failed'

      data.putLong(doneRoundKey, round)
      if (DEBUG) player.tell(`§8[BarnDebug] ${task.logicKey}: submit success§r`)
      return 'submitted'
    })
  })
})()
