// Gamifikace — shop, odznaky, streaky.

// ─── SHOP catalog ────────────────────────────────────────────
const SHOP_ITEMS = [
  { id: 'bow',          name: 'Mašlička',              price: 15, category: 'head',  emoji: '🎀', rarity: 'common' },
  { id: 'flower',       name: 'Kytička za ušima',      price: 18, category: 'ear',   emoji: '🌸', rarity: 'common' },
  { id: 'hat',          name: 'Slaměný klobouček',     price: 25, category: 'head',  emoji: '👒', rarity: 'common' },
  { id: 'glasses',      name: 'Kulaté brýličky',       price: 30, category: 'face',  emoji: '👓', rarity: 'common' },
  { id: 'bowtie',       name: 'Motýlek',               price: 28, category: 'neck',  emoji: '🎀', rarity: 'common' },
  { id: 'scarf',        name: 'Pletená šála',          price: 35, category: 'neck',  emoji: '🧣', rarity: 'rare' },
  { id: 'birthday-hat', name: 'Narozeninová čepice',   price: 40, category: 'head',  emoji: '🎉', rarity: 'rare' },
  { id: 'headphones',   name: 'Sluchátka DJ Pandy',    price: 55, category: 'head',  emoji: '🎧', rarity: 'rare' },
  { id: 'crown',        name: 'Korunka princezny',     price: 80, category: 'head',  emoji: '👑', rarity: 'epic' },
  { id: 'wizard-hat',   name: 'Čarodějnický klobouk',  price: 75, category: 'head',  emoji: '🧙', rarity: 'epic' },
  { id: 'cape',         name: 'Hrdinský plášť',        price: 100, category: 'body', emoji: '🦸', rarity: 'epic' },
  { id: 'rainbow',      name: 'Duhové křídla',         price: 150, category: 'back', emoji: '🌈', rarity: 'legendary' },
];

const RARITY = {
  common:    { label: 'Běžné',       color: '#B5C9D4' },
  rare:      { label: 'Vzácné',      color: '#7FB5E8' },
  epic:      { label: 'Epické',      color: '#C78BE0' },
  legendary: { label: 'Legendární',  color: '#F4C95D' },
};

function getShopItem(id) {
  return SHOP_ITEMS.find(i => i.id === id);
}

// ─── Profile inventory helpers ───────────────────────────────
function getOwnedItems(profile) {
  return (profile?.inventory && profile.inventory.owned) || [];
}
function getEquippedItems(profile) {
  return (profile?.inventory && profile.inventory.equipped) || [];
}
function isOwned(profile, id) {
  return getOwnedItems(profile).includes(id);
}
function isEquipped(profile, id) {
  return getEquippedItems(profile).includes(id);
}

function purchaseItem(profile, itemId) {
  const item = getShopItem(itemId);
  if (!item) throw new Error('Předmět neexistuje.');
  if (isOwned(profile, itemId)) throw new Error('Už to máš.');
  if ((profile.coins || 0) < item.price) throw new Error('Nemáš dost mincí.');
  const nextProfile = {
    ...profile,
    coins: profile.coins - item.price,
    inventory: {
      owned: [...getOwnedItems(profile), itemId],
      equipped: getEquippedItems(profile),
    },
  };
  return nextProfile;
}

function toggleEquipped(profile, itemId) {
  const item = getShopItem(itemId);
  if (!item || !isOwned(profile, itemId)) return profile;
  const equipped = getEquippedItems(profile);
  // pouze jeden kus na kategorii
  const filtered = equipped.filter(eid => {
    const other = getShopItem(eid);
    return other && other.category !== item.category;
  });
  const next = equipped.includes(itemId)
    ? equipped.filter(id => id !== itemId)
    : [...filtered, itemId];
  return { ...profile, inventory: { owned: getOwnedItems(profile), equipped: next } };
}

