// ----- CONFIG -----

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;
const STORAGE_KEY = "darryl_habit_xp_state_v1";

// ----- STATE -----

let xpTotal = 0;
let level = 1;
let streak = 0;
let todayXP = 0;
let dailyPerfect = false;
let completedTasks = {}; // { taskId: true }

// ----- 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}%`;

  // restore checkbox states
  document.querySelectorAll("input[type=checkbox][data-task-id]").forEach((cb) => {
    const id = cb.dataset.taskId;
    cb.checked = !!completedTasks[id];
  });
}

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

// ----- LOCAL STORAGE -----

function saveState() {
  const state = {
    xpTotal,
    level,
    streak,
    todayXP,
    dailyPerfect,
    completedTasks,
    lastDate: new Date().toISOString().slice(0, 10),
  };
  localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
}

function loadState() {
  const raw = localStorage.getItem(STORAGE_KEY);
  if (!raw) return;

  try {
    const state = JSON.parse(raw);
    const today = new Date().toISOString().slice(0, 10);

    // If date changed, reset daily stuff but keep xpTotal/level/streak
    if (state.lastDate !== today) {
      xpTotal = state.xpTotal;
      level = state.level;
      streak = state.streak;
      todayXP = 0;
      dailyPerfect = false;
      completedTasks = {};
    } else {
      xpTotal = state.xpTotal;
      level = state.level;
      streak = state.streak;
      todayXP = state.todayXP || 0;
      dailyPerfect = state.dailyPerfect || false;
      completedTasks = state.completedTasks || {};
    }
  } catch (e) {
    console.error("Failed to load state", e);
  }
}

// ----- TASK HANDLERS -----

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) {
    completedTasks[taskId] = true;
    addXP(xp);
  } else {
    delete completedTasks[taskId];
    xpTotal -= xp;
    todayXP -= xp;
    if (xpTotal < 0) xpTotal = 0;
    if (todayXP < 0) todayXP = 0;
    updateLevel();
    updateUI();
    saveState();
  }
}

// ----- DAILY PERFECT -----

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

// ----- SAVE DAY (local only) -----

function saveDay() {
  // For now this just ensures state is persisted; you could extend to history later.
  saveState();
  alert("Day saved locally.");
}

// ----- EXPORT / IMPORT JSON -----

function exportJSON() {
  const raw = localStorage.getItem(STORAGE_KEY) || "{}";
  const blob = new Blob([raw], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "habit_xp_state.json";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

function importJSON(file) {
  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      localStorage.setItem(STORAGE_KEY, e.target.result);
      loadState();
      updateUI();
      alert("State imported.");
    } catch (err) {
      console.error(err);
      alert("Failed to import JSON.");
    }
  };
  reader.readAsText(file);
}

// ----- PRODUCTS.TXT PARSING -----

async function loadProducts() {
  const url = "https://idontbyte.com/products/products.txt";
  try {
    const res = await fetch(url);
    const text = await res.text();
    const products = parseProductsText(text);
    renderProducts(products);
  } catch (e) {
    console.error("Failed to load products.txt", e);
  }
}

// Simple parser based on your format: blocks separated by blank lines
function parseProductsText(text) {
  const blocks = text
    .split(/\n\s*\n/) // blank-line separated
    .map((b) => b.trim())
    .filter(Boolean);

  const products = [];

  for (const block of blocks) {
    const lines = block.split("\n").map((l) => l.trim()).filter(Boolean);
    if (lines.length < 4) continue;

    const name = lines[0];
    const category = lines[1] || "";
    const status = lines[2] || "";
    const imageUrl = lines[3] || "";
    let subtitle = "";
    let link = "";

    if (lines[4]) {
      if (lines[4].toLowerCase().startsWith("subtitle:")) {
        subtitle = lines[4].replace(/^subtitle:\s*/i, "");
        link = lines[5] || "";
      } else {
        subtitle = lines[4];
        link = lines[5] || "";
      }
    }

    products.push({
      name,
      category,
      status,
      imageUrl,
      subtitle,
      link,
    });
  }

  return products;
}

function renderProducts(products) {
  const container = document.getElementById("products-container");
  container.innerHTML = "";

  products.forEach((p) => {
    const card = document.createElement("div");
    card.className = "product-card";

    const img = document.createElement("img");
    img.src = p.imageUrl;
    img.alt = p.name;

    const info = document.createElement("div");
    info.className = "product-info";

    const title = document.createElement("div");
    title.className = "product-title";
    title.textContent = p.name;

    const meta = document.createElement("div");
    meta.className = "product-meta";
    meta.textContent = `${p.category} • ${p.status}`;

    const subtitle = document.createElement("div");
    subtitle.className = "product-meta";
    subtitle.textContent = p.subtitle;

    info.appendChild(title);
    info.appendChild(meta);
    if (p.subtitle) info.appendChild(subtitle);

    if (p.link) {
      const a = document.createElement("a");
      a.href = p.link;
      a.target = "_blank";
      a.rel = "noopener noreferrer";
      a.className = "product-link";
      a.textContent = "View product";
      info.appendChild(a);
    }

    card.appendChild(img);
    card.appendChild(info);
    container.appendChild(card);
  });
}

// ----- INIT -----

function init() {
  loadState();
  updateUI();

  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);

  document.getElementById("export-btn").addEventListener("click", exportJSON);

  document
    .getElementById("import-input")
    .addEventListener("change", (e) => {
      const file = e.target.files[0];
      if (file) importJSON(file);
    });

  loadProducts();
}

document.addEventListener("DOMContentLoaded", init);