// XP values per task
const TASK_XP = {
  // Morning
  omeprazole: 5,
  setrona_morning: 5,
  acv_morning: 5,
  greens: 5,
  mushroom: 5,
  joint: 5,
  protein_morning: 5,
  water_morning: 10,
  no_doomscroll: 10,
  light_movement: 10,

  // First break
  l_theanine: 5,
  breathing_break: 10,
  stress_check: 5,
  coffee_here: 5,

  // Midday
  setrona_midday: 5,
  acv_midday: 5,
  voltaren_midday: 5,
  manshake: 5,
  midday_walk: 10,
  protein_lunch: 10,
  step_check: 10,

  // Pre-workout
  creatine: 5,
  pre_stim: 5,
  water_pre: 10,
  warmup: 10,
  energy_rating: 5,

  // Workout
  bcaa: 5,
  complete_workout: 10,
  track_reps: 5,
  stretch_post: 5,

  // Evening
  voltaren_evening: 5,
  magnesium: 5,
  inositol: 5,
  prazosin: 5,
  no_screens: 10,
  evening_breathing: 10,
  plan_meals: 10,
  sleep_goal: 10,

  // Fat-loss
  protein_target: 10,
  calorie_target: 10,
  steps_target: 10,
  water_total: 10,

  // Anxiety
  no_caffeine_after_2: 10,
  breathing_total: 10,
  sleep_routine: 10,
};

const DAILY_PERFECT_BONUS = 50;

// State
let xpTotal = 0;
let level = 1;
let streak = 0;
let todayXP = 0;
let dailyPerfect = false;

// Helpers
function formatToday() {
  const d = new Date();
  return d.toLocaleDateString(undefined, {
    weekday: "short",
    month: "short",
    day: "numeric",
  });
}

function getXPToNextLevel(level) {
  if (level <= 1) return 500;
  if (level <= 2) return 1000;
  if (level <= 3) return 1500;
  if (level <= 4) return 2000;
  if (level <= 10) return 2500;
  if (level <= 20) return 3000;
  if (level <= 30) return 4000;
  if (level <= 40) return 5000;
  return 7500;
}

function updateLevel() {
  let xpNeeded = getXPToNextLevel(level);
  while (xpTotal >= xpNeeded && level < 50) {
    xpTotal -= xpNeeded;
    level += 1;
    xpNeeded = getXPToNextLevel(level);
  }
}

function updateUI() {
  document.getElementById("today-date").textContent = formatToday();
  document.getElementById("level").textContent = level;
  document.getElementById("xp").textContent = xpTotal;
  document.getElementById("streak").textContent = streak;

  const xpToNext = getXPToNextLevel(level);
  document.getElementById("xp-to-next").textContent = xpToNext;

  const ratio = Math.min(1, xpTotal / xpToNext);
  document.getElementById("xp-bar").style.width = `${ratio * 100}%`;
}

function addXP(amount) {
  xpTotal += amount;
  todayXP += amount;
  updateLevel();
  updateUI();
}

// Task toggle
function onTaskToggle(e) {
  const checkbox = e.target;
  if (checkbox.tagName !== "INPUT" || checkbox.type !== "checkbox") return;

  const taskId = checkbox.dataset.taskId;
  const xp = TASK_XP[taskId] || 0;

  if (checkbox.checked) {
    addXP(xp);
  } else {
    xpTotal -= xp;
    todayXP -= xp;
    if (xpTotal < 0) xpTotal = 0;
    if (todayXP < 0) todayXP = 0;
    updateLevel();
    updateUI();
  }
}

// Daily perfect
function markDailyPerfect() {
  if (dailyPerfect) return;
  dailyPerfect = true;
  addXP(DAILY_PERFECT_BONUS);
  streak += 1;
  updateUI();
}

// Save day (stub for backend)
async function saveDay() {
  const payload = {
    date: new Date().toISOString().slice(0, 10),
    xp_earned: todayXP,
    daily_perfect: dailyPerfect,
    level,
    streak,
  };

  console.log("Save payload:", payload);

  // Example for later:
  // await fetch("/api/daily-log", {
  //   method: "POST",
  //   headers: { "Content-Type": "application/json" },
  //   body: JSON.stringify(payload),
  // });
}

// Init
function init() {
  document.querySelectorAll(".task-list").forEach((list) => {
    list.addEventListener("change", onTaskToggle);
  });

  document
    .getElementById("daily-perfect-btn")
    .addEventListener("click", markDailyPerfect);

  document.getElementById("save-day-btn").addEventListener("click", saveDay);

  updateUI();
}

document.addEventListener("DOMContentLoaded", init);