// Screens 3-5: Adventure map, Task player, Parent dashboard

// ───────────────────────────────────────────────────────
// SCREEN 3 — Adventure map (vertical level path)
// ───────────────────────────────────────────────────────
function AdventureMapScreen({ palette, metaphor, age, playfulness, profile, category, subscription, onBack, onLevel, onUpgrade }) {
  const meta = METAPHORS[metaphor];
  const tasksInCat = useMemo(() => getTasksByCategory(category.id || 'hearing'), [category.id]);
  const progress = (profile.progress && profile.progress[category.id]) || 0;
  const maxUnlocked = maxUnlockedLevels(subscription, tasksInCat.length);
  const [showPaywall, setShowPaywall] = useState(false);
  const levels = tasksInCat.length > 0 ? tasksInCat.map((t, i) => {
    const beyondFree = i >= maxUnlocked;
    let state = i < progress ? 'done' : i === progress ? 'current' : 'locked';
    if (beyondFree && state !== 'done') state = 'premium-locked';
    const stars = state === 'done' ? 3 : state === 'current' ? 1 : 0;
    return { n: i + 1, label: (t.titleShort || t.title).slice(0, 24), stars, state, task: t, boss: t.boss };
  }) : [{ n: 1, label: 'Brzy!', stars: 0, state: 'locked' }];

  const handleLevelClick = (lvl) => {
    if (lvl.state === 'premium-locked') { setShowPaywall(true); return; }
    if (lvl.state === 'locked') return;
    onLevel(lvl);
  };

  // Zig-zag positions for path
  const pathX = (i) => {
    const amp = 90;
    return 50 + Math.sin(i * 0.95) * amp / 4; // percentage 50±amp
  };

  const skyGrad = `linear-gradient(180deg, ${meta.sky[0]}, ${meta.sky[1]})`;

  return (
    <div style={{ position: 'relative', minHeight: '100%', zIndex: 1 }}>
      {/* Sky-like overlay behind path */}
      <div style={{
        position: 'absolute', inset: 0, background: skyGrad, zIndex: -1,
        opacity: metaphor === 'space' ? 1 : 0.6,
      }}/>
      {metaphor === 'space' && (
        <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0, zIndex: -1 }}>
          {Array.from({ length: 40 }).map((_, i) => (
            <circle key={i} cx={`${(i * 37) % 100}%`} cy={`${(i * 53) % 100}%`} r={Math.random() * 1.5 + 0.5}
              fill="#fff" opacity={0.3 + Math.random() * 0.6}/>
          ))}
        </svg>
      )}

      {/* Top bar */}
      <div style={{
        padding: '20px 20px 14px', display: 'flex', alignItems: 'center', gap: 12,
        position: 'sticky', top: 0, zIndex: 10,
        background: metaphor === 'space' ? 'rgba(30,23,69,0.6)' : 'rgba(255,244,226,0.5)',
        backdropFilter: 'blur(8px)',
      }}>
        <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',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24">
            <path d="M15 6l-6 6 6 6" stroke={palette.ink} strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </motion.button>

        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 600,
            color: metaphor === 'space' ? '#C9BCFF' : palette.inkSoft,
            letterSpacing: '0.08em', textTransform: 'uppercase',
          }}>{meta.pathLabel}</div>
          <div style={{
            fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 22,
            color: metaphor === 'space' ? '#fff' : palette.ink,
            lineHeight: 1.1,
          }}>{category.name}</div>
        </div>
        <CoinChip amount={profile.coins} palette={palette} size="md"/>
      </div>

      {/* Path */}
      <div style={{
        position: 'relative', padding: '20px 0 60px',
        minHeight: Math.max(500, 60 + levels.length * 110 + 80),
      }}>
        {/* Dashed path SVG */}
        <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0, zIndex: 0 }} preserveAspectRatio="none">
          <path
            d={levels.map((_, i) => {
              const x = pathX(i);
              const y = 60 + i * 110;
              return `${i === 0 ? 'M' : 'L'} ${x}% ${y}`;
            }).join(' ')}
            stroke={metaphor === 'space' ? '#C9BCFF80' : '#FFFFFF'}
            strokeWidth="8" strokeDasharray="2 14" strokeLinecap="round" fill="none"
          />
        </svg>

        {/* Level nodes */}
        {levels.map((lvl, i) => {
          const x = pathX(i);
          const y = 60 + i * 110;
          const done = lvl.state === 'done';
          const current = lvl.state === 'current';
          const locked = lvl.state === 'locked';
          const premiumLocked = lvl.state === 'premium-locked';
          const bg = done ? palette.success
                  : current ? palette.primary
                  : premiumLocked ? palette.sun
                  : palette.ink + '30';
          const ring = done ? '#4A8E67'
                    : current ? palette.primaryDeep
                    : premiumLocked ? '#B8821E'
                    : palette.ink + '40';

          return (
            <div key={i} style={{
              position: 'absolute', left: `${x}%`, top: y,
              transform: 'translate(-50%, -50%)',
            }}>
              {/* Side landmark */}
              {i % 2 === 0 && (
                <Landmark emoji={meta.landmarks[i % meta.landmarks.length]}
                  size={48}
                  style={{ position: 'absolute', left: -80, top: -10 }}
                  rotate={-15}
                />
              )}
              {i % 2 === 1 && (
                <Landmark emoji={meta.landmarks[i % meta.landmarks.length]}
                  size={44}
                  style={{ position: 'absolute', right: -80, top: -5 }}
                  rotate={15}
                />
              )}

              <motion.button
                onClick={locked ? undefined : () => handleLevelClick(lvl)}
                aria-label={premiumLocked ? `Úroveň ${lvl.n} — dostupná s Premium` : `Úroveň ${lvl.n}`}
                whileHover={locked ? undefined : { scale: 1.06, y: -3 }}
                whileTap={locked ? undefined : { scale: 0.95 }}
                animate={current ? { y: [-2, 2, -2] } : undefined}
                transition={current ? { duration: 2, repeat: Infinity, ease: 'easeInOut' } : undefined}
                style={{
                  width: lvl.boss ? 96 : 84, height: lvl.boss ? 96 : 84,
                  borderRadius: '50%', border: `5px solid ${ring}`,
                  background: bg, cursor: locked ? 'not-allowed' : 'pointer',
                  boxShadow: `0 6px 0 ${ring}, 0 10px 24px rgba(0,0,0,0.15)`,
                  display: 'flex', flexDirection: 'column',
                  alignItems: 'center', justifyContent: 'center',
                  color: '#fff', position: 'relative',
                  opacity: locked ? 0.6 : 1,
                }}
              >
                <div style={{
                  fontFamily: '"Baloo 2"', fontWeight: 700,
                  fontSize: lvl.boss ? 34 : 30, lineHeight: 1,
                  color: '#fff',
                  textShadow: '0 2px 0 rgba(0,0,0,0.15)',
                }}>
                  {locked ? '🔒' : premiumLocked ? '⭐' : lvl.boss ? '🎁' : lvl.n}
                </div>
                {/* Stars */}
                {done && (
                  <div style={{ display: 'flex', gap: 1, marginTop: 2 }}>
                    {[0,1,2].map(s => (
                      <span key={s} style={{
                        fontSize: 12,
                        filter: s < lvl.stars ? 'none' : 'grayscale(1) opacity(0.4)',
                      }}>⭐</span>
                    ))}
                  </div>
                )}
                {current && (
                  <motion.div
                    animate={{ scale: [1, 1.2, 1], opacity: [0.6, 0.2, 0.6] }}
                    transition={{ duration: 2, repeat: Infinity }}
                    style={{
                      position: 'absolute', inset: -10, borderRadius: '50%',
                      border: `3px solid ${palette.primary}`,
                      pointerEvents: 'none',
                    }}
                  />
                )}
              </motion.button>

              {/* Label */}
              <div style={{
                marginTop: 6, textAlign: 'center',
                fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 14,
                color: metaphor === 'space' ? '#fff' : palette.ink,
                textShadow: metaphor === 'space' ? '0 1px 2px rgba(0,0,0,0.5)' : undefined,
              }}>{lvl.label}</div>

              {/* Pandička on current level */}
              {current && (
                <motion.div
                  initial={{ y: -60, opacity: 0 }}
                  animate={{ y: -72, opacity: 1 }}
                  transition={{ delay: 0.3, type: 'spring' }}
                  style={{
                    position: 'absolute', left: '50%', top: 0,
                    transform: 'translate(-50%, -100%)',
                  }}
                >
                  <Pandicka size={64} pose="wave" expression="happy" accent={palette.accent}
                    accessories={getEquippedItems(profile)}/>
                </motion.div>
              )}
            </div>
          );
        })}
      </div>

      {/* Free-tier banner */}
      {!isPremium(subscription) && tasksInCat.length > maxUnlocked && (
        <div style={{
          margin: '0 20px 24px',
          padding: 16, borderRadius: 22,
          background: `linear-gradient(135deg, ${palette.sun}, ${palette.primary})`,
          color: '#fff', fontFamily: '"Baloo 2"',
          display: 'flex', alignItems: 'center', gap: 12,
          boxShadow: '0 10px 30px rgba(0,0,0,0.15)',
        }}>
          <div style={{ fontSize: 36 }}>⭐</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 15 }}>
              Ochutnávka zdarma: {maxUnlocked} z {tasksInCat.length} úkolů
            </div>
            <div style={{ fontSize: 12, opacity: 0.9 }}>
              Odemkni celý katalog s Pandička Premium.
            </div>
          </div>
          <button onClick={() => setShowPaywall(true)} style={{
            padding: '10px 14px', borderRadius: 999, border: 'none', cursor: 'pointer',
            background: '#fff', color: palette.primaryDeep,
            fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 13,
          }}>Odemknout</button>
        </div>
      )}

      {showPaywall && (
        <PaywallModal palette={palette}
          onClose={() => setShowPaywall(false)}/>
      )}
    </div>
  );
}

