// Screens — Login & Mission Map (Home)
const { useState, useEffect } = React;

function StarfieldBg() {
  return (
    <div className="starfield" aria-hidden="true">
      {Array.from({ length: 80 }).map((_, i) => {
        const top = Math.random() * 100;
        const left = Math.random() * 100;
        const size = Math.random() * 2.5 + 0.8;
        const delay = Math.random() * 4;
        return (
          <span
            key={i}
            className="star"
            style={{
              top: `${top}%`,
              left: `${left}%`,
              width: `${size}px`,
              height: `${size}px`,
              animationDelay: `${delay}s`
            }}
          />
        );
      })}
      {/* shooting stars */}
      <span className="shooting-star ss1" />
      <span className="shooting-star ss2" />
    </div>
  );
}

function LoginScreen({ onLogin }) {
  const [users, setUsers] = useState([]);
  const [mode, setMode] = useState('choose');
  const [name, setName] = useState('');
  const [nick, setNick] = useState('');
  const [avatar, setAvatar] = useState('luna');
  const [error, setError] = useState('');
  const [filterKind, setFilterKind] = useState('Todos');

  useEffect(() => {
    window.AppStorage.getUsers().then(setUsers);
  }, []);

  async function handleCreate() {
    if (!name.trim() || !nick.trim()) {
      setError('Preencha seu nome e apelido!');
      return;
    }
    const id = nick.trim().toLowerCase().replace(/\s+/g, '_') + '_' + Date.now().toString(36).slice(-4);
    const user = { id, name: name.trim(), nick: nick.trim(), avatar };
    await window.AppStorage.createUser(user);
    await window.AppStorage.setCurrentUserId(id);
    onLogin(user);
  }

  async function handlePick(u) {
    await window.AppStorage.setCurrentUserId(u.id);
    onLogin(u);
  }

  const kinds = ['Todos', 'Cadete', 'Alien', 'Espacial'];
  const filteredAvatars = filterKind === 'Todos'
    ? window.Avatars.list
    : window.Avatars.list.filter(a => a.kind === filterKind);

  return (
    <div className="screen login-screen">
      <StarfieldBg />
      <div className="login-card">
        <div className="login-logo">
          <div className="logo-planet">🌍</div>
          <h1>Missão Planeta Azul</h1>
          <p>Vire um(a) Cadete da Frota Terra!</p>
        </div>

        {mode === 'choose' && (
          <div className="login-mode">
            {users.length > 0 && (
              <div className="returning">
                <h3>Já sou cadete!</h3>
                <div className="user-list">
                  {users.map(u => {
                    const Av = window.Avatars.get(u.avatar).component;
                    return (
                      <button key={u.id} className="user-chip" onClick={() => handlePick(u)}>
                        <Av size={48} />
                        <div className="chip-info">
                          <strong>{u.nick}</strong>
                          <span>{u.name}</span>
                        </div>
                        <span className="chip-arrow">→</span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}
            <button className="btn-primary big" onClick={() => setMode('new')}>
              🚀 Sou Cadete Novo!
            </button>
          </div>
        )}

        {mode === 'new' && (
          <div className="login-form">
            <h3>Crie sua conta de cadete</h3>
            <label>
              <span>Seu nome:</span>
              <input
                type="text"
                value={name}
                onChange={e => setName(e.target.value)}
                placeholder="Ex: Ícaro"
                maxLength={30}
              />
            </label>
            <label>
              <span>Seu apelido espacial:</span>
              <input
                type="text"
                value={nick}
                onChange={e => setNick(e.target.value)}
                placeholder="Ex: SuperÍcaro"
                maxLength={20}
              />
            </label>
            <div className="avatar-pick">
              <span>Escolha seu personagem:</span>
              <div className="kind-tabs">
                {kinds.map(k => (
                  <button
                    key={k}
                    className={`kind-tab ${filterKind === k ? 'active' : ''}`}
                    onClick={() => setFilterKind(k)}
                    type="button"
                  >
                    {k === 'Todos' && '🌟 Todos'}
                    {k === 'Cadete' && '👨‍🚀 Cadetes'}
                    {k === 'Alien' && '👽 Aliens'}
                    {k === 'Espacial' && '☄️ Espaciais'}
                  </button>
                ))}
              </div>
              <div className="avatar-grid">
                {filteredAvatars.map(a => {
                  const Av = a.component;
                  return (
                    <button
                      key={a.id}
                      className={`avatar-btn ${avatar === a.id ? 'selected' : ''}`}
                      onClick={() => setAvatar(a.id)}
                      style={{ borderColor: avatar === a.id ? a.color : 'transparent' }}
                      type="button"
                    >
                      <Av size={64} />
                      <span>{a.name}</span>
                    </button>
                  );
                })}
              </div>
            </div>
            {error && <div className="error">{error}</div>}
            <div className="form-actions">
              <button className="btn-ghost" onClick={() => { setMode('choose'); setError(''); }}>
                ← Voltar
              </button>
              <button className="btn-primary" onClick={handleCreate}>
                Começar aventura! 🚀
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function StarBadge({ stars, max = 3, size = 'sm' }) {
  return (
    <div className={`star-badge size-${size}`}>
      {Array.from({ length: max }).map((_, i) => (
        <span key={i} className={i < stars ? 'star-on' : 'star-off'}>★</span>
      ))}
    </div>
  );
}

function MissionMap({ user, progress, onOpenMission, onOpenGlossary, onOpenMural, onOpenTrophies, onOpenVideos, onLogout }) {
  const Av = window.Avatars.get(user.avatar).component;
  const missions = window.MISSIONS;

  const totalStars = missions.reduce((sum, m) => sum + (Number.isFinite(progress.missions[m.id]?.stars) ? progress.missions[m.id].stars : 0), 0);
  const maxStars = missions.length * 3;
  const fuelPct = Math.min(100, Math.round((totalStars / maxStars) * 100));
  const rank = window.Avatars.getRank(totalStars);

  // Sequential unlock: mission N is unlocked if mission N-1 is completed (>=1 star).
  function isUnlocked(idx) {
    if (idx === 0) return true;
    const prev = missions[idx - 1];
    return (progress.missions[prev.id]?.stars || 0) >= 1;
  }

  return (
    <div className="screen map-screen">
      <StarfieldBg />

      <header className="topbar">
        <div className="topbar-left">
          <div className="avatar-bubble" style={{ background: 'transparent', border: 'none', padding: 0 }}>
            <window.Avatars.RankedAvatar avatarId={user.avatar} stars={totalStars} size={48} />
          </div>
          <div className="user-info">
            <strong>{user.nick}</strong>
            <span style={{ color: rank.color, fontWeight: 700, fontSize: 13 }}>
              {rank.emoji} {rank.title}
            </span>
          </div>
        </div>
        <div className="topbar-right">
          <button className="icon-btn" onClick={onOpenVideos} title="Vídeos da Aula">🎬</button>
          <button className="icon-btn" onClick={onOpenGlossary} title="Dicionário">📖</button>
          <button className="icon-btn" onClick={onOpenTrophies} title="Sala de Troféus">🏆</button>
          <button className="icon-btn" onClick={onOpenMural} title="Mural da Turma">👥</button>
          <button className="icon-btn" onClick={onLogout} title="Sair">🚪</button>
        </div>
      </header>

      <div className="hud">
        <div className="hud-card">
          <div className="hud-label">Combustível 🚀</div>
          <div className="fuel-bar">
            <div className="fuel-fill" style={{ width: `${fuelPct}%` }} />
            <span className="fuel-pct">{fuelPct}%</span>
          </div>
        </div>
        <div className="hud-card">
          <div className="hud-label">Estrelas</div>
          <div className="hud-value">⭐ {totalStars}/{maxStars}</div>
        </div>
        <div className="hud-card">
          <div className="hud-label">Medalhas</div>
          <div className="hud-value">🏅 {(progress.badges || []).length}</div>
        </div>
      </div>

      <div className="map-title">
        <h2>Mapa de Missões</h2>
        <p>Complete cada missão para virar Comandante da Frota Terra!</p>
      </div>

      <div className="missions-grid">
        {missions.map((m, idx) => {
          const mp = progress.missions[m.id];
          const stars = mp?.stars || 0;
          const completed = mp?.completed || false;
          const locked = !isUnlocked(idx);
          const total = m.questions.length;
          // resume info
          const resume = mp?.resume;
          const answered = resume?.answeredCount || (completed ? total : 0);
          const pct = Math.round((answered / total) * 100);
          const inProgress = !completed && answered > 0;

          return (
            <button
              key={m.id}
              className={`mission-card ${locked ? 'locked' : ''} ${completed ? 'completed' : ''} ${inProgress ? 'in-progress' : ''}`}
              onClick={() => !locked && onOpenMission(m)}
              disabled={locked}
              style={{ '--accent': m.accent }}
            >
              <div className={`mission-bg bg-gradient-to-br ${m.color}`}>
                <div className="mission-num">{idx + 1}</div>
                <div className="mission-icon">{m.icon}</div>
                {locked && <div className="lock-overlay"><span className="lock-emoji">🔒</span></div>}
                {completed && <div className="completed-ribbon">✓</div>}
                {inProgress && <div className="progress-pill">▶ {pct}%</div>}
              </div>
              <div className="mission-body">
                <h3>{m.title}</h3>
                <p>{m.subtitle}</p>
                <div className="mini-progress">
                  <div className="mini-bar">
                    <div className="mini-fill" style={{ width: `${pct}%`, background: m.accent }} />
                  </div>
                  <span className="mini-count">{answered}/{total}</span>
                </div>
                <div className="mission-meta">
                  <StarBadge stars={stars} />
                  {!locked && !inProgress && !completed && <span className="cta">Começar →</span>}
                  {inProgress && <span className="cta cta-resume">Continuar ▶</span>}
                  {completed && <span className="cta cta-done">Jogar de novo ↻</span>}
                </div>
                {locked && <div className="locked-hint">🔒 Conclua a missão {idx} para destravar!</div>}
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

window.Screens = { LoginScreen, MissionMap, StarBadge, StarfieldBg };
