// Shared dice/degree helpers used by the combat and skill rollers.

export function d100() { return Math.floor(Math.random() * 100) + 1 }

export function degrees(target, roll) {
  const success = roll <= target
  if (success) { const diff = target - roll; const dos = 1 + Math.floor(diff / 10); return { success, dos, dof: 0 } }
  const diff = roll - target; const dof = 1 + Math.floor(diff / 10); return { success, dos: 0, dof }
}

export function uid() { return Math.random().toString(36).slice(2) + Date.now().toString(36) }

// Apply a spent fate point to a recorded test result (one with target /
// attackRoll / success / dos / dof). Returns a new result object; the caller
// is responsible for decrementing/persisting the fate point itself.
//   'reroll' - re-roll the d100 against the same target
//   'plus10' - add +10 to the target and re-evaluate the same roll
//   'dos'    - add one degree of success (turning a failure into a pass)
export function applyFateToTest(prev, action) {
  const out = { ...prev, fate: [...(prev.fate || [])] }
  if (action === 'reroll') {
    out.attackRoll = d100()
    const dg = degrees(out.target, out.attackRoll)
    out.success = dg.success; out.dos = dg.dos; out.dof = dg.dof
    out.fate.push('reroll')
  } else if (action === 'plus10') {
    out.target = Math.min(100, (Number(out.target) || 0) + 10)
    const dg = degrees(out.target, out.attackRoll)
    out.success = dg.success; out.dos = dg.dos; out.dof = dg.dof
    out.fate.push('+10')
  } else if (action === 'dos') {
    if (out.success) { out.dos = (Number(out.dos) || 0) + 1 }
    else { out.success = true; out.dos = 1; out.dof = 0 }
    out.fate.push('+DoS')
  }
  return out
}
