// Screen components: AuthScreen, Home, Quests, Badges, Rank, Profile, Settings

// ── Auth ──────────────────────────────────────────────────────────────────────
const AuthScreen = ({ login, register }) => {
  const [mode,     setMode]     = React.useState('login');
  const [name,     setName]     = React.useState('');
  const [email,    setEmail]    = React.useState('');
  const [password, setPassword] = React.useState('');
  const [loading,  setLoading]  = React.useState(false);
  const [error,    setError]    = React.useState('');

  const switchMode = (m) => { setMode(m); setError(''); };

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      if (mode === 'login') {
        await login(email, password);
      } else {
        await register(name.trim() || 'Aventureiro', email, password);
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="auth-page">
      <div className="auth-rays" />
      <div className="auth-card panel ornate">
        <div className="auth-brand">
          <div className="crest">XP</div>
          <div>
            <div className="auth-brand-name display">Produtividade Gameficada</div>
            <div className="eyebrow" style={{ marginTop: 2 }}>v2.0 · modo campanha</div>
          </div>
        </div>

        <div className="divider" style={{ margin: '16px 0 20px' }} />

        <div style={{ marginBottom: 22 }}>
          <h2 className="auth-h display">
            {mode === 'login' ? 'Entrar na campanha' : 'Iniciar a jornada'}
          </h2>
          <p className="auth-sub">
            {mode === 'login' ? 'Bem-vindo de volta, aventureiro.' : 'Crie sua conta e comece a acumular XP.'}
          </p>
        </div>

        <form onSubmit={submit} autoComplete="on">
          {mode === 'register' && (
            <div className="field">
              <label>Nome do aventureiro</label>
              <input
                className="input"
                placeholder="Ex.: Bruno, o Implacável"
                value={name}
                onChange={(e) => setName(e.target.value)}
                autoFocus
              />
            </div>
          )}
          <div className="field">
            <label>E-mail</label>
            <input
              className="input"
              type="email"
              placeholder="seu@email.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              autoFocus={mode === 'login'}
              required
            />
          </div>
          <div className="field">
            <label>Senha {mode === 'register' && <span style={{ color: 'var(--ink-4)', fontFamily: 'JetBrains Mono,monospace', fontSize: 9.5, letterSpacing: '0.12em' }}>MÍN. 6 CHARS</span>}</label>
            <input
              className="input"
              type="password"
              placeholder={mode === 'register' ? 'Mínimo 6 caracteres' : '••••••••'}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </div>

          {error && (
            <div className="auth-error">
              <I.x style={{ width: 13, height: 13, flexShrink: 0 }} /> {error}
            </div>
          )}

          <button
            className="btn gold lg"
            type="submit"
            disabled={loading}
            style={{ width: '100%', justifyContent: 'center', marginTop: 6 }}
          >
            {loading
              ? <span style={{ fontFamily: 'JetBrains Mono,monospace', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>carregando…</span>
              : <>{mode === 'login' ? <I.shield /> : <I.bolt />} {mode === 'login' ? 'Entrar' : 'Criar conta'}</>
            }
          </button>
        </form>

        <div className="auth-switch">
          {mode === 'login'
            ? <>Novo por aqui? <button className="auth-link" onClick={() => switchMode('register')}>Criar uma conta</button></>
            : <>Já tem conta? <button className="auth-link" onClick={() => switchMode('login')}>Entrar</button></>
          }
        </div>
      </div>
    </div>
  );
};

// ── Home ──────────────────────────────────────────────────────────────────────
const Home = ({ s }) => {
  // Recurring quests are always 'open'; exclude them from the "Concluídas" tab
  const open   = s.quests.filter((q) => q.status === 'open');
  const done   = s.quests.filter((q) => q.status === 'done' && !q.recurrence);
  const [tab, setTab] = React.useState('open');
  const list   = tab === 'open' ? open : done;
  const xpPct  = Math.round((s.lvl.intoLevel / s.lvl.needLevel) * 100);
  // Count missions due today: one-time with deadline='Hoje' + recurring not yet done today
  const today  = open.filter((q) => q.recurrence ? isRecurringDueToday(q) : q.deadline === 'Hoje').length;
  const tier   = s.tier;
  const initials = (s.user?.adventurerName || 'A').charAt(0).toUpperCase();

  return (
    <>
      <Topbar crumb="Modo Campanha" here="Home" streak={s.streak} onForge={() => s.setShowForge(true)} />

      <section className="hero">
        <div className="hero-left panel ornate">
          <div className="hero-eyebrow">
            <span className="dot" />
            <span className="eyebrow mana">Painel da campanha · {new Date().toLocaleDateString('pt-BR', { weekday: 'long', day: '2-digit', month: 'long' })}</span>
          </div>
          <h1>O dia te aguarda, <span className="accent">aventureiro.</span></h1>
          <p className="lede">
            Você tem <strong style={{ color: 'var(--ink)' }}>{today} missões marcadas para hoje</strong> e {open.length - today} na fila.
            Cada execução vira XP, cada dia consistente acende a chama do streak.
          </p>
          <div className="hero-cta">
            <button className="btn primary lg" onClick={() => s.setShowForge(true)}><I.plus /> Forjar nova missão</button>
            <button className="btn lg" onClick={() => s.setRoute('quests')}><I.scroll /> Abrir Quest Log</button>
          </div>
        </div>

        <div className="adv-card">
          <div className="adv-head">
            <div className="av">{initials}</div>
            <div>
              <h2>{s.user?.adventurerName || 'Aventureiro'}</h2>
              <div className="title-line">{tier.name} · Caminho do executor</div>
            </div>
          </div>
          <div className="lvl-row">
            <span className="lvl-n">{s.lvl.level}</span>
            <span className="lvl-l">Nível atual</span>
            <span className="xp-num"><strong>{s.lvl.intoLevel}</strong> / {s.lvl.needLevel} XP</span>
          </div>
          <div className="xp-bar"><div className="fill" style={{ '--p': xpPct + '%' }} /><div className="ticks" /></div>
          <div className="tier-row">
            {TIERS.map((t, i) => (
              <div key={t.name} className={`step ${i === tier.idx ? 'cur' : i < tier.idx ? 'passed' : ''}`}>{t.name}</div>
            ))}
          </div>
        </div>
      </section>

      <section className="stat-grid">
        <Stat kind="gold"    label="XP Total"         value={s.totalXp.toLocaleString('pt-BR')} unit="XP"      icoName="bolt"   sub={<><span className="delta">+{done.reduce((x, q) => x + q.xp, 0)}</span> nesta sessão</>} />
        <Stat kind="violet"  label="Nível"            value={s.lvl.level}                        unit={`/ ${tier.name}`} icoName="crown" sub={<><span>{xpPct}%</span> rumo ao próximo</>} />
        <Stat kind="emerald" label="Streak"           value={s.streak}                           unit="dias"    icoName="flame"  sub={<>Melhor sequência: <strong style={{ color: 'var(--ink)' }}>{s.bestStreak}</strong></>} />
        <Stat kind="mana"    label="Missões em campo" value={open.length}                        unit="abertas" icoName="scroll" sub={<><strong style={{ color: 'var(--ink)' }}>{today}</strong> com prazo hoje</>} />
      </section>

      <section className="two-col">
        <div className="panel ornate">
          <div className="panel-h">
            <h3>Fila de execução</h3>
            <div className="tabs">
              <button className={tab === 'open' ? 'on' : ''} onClick={() => setTab('open')}><I.sword /> Abertas <span className="count">{open.length}</span></button>
              <button className={tab === 'done' ? 'on' : ''} onClick={() => setTab('done')}><I.check /> Concluídas <span className="count">{done.length}</span></button>
            </div>
          </div>
          <div className="panel-body">
            {list.length === 0
              ? <Empty ico="scroll" title="Sem missões nesta fila" body="Forje uma nova missão para entrar em campo." />
              : list.map((q) => <Quest key={q.id} q={q} onComplete={s.completeQuest} onCompleteDay={s.completeDayRecurring} onDelete={s.deleteQuest} />)
            }
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="panel ornate">
            <div className="panel-h">
              <h3>Crônicas recentes</h3>
              <button className="btn ghost sm" onClick={() => s.setRoute('quests')}>Ver tudo <I.chevR /></button>
            </div>
            <div className="panel-body">
              {s.history.length === 0
                ? <Empty ico="log" title="Nenhuma ação registrada" body="Conclua sua primeira missão para começar a história." />
                : (
                  <div className="feed">
                    {s.history.slice(0, 5).map((h) => (
                      <div key={h.id} className={`feed-row ${h.kind}`}>
                        <div className="ico-wrap">{h.kind === 'level' ? <I.crown /> : h.kind === 'forge' ? <I.scroll /> : <I.bolt />}</div>
                        <div className="text" dangerouslySetInnerHTML={{ __html: h.text }} />
                        <div className="when">{h.when}</div>
                      </div>
                    ))}
                  </div>
                )
              }
            </div>
          </div>

          <div className="panel ornate">
            <div className="panel-h">
              <h3>Troféus recentes</h3>
              <button className="btn ghost sm" onClick={() => s.setRoute('badges')}>Salão <I.chevR /></button>
            </div>
            <div className="panel-body">
              <div className="badge-grid">
                {BADGES.slice(0, 4).map((b) => <Badge key={b.id} b={b} state={s.stateForBadges} />)}
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="panel ornate" style={{ marginBottom: 22 }}>
        <div className="panel-h">
          <h3>Mapa da consistência</h3>
          <div className="eyebrow mana">últimas 20 semanas</div>
        </div>
        <div className="panel-body">
          <Heatmap data={s.heatData} />
        </div>
      </section>
    </>
  );
};

// ── Quest Log ─────────────────────────────────────────────────────────────────
const QuestsScreen = ({ s }) => {
  const [filter, setFilter] = React.useState('all');
  const [cat,    setCat]    = React.useState('all');

  // "done" filter excludes recurring quests (they're ongoing)
  const matchesFilter = (q) => {
    if (filter === 'done') return q.status === 'done' && !q.recurrence;
    if (filter === 'open') return q.status === 'open';
    return true; // 'all'
  };
  const filtered = s.quests.filter((q) => matchesFilter(q) && (cat === 'all' || q.category === cat));
  const doneCount = s.quests.filter((q) => q.status === 'done' && !q.recurrence).length;

  return (
    <>
      <Topbar crumb="Modo Campanha" here="Quest Log" streak={s.streak} onForge={() => s.setShowForge(true)} />
      <div className="page-h">
        <div>
          <div className="eyebrow mana">Quest log · {filtered.length} miss{filtered.length === 1 ? 'ão' : 'ões'}</div>
          <h1>Toda missão em campo</h1>
          <p>Filtre por estado e categoria. Conclua para ganhar XP — missões raras valem o esforço.</p>
        </div>
        <div className="tabs">
          <button className={filter === 'all'  ? 'on' : ''} onClick={() => setFilter('all')}>Todas <span className="count">{s.quests.length}</span></button>
          <button className={filter === 'open' ? 'on' : ''} onClick={() => setFilter('open')}>Abertas <span className="count">{s.quests.filter(q => q.status === 'open').length}</span></button>
          <button className={filter === 'done' ? 'on' : ''} onClick={() => setFilter('done')}>Concluídas <span className="count">{doneCount}</span></button>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
        <button className={`cat-pill ${cat === 'all' ? 'on' : ''}`} onClick={() => setCat('all')}><I.filter /> Todas categorias</button>
        {CATEGORIES.map((c) => {
          const Ico = I[c.ico];
          return <button key={c.id} className={`cat-pill ${cat === c.id ? 'on' : ''}`} onClick={() => setCat(c.id)}><Ico /> {c.label}</button>;
        })}
      </div>
      <div className="panel ornate">
        <div className="panel-body">
          {filtered.length === 0
            ? <Empty title="Nada por aqui" body="Ajuste os filtros ou forje uma nova missão." />
            : filtered.map((q) => <Quest key={q.id} q={q} onComplete={s.completeQuest} onCompleteDay={s.completeDayRecurring} onDelete={s.deleteQuest} />)
          }
        </div>
      </div>
    </>
  );
};

// ── Badges ────────────────────────────────────────────────────────────────────
const BadgesScreen = ({ s }) => (
  <>
    <Topbar crumb="Modo Campanha" here="Salão de troféus" streak={s.streak} onForge={() => s.setShowForge(true)} />
    <div className="page-h">
      <div>
        <div className="eyebrow gold">Hall of fame · {s.unlockedBadges.length} de {BADGES.length} conquistados</div>
        <h1>Salão de troféus</h1>
        <p>Marcos que você gravou em pedra. Cada um conta uma decisão repetida.</p>
      </div>
    </div>
    <div className="badge-grid full">
      {BADGES.map((b) => <Badge key={b.id} b={b} full state={s.stateForBadges} />)}
    </div>
  </>
);

// ── Ranking ───────────────────────────────────────────────────────────────────
const RankScreen = ({ s }) => {
  const list  = s.ranking.length > 0 ? s.ranking : [{ name: s.user?.adventurerName || 'Você', title: s.tier.name, xp: s.totalXp, you: true }];
  const myPos = list.findIndex((r) => r.you) + 1;
  return (
    <>
      <Topbar crumb="Modo Campanha" here="Ranking" streak={s.streak} onForge={() => s.setShowForge(true)} />
      <div className="page-h">
        <div>
          <div className="eyebrow violet">Guilda · classificação geral</div>
          <h1>Ranking pessoal</h1>
          <p>Você está em <strong style={{ color: 'var(--ink)' }}>#{myPos}</strong> de {list.length} aventureiros.</p>
        </div>
      </div>
      <div className="panel ornate">
        <div className="panel-body">
          <div className="rank-list">
            {list.map((r, i) => {
              const cls = i === 0 ? 'gold' : i === 1 ? 'silver' : i === 2 ? 'bronze' : '';
              return (
                <div key={r.name + i} className={`rank-row ${cls} ${r.you ? 'you' : ''}`}>
                  <div className="pos">{i === 0 ? <I.crown /> : `#${i + 1}`}</div>
                  <div className="who">
                    <div className="av">{r.name.charAt(0).toUpperCase()}</div>
                    <div className="nm">{r.name}{r.you && ' (você)'}<small>{r.title}</small></div>
                  </div>
                  <div className="stat-cell">{r.xp.toLocaleString('pt-BR')}<small>XP</small></div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </>
  );
};

// ── Profile ───────────────────────────────────────────────────────────────────
const ProfileScreen = ({ s }) => {
  const name     = s.user?.adventurerName || 'Aventureiro';
  const initials = name.charAt(0).toUpperCase();
  const attrs = [
    { ico: 'fist',    label: 'Foco',       sub: 'Missões épicas concluídas', v: s.stateForBadges.completedByRarity?.epic || 0 },
    { ico: 'feather', label: 'Constância', sub: 'Streak atual',              v: s.streak + 'd' },
    { ico: 'eye',     label: 'Visão',      sub: 'Missões totais concluídas', v: s.totalCompleted },
    { ico: 'compass', label: 'Disciplina', sub: 'Melhor sequência',          v: s.bestStreak + 'd' },
    { ico: 'spark',   label: 'Aura',       sub: 'Troféus conquistados',      v: s.unlockedBadges.length },
  ];
  return (
    <>
      <Topbar crumb="Modo Campanha" here="Aventureiro" streak={s.streak} onForge={() => s.setShowForge(true)} />
      <div className="page-h">
        <div>
          <div className="eyebrow gold">Ficha do aventureiro</div>
          <h1>{name}</h1>
          <p>Sua identidade nesta campanha — atributos que crescem com sua prática.</p>
        </div>
      </div>
      <div className="profile-grid">
        <div className="profile-card">
          <div className="av-big">{initials}</div>
          <h2>{name}</h2>
          <div className="title-line title">{s.tier.name} · Nível {s.lvl.level}</div>
          <div className="attr-list">
            {attrs.map((a) => {
              const Ico = I[a.ico];
              return (
                <div key={a.label} className="attr-row">
                  <div className="a-ico"><Ico /></div>
                  <div className="a-l"><strong>{a.label}</strong>{a.sub}</div>
                  <div className="a-v">{a.v}</div>
                </div>
              );
            })}
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div className="panel ornate">
            <div className="panel-h"><h3>Distribuição de XP por categoria</h3></div>
            <div className="panel-body">
              {CATEGORIES.map((c) => {
                const Ico    = I[c.ico];
                const earned = s.quests.filter((q) => q.status === 'done' && q.category === c.id).reduce((sum, q) => sum + q.xp, 0);
                const allMax = Math.max(...CATEGORIES.map((cat) => s.quests.filter((q) => q.status === 'done' && q.category === cat.id).reduce((sum, q) => sum + q.xp, 0)), 200);
                const p      = Math.min(100, Math.round((earned / allMax) * 100));
                return (
                  <div key={c.id} style={{ marginBottom: 12 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                      <Ico style={{ color: c.color, width: 14, height: 14 }} />
                      <span style={{ fontSize: 13, fontWeight: 600 }}>{c.label}</span>
                      <span style={{ marginLeft: 'auto', fontFamily: 'JetBrains Mono,monospace', fontSize: 12, color: 'var(--gold)' }}>{earned} XP</span>
                    </div>
                    <div className="xp-bar" style={{ height: 6 }}>
                      <div className="fill" style={{ '--p': p + '%', background: `linear-gradient(90deg, ${c.color}55, ${c.color})`, boxShadow: 'none' }} />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="panel ornate">
            <div className="panel-h"><h3>Próximos marcos</h3></div>
            <div className="panel-body">
              <div className="badge-grid">
                {BADGES.filter((b) => !b.cond(s.stateForBadges)).slice(0, 4).map((b) => <Badge key={b.id} b={b} state={s.stateForBadges} />)}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

// ── Settings ──────────────────────────────────────────────────────────────────
const SettingsScreen = ({ s, theme, setTheme }) => {
  const [name,    setName]    = React.useState(s.user?.adventurerName || '');
  const [email,   setEmail]   = React.useState(s.user?.email || '');
  const [pw,      setPw]      = React.useState('');
  const [saving,  setSaving]  = React.useState(false);
  const [saved,   setSaved]   = React.useState(false);
  const [saveErr, setSaveErr] = React.useState('');

  const save = async () => {
    setSaving(true); setSaveErr('');
    try {
      const updates = { adventurerName: name, email };
      if (pw.trim()) updates.password = pw;
      await s.updateUser(updates);
      setSaved(true); setPw('');
      setTimeout(() => setSaved(false), 2500);
    } catch (err) {
      setSaveErr(err.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <Topbar crumb="Modo Campanha" here="Configurações" streak={s.streak} onForge={() => s.setShowForge(true)} />
      <div className="page-h">
        <div>
          <div className="eyebrow mana">Preferências</div>
          <h1>Configurações</h1>
          <p>Ajuste o tom e seus dados de campanha.</p>
        </div>
      </div>
      <div className="two-col">
        <div className="panel ornate">
          <div className="panel-h"><h3>Aparência</h3></div>
          <div className="panel-body">
            <div className="field">
              <label>Tema</label>
              <div className="diff-row" style={{ gridTemplateColumns: 'repeat(2, 1fr)' }}>
                <button className={`diff-pill ${theme === 'dark' ? 'on' : ''}`} data-r="rare" onClick={() => setTheme('dark')}>
                  <div className="lab">Caverna</div><div className="xp">Modo escuro</div>
                </button>
                <button className={`diff-pill ${theme === 'light' ? 'on' : ''}`} data-r="legendary" onClick={() => setTheme('light')}>
                  <div className="lab">Pergaminho</div><div className="xp">Modo claro</div>
                </button>
              </div>
            </div>
          </div>
        </div>

        <div className="panel ornate">
          <div className="panel-h"><h3>Conta</h3></div>
          <div className="panel-body">
            <div className="field">
              <label>Nome de aventureiro</label>
              <input className="input" value={name} onChange={(e) => setName(e.target.value)} />
            </div>
            <div className="field">
              <label>E-mail</label>
              <input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
            </div>
            <div className="field">
              <label>Nova senha <span style={{ color: 'var(--ink-4)', fontFamily: 'JetBrains Mono,monospace', fontSize: 9, letterSpacing: '0.1em' }}>DEIXE EM BRANCO PARA MANTER</span></label>
              <input className="input" type="password" placeholder="••••••" value={pw} onChange={(e) => setPw(e.target.value)} />
            </div>
            {saveErr && <div className="auth-error" style={{ marginBottom: 12, display: 'flex', gap: 6 }}><I.x style={{ width: 13, height: 13, flexShrink: 0 }} /> {saveErr}</div>}
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <button className="btn primary" onClick={save} disabled={saving}>
                {saving ? 'Salvando…' : saved ? '✓ Salvo!' : 'Salvar alterações'}
              </button>
              <button className="btn danger" onClick={s.logout}><I.logout /> Sair da campanha</button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

window.AuthScreen     = AuthScreen;
window.Home           = Home;
window.QuestsScreen   = QuestsScreen;
window.BadgesScreen   = BadgesScreen;
window.RankScreen     = RankScreen;
window.ProfileScreen  = ProfileScreen;
window.SettingsScreen = SettingsScreen;
