/* TTS Community Board — trade-grouped boards, threads, and thread view. */
const { Card, Badge, Tag, Button, Avatar } = window.TTSTechnicalTradeSchoolDesignSystem_281306;

function boardById(id) { return window.TTS_BOARD.boards.find((b) => b.id === id); }

/* ---- Board index, grouped by trade ---- */
function BoardIndex({ go, mobile }) {
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const B = window.TTS_BOARD;
  return (
    <div style={{ maxWidth: 980, margin: "0 auto", padding: mobile ? "24px 16px 72px" : "32px 20px 72px" }}>
      {B.trades.map((tr) => {
        const boards = B.boards.filter((b) => b.trade === tr.id);
        const soon = tr.status === "soon";
        return (
          <section key={tr.id} style={{ marginBottom: 32 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, borderBottom: "2px solid var(--color-ink)", paddingBottom: 10, marginBottom: 14 }}>
              <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 19 : 22, letterSpacing: "-0.01em", margin: 0 }}>{tr.name}</h2>
              {soon
                ? <Badge tone="neutral" variant="outline">Coming soon</Badge>
                : <Badge tone="success" variant="soft" dot>Live</Badge>}
              <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>{tr.blurb}</span>
            </div>

            {soon ? (
              <Card padding={20} style={{ display: "flex", alignItems: "center", gap: 14, opacity: 0.85 }}>
                <span style={{ width: 42, height: 42, borderRadius: "var(--radius-md)", background: "var(--bg-subtle)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
                  <FIcon name="lock" size={18} color="var(--text-muted)" />
                </span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 700, color: "var(--text-secondary)" }}>{tr.name} boards open with the {tr.name} program</div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-muted)", marginTop: 2 }}>Be first in — we'll seed it with the founding cohort.</div>
                </div>
                <Button size="sm" variant="secondary" onClick={() => go("newthread")}>Request early access</Button>
              </Card>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                {boards.map((b) => (
                  <Card key={b.id} padding={0} interactive onClick={() => go("board", b.id)} style={{ display: "flex", alignItems: "stretch" }}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "center", width: 60, flex: "none", background: "var(--color-stone-50)", borderRight: "1px solid var(--color-line)" }}>
                      <FBrand name={b.icon} size={24} color="var(--color-ember-600)" />
                    </div>
                    <div style={{ flex: 1, padding: "14px 18px", minWidth: 0 }}>
                      <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16, letterSpacing: "-0.01em" }}>{b.name}</div>
                      <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: "var(--text-secondary)", marginTop: 2 }}>{b.desc}</div>
                    </div>
                    {!mobile && (
                      <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", gap: 4, padding: "0 18px", borderLeft: "1px solid var(--color-line)", minWidth: 150 }}>
                        <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>{b.threads} threads · {b.posts.toLocaleString()} posts</div>
                        <div style={{ fontFamily: "var(--font-sans)", fontSize: 12, color: "var(--text-primary)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 150 }}>{b.last.title}</div>
                        <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-muted)" }}>{b.last.who} · {b.last.time}</div>
                      </div>
                    )}
                  </Card>
                ))}
              </div>
            )}
          </section>
        );
      })}
    </div>
  );
}

