// Screens 1-2: Profile picker & Home hub

const { useState, useEffect, useMemo } = React;

// ───────────────────────────────────────────────────────
// SCREEN 1 — Profile picker (rodič vybírá profil dítěte)
// ───────────────────────────────────────────────────────
const CHILD_COLORS = [
  { id: 'pink',   accent: '#F4B5C1' },
  { id: 'sky',    accent: '#A5CCE8' },
  { id: 'mint',   accent: '#B8E0C2' },
  { id: 'sun',    accent: '#FFD66B' },
  { id: 'peach',  accent: '#F4B585' },
  { id: 'lilac',  accent: '#D5B8E8' },
];

function ProfilePickerScreen({ palette, metaphor, age, playfulness, user, onPick, onParent }) {
  const [profiles, setProfiles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);

  const reload = async () => {
    try {
      const list = await listProfiles(user?.uid);
      setProfiles(list);
    } catch { setProfiles([]); }
    setLoading(false);
  };

  useEffect(() => { reload(); }, [user?.uid]);

  const handleCreate = async ({ name, accent }) => {
    const id = 'p-' + Date.now().toString(36);
    const profile = {
      id, name: name.trim() || 'Panďátko',
      accent, level: 1, xp: 0, coins: 0, progress: {},
      createdAt: new Date().toISOString(),
    };
    await saveProfile(user?.uid, profile);
    setShowCreate(false);
    await reload();
  };

  const handleDelete = async (p) => {
    if (!confirm(`Smazat profil „${p.name}"? Ztratí se všechny odměny a pokrok.`)) return;
    await deleteProfile(user?.uid, p.id);
    await reload();
  };

  return (
    <div style={{ position: 'relative', minHeight: '100%', padding: '40px 24px 80px', zIndex: 1 }}>
      <Landmark emoji={METAPHORS[metaphor].landmarks[0]} size={56}
        style={{ position: 'absolute', top: 60, left: 30 }} rotate={-8}/>
      <Landmark emoji={METAPHORS[metaphor].landmarks[2]} size={44}
        style={{ position: 'absolute', top: 120, right: 40 }} rotate={10}/>

      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 28, marginTop: 10 }}>
        <motion.div animate={{ y: [0, -6, 0] }} transition={{ duration: 3, repeat: Infinity, ease: 'easeInOut' }}>
          <Pandicka size={140} pose="wave" expression="happy" accent={palette.accent}/>
        </motion.div>
        <div style={{
          position: 'relative', marginTop: -6, padding: '14px 24px',
          background: palette.card, borderRadius: 24, boxShadow: playfulShadow(playfulness),
          fontFamily: '"Baloo 2", system-ui', fontWeight: 600, fontSize: 20, color: palette.ink, textAlign: 'center',
        }}>
          {profiles.length === 0
            ? 'Ahoj! Vytvoř první profil pro své dítko.'
            : 'Ahoj! Kdo si chce dneska hrát?'}
          <svg width="20" height="10" viewBox="0 0 20 10" style={{ position: 'absolute', top: -9, left: '50%', marginLeft: -10 }}>
            <path d="M0 10 L10 0 L20 10 Z" fill={palette.card}/>
          </svg>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 440, margin: '0 auto' }}>
        {loading && (
          <div style={{ textAlign: 'center', padding: 30, fontFamily: '"Baloo 2"', color: palette.inkSoft }}>
            Načítám profily…
          </div>
        )}

        {!loading && profiles.length === 0 && (
          <SoftCard palette={palette} playfulness={playfulness}
            style={{ padding: 24, textAlign: 'center' }}>
            <div style={{ fontSize: 42, marginBottom: 8 }}>🐼</div>
            <div style={{ fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 17, color: palette.ink }}>
              Zatím tu nikdo není
            </div>
            <div style={{ fontFamily: '"Baloo 2"', fontSize: 14, color: palette.inkSoft, marginTop: 4, marginBottom: 14 }}>
              Vytvoř profil pro své dítě a pojďme si hrát.
            </div>
            <BigButton palette={palette} variant="primary" size="md" onClick={() => setShowCreate(true)}>
              ➕ Vytvořit profil
            </BigButton>
          </SoftCard>
        )}

        {!loading && profiles.map(p => (
          <SoftCard key={p.id} palette={palette} playfulness={playfulness}
            onClick={() => onPick(p)}
            style={{ padding: 18, display: 'flex', alignItems: 'center', gap: 18 }}>
            <div style={{
              width: 72, height: 72, borderRadius: 20,
              background: (p.accent || '#F4B5C1') + '40',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: `2px solid ${p.accent || '#F4B5C1'}`, flexShrink: 0,
            }}>
              <Pandicka size={62} pose="sit" expression="happy" accent={p.accent || '#F4B5C1'}
                accessories={getEquippedItems(p)}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 22, color: palette.ink }}>{p.name}</div>
              <div style={{ display: 'flex', gap: 8, marginTop: 6, alignItems: 'center', flexWrap: 'wrap' }}>
                <div style={{
                  padding: '3px 10px', borderRadius: 10,
                  background: palette.accent + '25', color: palette.ink,
                  fontFamily: '"Baloo 2"', fontSize: 12, fontWeight: 600,
                }}>Úroveň {p.level || 1}</div>
                <CoinChip amount={p.coins || 0} palette={palette} size="sm"/>
              </div>
            </div>
            <button onClick={(e) => { e.stopPropagation(); handleDelete(p); }}
              aria-label={`Smazat profil ${p.name}`}
              style={{
                width: 32, height: 32, borderRadius: 10, border: 'none',
                background: palette.ink + '08', cursor: 'pointer', fontSize: 14,
              }}>🗑️</button>
          </SoftCard>
        ))}

        {!loading && profiles.length > 0 && profiles.length < 5 && (
          <SoftCard palette={palette} playfulness={playfulness}
            onClick={() => setShowCreate(true)}
            style={{
              padding: 18, display: 'flex', alignItems: 'center', gap: 18,
              background: 'transparent', border: `2px dashed ${palette.ink}25`, boxShadow: 'none',
            }}>
            <div style={{
              width: 72, height: 72, borderRadius: 20, background: palette.ink + '08',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 36, color: palette.inkSoft, fontWeight: 300,
            }}>+</div>
            <div style={{ flex: 1, fontFamily: '"Baloo 2"', fontWeight: 500, fontSize: 18, color: palette.inkSoft }}>
              Přidat další dítko
            </div>
          </SoftCard>
        )}
      </div>

      <div style={{ textAlign: 'center', marginTop: 28 }}>
        <button onClick={onParent} style={{
          padding: '10px 18px', borderRadius: 999, border: 'none',
          background: 'transparent', cursor: 'pointer',
          fontFamily: '"Baloo 2"', fontSize: 14, color: palette.inkSoft,
          textDecoration: 'underline dotted',
        }}>
          🔐 Vstup pro rodiče
        </button>
      </div>

      {showCreate && (
        <CreateProfileModal palette={palette} playfulness={playfulness}
          onSave={handleCreate} onCancel={() => setShowCreate(false)}/>
      )}
    </div>
  );
}

