// The Workshop app: routing, the dashboard, badges and profile.
// Routes: /  /space-explorer  /explore/<slug>  /math-lab  /wishes  /badges  /me
// (the creative labs are their own pages under /activities/).

function routeFromPath(path) {
  if (path === '/space-explorer') return { page: 'space' };
  if (path.startsWith('/explore/')) return { page: 'explore', slug: decodeURIComponent(path.slice('/explore/'.length).replace(/\/$/, '')) };
  if (path === '/math-lab') return { page: 'math' };
  if (path === '/wishes') return { page: 'wishes' };
  if (path === '/badges') return { page: 'badges' };
  if (path === '/me') return { page: 'profile' };
  return { page: 'dashboard' };
}

// New this refresh: a NEW! tag until she opens it (per device; storage may be unavailable).
const NEW_ACTIVITIES = ['math-lab', 'weather-explorer', 'ocean-explorer', 'dinosaur-explorer', 'bug-explorer'];
function seenActivity(slug) { try { return localStorage.getItem('wk_seen_' + slug) === '1'; } catch (e) { return false; } }
function markSeen(slug) { try { localStorage.setItem('wk_seen_' + slug, '1'); } catch (e) {} }

const RARITY_COLORS = { common: '#2ECC71', rare: '#3498DB', epic: '#9B59B6', legendary: '#F39C12' };
const AVATARS = ['🧑‍🚀','👩‍🔬','🦊','🐱','🦄','🐸','🦉','🐼','🐶','🦋','🌟','🚀','🎨','🎵','👾','🧙‍♀️','🧜‍♀️','🦸‍♀️','🤖','🐉'];

function timeAgo(at) {
  const t = new Date(at);
  if (isNaN(t)) return '';
  const mins = Math.round((Date.now() - t) / 60000);
  if (mins < 2) return 'just now';
  if (mins < 60) return `${mins} min ago`;
  const hrs = Math.round(mins / 60);
  if (hrs < 24) return `${hrs} hour${hrs === 1 ? '' : 's'} ago`;
  const days = Math.round(hrs / 24);
  return days === 1 ? 'yesterday' : `${days} days ago`;
}

