/* screens-community.jsx — The Commons: cohort discussion space */
const { useState: cState, useRef: cRef } = React;

const KINDS = {
  Question: { c: '#6BA8E8', d: '#2C5E94' },
  Idea: { c: 'var(--lime)', d: 'var(--lime-strong)' },
  Resource: { c: '#E8973A', d: '#9A5A12' },
  Reflection: { c: '#A98BD8', d: '#6A4DA0' },
};
function KindPill({ kind, small }) {
  const k = KINDS[kind] || KINDS.Question;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: small ? 11.5 : 12.5, fontWeight: 700,
      letterSpacing: '.04em', textTransform: 'uppercase', padding: small ? '3px 9px' : '4px 11px', borderRadius: 'var(--radius-pill)',
      background: `color-mix(in srgb, ${k.c} 20%, var(--surface))`, color: k.d }}>
      <span className="dot" style={{ width: 7, height: 7, background: k.c }} /> {kind}
    </span>
  );
}

function Avatar({ a, instructor, size = 44 }) {
  return <div className="avatar" style={{ width: size, height: size, fontSize: size * 0.34,
    background: instructor ? 'linear-gradient(135deg,#6BA8E8,#2C5E94)' : undefined }}>{a}</div>;
}

function ReplyComposer({ onSend }) {
  const [text, setText] = cState('');
  const send = () => { if (!text.trim()) return; onSend(text.trim()); setText(''); };
  return (
    <div className="row gap-10" style={{ alignItems: 'flex-start', marginTop: 14 }}>
      <Avatar a={window.EDSTUTIA.learner.avatar} size={36} />
      <div style={{ flex: 1 }}>
        <textarea value={text} onChange={e => setText(e.target.value)} placeholder="Write a considered reply…"
          style={{ width: '100%', minHeight: 48, resize: 'vertical', padding: 12, fontFamily: 'var(--font-body)', fontSize: 15.5,
            lineHeight: 1.5, borderRadius: 'var(--radius)', border: '1.5px solid var(--border)', background: 'var(--surface)', color: 'var(--text)', outline: 'none' }} />
        <div className="row" style={{ justifyContent: 'flex-end', marginTop: 8 }}>
          <button className="btn btn-soft btn-sm" onClick={send} disabled={!text.trim()}><Icon name="send" size={15} /> Reply</button>
        </div>
      </div>
    </div>
  );
}

function ThreadCard({ thread, onReply, onHelpful, helpful }) {
  const [open, setOpen] = cState(false);
  const marked = helpful.includes(thread.id);
  return (
    <article className="card card-pad" style={{ marginTop: 16 }}>
      <div className="row gap-10" style={{ alignItems: 'flex-start' }}>
        <Avatar a={thread.avatar} instructor={thread.role === 'Instructor'} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="row gap-10" style={{ flexWrap: 'wrap', alignItems: 'center' }}>
            <strong style={{ fontSize: 16 }}>{thread.author}</strong>
            <span className="muted" style={{ fontSize: 14 }}>{thread.role}</span>
            <span className="muted" style={{ fontSize: 13.5, marginLeft: 'auto' }}>{thread.when}</span>
          </div>
          <div className="row gap-10" style={{ margin: '10px 0 8px', alignItems: 'center' }}>
            <KindPill kind={thread.kind} />
            <h3 style={{ fontSize: 21, lineHeight: 1.25 }}>{thread.title}</h3>
          </div>
          <p style={{ fontSize: 16.5, lineHeight: 1.6, color: 'var(--text)' }}>{thread.body}</p>
          <div className="row gap-16" style={{ marginTop: 14 }}>
            <button className="row gap-6" onClick={() => onHelpful(thread.id)}
              style={{ border: '1.5px solid ' + (marked ? 'var(--lime)' : 'var(--border-strong)'), background: marked ? 'var(--lime-soft)' : 'var(--surface)',
                color: marked ? 'var(--lime-strong)' : 'var(--text-muted)', cursor: 'pointer', fontWeight: 700, fontSize: 14,
                padding: '7px 14px', borderRadius: 'var(--radius-pill)' }}>
              <Icon name="check" size={16} /> Helpful · {thread.helpful}
            </button>
            <button className="row gap-6" onClick={() => setOpen(o => !o)}
              style={{ border: 'none', background: 'none', color: 'var(--text-muted)', cursor: 'pointer', fontWeight: 700, fontSize: 14, padding: '7px 4px' }}>
              <Icon name="chat" size={16} /> {thread.replies.length} {thread.replies.length === 1 ? 'reply' : 'replies'}
              <Icon name="chevdown" size={15} style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .2s' }} />
            </button>
          </div>
          {open && (
            <div style={{ marginTop: 14, paddingTop: 6, borderTop: '1px solid var(--border)' }}>
              {thread.replies.map((r, i) => (
                <div key={i} className="row gap-10" style={{ alignItems: 'flex-start', marginTop: 14 }}>
                  <Avatar a={r.avatar} instructor={r.role === 'Instructor'} size={36} />
                  <div style={{ flex: 1 }}>
                    <div className="row gap-10" style={{ alignItems: 'center', flexWrap: 'wrap' }}>
                      <strong style={{ fontSize: 15 }}>{r.who}</strong>
                      <span className="muted" style={{ fontSize: 13 }}>{r.role}</span>
                      <span className="muted" style={{ fontSize: 12.5, marginLeft: 'auto' }}>{r.when}</span>
                    </div>
                    <p style={{ fontSize: 15.5, lineHeight: 1.55, marginTop: 4 }}>{r.text}</p>
                  </div>
                </div>
              ))}
              <ReplyComposer onSend={(text) => onReply(thread.id, text)} />
            </div>
          )}
        </div>
      </div>
    </article>
  );
}