function PaywallModal({ palette, onClose }) {
  return (
    <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(20,14,20,0.6)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
      }}>
      <motion.div initial={{ scale: 0.9, y: 20 }} animate={{ scale: 1, y: 0 }}
        onClick={e => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: 380, background: palette.card, borderRadius: 28, padding: 24,
          boxShadow: '0 30px 60px rgba(0,0,0,0.3)', textAlign: 'center',
        }}>
        <Pandicka size={120} pose="read" expression="thinking" accent={palette.accent}/>
        <div style={{ fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 24, color: palette.ink, marginTop: 4 }}>
          Pandička Premium ⭐
        </div>
        <div style={{ fontFamily: '"Baloo 2"', fontSize: 14, color: palette.inkSoft, marginTop: 6, marginBottom: 16 }}>
          S Premium odemkneš všech 46 úkolů, pokročilé reporty a nové typy úkolů.
        </div>
        <div style={{
          background: palette.bgDeep + '60', borderRadius: 16, padding: 14, marginBottom: 14,
          textAlign: 'left', fontFamily: '"Baloo 2"', fontSize: 13, color: palette.ink,
        }}>
          <div style={{ marginBottom: 4 }}>✅ Všechny úkoly ve všech kategoriích</div>
          <div style={{ marginBottom: 4 }}>✅ Pokročilé reporty pro rodiče</div>
          <div style={{ marginBottom: 4 }}>✅ Nové úkoly každý měsíc</div>
          <div>✅ Podpora projektu</div>
        </div>
        <div style={{
          padding: '14px 16px', borderRadius: 16,
          background: palette.sun + '30', border: `1.5px solid ${palette.sun}80`,
          fontFamily: '"Baloo 2"', fontSize: 14, color: palette.ink, fontWeight: 600,
          marginBottom: 12,
        }}>
          🚧 Připravuje se způsob pro odemknutí
          <div style={{ fontSize: 12, fontWeight: 500, color: palette.inkSoft, marginTop: 4 }}>
            Brzy tady bude možnost aktivace Premium. Prozatím si užij ochutnávku zdarma.
          </div>
        </div>
        <button onClick={onClose} style={{
          padding: '12px 24px', borderRadius: 999, border: 'none', cursor: 'pointer',
          background: palette.primary, color: '#fff',
          fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 14,
          boxShadow: `0 3px 0 ${palette.primaryDeep}`,
        }}>Rozumím 🐾</button>
      </motion.div>
    </motion.div>
  );
}