function CreateProfileModal({ palette, playfulness, onSave, onCancel }) {
  const [name, setName] = useState('');
  const [accentId, setAccentId] = useState('pink');
  const accent = CHILD_COLORS.find(c => c.id === accentId)?.accent;

  return (
    <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
      onClick={onCancel}
      style={{
        position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(20,14,20,0.55)',
        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: 400, background: palette.card, borderRadius: 28, padding: 24,
          boxShadow: '0 30px 60px rgba(0,0,0,0.3)',
        }}>
        <div style={{ textAlign: 'center', marginBottom: 14 }}>
          <Pandicka size={110} pose="wave" expression="happy" accent={accent}/>
          <div style={{ fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 22, color: palette.ink, marginTop: 6 }}>
            Nové panďátko
          </div>
          <div style={{ fontFamily: '"Baloo 2"', fontSize: 13, color: palette.inkSoft }}>
            Jak se jmenuje a jakou má rád barvu?
          </div>
        </div>

        <label style={{ display: 'block', marginBottom: 12 }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 700, color: palette.inkSoft,
            letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 4,
          }}>Jméno nebo přezdívka</div>
          <input value={name} onChange={e => setName(e.target.value)}
            placeholder="Terezka, Kuba, panďátko…"
            maxLength={20}
            style={{
              width: '100%', padding: '12px 14px', borderRadius: 14,
              border: `1.5px solid ${palette.ink}20`, outline: 'none',
              fontFamily: '"Baloo 2"', fontSize: 15, color: palette.ink, background: '#fff',
            }}/>
        </label>

        <div style={{ marginBottom: 18 }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 700, color: palette.inkSoft,
            letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 6,
          }}>Oblíbená barva</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {CHILD_COLORS.map(c => (
              <button key={c.id} onClick={() => setAccentId(c.id)}
                aria-label={`Barva ${c.id}`}
                aria-pressed={accentId === c.id}
                style={{
                  width: 42, height: 42, borderRadius: '50%',
                  border: `3px solid ${accentId === c.id ? palette.ink : '#fff'}`,
                  background: c.accent, cursor: 'pointer',
                  boxShadow: '0 2px 6px rgba(0,0,0,0.15)',
                }}/>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', gap: 10 }}>
          <BigButton palette={palette} variant="ghost" size="sm" onClick={onCancel} style={{ flex: 1 }}>
            Zrušit
          </BigButton>
          <BigButton palette={palette} variant="primary" size="sm"
            disabled={!name.trim()}
            onClick={() => onSave({ name, accent })}
            style={{ flex: 1 }}>
            Vytvořit 🐾
          </BigButton>
        </div>
      </motion.div>
    </motion.div>
  );
}

// ───────────────────────────────────────────────────────
// SCREEN 2 — Home hub (kategorie)
// ───────────────────────────────────────────────────────
function HomeHubScreen({ palette, metaphor, age, playfulness, profile, onBack, onCategory, onShop, onAchievements, onUpdateProfile }) {
  // Dotkni streaku, když dítě otevře hub (jednou za den)
  useEffect(() => {
    const next = touchStreak(profile);
    if (next !== profile && onUpdateProfile) onUpdateProfile(next);
  }, []);

  const categories = CATEGORIES_META.map(c => {
    const total = getTasksByCategory(c.id).length;
    const progress = Math.min(total, (profile.progress && profile.progress[c.id]) || 0);
    return { ...c, total: Math.max(total, 1), progress };
  });

  const showText = AGE_MODES[age].showText;

  return (
    <div style={{ position: 'relative', minHeight: '100%', zIndex: 1 }}>
      {/* Top bar */}
      <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="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, padding: '10px 16px', borderRadius: 999,
          background: palette.card, boxShadow: playfulShadow(1),
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <div style={{
            width: 34, height: 34, borderRadius: '50%',
            background: profile.accent + '40',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            overflow: 'hidden', flexShrink: 0,
          }}>
            <PandickaChip size={32}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 14, color: palette.ink,
              lineHeight: 1.1,
            }}>{profile.name}</div>
            <XPBar xp={profile.xp % 100} xpMax={100} level={profile.level} palette={palette}/>
          </div>
        </div>

        <CoinChip amount={profile.coins} palette={palette} size="md"/>
      </div>

      {/* Greeting strip */}
      <div style={{ padding: '8px 24px 20px' }}>
        <div style={{
          fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 30, color: palette.ink,
          lineHeight: 1.1, letterSpacing: '-0.01em',
        }}>
          Kam dneska vyrazíme,{' '}
          <span style={{ color: palette.primaryDeep }}>{profile.name}</span>?
        </div>
        <div style={{
          marginTop: 6, fontFamily: '"Baloo 2"', fontSize: 15,
          color: palette.inkSoft, fontWeight: 400,
        }}>
          Vyber si svět, kam chceš jít.
        </div>
      </div>

      {/* Shop + Achievements quick tiles */}
      <div style={{
        padding: '0 20px 14px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10,
      }}>
        <motion.button whileHover={{ y: -3 }} whileTap={{ scale: 0.96 }}
          onClick={onShop}
          aria-label="Obchůdek — utratit mince za doplňky"
          style={{
            padding: '14px 10px', borderRadius: 20, border: 'none', cursor: 'pointer',
            background: palette.card, boxShadow: playfulShadow(1),
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
          }}>
          <div style={{ fontSize: 28 }}>🛍️</div>
          <div style={{ fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 12, color: palette.ink }}>Obchůdek</div>
        </motion.button>
        <motion.button whileHover={{ y: -3 }} whileTap={{ scale: 0.96 }}
          onClick={onAchievements}
          aria-label="Síň slávy — tvé odznáčky"
          style={{
            padding: '14px 10px', borderRadius: 20, border: 'none', cursor: 'pointer',
            background: palette.card, boxShadow: playfulShadow(1),
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
          }}>
          <div style={{ fontSize: 28 }}>🏆</div>
          <div style={{ fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 12, color: palette.ink }}>Trofeje</div>
          <div style={{ fontFamily: '"Baloo 2"', fontSize: 10, color: palette.inkSoft }}>
            {getUnlockedAchievements(profile).length}/{ACHIEVEMENTS.length}
          </div>
        </motion.button>
        <div style={{
          padding: '14px 10px', borderRadius: 20,
          background: palette.sun + '25',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
        }}>
          <div style={{ fontSize: 28 }}>🔥</div>
          <div style={{ fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 12, color: palette.ink }}>Série</div>
          <div style={{ fontFamily: '"Baloo 2"', fontSize: 13, fontWeight: 700, color: palette.primaryDeep }}>
            {profile.streak?.count || 0} {(profile.streak?.count || 0) === 1 ? 'den' : 'dnů'}
          </div>
        </div>
      </div>

      {/* Featured hero card — Pandička invites */}
      <div style={{ padding: '0 20px 20px' }}>
        <SoftCard palette={palette} playfulness={playfulness}
          style={{
            background: `linear-gradient(135deg, ${palette.sun}, ${palette.primary})`,
            padding: '18px 20px',
            display: 'flex', alignItems: 'center', gap: 14,
            color: '#fff',
            overflow: 'hidden', position: 'relative',
          }}
        >
          <div style={{ flex: 1 }}>
            <div style={{
              fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 600,
              opacity: 0.85, letterSpacing: '0.08em', textTransform: 'uppercase',
            }}>Dnešní dobrodružství</div>
            <div style={{
              fontFamily: '"Baloo 2"', fontSize: 22, fontWeight: 700,
              color: '#fff', marginTop: 2, lineHeight: 1.1,
            }}>Najdi skryté zvuky v lese</div>
            <div style={{ marginTop: 10, display: 'flex', gap: 8, alignItems: 'center' }}>
              <div style={{
                padding: '4px 10px', borderRadius: 999,
                background: 'rgba(255,255,255,0.25)',
                fontSize: 12, fontFamily: '"Baloo 2"', fontWeight: 600,
              }}>🎁 +15 mincí</div>
              <div style={{
                padding: '4px 10px', borderRadius: 999,
                background: 'rgba(255,255,255,0.25)',
                fontSize: 12, fontFamily: '"Baloo 2"', fontWeight: 600,
              }}>⏱ 5 min</div>
            </div>
          </div>
          <motion.div
            animate={{ rotate: [-4, 4, -4] }}
            transition={{ duration: 4, repeat: Infinity, ease: 'easeInOut' }}
          >
            <Pandicka size={92} pose="cheer" expression="excited" accent={palette.accent}/>
          </motion.div>
        </SoftCard>
      </div>

      {/* Category grid */}
      <div style={{
        padding: '0 20px 40px',
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14,
      }}>
        {categories.map((c, i) => (
          <motion.div
            key={c.id}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.05 * i }}
          >
            <SoftCard palette={palette} playfulness={playfulness}
              onClick={() => onCategory(c)}
              style={{
                padding: 16, minHeight: 140,
                display: 'flex', flexDirection: 'column', gap: 10,
                background: c.color + '28',
                borderColor: c.color + '50',
                position: 'relative', overflow: 'hidden',
              }}
            >
              <div style={{
                width: 56, height: 56, borderRadius: 18,
                background: c.color,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 30,
                boxShadow: '0 3px 0 rgba(0,0,0,0.08)',
              }}>{c.icon}</div>
              <div>
                <div style={{
                  fontFamily: '"Baloo 2"', fontWeight: 600,
                  fontSize: showText ? 16 : 18, color: palette.ink,
                  lineHeight: 1.1,
                }}>
                  {showText ? c.name : c.shortName}
                </div>
                {showText && (
                  <div style={{
                    marginTop: 2, fontFamily: '"Baloo 2"', fontSize: 12,
                    color: palette.inkSoft, fontWeight: 400,
                  }}>{c.desc}</div>
                )}
              </div>
              {/* progress dots */}
              <div style={{ display: 'flex', gap: 4, marginTop: 'auto' }}>
                {Array.from({ length: c.total }).map((_, j) => (
                  <div key={j} style={{
                    width: 10, height: 10, borderRadius: '50%',
                    background: j < c.progress ? palette.success : palette.ink + '15',
                  }}/>
                ))}
              </div>
            </SoftCard>
          </motion.div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ProfilePickerScreen, HomeHubScreen });