function Composer({ onPost }) {
  const [kind, setKind] = cState('Question');
  const [title, setTitle] = cState('');
  const [body, setBody] = cState('');
  const post = () => {
    if (!title.trim() || !body.trim()) return;
    onPost({ kind, title: title.trim(), body: body.trim() });
    setTitle(''); setBody(''); setKind('Question');
  };
  return (
    <div className="card card-pad">
      <div className="row gap-10" style={{ marginBottom: 14 }}>
        <Avatar a={window.EDSTUTIA.learner.avatar} />
        <div className="col" style={{ justifyContent: 'center' }}>
          <strong style={{ fontSize: 16 }}>Start a discussion</strong>
          <span className="muted" style={{ fontSize: 14 }}>Pose a question, share an idea or pass on a resource.</span>
        </div>
      </div>
      <div className="row gap-6" style={{ marginBottom: 12, flexWrap: 'wrap' }}>
        {Object.keys(KINDS).map(k => (
          <button key={k} onClick={() => setKind(k)} style={{ cursor: 'pointer', padding: '7px 14px', borderRadius: 'var(--radius-pill)',
            border: '1.5px solid ' + (kind === k ? KINDS[k].c : 'var(--border-strong)'),
            background: kind === k ? `color-mix(in srgb, ${KINDS[k].c} 16%, var(--surface))` : 'var(--surface)',
            color: kind === k ? KINDS[k].d : 'var(--text-muted)', fontWeight: 700, fontSize: 14, fontFamily: 'var(--font-body)' }}>{k}</button>
        ))}
      </div>
      <input value={title} onChange={e => setTitle(e.target.value)} placeholder="A clear title…"
        style={{ width: '100%', padding: '12px 14px', fontFamily: 'var(--font-head)', fontSize: 18, fontWeight: 600,
          borderRadius: 'var(--radius)', border: '1.5px solid var(--border)', background: 'var(--surface-2)', color: 'var(--text)', outline: 'none', marginBottom: 10 }} />
      <textarea value={body} onChange={e => setBody(e.target.value)} placeholder="Share your thinking. Specific examples help your cohort most…"
        style={{ width: '100%', minHeight: 90, resize: 'vertical', padding: 14, fontFamily: 'var(--font-body)', fontSize: 16, lineHeight: 1.55,
          borderRadius: 'var(--radius)', border: '1.5px solid var(--border)', background: 'var(--surface-2)', color: 'var(--text)', outline: 'none' }} />
      <div className="row" style={{ justifyContent: 'flex-end', marginTop: 12 }}>
        <button className="btn btn-primary" onClick={post} disabled={!title.trim() || !body.trim()}><Icon name="send" size={17} /> Post to the cohort</button>
      </div>
    </div>
  );
}