/* ---- Thread list for one board ---- */
function BoardThreads({ go, boardId, mobile }) {
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const b = boardById(boardId);
  const threads = window.TTS_BOARD.threads.filter((t) => t.board === boardId);
  const trade = window.TTS_BOARD.trades.find((x) => x.id === b.trade);
  return (
    <div style={{ maxWidth: 980, margin: "0 auto", padding: mobile ? "20px 16px 72px" : "32px 20px 72px" }}>
      <a href="#" onClick={(e) => { e.preventDefault(); go("boards"); }} style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-secondary)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6, marginBottom: 16 }}>
        <FIcon name="arrow-left" size={14} /> All boards
      </a>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12, flexWrap: "wrap", marginBottom: 18 }}>
        <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
          <span style={{ width: 48, height: 48, borderRadius: "var(--radius-md)", background: "var(--color-ember-50)", border: "1px solid var(--color-ember-100)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <FBrand name={b.icon} size={26} color="var(--color-ember-600)" />
          </span>
          <div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-muted)" }}>{trade.name}</div>
            <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 24 : 30, letterSpacing: "-0.02em", margin: "2px 0 0" }}>{b.name}</h1>
          </div>
        </div>
        <Button onClick={() => go("newthread")} leftIcon={<FIcon name="plus" size={18} />}>New thread</Button>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {threads.length === 0 && (
          <Card padding={28} style={{ textAlign: "center" }}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, marginBottom: 6 }}>No threads yet</div>
            <p style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)", margin: "0 0 16px" }}>Be the first to post on this board.</p>
            <Button onClick={() => go("newthread")} leftIcon={<FIcon name="plus" size={18} />}>Start a thread</Button>
          </Card>
        )}
        {threads.map((t) => (
          <Card key={t.id} padding={0} interactive onClick={() => go("thread", t.id)} style={{ display: "flex" }}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 3, padding: "0 16px", minWidth: 70, flex: "none", background: "var(--color-stone-50)", borderRight: "1px solid var(--color-line)" }}>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, lineHeight: 1, color: t.resolved ? "var(--color-growth-600)" : "var(--text-secondary)" }}>{t.replies}</div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.08em", color: "var(--text-muted)" }}>REPLIES</div>
            </div>
            <div style={{ flex: 1, padding: "14px 18px", minWidth: 0 }}>
              <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 6, flexWrap: "wrap" }}>
                {t.pinned && <Badge tone="info" variant="outline"><FIcon name="pin" size={12} color="currentColor" /> Pinned</Badge>}
                {t.resolved && <Badge tone="success" variant="soft" dot>Resolved</Badge>}
              </div>
              <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 15.5 : 17, letterSpacing: "-0.01em", margin: "0 0 8px", lineHeight: 1.2 }}>{t.title}</h3>
              <div style={{ display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>
                <Avatar name={t.author} size={20} shape="circle" /> {t.author} · {t.time} · {t.views} views
              </div>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

/* ---- Thread view: original post + replies + resolution ---- */
function ThreadPost({ p, op, mobile, idx, onResolve }) {
  return (
    <div style={{ display: "flex", gap: mobile ? 0 : 16, flexDirection: mobile ? "column" : "row", padding: "20px 0", borderTop: op ? "none" : "1px solid var(--color-line)" }}>
      <div style={{ flex: "none", width: mobile ? "auto" : 140, display: "flex", flexDirection: mobile ? "row" : "column", alignItems: "center", gap: 8, marginBottom: mobile ? 12 : 0 }}>
        <Avatar name={p.author} size={mobile ? 32 : 44} shape="circle" />
        <div style={{ textAlign: mobile ? "left" : "center" }}>
          <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 700, display: "flex", alignItems: "center", gap: 5 }}>
            {p.author}{p.verified && <FIcon name="badge-check" size={14} color="var(--color-ember-500)" />}
          </div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--text-muted)" }}>{p.role}</div>
        </div>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 8, flexWrap: "wrap" }}>
          {op && <Badge tone="neutral" variant="soft">Original post</Badge>}
          {p.solution && <Badge tone="success" variant="soft"><FIcon name="check" size={13} color="currentColor" /> Marked as resolution</Badge>}
          {p.verified && <Badge tone="ember" variant="soft" dot>Instructor</Badge>}
          <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>{p.time}</span>
        </div>
        <p style={{ fontFamily: "var(--font-sans)", fontSize: 15, color: "var(--text-primary)", lineHeight: 1.65, margin: 0 }}>{p.body}</p>
        <div style={{ display: "flex", gap: 14, marginTop: 14, fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)" }}>
          <button style={tLink}><FIcon name="arrow-up" size={14} color="currentColor" /> Helpful</button>
          <button style={tLink}><FIcon name="message-square" size={14} color="currentColor" /> Quote</button>
          {!op && !p.solution && onResolve && (
            <button style={{ ...tLink, color: "var(--color-growth-600)" }} onClick={() => onResolve(p._uid || ("seed:" + idx))}>
              <FIcon name="check-circle-2" size={14} color="currentColor" /> Mark as resolution
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function ThreadView({ go, tid, mobile }) {
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const t = window.TTS_BOARD.threads.find((x) => x.id === tid) || window.TTS_BOARD.threads[0];
  const b = boardById(t.board);
  const [reply, setReply] = React.useState("");
  const [, bump] = React.useReducer((x) => x + 1, 0);
  const postReply = () => { if (!reply.trim()) return; window.TTSForumStore.addPost(t.id, reply.trim()); setReply(""); bump(); };
  const resolve = (marker) => { window.TTSForumStore.markResolution(t.id, marker); bump(); };

  return (
    <div style={{ maxWidth: 860, margin: "0 auto", padding: mobile ? "20px 16px 72px" : "32px 20px 72px" }}>
      <a href="#" onClick={(e) => { e.preventDefault(); go("board", t.board); }} style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-secondary)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6, marginBottom: 16 }}>
        <FIcon name="arrow-left" size={14} /> {b.name}
      </a>

      <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 10, flexWrap: "wrap" }}>
        {t.pinned && <Badge tone="info" variant="outline"><FIcon name="pin" size={12} color="currentColor" /> Pinned</Badge>}
        {t.resolved && <Badge tone="success" variant="soft" dot>Resolved</Badge>}
        <Tag tone="neutral">{b.name}</Tag>
      </div>
      <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 23 : 30, letterSpacing: "-0.02em", margin: "0 0 8px", lineHeight: 1.15 }}>{t.title}</h1>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)", marginBottom: 8 }}>{t.replies} replies · {t.views} views</div>

      {/* resolution summary banner */}
      {t.resolved && (() => {
        const sol = t.postList.find((p) => p.solution);
        return sol ? (
          <Card padding={16} style={{ borderColor: "var(--color-growth-300)", background: "var(--color-growth-50)", marginBottom: 8 }}>
            <div style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
              <FIcon name="check-circle-2" size={20} color="var(--color-growth-600)" />
              <div>
                <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 700, color: "var(--color-growth-700)", marginBottom: 3 }}>Resolution — by {sol.author}{sol.verified ? " (instructor)" : ""}</div>
                <div style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-primary)", lineHeight: 1.5 }}>{sol.body.length > 180 ? sol.body.slice(0, 178) + "…" : sol.body}</div>
              </div>
            </div>
          </Card>
        ) : null;
      })()}

      <ThreadPost p={{ author: t.author, role: t.role, time: t.time, body: t.body, verified: false }} op mobile={mobile} />
      {t.postList.map((p, i) => <ThreadPost key={i} idx={i} p={p} mobile={mobile} onResolve={resolve} />)}

      {/* reply box */}
      <Card padding={20} style={{ marginTop: 24 }}>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16, marginBottom: 12 }}>Post a reply</div>
        <textarea value={reply} onChange={(e) => setReply(e.target.value)} rows={4} placeholder="Add to the conversation. If this solves it, the OP or a mod can mark your reply as the resolution."
          style={{ width: "100%", boxSizing: "border-box", border: "1px solid var(--color-line)", borderRadius: "var(--radius-md)", padding: "12px 14px", fontFamily: "var(--font-sans)", fontSize: 14, resize: "vertical", outline: "none" }} />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12, gap: 10, flexWrap: "wrap" }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>Posting as {window.TTS_FORUM.me.name}</span>
          <Button disabled={!reply.trim()} onClick={postReply}>Post reply</Button>
        </div>
      </Card>
    </div>
  );
}