function App() {
  const [route, setRoute] = useState(() => routeFromPath(window.location.pathname));
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState(false);
  const [me, setMe] = useState(null);
  const [activities, setActivities] = useState([]);
  const [summary, setSummary] = useState(null);
  const [badges, setBadges] = useState(null);
  const [category, setCategory] = useState('all');
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);

  const go = useCallback((path) => {
    window.history.pushState({}, '', path);
    setRoute(routeFromPath(path));
    window.scrollTo(0, 0);
  }, []);
  useEffect(() => {
    const onPop = () => setRoute(routeFromPath(window.location.pathname));
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  const loadData = useCallback(async () => {
    setLoadError(false);
    const [m, acts, sum] = await Promise.all([api('/api/me'), api('/api/activities'), api('/api/activity-summary')]);
    if (!m || m.error || !Array.isArray(acts)) {
      setLoadError(true);
      setLoading(false);
      return;
    }
    setMe(m);
    setActivities(acts);
    setSummary(sum && !sum.error ? sum : null);
    setLoading(false);
  }, []);
  useEffect(() => { loadData(); HootVoice.load(); }, [loadData]);
  // Coming back to the dashboard (from a quiz or a page) refreshes it.
  useEffect(() => { if (route.page === 'dashboard' && !loading) loadData(); }, [route.page]);

  const loadBadges = useCallback(async () => {
    const d = await api('/api/badges');
    if (Array.isArray(d)) setBadges(d);
  }, []);
  useEffect(() => { if (route.page === 'badges') loadBadges(); }, [route.page, loadBadges]);

  const updateAvatar = async (emoji) => {
    await api('/api/me', { method: 'PATCH', body: { avatarEmoji: emoji } });
    setMe(m => ({ ...m, user: { ...m.user, avatarEmoji: emoji } }));
    setShowEmojiPicker(false);
  };

  const openActivity = (a) => {
    if (!a.route) return;
    markSeen(a.slug);
    if (a.route.startsWith('/activities/')) window.location.href = a.route;
    else go(a.route);
  };
  const toDashboard = () => go('/');

  if (loading) {
    return (
      <div className="loading-screen">
        <div className="spinner" />
        <div style={{ fontFamily: 'Fredoka One', fontSize: '1.2rem' }}>Opening the Workshop…</div>
      </div>
    );
  }
  if (loadError) {
    return <div className="craft-page"><div className="craft-content"><OopsCard onRetry={() => { setLoading(true); loadData(); }} /></div></div>;
  }

  const user = me.user;
  const stats = me.stats;
  const features = me.features || {};

  if (route.page === 'space') return <SpaceExplorer onBack={toDashboard} />;
  if (route.page === 'explore') return <Explorer key={route.slug} slug={route.slug} onBack={toDashboard} />;
  if (route.page === 'math') return <MathLab onBack={toDashboard} features={features} />;
  if (route.page === 'wishes') return <WishBoxPage onBack={toDashboard} />;

  // ─── BADGE COLLECTION ──────
  if (route.page === 'badges') {
    const earned = badges ? badges.filter(b => b.earned).length : 0;
    return (
      <>
        <header className="app-header">
          <button className="avatar-btn" onClick={toDashboard} aria-label="Back to the Workshop">←</button>
          <h1>Badge Collection</h1>
          <span className="streak-badge">{earned} / {badges ? badges.length : '…'}</span>
        </header>
        <div className="badge-grid">
          {(badges || []).map(b => (
            <div key={b.id} className={`badge-full ${b.earned ? '' : 'locked'}`} style={{ borderTop: `4px solid ${RARITY_COLORS[b.rarity]}` }}>
              <div className="badge-art">{b.earned ? <BadgeArt badge={b} size={72} /> : <span className="emoji">🔒</span>}</div>
              <div className="name">{b.name}</div>
              <div className="badge-rarity" style={{ color: RARITY_COLORS[b.rarity] }}>{b.rarity}</div>
              <div className="desc">{b.description}</div>
              {b.earned && b.earnedAt && <div className="earned-date">Earned {new Date(b.earnedAt).toLocaleDateString()}</div>}
            </div>
          ))}
        </div>
      </>
    );
  }

  // ─── PROFILE ───────────────
  if (route.page === 'profile') {
    return (
      <>
        <header className="app-header">
          <button className="avatar-btn" onClick={toDashboard} aria-label="Back to the Workshop">←</button>
          <h1>My Profile</h1>
          <span />
        </header>
        <div className="profile-page">
          <div className="profile-header">
            <button className="profile-avatar" onClick={() => setShowEmojiPicker(true)} aria-label="Change my picture">
              {user.avatarEmoji || '🧑‍🚀'}
            </button>
            <div className="profile-hint">Tap to change</div>
            <div className="profile-name">{user.displayName}</div>
            <div className="profile-level">Level {user.explorerLevel} Explorer</div>
          </div>
          <div className="profile-stats">
            <div className="profile-stat"><div className="val">{stats.quizzesCompleted}</div><div className="label">Quizzes done</div></div>
            <div className="profile-stat"><div className="val">{stats.longestStreak}</div><div className="label">Best streak</div></div>
            <div className="profile-stat"><div className="val">{summary ? summary.thingsMade : 0}</div><div className="label">Things made</div></div>
            <div className="profile-stat"><div className="val">{stats.accuracy}%</div><div className="label">Answers right</div></div>
          </div>
          <button className="btn-secondary wide" onClick={() => go('/badges')}>🏅 See all my badges</button>
        </div>
        {showEmojiPicker && (
          <div className="emoji-picker-overlay" onClick={() => setShowEmojiPicker(false)}>
            <div className="emoji-picker" onClick={e => e.stopPropagation()}>
              {AVATARS.map(e => <button key={e} className="emoji-option" onClick={() => updateAvatar(e)}>{e}</button>)}
            </div>
          </div>
        )}
      </>
    );
  }

  // ─── DASHBOARD ─────────────
  const isNew = stats.quizzesCompleted === 0 && !(summary && (summary.thingsMade || summary.thingsSaved));
  const hootPool = isNew ? 'welcome_new' : stats.currentStreak >= 2 ? 'welcome_streak' : stats.playedToday ? 'played_today' : 'welcome_back';
  const filtered = category === 'all' ? activities : activities.filter(a => a.category === category);
  const recent = summary ? summary.recent : [];

  return (
    <>
      <header className="app-header">
        <h1 className="rainbow-title">
          {"Sarah's Workshop".split('').map((ch, i) => {
            if (ch === ' ') return <span key={i} className="space" />;
            const colors = ['#FFFFFF','#4ECDC4','#f5c842','#C3B1E1','#95E1D3','#FF9F43'];
            const rot = ((i * 7 + 3) % 7 - 3).toFixed(1);
            return <span key={i} className="letter" style={{ color: colors[i % colors.length], transform: `rotate(${rot}deg)` }}>{ch}</span>;
          })}
        </h1>
        <div className="header-right">
          {stats.currentStreak > 0 && <span className="streak-badge">🔥 {stats.currentStreak} day{stats.currentStreak === 1 ? '' : 's'}</span>}
          <button className="avatar-btn" onClick={() => go('/me')} aria-label="My profile">{user.avatarEmoji || '🧑‍🚀'}</button>
        </div>
      </header>

      <div className="dashboard">
        <div className="hero">
          <HootSays pool={hootPool} pose={isNew ? 'hello' : 'hello'} size={120}>
            <div className="hero-hello">Hi, {user.displayName}!</div>
          </HootSays>
        </div>

        {!isNew && (
          <div className="progress-card">
            <div><div className="progress-stat">{stats.quizzesCompleted}</div><div className="progress-label">Quizzes done</div></div>
            <div><div className="progress-stat">{stats.currentStreak}</div><div className="progress-label">Day streak</div></div>
            <div><div className="progress-stat">Lv.{user.explorerLevel}</div><div className="progress-label">Explorer level</div></div>
            <div><div className="progress-stat">{summary ? summary.thingsMade : 0}</div><div className="progress-label">Things made</div></div>
          </div>
        )}

        <WishBoxCard onOpen={() => go('/wishes')} />

        <div className="nav-tabs" role="tablist">
          {[['all', 'All', ''], ['science', 'Science', '🔬 '], ['creative', 'Creative', '🎨 '], ['adventure', 'Adventure', '🗺️ ']].map(([key, label, icon]) => (
            <button key={key} className={`nav-tab ${category === key ? 'active' : ''}`} onClick={() => setCategory(key)}
              role="tab" aria-selected={category === key}>{icon}{label}</button>
          ))}
        </div>

        <h2 className="section-title">Activities</h2>
        <div className="activity-grid">
          {filtered.map(a => (
            <button key={a.id} className="activity-card" onClick={() => openActivity(a)} style={{ borderColor: a.color + '33' }}>
              {NEW_ACTIVITIES.includes(a.slug) && !seenActivity(a.slug) && <span className="new-badge">NEW!</span>}
              <ActivityIcon activity={a} />
              <div className="name" style={{ color: a.color === '#1a1a4e' ? '#3b3b8f' : a.color }}>{a.name}</div>
              <div className="desc">{a.description}</div>
              {a.progressPercent !== null && a.progressPercent !== undefined && (
                <div className="progress-ring-container">
                  <ProgressRing percent={a.progressPercent} color={a.color === '#1a1a4e' ? '#5b5bd6' : a.color} />
                  <span className="progress-pct">{a.progressPercent === 0 ? 'Not started yet' : `${a.progressPercent}% of quizzes done`}</span>
                </div>
              )}
              {a.madeCount > 0 && <div className="made-count">✨ Made {a.madeCount} thing{a.madeCount === 1 ? '' : 's'}</div>}
            </button>
          ))}
        </div>

        <h2 className="section-title">What I've been up to</h2>
        {recent.length === 0 ? (
          <div className="empty-note">Nothing yet! Take a quiz or make something, and it will show up here.</div>
        ) : (
          <ul className="recent-list">
            {recent.map((r, i) => (
              <li key={i} className="recent-item">
                <span className="recent-icon">{r.icon}</span>
                <span className="recent-text">
                  {r.kind === 'quiz'
                    ? <>Scored <strong>{r.score}/{r.total}</strong> on {r.detail}</>
                    : <>{r.event === 'saved' ? 'Saved' : 'Made'} {r.detail ? <strong>{r.detail}</strong> : 'something'} in {r.name}</>}
                </span>
                <span className="recent-when">{timeAgo(r.at)}</span>
              </li>
            ))}
          </ul>
        )}

        <h2 className="section-title">My badges</h2>
        {me.recentBadges && me.recentBadges.length > 0 ? (
          <div className="badge-row">
            {me.recentBadges.slice(0, 3).map(b => (
              <button key={b.id} className="badge-chip" onClick={() => go('/badges')}>
                <BadgeArt badge={b} size={40} />
                <div>
                  <div className="badge-name">{b.name}</div>
                  <div className={`badge-rarity ${b.rarity}`}>{b.rarity}</div>
                </div>
              </button>
            ))}
            <button className="badge-chip see-all" onClick={() => go('/badges')}>See all →</button>
          </div>
        ) : (
          <button className="empty-note as-button" onClick={() => go('/badges')}>
            No badges yet. Finish your first quiz to earn <strong>First Steps</strong> 🌟 — tap to see them all!
          </button>
        )}
      </div>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