function Community({ go }) {
  const E = window.EDSTUTIA;
  const [threads, setThreads] = cState([]);
  const [helpful, setHelpful] = usePersist('community_helpful', []);
  const [filter, setFilter] = cState('All');

  // Fetch threads from Supabase
  React.useEffect(() => {
    async function load() {
      if (!window.supabaseClient) return;
      const { data, error } = await window.supabaseClient
        .from('community_threads')
        .select(`
          id, kind, title, body, helpful_count, created_at,
          profiles:author_id (name, role, avatar),
          community_replies ( id, body, created_at, profiles:author_id (name, role, avatar) )
        `)
        .order('created_at', { ascending: false });
        
      if (data) {
        // Map to expected frontend format
        const mapped = data.map(t => ({
          id: t.id,
          author: t.profiles?.name || 'Unknown',
          role: t.profiles?.role || '',
          avatar: t.profiles?.avatar || '?',
          kind: t.kind,
          title: t.title,
          body: t.body,
          helpful: t.helpful_count || 0,
          when: new Date(t.created_at).toLocaleDateString(),
          replies: (t.community_replies || []).map(r => ({
            id: r.id,
            who: r.profiles?.name || 'Unknown',
            role: r.profiles?.role || '',
            avatar: r.profiles?.avatar || '?',
            text: r.body,
            when: new Date(r.created_at).toLocaleDateString()
          }))
        }));
        setThreads(mapped);
      }
    }
    load();
  }, []);

  const addThread = async (t) => {
    // Optimistic update
    const tempId = 'temp-' + Date.now();
    setThreads([{ id: tempId, author: E.learner.name, role: E.learner.role.replace('Faculty · ', ''),
      avatar: E.learner.avatar, when: 'just now', helpful: 0, replies: [], ...t }, ...threads]);
      
    if (window.supabaseClient && window.ME_UUID) {
      await window.supabaseClient.from('community_threads').insert({
        author_id: window.ME_UUID,
        kind: t.kind,
        title: t.title,
        body: t.body
      });
      // A real app would fetch again here or replace the tempId
    }
  };

  const addReply = async (id, text) => {
    setThreads(threads.map(t => t.id === id
      ? { ...t, replies: [...t.replies, { who: E.learner.name, role: E.learner.role.replace('Faculty · ', ''), avatar: E.learner.avatar, when: 'just now', text }] } : t));
      
    if (window.supabaseClient && window.ME_UUID) {
      await window.supabaseClient.from('community_replies').insert({
        thread_id: id,
        author_id: window.ME_UUID,
        body: text
      });
    }
  };

  const toggleHelpful = async (id) => {
    const isHelpful = helpful.includes(id);
    const mod = isHelpful ? -1 : 1;
    
    if (isHelpful) setHelpful(helpful.filter(x => x !== id));
    else setHelpful([...helpful, id]);
    
    setThreads(threads.map(t => t.id === id ? { ...t, helpful: t.helpful + mod } : t));
    
    if (window.supabaseClient && !id.toString().startsWith('temp-') && !id.toString().startsWith('u')) {
      const thread = threads.find(t => t.id === id);
      if (thread) {
        await window.supabaseClient.from('community_threads')
          .update({ helpful_count: thread.helpful + mod })
          .eq('id', id);
      }
    }
  };

  const tabs = ['All', 'Question', 'Idea', 'Resource', 'Reflection'];
  const shown = filter === 'All' ? threads : threads.filter(t => t.kind === filter);

  return (
    <div className="page page-wide">

      <h1 style={{ fontSize: 38, marginTop: 6 }}>Community</h1>
      <p className="muted" style={{ fontSize: 18, marginTop: 6, maxWidth: 660 }}>Ask, share, and build on ideas between live sessions.</p>

      <div className="grid" style={{ gridTemplateColumns: 'minmax(0,1fr) 300px', gap: 26, marginTop: 26, alignItems: 'start' }}>
        <div>
          {/* Prompt */}
          <div className="card card-pad" style={{ background: 'var(--lime-soft)', borderColor: 'transparent' }}>
            <span className="eyebrow">{E.community.prompt.tag}</span>
            <h2 style={{ fontSize: 24, margin: '8px 0 10px', lineHeight: 1.25 }}>{E.community.prompt.title}</h2>
            <p style={{ fontSize: 16.5, lineHeight: 1.6 }}>{E.community.prompt.body}</p>
          </div>

          <div style={{ marginTop: 16 }}><Composer onPost={addThread} /></div>

          {/* Filters */}
          <div className="row gap-6" style={{ margin: '24px 0 4px', flexWrap: 'wrap', alignItems: 'center' }}>
            <span className="muted" style={{ fontWeight: 700, fontSize: 14, marginRight: 6 }}>Show</span>
            {tabs.map(t => (
              <button key={t} onClick={() => setFilter(t)} style={{ cursor: 'pointer', padding: '6px 13px', borderRadius: 'var(--radius-pill)',
                border: '1.5px solid ' + (filter === t ? 'var(--lime)' : 'var(--border)'),
                background: filter === t ? 'var(--lime-soft)' : 'transparent', color: filter === t ? 'var(--lime-strong)' : 'var(--text-muted)',
                fontWeight: 700, fontSize: 13.5, fontFamily: 'var(--font-body)' }}>{t}</button>
            ))}
          </div>

          {shown.map(t => <ThreadCard key={t.id} thread={t} helpful={helpful} onReply={addReply} onHelpful={toggleHelpful} />)}
          {!shown.length && <p className="muted" style={{ marginTop: 20, fontStyle: 'italic' }}>No posts here yet — why not start one?</p>}
        </div>

        {/* Sidebar: cohort */}
        <aside style={{ position: 'sticky', top: 84 }}>
          <div className="card card-pad">
            <div className="row" style={{ justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
              <h3 style={{ fontSize: 18 }}>Your cohort</h3>
              <span className="muted" style={{ fontSize: 13.5, fontWeight: 700 }}>{E.community.cohort.length} people</span>
            </div>
            <p className="muted" style={{ fontSize: 13.5, marginBottom: 12 }}>Immersive Learning Lab · Summer 2026</p>
            <div className="stack" style={{ gap: 0 }}>
              {E.community.cohort.map((m, i) => (
                <div key={i} className="row gap-10" style={{ padding: '10px 0', borderTop: i ? '1px solid var(--border)' : 'none', alignItems: 'center' }}>
                  <Avatar a={m.avatar} instructor={m.instructor} size={36} />
                  <div className="col" style={{ minWidth: 0 }}>
                    <strong style={{ fontSize: 14.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.name}{m.you && <span className="muted" style={{ fontWeight: 400 }}> · you</span>}</strong>
                    <span className="muted" style={{ fontSize: 13 }}>{m.role}</span>
                  </div>
                  {m.instructor && <span className="pill mixed" style={{ marginLeft: 'auto', fontSize: 10.5, padding: '3px 8px' }}>Host</span>}
                </div>
              ))}
            </div>
          </div>
          <div className="card card-pad" style={{ marginTop: 16 }}>
            <div className="row gap-10" style={{ alignItems: 'flex-start' }}>
              <Icon name="calendar" size={22} style={{ color: 'var(--lime-strong)', flex: 'none', marginTop: 2 }} />
              <div>
                <strong style={{ fontSize: 15.5 }}>Meet in real time</strong>
                <p className="muted" style={{ fontSize: 14, marginTop: 4, lineHeight: 1.5 }}>Ideas from here often carry into the live sessions.</p>
                <button className="btn btn-ghost btn-sm" style={{ marginTop: 10 }} onClick={() => go({ name: 'live' })}>See live sessions <Icon name="arrow" size={15} /></button>
              </div>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

Object.assign(window, { Community });