// ───────────────────────────────────────────────────────
// SCREEN 4 — Task player (choice task)
// ───────────────────────────────────────────────────────
function TaskPlayerScreen({ palette, metaphor, age, playfulness, profile, level, category, onBack, onComplete }) {
  const [phase, setPhase] = useState('question'); // question | correct | wrong | feedback
  const [selected, setSelected] = useState(null);
  const [attempts, setAttempts] = useState(0);
  const [feedbackEmoji, setFeedbackEmoji] = useState(null);

  const task = level && level.task ? level.task : getTasksByCategory(category?.id || 'hearing')[0];

  const question = task ? {
    prompt: task.title,
    promptShort: task.titleShort || task.title,
    audio: task.audio,
    options: task.options || [],
  } : {
    prompt: 'Zatím žádné úkoly', promptShort: 'Brzy!', audio: '',
    options: [],
  };

  const totalInCat = (getTasksByCategory(category?.id || 'hearing') || []).length || 1;
  const currentN = level?.n || 1;

  const handlePick = (opt) => {
    if (phase !== 'question') return;
    setSelected(opt.id);
    if (opt.correct) {
      setPhase('correct');
      announceAssertive('Správně! Výborně.');
      trackTaskAttempt({ taskId: task?.id, categoryId: task?.categoryId, correct: true, attempts: attempts + 1 });
      setTimeout(() => setPhase('feedback'), 1600);
    } else {
      setPhase('wrong');
      setAttempts(a => a + 1);
      announce('Zkus to znovu.');
      trackTaskAttempt({ taskId: task?.id, categoryId: task?.categoryId, correct: false, attempts: attempts + 1 });
      setTimeout(() => { setPhase('question'); setSelected(null); }, 1200);
    }
  };

  const handleFeedback = (emoji) => {
    setFeedbackEmoji(emoji);
    const reward = task?.reward || { xp: 10, coins: 5 };
    onComplete({ xp: reward.xp, coins: reward.coins, attempts, feedback: emoji });
  };

  const playAudio = () => {
    if (typeof window.speechSynthesis !== 'undefined') {
      const u = new SpeechSynthesisUtterance(question.audio);
      u.lang = 'cs-CZ'; u.rate = 0.9;
      window.speechSynthesis.cancel();
      window.speechSynthesis.speak(u);
    }
  };

  return (
    <div style={{
      position: 'relative', minHeight: '100%', zIndex: 1,
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Top bar with progress */}
      <div style={{
        padding: '20px 20px 16px', 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',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24">
            <path d="M6 6l12 12M6 18L18 6" stroke={palette.ink} strokeWidth="2.5" fill="none" strokeLinecap="round"/>
          </svg>
        </motion.button>
        <div style={{
          flex: 1, height: 14, background: palette.ink + '14',
          borderRadius: 7, overflow: 'hidden',
        }}>
          <motion.div
            animate={{ width: `${(currentN / totalInCat) * 100}%` }}
            style={{
              height: '100%',
              background: `linear-gradient(90deg, ${palette.sun}, ${palette.primary})`,
              borderRadius: 7,
            }}
          />
        </div>
        <div style={{
          padding: '6px 12px', borderRadius: 999,
          background: palette.ink + '10',
          fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 13, color: palette.ink,
        }}>{currentN}/{totalInCat}</div>
      </div>

      {/* Question area */}
      <div style={{ padding: '10px 24px 0', textAlign: 'center' }}>
        <div style={{
          fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 600,
          letterSpacing: '0.08em', textTransform: 'uppercase',
          color: palette.inkSoft,
        }}>Úkol · {category?.shortName || category?.name || 'Pandička'}</div>
        <div style={{
          fontFamily: '"Baloo 2"', fontWeight: 700,
          fontSize: AGE_MODES[age].showText ? 28 : 34,
          color: palette.ink, marginTop: 6, lineHeight: 1.1,
        }}>
          {AGE_MODES[age].showText ? question.prompt : question.promptShort}
        </div>

        {/* Audio button */}
        <motion.button
          onClick={playAudio}
          whileTap={{ scale: 0.95 }}
          animate={phase === 'question' ? { scale: [1, 1.04, 1] } : {}}
          transition={{ duration: 2, repeat: Infinity }}
          style={{
            marginTop: 16, padding: '12px 24px',
            borderRadius: 999, border: 'none',
            background: palette.sky,
            fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 16,
            color: palette.ink, cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 8,
            boxShadow: '0 3px 0 rgba(59,42,47,0.15)',
          }}
        >
          <span style={{ fontSize: 22 }}>🔊</span>
          Poslechni si
        </motion.button>
      </div>

      {/* Options */}
      <div style={{
        padding: '28px 20px', display: 'grid',
        gridTemplateColumns: '1fr 1fr', gap: 14, maxWidth: 500, margin: '0 auto', width: '100%',
      }}>
        {question.options.map(opt => {
          const isSel = selected === opt.id;
          const showCorrect = phase === 'correct' && opt.correct;
          const showWrong = phase === 'wrong' && isSel;
          return (
            <motion.button
              key={opt.id}
              onClick={() => handlePick(opt)}
              aria-label={opt.label}
              aria-pressed={isSel}
              disabled={phase !== 'question'}
              whileHover={phase === 'question' ? { y: -4, scale: 1.03 } : undefined}
              whileTap={phase === 'question' ? { scale: 0.96 } : undefined}
              animate={showWrong ? { x: [-6, 6, -6, 6, 0] } : showCorrect ? { scale: [1, 1.12, 1] } : {}}
              transition={{ duration: 0.5 }}
              style={{
                aspectRatio: '1 / 1',
                border: `4px solid ${
                  showCorrect ? palette.success :
                  showWrong ? palette.danger :
                  isSel ? palette.primary : palette.ink + '18'
                }`,
                borderRadius: 28,
                background:
                  showCorrect ? palette.success + '20' :
                  showWrong ? palette.danger + '20' : palette.card,
                cursor: phase === 'question' ? 'pointer' : 'default',
                display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center',
                gap: 6, padding: 10,
                boxShadow: playfulShadow(playfulness),
                position: 'relative',
              }}
            >
              <div style={{ fontSize: 76, lineHeight: 1 }}>{opt.emoji}</div>
              {AGE_MODES[age].showText && (
                <div style={{
                  fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 17,
                  color: palette.ink,
                }}>{opt.label}</div>
              )}
              {showCorrect && (
                <motion.div
                  initial={{ scale: 0 }} animate={{ scale: 1 }}
                  style={{
                    position: 'absolute', top: -14, right: -14,
                    width: 44, height: 44, borderRadius: '50%',
                    background: palette.success, color: '#fff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 22, fontWeight: 700,
                    boxShadow: '0 4px 10px rgba(0,0,0,0.2)',
                  }}>✓</motion.div>
              )}
            </motion.button>
          );
        })}
      </div>

      {/* Footer — Pandička reaction */}
      <div style={{ marginTop: 'auto', padding: '10px 24px 32px', textAlign: 'center' }}>
        <AnimatePresence mode="wait">
          {phase === 'question' && (
            <motion.div key="q" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
              <Pandicka size={90} pose="sit" expression="thinking" accent={palette.accent}
                accessories={getEquippedItems(profile)}/>
              <div style={{
                fontFamily: '"Baloo 2"', fontSize: 14, color: palette.inkSoft, marginTop: -6,
              }}>Vyber správnou odpověď</div>
            </motion.div>
          )}
          {phase === 'wrong' && (
            <motion.div key="w" initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }}>
              <Pandicka size={90} pose="sit" expression="thinking" accent={palette.accent}
                accessories={getEquippedItems(profile)}/>
              <div style={{
                fontFamily: '"Baloo 2"', fontSize: 16, color: palette.danger, marginTop: -6, fontWeight: 600,
              }}>Skoro! Zkus to ještě jednou 🐾</div>
            </motion.div>
          )}
          {phase === 'correct' && (
            <motion.div key="c" initial={{ opacity: 0, scale: 0.8 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0 }}>
              <Pandicka size={100} pose="cheer" expression="excited" accent={palette.accent}
                accessories={getEquippedItems(profile)}/>
              <div style={{
                fontFamily: '"Baloo 2"', fontSize: 18, color: palette.success, fontWeight: 700, marginTop: -4,
              }}>Výborně! 🎉</div>
            </motion.div>
          )}
          {phase === 'feedback' && (
            <motion.div key="f" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
              <div style={{
                fontFamily: '"Baloo 2"', fontSize: 22, fontWeight: 700, color: palette.ink,
                marginBottom: 14,
              }}>Jak to šlo?</div>
              <div style={{ display: 'flex', justifyContent: 'center', gap: 14 }}>
                {[
                  { e: '😅', t: 'Těžké' },
                  { e: '🙂', t: 'Akorát' },
                  { e: '🤩', t: 'Hračka' },
                ].map(f => (
                  <motion.button
                    key={f.e} whileHover={{ y: -4, scale: 1.1 }} whileTap={{ scale: 0.9 }}
                    onClick={() => handleFeedback(f.e)}
                    style={{
                      width: 90, padding: '14px 4px',
                      borderRadius: 22, border: `3px solid ${feedbackEmoji === f.e ? palette.primary : palette.ink + '18'}`,
                      background: palette.card, cursor: 'pointer',
                      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                      boxShadow: playfulShadow(2),
                    }}
                  >
                    <div style={{ fontSize: 40 }}>{f.e}</div>
                    <div style={{ fontFamily: '"Baloo 2"', fontSize: 13, color: palette.ink, fontWeight: 600 }}>{f.t}</div>
                  </motion.button>
                ))}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────
// SCREEN 5 — Parent dashboard
// ───────────────────────────────────────────────────────
function ParentDashboardScreen({ palette, metaphor, age, playfulness, user, subscription, onBack, onAdmin, onPrivacy, onLogout }) {
  // Reálná data z localStorage progress logu (+ Firebase, pokud je k dispozici — nacteme sync ze synclu).
  const kids = useMemo(() => loadRealKids(), []);
  const [showPaywall, setShowPaywall] = useState(false);

  return (
    <div style={{ position: 'relative', minHeight: '100%', zIndex: 1, padding: '0 0 60px' }}>
      {/* Top bar */}
      <div style={{
        padding: '22px 24px 16px', 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',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24">
            <path d="M15 6l-6 6 6 6" stroke={palette.ink} strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </motion.button>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 600,
            letterSpacing: '0.08em', textTransform: 'uppercase', color: palette.inkSoft,
          }}>Rodičovský kout</div>
          <div style={{
            fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 24, color: palette.ink, lineHeight: 1.1,
          }}>Jak se naše panďátka mají?</div>
        </div>
      </div>

      {/* Summary cards */}
      <div style={{ padding: '0 24px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginBottom: 18 }}>
        {(() => {
          const totals = kids.reduce((a, k) => ({
            week: a.week + k.weeklyMin, tasks: a.tasks + k.tasks,
            correct: a.correct + k.correct, attempts: a.attempts + k.attempts,
          }), { week: 0, tasks: 0, correct: 0, attempts: 0 });
          const accuracy = totals.attempts ? Math.round((totals.correct / totals.attempts) * 100) : 0;
          return [
            { label: 'Tento týden', value: `${totals.week} min`, hint: kids.length ? `${kids.length} ${kids.length === 1 ? 'dítě' : 'děti'}` : '—', tint: palette.sky },
            { label: 'Úkolů hotovo', value: String(totals.tasks), hint: totals.tasks ? 'celkem' : 'žádné', tint: palette.secondary },
            { label: 'Úspěšnost', value: `${accuracy} %`, hint: totals.attempts ? `${totals.attempts} pokusů` : '—', tint: palette.sun },
          ];
        })().map(s => (
          <SoftCard key={s.label} palette={palette} playfulness={playfulness}
            style={{ padding: '14px 16px' }}
          >
            <div style={{
              fontFamily: '"Baloo 2"', fontSize: 11, color: palette.inkSoft,
              letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600,
            }}>{s.label}</div>
            <div style={{
              fontFamily: '"Baloo 2"', fontSize: 28, fontWeight: 700, color: palette.ink, lineHeight: 1,
              marginTop: 4,
            }}>{s.value}</div>
            <div style={{
              display: 'inline-block', marginTop: 6, padding: '2px 8px', borderRadius: 999,
              background: s.tint + '40', fontFamily: '"Baloo 2"', fontSize: 11, color: palette.ink, fontWeight: 600,
            }}>{s.hint}</div>
          </SoftCard>
        ))}
      </div>

      {/* Kid detail cards */}
      <div style={{ padding: '0 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {kids.length === 0 && (
          <SoftCard palette={palette} playfulness={playfulness}
            style={{ padding: 20, textAlign: 'center' }}>
            <div style={{ fontSize: 36, marginBottom: 6 }}>🐾</div>
            <div style={{ fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 15, color: palette.ink }}>
              Zatím žádné dítě
            </div>
            <div style={{ fontFamily: '"Baloo 2"', fontSize: 12, color: palette.inkSoft, marginTop: 2 }}>
              Na domovské obrazovce si vytvoř profil pro své dítě.
            </div>
          </SoftCard>
        )}
        {kids.map(k => (
          <SoftCard key={k.name} palette={palette} playfulness={playfulness} style={{ padding: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
              <div style={{
                width: 56, height: 56, borderRadius: 18,
                background: k.accent + '40', border: `2px solid ${k.accent}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Pandicka size={48} pose="sit" expression="happy" accent={k.accent}/>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 20, color: palette.ink }}>{k.name}</div>
                <div style={{ fontFamily: '"Baloo 2"', fontSize: 13, color: palette.inkSoft }}>Úroveň {k.level} · {k.weeklyMin} min tento týden</div>
              </div>
              <button style={{
                padding: '8px 14px', borderRadius: 999, border: `1.5px solid ${palette.ink}20`,
                background: 'transparent', cursor: 'pointer',
                fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 13, color: palette.ink,
              }}>Detail →</button>
            </div>

            {/* Inline chart */}
            <div style={{
              display: 'flex', alignItems: 'flex-end', gap: 6, height: 64,
              padding: 12, background: palette.bgDeep + '60', borderRadius: 16,
              marginBottom: 12,
            }}>
              {k.trend.map((v, i) => (
                <div key={i} style={{
                  flex: 1, height: `${(v / 10) * 100}%`,
                  minHeight: 6,
                  background: `linear-gradient(180deg, ${palette.primary}, ${palette.primaryDeep})`,
                  borderRadius: '6px 6px 3px 3px',
                }}/>
              ))}
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
              <MiniStat label="Přesnost" value={`${k.accuracy} %`} palette={palette}/>
              <MiniStat label="Silná stránka" value={k.strong} palette={palette} tint={palette.success + '30'}/>
              <MiniStat label="Procvičit" value={k.weak} palette={palette} tint={palette.accent + '30'}/>
            </div>
          </SoftCard>
        ))}

        {/* Tip from the coach */}
        <SoftCard palette={palette} playfulness={playfulness}
          style={{
            padding: 16, display: 'flex', alignItems: 'center', gap: 14,
            background: palette.sun + '30', borderColor: palette.sun + '70',
          }}
        >
          <Pandicka size={64} pose="read" expression="happy" accent={palette.accent}/>
          <div style={{ flex: 1 }}>
            <div style={{
              fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 600,
              letterSpacing: '0.08em', textTransform: 'uppercase', color: palette.inkSoft,
            }}>Doporučení panďátka</div>
            <div style={{
              fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 16, color: palette.ink, marginTop: 2,
            }}>
              Matýskovi by pomohlo pár minut denně s písmenky — zkuste kartičky před spaním.
            </div>
          </div>
        </SoftCard>

        {/* Privacy entry */}
        {onPrivacy && (
          <SoftCard palette={palette} playfulness={1}
            onClick={onPrivacy}
            style={{
              padding: 14, display: 'flex', alignItems: 'center', gap: 12,
              background: palette.sky + '20', borderColor: palette.sky + '60',
            }}>
            <div style={{ fontSize: 28 }}>🔒</div>
            <div style={{ flex: 1 }}>
              <div style={{
                fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 15, color: palette.ink,
              }}>Soukromí a moje data</div>
              <div style={{
                fontFamily: '"Baloo 2"', fontSize: 12, color: palette.inkSoft,
              }}>Export dat, výmaz, souhlasy</div>
            </div>
            <svg width="22" height="22" viewBox="0 0 24 24">
              <path d="M9 6l6 6-6 6" stroke={palette.inkSoft} strokeWidth="2.5" fill="none" strokeLinecap="round"/>
            </svg>
          </SoftCard>
        )}

        {/* Subscription card */}
        <SoftCard palette={palette} playfulness={playfulness}
          style={{
            padding: 16, display: 'flex', alignItems: 'center', gap: 14,
            background: isPremium(subscription) ? palette.success + '20' : palette.bgDeep + '40',
            borderColor: isPremium(subscription) ? palette.success + '60' : palette.ink + '20',
          }}>
          <div style={{ fontSize: 36 }}>{isPremium(subscription) ? '⭐' : '🆓'}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 600,
              letterSpacing: '0.08em', textTransform: 'uppercase', color: palette.inkSoft }}>
              Předplatné
            </div>
            <div style={{ fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 17, color: palette.ink, marginTop: 2 }}>
              {isPremium(subscription) ? 'Pandička Premium' : 'Zdarma (ochutnávka)'}
            </div>
            <div style={{ fontFamily: '"Baloo 2"', fontSize: 12, color: palette.inkSoft }}>
              {isPremium(subscription)
                ? (subscription?.role === 'admin' ? 'Administrátorský přístup' : 'Všechny úkoly odemčené')
                : `${FREE_TIER_LEVELS_PER_CATEGORY} úkoly na kategorii zdarma`}
            </div>
          </div>
          {!isPremium(subscription) && (
            <button onClick={() => setShowPaywall(true)} style={{
              padding: '10px 14px', borderRadius: 999, border: 'none', cursor: 'pointer',
              background: palette.primary, color: '#fff',
              fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 13,
              boxShadow: `0 3px 0 ${palette.primaryDeep}`,
            }}>Info</button>
          )}
        </SoftCard>

        {/* Admin entry — pouze skutečný admin */}
        {onAdmin && (
          <SoftCard palette={palette} playfulness={playfulness}
            onClick={onAdmin}
            style={{
              padding: 16, display: 'flex', alignItems: 'center', gap: 14,
              background: `linear-gradient(135deg, ${palette.primary}, ${palette.primaryDeep})`,
              color: '#fff',
            }}
          >
            <div style={{
              width: 56, height: 56, borderRadius: 18,
              background: 'rgba(255,255,255,0.2)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 28,
            }}>🛡️</div>
            <div style={{ flex: 1 }}>
              <div style={{
                fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 600,
                letterSpacing: '0.08em', textTransform: 'uppercase', opacity: 0.85,
              }}>Admin</div>
              <div style={{
                fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 17, color: '#fff', marginTop: 2,
              }}>Spravovat úkoly Pandičky</div>
            </div>
            <svg width="24" height="24" viewBox="0 0 24 24">
              <path d="M9 6l6 6-6 6" stroke="#fff" strokeWidth="2.5" fill="none" strokeLinecap="round"/>
            </svg>
          </SoftCard>
        )}

        {/* Logged-in info + Odhlásit */}
        {user && (
          <div style={{
            padding: '12px 16px', borderRadius: 18,
            background: palette.ink + '08',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            {user.photoURL && (
              <img src={user.photoURL} alt="" aria-hidden="true"
                style={{ width: 32, height: 32, borderRadius: '50%' }}/>
            )}
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily: '"Baloo 2"', fontSize: 13, fontWeight: 600, color: palette.ink,
                overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              }}>{user.displayName || user.email}</div>
              <div style={{
                fontFamily: '"Baloo 2"', fontSize: 11, color: palette.inkSoft,
              }}>Přihlášen přes Google</div>
            </div>
            {onLogout && (
              <button onClick={onLogout} style={{
                padding: '8px 12px', borderRadius: 999, border: `1.5px solid ${palette.ink}20`,
                background: 'transparent', cursor: 'pointer',
                fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 12, color: palette.ink,
              }}>Odhlásit</button>
            )}
          </div>
        )}
      </div>

      {showPaywall && (
        <PaywallModal palette={palette} onClose={() => setShowPaywall(false)}/>
      )}
    </div>
  );
}

// Reálná data dětí z localStorage progress logu + profiles.
function loadRealKids() {
  try {
    const list = JSON.parse(localStorage.getItem('pandicka-profiles') || '[]');
    const weekAgo = Date.now() - 7 * 24 * 3600 * 1000;
    return list.map(p => {
      const entries = JSON.parse(localStorage.getItem(`pandicka-progress-${p.id}`) || '[]');
      const recent = entries.filter(e => new Date(e.timestamp).getTime() >= weekAgo);
      const tasks = recent.length;
      const attempts = recent.reduce((a, e) => a + Math.max(1, (e.attempts || 0) + 1), 0);
      const correct = recent.length;
      // Průměrně ~2 min na úkol — odhad; reálně později z timestampů.
      const weeklyMin = Math.round(tasks * 2);
      // Denní trend 7 dní
      const trend = Array.from({ length: 7 }).map((_, i) => {
        const dayStart = weekAgo + i * 24 * 3600 * 1000;
        const dayEnd = dayStart + 24 * 3600 * 1000;
        return recent.filter(e => {
          const t = new Date(e.timestamp).getTime();
          return t >= dayStart && t < dayEnd;
        }).length;
      });
      // Nejsilnější / nejslabší kategorie
      const byCat = {};
      recent.forEach(e => { byCat[e.categoryId] = (byCat[e.categoryId] || 0) + 1; });
      const sorted = Object.entries(byCat).sort((a, b) => b[1] - a[1]);
      const catName = (id) => CATEGORIES_META.find(c => c.id === id)?.shortName || id;
      return {
        ...p,
        weeklyMin, tasks, attempts, correct,
        accuracy: attempts ? Math.round((correct / attempts) * 100) : 0,
        strong: sorted[0] ? catName(sorted[0][0]) : '—',
        weak:   sorted.length > 1 ? catName(sorted[sorted.length - 1][0]) : (sorted[0] ? 'Vše ostatní' : '—'),
        trend,
      };
    });
  } catch {
    return [];
  }
}

function MiniStat({ label, value, palette, tint }) {
  return (
    <div style={{
      padding: '10px 12px', borderRadius: 14,
      background: tint || palette.bgDeep + '60',
    }}>
      <div style={{
        fontFamily: '"Baloo 2"', fontSize: 10, color: palette.inkSoft, fontWeight: 600,
        letterSpacing: '0.06em', textTransform: 'uppercase',
      }}>{label}</div>
      <div style={{
        fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 15, color: palette.ink, marginTop: 2,
      }}>{value}</div>
    </div>
  );
}

Object.assign(window, { AdventureMapScreen, TaskPlayerScreen, ParentDashboardScreen });