// ─── ACHIEVEMENTS ────────────────────────────────────────────
const ACHIEVEMENTS = [
  { id: 'first-step',    name: 'První krůček',        icon: '🐾', desc: 'Dokonči první úkol',              reward: 5,
    test: (stats) => stats.tasksCompleted >= 1 },
  { id: 'learner',       name: 'Učenlivý',            icon: '📚', desc: 'Dokonči 5 úkolů',                 reward: 10,
    test: (stats) => stats.tasksCompleted >= 5 },
  { id: 'master',        name: 'Mistr',               icon: '🏆', desc: 'Dokonči 20 úkolů',                reward: 25,
    test: (stats) => stats.tasksCompleted >= 20 },
  { id: 'pro',           name: 'Profík',              icon: '🎯', desc: 'Dokonči 50 úkolů',                reward: 50,
    test: (stats) => stats.tasksCompleted >= 50 },
  { id: 'explorer',      name: 'Prozkoumatel',        icon: '🧭', desc: 'Zkus všech 6 kategorií',          reward: 20,
    test: (stats) => (stats.categoriesTried?.length || 0) >= 6 },
  { id: 'perfectionist', name: 'Dokonalost',          icon: '⭐', desc: '3 úkoly správně napoprvé za sebou', reward: 15,
    test: (stats) => (stats.perfectStreak || 0) >= 3 },
  { id: 'collector',     name: 'Sběratel',            icon: '🎁', desc: 'Kup 3 předměty v obchodě',        reward: 10,
    test: (stats) => (stats.itemsOwned || 0) >= 3 },
  { id: 'rich',          name: 'Boháč',               icon: '💰', desc: 'Nasbírej 100 mincí',              reward: 10,
    test: (stats) => (stats.coins || 0) >= 100 },
  { id: 'streak-3',      name: 'Ve třech je síla',    icon: '🔥', desc: 'Hraj 3 dny v řadě',               reward: 15,
    test: (stats) => (stats.streak || 0) >= 3 },
  { id: 'streak-7',      name: 'Týden s Pandičkou',   icon: '🌟', desc: 'Hraj 7 dní v řadě',               reward: 40,
    test: (stats) => (stats.streak || 0) >= 7 },
  { id: 'level-5',       name: 'Pátá úroveň',         icon: '🎖️', desc: 'Dosáhni úrovně 5',                 reward: 20,
    test: (stats) => (stats.level || 0) >= 5 },
];

function getUnlockedAchievements(profile) {
  return (profile?.achievements && profile.achievements.unlocked) || [];
}

function computeStats(profile) {
  const progress = profile?.progress || {};
  const tasksCompleted = Object.values(progress).reduce((a, b) => a + (b || 0), 0);
  const categoriesTried = Object.keys(progress).filter(k => progress[k] > 0);
  return {
    tasksCompleted,
    categoriesTried,
    coins: profile?.coins || 0,
    level: profile?.level || 1,
    streak: profile?.streak?.count || 0,
    perfectStreak: profile?.perfectStreak || 0,
    itemsOwned: getOwnedItems(profile).length,
  };
}

function checkNewAchievements(profile) {
  const stats = computeStats(profile);
  const unlocked = getUnlockedAchievements(profile);
  const newly = ACHIEVEMENTS.filter(a => !unlocked.includes(a.id) && a.test(stats));
  return newly;
}

function grantAchievement(profile, achievementId) {
  const ach = ACHIEVEMENTS.find(a => a.id === achievementId);
  if (!ach || getUnlockedAchievements(profile).includes(achievementId)) return profile;
  return {
    ...profile,
    coins: (profile.coins || 0) + (ach.reward || 0),
    achievements: {
      unlocked: [...getUnlockedAchievements(profile), achievementId],
    },
  };
}

// ─── STREAK (denní návštěva) ─────────────────────────────────
function todayKey() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}
function yesterdayKey() {
  const d = new Date(Date.now() - 24*3600*1000);
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}

function touchStreak(profile) {
  const streak = profile?.streak || { count: 0, lastDay: null };
  const today = todayKey();
  if (streak.lastDay === today) return profile; // dnes už bylo
  const nextCount = streak.lastDay === yesterdayKey() ? (streak.count || 0) + 1 : 1;
  return { ...profile, streak: { count: nextCount, lastDay: today } };
}

// ─── Perfect streak update (správně napoprvé) ─────────────────
function recordAttempt(profile, { correct, firstTry }) {
  const next = { ...profile };
  if (correct && firstTry) next.perfectStreak = (profile.perfectStreak || 0) + 1;
  else if (!correct) next.perfectStreak = 0;
  return next;
}

Object.assign(window, {
  SHOP_ITEMS, RARITY, getShopItem,
  getOwnedItems, getEquippedItems, isOwned, isEquipped,
  purchaseItem, toggleEquipped,
  ACHIEVEMENTS, getUnlockedAchievements, computeStats,
  checkNewAchievements, grantAchievement,
  todayKey, touchStreak, recordAttempt,
});
