/* Forum — community discussion board for cannabis subjects & news. */
(function () {
  const D = window.WeedReviewDesignSystem_dcaedb;
  const { Card, Avatar, Tag, Badge, Button, Divider, Select, Icon, LeafFall, Textarea } = D;
  const WR = window.WR_DATA;
  const { useState } = React;

  const Wrap = ({ children, style }) => (
    <div style={{ maxWidth: 'var(--container-max)', margin: '0 auto', padding: '0 var(--space-7)', ...style }}>{children}</div>
  );

  function ThreadRow({ t, navigate }) {
    const [hover, setHover] = useState(false);
    const [votes, setVotes] = useState(t.upvotes);
    const [voted, setVoted] = useState(false);
    return (
      <div onClick={() => navigate('thread', t.id)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{ display: 'grid', gridTemplateColumns: '52px 1fr auto', gap: 'var(--space-5)', alignItems: 'flex-start', padding: 'var(--space-5)', borderRadius: 'var(--radius-md)', background: hover ? 'var(--surface-page-alt)' : 'transparent', cursor: 'pointer', transition: 'var(--transition-colors)' }}>
        <button type="button" onClick={(e) => { e.stopPropagation(); setVoted(!voted); setVotes(votes + (voted ? -1 : 1)); }}
          style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2, padding: '8px 4px', border: `1px solid ${voted ? 'var(--sage-400)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-md)', background: voted ? 'var(--surface-leaf-soft)' : 'var(--surface-card)', color: voted ? 'var(--sage-700)' : 'var(--text-muted)', cursor: 'pointer', transition: 'var(--transition-colors)' }}>
          <Icon name="chevron-up" size={16} strokeWidth={2.4} />
          <span className="u-tnum" style={{ fontSize: 13, fontWeight: 700 }}>{votes}</span>
        </button>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            {t.pinned && <Badge variant="amber" size="sm" icon="pin">Pinned</Badge>}
            <span style={{ fontFamily: 'var(--font-serif)', fontWeight: 600, fontSize: 'var(--text-lg)', color: 'var(--text-heading)', letterSpacing: '-0.01em' }}>{t.title}</span>
          </div>
          <p style={{ fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.5, margin: '4px 0 8px', maxWidth: 640 }}>{t.excerpt}</p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <Tag tone="sage" size="sm">{t.category}</Tag>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 13, color: 'var(--text-faint)' }}>
              <Avatar name={t.author} size="xs" /> {t.author}
            </span>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4, whiteSpace: 'nowrap' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 13, color: 'var(--text-muted)' }}>
            <Icon name="message-circle" size={14} /> <b className="u-tnum">{t.replies}</b> replies
          </span>
          <span className="u-tnum" style={{ fontSize: 12, color: 'var(--text-faint)' }}>{t.replies > 0 ? 'active ' + t.lastActive : 'be the first to reply'}</span>
        </div>
      </div>
    );
  }

  function Post({ p, depth = 0, isOp }) {
    const [votes, setVotes] = useState(p.upvotes);
    const [voted, setVoted] = useState(false);
    const [replying, setReplying] = useState(false);
    const [draft, setDraft] = useState('');
    const [extra, setExtra] = useState([]);
    const kids = (p.replies || []).concat(extra);
    return (
      <div style={{ display: 'flex', gap: 'var(--space-4)', marginLeft: depth ? 44 : 0, paddingTop: depth ? 14 : 0 }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 'none' }}>
          <Avatar name={p.author} size={depth ? 'sm' : 'md'} />
          {kids.length > 0 && <div style={{ flex: 1, width: 2, background: 'var(--divider)', marginTop: 8, borderRadius: 1 }} />}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <span style={{ fontWeight: 700, fontSize: 15, color: 'var(--text-heading)' }}>{p.author}</span>
            {isOp && <Badge variant="forest" size="sm">OP</Badge>}
            <span className="u-tnum" style={{ fontSize: 12, color: 'var(--text-faint)' }}>· {p.time}</span>
          </div>
          <p style={{ fontSize: 15, color: 'var(--text-body)', lineHeight: 1.6, margin: '6px 0 8px' }}>{p.text}</p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <button type="button" onClick={() => { setVoted(!voted); setVotes(votes + (voted ? -1 : 1)); }}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 5, height: 28, padding: '0 10px', border: `1px solid ${voted ? 'var(--sage-400)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-pill)', background: voted ? 'var(--surface-leaf-soft)' : 'transparent', color: voted ? 'var(--sage-700)' : 'var(--text-muted)', cursor: 'pointer', fontSize: 13, fontWeight: 600, transition: 'var(--transition-colors)' }}>
              <Icon name="chevron-up" size={14} strokeWidth={2.4} /> <span className="u-tnum">{votes}</span>
            </button>
            <button type="button" onClick={() => setReplying(!replying)} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, border: 'none', background: 'none', color: 'var(--text-muted)', cursor: 'pointer', fontSize: 13, fontWeight: 600, padding: 0 }}>
              <Icon name="reply" size={14} /> Reply
            </button>
          </div>
          {replying && (
            <div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
              <Avatar name="@you" size="sm" />
              <div style={{ flex: 1 }}>
                <Textarea rows={2} placeholder={`Reply to ${p.author}…`} value={draft} onChange={(e) => setDraft(e.target.value)} />
                <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
                  <Button size="sm" disabled={!draft.trim()} onClick={() => { setExtra([...extra, { author: '@you', time: 'just now', upvotes: 1, text: draft }]); setDraft(''); setReplying(false); }}>Reply</Button>
                  <Button size="sm" variant="ghost" onClick={() => setReplying(false)}>Cancel</Button>
                </div>
              </div>
            </div>
          )}
          {kids.map((r, i) => <Post key={i} p={r} depth={depth + 1} />)}
        </div>
      </div>
    );
  }

  function ThreadPage({ navigate, id }) {
    const t = WR.forumThreads.find((x) => x.id === id) || WR.forumThreads[0];
    const basePosts = WR.forumPosts[t.id] || [
      { author: t.author, op: true, time: 'seeded at launch', upvotes: t.upvotes, text: t.excerpt + ' (This thread is waiting on the community — be the first to reply.)' },
    ];
    const [posts, setPosts] = useState(basePosts);
    const [draft, setDraft] = useState('');
    const op = posts[0];
    return (
      <div style={{ paddingBottom: 80 }}>
        <Wrap style={{ paddingTop: 24, maxWidth: 'var(--container-narrow)' }}>
          <button onClick={() => navigate('forum')} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', color: 'var(--text-link)', fontWeight: 600, fontSize: 14, cursor: 'pointer', padding: 0, marginBottom: 18 }}>
            <Icon name="arrow-left" size={15} /> Back to The Sesh
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 8 }}>
            {t.pinned && <Badge variant="amber" size="sm" icon="pin">Pinned</Badge>}
            <Tag tone="sage" size="sm">{t.category}</Tag>
            <span className="u-tnum" style={{ fontSize: 13, color: 'var(--text-faint)' }}>{posts.length} posts · active {t.lastActive}</span>
          </div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-3xl)', fontWeight: 600, color: 'var(--text-heading)', letterSpacing: '-0.02em', lineHeight: 1.15, marginBottom: 'var(--space-7)' }}>{t.title}</h1>
          <Card padding="lg" elevation="sm">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-7)' }}>
              {posts.map((p, i) => (
                <React.Fragment key={i}>
                  {i > 0 && <Divider />}
                  <Post p={p} isOp={p.op} />
                </React.Fragment>
              ))}
            </div>
            <Divider style={{ margin: 'var(--space-7) 0' }} />
            <div style={{ display: 'flex', gap: 12 }}>
              <Avatar name="@you" size="md" />
              <div style={{ flex: 1 }}>
                <Textarea rows={3} placeholder="Join the sesh — add your take…" value={draft} onChange={(e) => setDraft(e.target.value)} />
                <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 10 }}>
                  <Button disabled={!draft.trim()} iconLeft="send" onClick={() => { setPosts([...posts, { author: '@you', time: 'just now', upvotes: 1, text: draft }]); setDraft(''); }}>Post reply</Button>
                </div>
              </div>
            </div>
          </Card>
        </Wrap>
      </div>
    );
  }

  function ForumPage({ navigate }) {
    const [cat, setCat] = useState('All');
    const [sort, setSort] = useState('Most Active');
    let rows = WR.forumThreads.filter((t) => cat === 'All' || t.category === cat);
    rows = rows.slice().sort((a, b) => (b.pinned ? 1 : 0) - (a.pinned ? 1 : 0) || (sort === 'Most Upvoted' ? b.upvotes - a.upvotes : b.replies - a.replies));

    return (
      <div style={{ paddingBottom: 80 }}>
        <section style={{ position: 'relative', background: 'radial-gradient(120% 140% at 85% 0%, #24503F 0%, #1B3B2F 60%, #14301F 100%)', overflow: 'hidden' }}>
          <LeafFall travel={320} count={13} />
          <Wrap style={{ position: 'relative', zIndex: 1, padding: '44px var(--space-7)', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap' }}>
            <div>
              <div className="u-label" style={{ color: 'var(--leaf-400)', marginBottom: 10 }}>Community</div>
              <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-4xl)', fontWeight: 600, color: '#F3EEE2', letterSpacing: '-0.02em' }}>The Sesh — Forum</h1>
              <p style={{ color: 'var(--text-on-forest-muted)', fontSize: 15, marginTop: 10, maxWidth: 560 }}>
                Strains, science, news, deals, grow logs — pull up a chair and pass it left.
              </p>
            </div>
            <Button iconLeft="pen-line" onClick={() => navigate('submit')}>Start a thread</Button>
          </Wrap>
        </section>

        <Wrap style={{ paddingTop: 24 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', marginBottom: 18 }}>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {WR.forumCategories.map((c) => <Tag key={c} interactive active={cat === c} onClick={() => setCat(c)}>{c}</Tag>)}
            </div>
            <div style={{ width: 180 }}><Select icon="arrow-up-down" options={['Most Active', 'Most Upvoted']} value={sort} onChange={(e) => setSort(e.target.value)} /></div>
          </div>
          <Card padding="sm" elevation="sm">
            {rows.map((t, i) => (
              <React.Fragment key={t.id}>
                {i > 0 && <Divider />}
                <ThreadRow t={t} navigate={navigate} />
              </React.Fragment>
            ))}
            {!rows.length && <p style={{ color: 'var(--text-muted)', padding: '20px 12px' }}>No threads in this category yet — start one.</p>}
          </Card>
          <p style={{ fontSize: 13, color: 'var(--text-faint)', marginTop: 20, textAlign: 'center' }}>
            Keep it friendly and legal — see the <a href="#" onClick={(e) => e.preventDefault()} style={{ fontWeight: 600 }}>community guidelines</a>.
          </p>
        </Wrap>
      </div>
    );
  }
  window.ForumPage = ForumPage;
  window.ThreadPage = ThreadPage;
})();
