// Obchůdek u Pandičky + Síň slávy (odznáčky) + Šatník

// ─── SHOP ────────────────────────────────────────────────────
function ShopScreen({ palette, metaphor, age, playfulness, profile, onBack, onUpdateProfile }) {
  const [filter, setFilter] = useState('all');
  const [toast, setToast] = useState(null);

  const filtered = filter === 'all' ? SHOP_ITEMS : SHOP_ITEMS.filter(i => i.category === filter);

  const buy = (item) => {
    try {
      const next = purchaseItem(profile, item.id);
      onUpdateProfile?.(next);
      setToast({ kind: 'success', msg: `${item.name} je tvá! 🎉` });
      announceAssertive(`Koupil jsi ${item.name}.`);
      trackEvent('shop_purchase', { itemId: item.id, price: String(item.price) });
    } catch (e) {
      setToast({ kind: 'error', msg: e.message });
    }
    setTimeout(() => setToast(null), 2200);
  };

  const toggle = (item) => {
    const next = toggleEquipped(profile, item.id);
    onUpdateProfile?.(next);
    announce(isEquipped(profile, item.id) ? `Sundal jsi ${item.name}` : `Nasadil jsi ${item.name}`);
  };

  const cats = [
    { id: 'all',  label: 'Vše', icon: '🛍️' },
    { id: 'head', label: 'Hlava', icon: '👒' },
    { id: 'face', label: 'Obličej', icon: '👓' },
    { id: 'ear',  label: 'Uši', icon: '🌸' },
    { id: 'neck', label: 'Krk', icon: '🧣' },
    { id: 'body', label: 'Tělo', icon: '🦸' },
    { id: 'back', label: 'Záda', icon: '🌈' },
  ];

  return (
    <div style={{ position: 'relative', minHeight: '100%', zIndex: 1, padding: '0 0 40px' }}>
      <div style={{
        padding: '20px 20px 14px', display: 'flex', alignItems: 'center', gap: 12,
        position: 'sticky', top: 0, zIndex: 10,
        background: `linear-gradient(180deg, ${palette.bg} 60%, ${palette.bg}00)`,
      }}>
        <motion.button whileTap={{ scale: 0.9 }} onClick={onBack} aria-label="Zpět" style={{
          width: 44, height: 44, borderRadius: 14, border: 'none',
          background: palette.card, boxShadow: playfulShadow(1), cursor: 'pointer',
        }}>←</motion.button>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 600,
            letterSpacing: '0.08em', textTransform: 'uppercase', color: palette.inkSoft,
          }}>Obchůdek</div>
          <div style={{
            fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 22, color: palette.ink,
          }}>Ozdob si Pandičku 🛍️</div>
        </div>
        <CoinChip amount={profile.coins || 0} palette={palette} size="md"/>
      </div>

      {/* Avatar preview */}
      <div style={{
        padding: '12px 20px 18px', display: 'flex', alignItems: 'center', gap: 16, justifyContent: 'center',
      }}>
        <div style={{
          width: 160, height: 160, borderRadius: 32,
          background: `radial-gradient(circle at 50% 40%, ${palette.sun}40, ${palette.bg})`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: playfulShadow(2),
        }}>
          <Pandicka size={150} pose="wave" expression="happy" accent={profile.accent}
            accessories={getEquippedItems(profile)}/>
        </div>
        <div style={{ maxWidth: 180 }}>
          <div style={{ fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 18, color: palette.ink }}>
            {profile.name}
          </div>
          <div style={{ fontFamily: '"Baloo 2"', fontSize: 13, color: palette.inkSoft, marginTop: 4 }}>
            {getEquippedItems(profile).length > 0
              ? `Má na sobě ${getEquippedItems(profile).length} ${getEquippedItems(profile).length === 1 ? 'doplněk' : 'doplňky'}.`
              : 'Ještě nic nemá. Vyber něco pěkného!'}
          </div>
        </div>
      </div>

      {/* Category filter */}
      <div style={{
        padding: '0 20px 12px', display: 'flex', gap: 8, overflowX: 'auto',
      }}>
        {cats.map(c => (
          <button key={c.id} onClick={() => setFilter(c.id)} style={{
            flexShrink: 0,
            padding: '8px 14px', borderRadius: 999,
            border: `1.5px solid ${filter === c.id ? palette.primaryDeep : palette.ink + '15'}`,
            background: filter === c.id ? palette.primary + '20' : palette.card,
            color: filter === c.id ? palette.primaryDeep : palette.ink,
            cursor: 'pointer',
            fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 13,
          }}>
            <span style={{ marginRight: 4 }}>{c.icon}</span>{c.label}
          </button>
        ))}
      </div>

      {/* Grid */}
      <div style={{
        padding: '0 20px', display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 12,
      }}>
        {filtered.map(item => {
          const owned = isOwned(profile, item.id);
          const equipped = isEquipped(profile, item.id);
          const canAfford = (profile.coins || 0) >= item.price;
          const rarity = RARITY[item.rarity] || RARITY.common;
          return (
            <motion.div key={item.id}
              whileHover={{ y: -3 }}
              style={{
                padding: 14, borderRadius: 20,
                background: palette.card,
                border: `2px solid ${equipped ? palette.success : rarity.color + '60'}`,
                boxShadow: playfulShadow(1),
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                position: 'relative',
              }}>
              <div style={{
                position: 'absolute', top: 8, right: 8,
                padding: '2px 8px', borderRadius: 999,
                background: rarity.color + '30', color: palette.ink,
                fontFamily: '"Baloo 2"', fontSize: 9, fontWeight: 700,
                letterSpacing: '0.06em', textTransform: 'uppercase',
              }}>{rarity.label}</div>
              <div style={{
                width: 70, height: 70, borderRadius: 18,
                background: rarity.color + '25',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 40, marginTop: 10,
              }}>{item.emoji}</div>
              <div style={{
                fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 13, color: palette.ink,
                textAlign: 'center', minHeight: 32,
              }}>{item.name}</div>
              {owned ? (
                <button onClick={() => toggle(item)} style={{
                  width: '100%', padding: '8px', borderRadius: 14, border: 'none', cursor: 'pointer',
                  background: equipped ? palette.success : palette.ink + '10',
                  color: equipped ? '#fff' : palette.ink,
                  fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 12,
                }} aria-pressed={equipped}>
                  {equipped ? '✓ Mám na sobě' : 'Nasadit'}
                </button>
              ) : (
                <button onClick={() => buy(item)} disabled={!canAfford} style={{
                  width: '100%', padding: '8px', borderRadius: 14, border: 'none',
                  cursor: canAfford ? 'pointer' : 'not-allowed',
                  background: canAfford ? palette.primary : palette.ink + '12',
                  color: canAfford ? '#fff' : palette.inkSoft,
                  fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 12,
                  boxShadow: canAfford ? `0 2px 0 ${palette.primaryDeep}` : 'none',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 4,
                }}>
                  💰 {item.price}
                </button>
              )}
            </motion.div>
          );
        })}
      </div>

      <AnimatePresence>
        {toast && (
          <motion.div
            initial={{ y: 100, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: 100, opacity: 0 }}
            role="status"
            style={{
              position: 'fixed', bottom: 80, left: '50%', transform: 'translateX(-50%)',
              padding: '12px 20px', borderRadius: 999,
              background: toast.kind === 'success' ? palette.success : palette.danger,
              color: '#fff', fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 14,
              boxShadow: '0 10px 30px rgba(0,0,0,0.2)', zIndex: 100,
            }}>{toast.msg}</motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

// ─── ACHIEVEMENTS (Síň slávy) ─────────────────────────────────
function AchievementsScreen({ palette, metaphor, age, playfulness, profile, onBack }) {
  const unlocked = getUnlockedAchievements(profile);
  const stats = computeStats(profile);
  const progress = `${unlocked.length}/${ACHIEVEMENTS.length}`;

  return (
    <div style={{ position: 'relative', minHeight: '100%', zIndex: 1, padding: '0 0 40px' }}>
      <div style={{ padding: '20px 20px 14px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <motion.button whileTap={{ scale: 0.9 }} onClick={onBack} aria-label="Zpět" style={{
          width: 44, height: 44, borderRadius: 14, border: 'none',
          background: palette.card, boxShadow: playfulShadow(1), cursor: 'pointer',
        }}>←</motion.button>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 600,
            letterSpacing: '0.08em', textTransform: 'uppercase', color: palette.inkSoft,
          }}>Síň slávy</div>
          <div style={{
            fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 22, color: palette.ink,
          }}>Tvé odznáčky 🏆</div>
        </div>
        <div style={{
          padding: '6px 12px', borderRadius: 999, background: palette.sun + '40',
          fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 14, color: palette.ink,
        }}>{progress}</div>
      </div>

      {/* Stats strip */}
      <div style={{ padding: '0 20px 14px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
        <StatMini palette={palette} label="Úkolů" value={stats.tasksCompleted}/>
        <StatMini palette={palette} label="Kategorií" value={stats.categoriesTried.length}/>
        <StatMini palette={palette} label="Série" value={`${stats.streak} 🔥`}/>
      </div>

      <div style={{
        padding: '0 20px', display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: 12,
      }}>
        {ACHIEVEMENTS.map(a => {
          const unl = unlocked.includes(a.id);
          return (
            <div key={a.id} style={{
              padding: 14, borderRadius: 20,
              background: unl ? palette.sun + '25' : palette.ink + '06',
              border: `2px solid ${unl ? palette.sun + '80' : palette.ink + '15'}`,
              textAlign: 'center',
              opacity: unl ? 1 : 0.6,
              filter: unl ? 'none' : 'grayscale(0.6)',
            }}>
              <div style={{ fontSize: 42, lineHeight: 1 }}>{unl ? a.icon : '🔒'}</div>
              <div style={{
                fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 14, color: palette.ink, marginTop: 6,
              }}>{a.name}</div>
              <div style={{
                fontFamily: '"Baloo 2"', fontSize: 11, color: palette.inkSoft, marginTop: 4, minHeight: 30,
              }}>{a.desc}</div>
              {unl && (
                <div style={{
                  marginTop: 8, padding: '3px 10px', borderRadius: 999,
                  background: palette.success + '30', color: palette.ink,
                  fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 700,
                  display: 'inline-block',
                }}>+{a.reward} 💰</div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function StatMini({ palette, label, value }) {
  return (
    <div style={{
      padding: '10px 12px', borderRadius: 14, background: palette.card,
      boxShadow: playfulShadow(1), textAlign: 'center',
    }}>
      <div style={{
        fontFamily: '"Baloo 2"', fontSize: 10, color: palette.inkSoft,
        letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600,
      }}>{label}</div>
      <div style={{
        fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 20, color: palette.ink, marginTop: 2,
      }}>{value}</div>
    </div>
  );
}

// ─── Achievement unlocked modal ──────────────────────────────
function AchievementToast({ achievement, palette, onClose }) {
  useEffect(() => {
    const t = setTimeout(onClose, 3500);
    return () => clearTimeout(t);
  }, []);
  if (!achievement) return null;
  return (
    <motion.div
      initial={{ y: -80, opacity: 0 }} animate={{ y: 20, opacity: 1 }} exit={{ y: -80, opacity: 0 }}
      role="alert"
      style={{
        position: 'fixed', top: 16, left: '50%', transform: 'translateX(-50%)',
        zIndex: 300, padding: '14px 18px', borderRadius: 20,
        background: `linear-gradient(135deg, ${palette.sun}, ${palette.primary})`,
        color: '#fff', fontFamily: '"Baloo 2"',
        boxShadow: '0 10px 40px rgba(0,0,0,0.25)',
        display: 'flex', alignItems: 'center', gap: 12, maxWidth: 340,
      }}
      onClick={onClose}>
      <div style={{ fontSize: 36 }}>{achievement.icon}</div>
      <div>
        <div style={{ fontSize: 11, fontWeight: 600, opacity: 0.9, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
          Nový odznáček!
        </div>
        <div style={{ fontWeight: 700, fontSize: 16 }}>{achievement.name}</div>
        <div style={{ fontSize: 12, opacity: 0.9 }}>+{achievement.reward} 💰</div>
      </div>
    </motion.div>
  );
}

Object.assign(window, { ShopScreen, AchievementsScreen, AchievementToast });
