/* ============================================================
   GLOBAL CONFIG
   ============================================================ */

const STORAGE_KEY = "darryl_habit_rpg_v4";

/* XP 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,

  // Midday
  l_theanine: 5,
  breathing_break: 10,
  stress_check: 5,
  coffee_here: 5,
  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,

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

/* Section mapping */
const TASK_SECTION = {};
Object.keys(TASK_XP).forEach(id => {
  if (id.includes("morning")) TASK_SECTION[id] = "morning";
  else if (id.includes("midday")) TASK_SECTION[id] = "midday";
  else if (["creatine","pre_stim","water_pre","warmup","energy_rating"].includes(id)) TASK_SECTION[id] = "pre";
  else if (["bcaa","complete_workout","track_reps","stretch_post"].includes(id)) TASK_SECTION[id] = "workout";
  else if (id.includes("evening")) TASK_SECTION[id] = "evening";
  else if (["protein_target","calorie_target","steps_target","water_total"].includes(id)) TASK_SECTION[id] = "fat";
  else if (["no_caffeine_after_2","breathing_total","sleep_routine"].includes(id)) TASK_SECTION[id] = "anx";
  else TASK_SECTION[id] = "morning";
});

const DAILY_PERFECT_BONUS = 50;

/* ============================================================
   HERO OF THE DAY
   ============================================================ */

const HEROES = {
  abby:  { name: "Abby",  class: "Shadow Ninja Assassin", portrait: "character-files/images/abby/portrait.png" },
  bazza: { name: "Bazza", class: "Barbarian Powerlifter", portrait: "character-files/images/bazza/portrait.png" },
  paddy: { name: "Paddy", class: "Paladin of Perfect Form", portrait: "character-files/images/paddy/portrait.png" },
  sara:  { name: "Sara",  class: "Comet Sorceress", portrait: "character-files/images/sara/portrait.png" },
  neil:  { name: "Neil",  class: "Cardio Ghost Necromancer", portrait: "character-files/images/neil/portrait.png" },
  zonya: { name: "Zonya", class: "Amazon Warrior Rogue Princess", portrait: "character-files/images/zonya/portrait.png" },
  david: { name: "David", class: "Ironman Druid", portrait: "character-files/images/david/portrait.png" }
};

const DAY_MAP = {
  0: "abby",
  1: "bazza",
  2: "paddy",
  3: "sara",
  4: "neil",
  5: "zonya",
  6: "david"
};

function loadHeroOfDay() {
  const heroKey = DAY_MAP[new Date().getDay()];
  const hero = HEROES[heroKey];

  document.getElementById("hero-name").textContent = hero.name;
  document.getElementById("hero-class").textContent = hero.class;
  document.getElementById("hero-portrait").src = hero.portrait;

  // Load hero CSS
  const css = document.createElement("link");
  css.rel = "stylesheet";
  css.href = `character-code/css/${heroKey}.css`;
  document.head.appendChild(css);

  // Load hero JS
  const js = document.createElement("script");
  js.src = `character-code/js/${heroKey}.js`;
  document.body.appendChild(js);

  window.dispatchEvent(new Event("heroLoaded"));
}

/* ============================================================
   STATE
   ============================================================ */

let xpTotal = 0;
let level = 1;
let streak = 0;
let gold = 0;
let todayXP = 0;
let dailyPerfect = false;
let completedTasks = {};
let days = {};
let inventoryCounts = {};

const todayISO = () => new Date().toISOString().slice(0,10);

/* ============================================================
   XP + GOLD LOGIC
   ============================================================ */

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 addXP(amount) {
  xpTotal += amount;
  todayXP += amount;
  updateLevel();
}

function addGoldRandom() {
  const gain = Math.floor(Math.random() * 6) + 3; // 3–8 gold
  gold += gain;
}

function updateLevel() {
  let needed = getXPToNextLevel(level);
  while (xpTotal >= needed) {
    xpTotal -= needed;
    level++;
    needed = getXPToNextLevel(level);
  }
}

/* ============================================================
   UI UPDATE
   ============================================================ */

function updateUI() {
  // Header XP bar
  const xpToNext = getXPToNextLevel(level);
  const ratio = Math.min(1, xpTotal / xpToNext);
  document.getElementById("hero-xp-bar").style.width = `${ratio * 100}%`;
  document.getElementById("xp-to-next").textContent = xpToNext;

  // Circular XP ring
  const angle = ratio * 360;
  document.querySelector(".hero-portrait-frame").style.background =
    `conic-gradient(#7aff9c ${angle}deg, #222 0deg)`;

  // Character screen XP bar
  document.getElementById("character-xp-bar").style.width = `${ratio * 100}%`;

  // Stats
  document.getElementById("level").textContent = level;
  document.getElementById("xp").textContent = xpTotal;
  document.getElementById("streak").textContent = streak;
  document.getElementById("gold-total").textContent = gold;
  document.getElementById("gold-total-character").textContent = gold;

  // Checkboxes
    // Task toggles
  // Task toggles
  document.querySelectorAll("input[data-task-id]").forEach(cb => {
    cb.addEventListener("change", onTaskToggle);
  });

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

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

  // Export / Import
  document.getElementById("export-btn").addEventListener("click", exportJSON);
  document.getElementById("import-input").addEventListener("change", e => {
    if (e.target.files[0]) importJSON(e.target.files[0]);
  });

  // Screen switching
  document.querySelectorAll(".nav-btn").forEach(btn => {
    btn.addEventListener("click", () => switchScreen(btn.dataset.target));
  });

  // Quest tab switching
  document.querySelectorAll(".quest-tab").forEach(btn => {
    btn.addEventListener("click", () => switchTab(btn.dataset.tab));
  });
}

document.addEventListener("DOMContentLoaded", init);