/* ---- New thread composer ---- */
function NewThread({ go, mobile }) {
  const { Input, Select } = window.TTSTechnicalTradeSchoolDesignSystem_281306;
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const [posted, setPosted] = React.useState(false);
  const liveBoards = window.TTS_BOARD.boards.filter((b) => { const tr = window.TTS_BOARD.trades.find((x) => x.id === b.trade); return tr.status === "live"; });
  const [boardName, setBoardName] = React.useState(liveBoards[0].name);
  const [title, setTitle] = React.useState("");
  const [body, setBody] = React.useState("");
  const submit = () => {
    if (!title.trim()) return;
    const bd = liveBoards.find((b) => b.name === boardName) || liveBoards[0];
    window.TTSForumStore.addThread({ board: bd.id, title: title.trim(), body: body.trim() || title.trim() });
    setPosted(true);
  };
  return (
    <div className="tts-blueprint-light" style={{ minHeight: "calc(100vh - 112px)" }}>
      <div style={{ maxWidth: 720, margin: "0 auto", padding: mobile ? "24px 16px 64px" : "40px 20px 72px" }}>
        <a href="#" onClick={(e) => { e.preventDefault(); go("boards"); }} style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-secondary)", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 6, marginBottom: 18 }}>
          <FIcon name="arrow-left" size={14} /> All boards
        </a>
        {posted ? (
          <Card padding={mobile ? 28 : 40} style={{ textAlign: "center" }}>
            <div style={{ width: 60, height: 60, borderRadius: "50%", background: "var(--color-growth-50)", display: "inline-flex", alignItems: "center", justifyContent: "center", margin: "0 auto 18px" }}>
              <FIcon name="check" size={30} color="var(--color-growth-600)" />
            </div>
            <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 26, letterSpacing: "-0.02em", margin: "0 0 8px" }}>Thread posted</h1>
            <p style={{ fontFamily: "var(--font-sans)", fontSize: 15, color: "var(--text-secondary)", margin: "0 auto 24px", maxWidth: 360, lineHeight: 1.6 }}>It's live on the board. Mark a reply as the resolution once your question is answered.</p>
            <Button onClick={() => go("boards")}>Back to boards</Button>
          </Card>
        ) : (
          <Card padding={mobile ? 24 : 36}>
            <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, letterSpacing: "-0.02em", margin: "0 0 6px" }}>Start a thread</h1>
            <p style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)", margin: "0 0 24px" }}>Post to a community or BAS board. HVAC, Electrical, and Plumbing boards open as those programs launch.</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <Select label="Board" value={boardName} onChange={(e) => setBoardName(e.target.value)} options={liveBoards.map((b) => b.name)} />
              <Input label="Thread title" placeholder="Keep it clear — what's the topic or question?" value={title} onChange={(e) => setTitle(e.target.value)} />
              <div>
                <label style={{ display: "block", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, marginBottom: 6 }}>Post</label>
                <textarea rows={6} value={body} onChange={(e) => setBody(e.target.value)} placeholder="Say your piece. Photos and diagrams help on the board."
                  style={{ width: "100%", boxSizing: "border-box", border: "1px solid var(--color-line)", borderRadius: "var(--radius-md)", padding: "12px 14px", fontFamily: "var(--font-sans)", fontSize: 14, resize: "vertical", outline: "none" }} />
              </div>
              <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
                <Button variant="ghost" onClick={() => go("boards")}>Cancel</Button>
                <Button disabled={!title.trim()} onClick={submit}>Post thread</Button>
              </div>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}

const tLink = { border: "none", background: "transparent", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)", padding: 0 };

Object.assign(window, { boardById, BoardIndex, BoardThreads, ThreadView, NewThread });
