// Classroom — live posts from Supabase + real SSE chat
const { useState: cUseState, useEffect: cUseEffect, useCallback: cUseCallback } = React;

function Classroom({ focusId }) {
  const [posts, setPosts] = cUseState([]);
  const [loading, setLoading] = cUseState(true);
  const [filter, setFilter] = cUseState('all');
  const [expanded, setExpanded] = cUseState(focusId || null);
  const [syncing, setSyncing] = cUseState(false);

  cUseEffect(() => {
    loadPosts();
  }, []);

  cUseEffect(() => {
    if (focusId) setExpanded(focusId);
  }, [focusId]);

  function loadPosts(force = false) {
    setLoading(true);
    const path = 'classroom_posts?order=posted_at.desc.nullslast,synced_at.desc&limit=200';
    (force ? dbGet(path) : dbGetCached(path))
      .then(rows => {
        const list = rows.map(transformPost);
        setPosts(list);
        window.CLASSROOM_POSTS = list;
        if (force) invalidateCache(path);
      })
      .catch(e => console.error('classroom_posts:', e))
      .finally(() => setLoading(false));
  }

  function handleSync() {
    setSyncing(true);
    setTimeout(() => { loadPosts(true); setSyncing(false); }, 1500);
  }

  const filtered = filter === 'all' ? posts : posts.filter(p => p.subject === filter);

  return (
    <>
      <Topbar
        crumbs={['Classroom']}
        actions={<>
          <button className="btn ghost" onClick={handleSync} disabled={syncing}>
            {syncing ? <><span className="spinner" /> Syncing…</> : <><I.Refresh size={11} /> Refresh</>}
          </button>
        </>}
      />

      <div className="tabs">
        <div className={`tab ${filter === 'all' ? 'active' : ''}`} onClick={() => setFilter('all')}>
          All {posts.length > 0 && <span className="tcount">{posts.length}</span>}
        </div>
        {VISIBLE_SUBJECTS.map(s => {
          const c = posts.filter(p => p.subject === s.id).length;
          return (
            <div key={s.id} className={`tab ${filter === s.id ? 'active' : ''}`} onClick={() => setFilter(s.id)}>
              <span className="subj-dot" style={{ background: s.hex }} />
              {s.short}
              {c > 0 && <span className="tcount">{c}</span>}
            </div>
          );
        })}
      </div>

      <div className="content">
        <div className="classroom-feed">
          {loading && (
            <div className="empty" style={{ padding: 48 }}><span className="spinner" /> Loading posts…</div>
          )}
          {!loading && filtered.map(p => (
            <PostCard
              key={p.id}
              post={p}
              expanded={expanded === p.id}
              onToggle={() => setExpanded(e => e === p.id ? null : p.id)}
            />
          ))}
          {!loading && filtered.length === 0 && (
            <div className="empty">
              {posts.length === 0 ? 'No classroom posts yet. The Apps Script will sync them.' : 'No posts for this subject.'}
            </div>
          )}
        </div>
      </div>
    </>
  );
}

function PostCard({ post, expanded, onToggle }) {
  return (
    <div className={`post-card ${expanded ? 'expanded' : ''}`}>
      <div className="post-head" onClick={onToggle}>
        <div style={{ background: (SUBJ_BY_ID[post.subject] || SUBJ_BY_ID.maths).hex, borderRadius: 1 }} />
        <div style={{ minWidth: 0 }}>
          <div className="hstack" style={{ marginBottom: 3, gap: 6 }}>
            <SubjectTag subject={post.subject} />
            <Badge>{post.type}</Badge>
            {post.teacher && <span className="dim" style={{ fontSize: 11.5 }}>· {post.teacher}</span>}
            <span className="dim" style={{ fontSize: 11.5, marginLeft: 'auto' }}>{post.date}</span>
          </div>
          <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 3 }}>{post.title}</div>
          <div className="muted" style={{ fontSize: 12, lineHeight: 1.5 }}>{post.excerpt}</div>
        </div>
        <div className="hstack faint" style={{ alignSelf: 'center' }}>
          {expanded ? <I.ChevronDown size={12} /> : <I.ChevronRight size={12} />}
        </div>
      </div>
      {expanded && <PostExpanded post={post} />}
    </div>
  );
}

function PostExpanded({ post }) {
  const opener = openerForPost(post);
  const [msgs, rawSend, streamIdx, busy] = useSSEChat(opener);

  const send = cUseCallback((text) => {
    rawSend(text, 'classroom-chat', { postId: post.postId || post.id, message: text });
  }, [rawSend, post]);

  return (
    <div style={{ borderTop: '1px solid var(--border)', padding: '12px 14px 0', background: 'var(--bg)' }}>
      <div style={{ fontSize: 12.5, lineHeight: 1.65, color: 'var(--fg-2)', whiteSpace: 'pre-wrap', marginBottom: 12 }}>
        {post.body || post.excerpt}
      </div>
      {post.files && post.files.length > 0 && (
        <div className="hstack" style={{ flexWrap: 'wrap', gap: 5, marginBottom: 12 }}>
          {post.files.map((f, i) => (
            <span key={i} className="chip"><I.File size={10} />{f}</span>
          ))}
        </div>
      )}
      <div style={{ margin: '0 -14px', borderTop: '1px solid var(--border)', background: 'var(--bg-1)' }}>
        <div className="hstack" style={{ padding: '7px 14px 0', gap: 6 }}>
          <I.Sparkle size={11} className="dim" />
          <span className="dim" style={{ fontSize: 11 }}>Lynxe · context: this post + your notes</span>
        </div>
        <div style={{ height: 200, display: 'flex', flexDirection: 'column' }}>
          <ChatThread messages={msgs} streamingIndex={streamIdx} />
          <ChatInput placeholder={`Ask about "${post.title}"…`} onSend={send} disabled={busy} />
        </div>
      </div>
    </div>
  );
}

function openerForPost(post) {
  if (post.type === 'Assignment')   return `I can help with "${post.title}". Want me to break it into a daily plan, draft an outline, or pull key concepts from your recent lectures?`;
  if (post.type === 'Material')     return `Ready to help with "${post.title}". I can summarise the key points, build flashcards, or quiz you on the trickier sections.`;
  if (post.type === 'Announcement') return `Noted the announcement. Anything you'd like me to follow up on or adjust in your study plan?`;
  if (post.type === 'Question')     return `I can help structure a response to ${post.teacher}'s question, or pull the relevant concept from your notes.`;
  return `How can I help with this post?`;
}

window.Classroom = Classroom;
