/* TTS Forum — community Q&A. Composes design-system primitives. */
const { Card, Badge, Tag, Button, Avatar, Input } = window.TTSTechnicalTradeSchoolDesignSystem_281306;

function useForumMobile(bp = 860) {
  const [m, setM] = React.useState(typeof window !== "undefined" && window.innerWidth < bp);
  React.useEffect(() => {
    const on = () => setM(window.innerWidth < bp);
    window.addEventListener("resize", on);
    return () => window.removeEventListener("resize", on);
  }, [bp]);
  return m;
}
function FIcon({ name, size = 18, color }) { return <i data-lucide={name} style={{ width: size, height: size, color }} />; }

// brand section glyph (inline so it inherits color)
function FBrand({ name, size = 22, color = "var(--color-ember-600)" }) {
  const g = {
    circuit: <g><g stroke="currentColor" strokeWidth="3.6" fill="none" strokeLinecap="round"><path d="M16 20H48"/><path d="M32 20V40"/></g><g fill="currentColor"><circle cx="16" cy="20" r="4.2"/><circle cx="48" cy="20" r="4.2"/></g><circle cx="32" cy="45" r="6.4" fill="none" stroke="currentColor" strokeWidth="3.6"/><circle cx="32" cy="45" r="1.7" fill="currentColor"/></g>,
    chip: <g><g fill="currentColor"><rect x="11" y="23" width="6" height="3.4" rx="1.2"/><rect x="11" y="30.3" width="6" height="3.4" rx="1.2"/><rect x="11" y="37.6" width="6" height="3.4" rx="1.2"/><rect x="47" y="23" width="6" height="3.4" rx="1.2"/><rect x="47" y="30.3" width="6" height="3.4" rx="1.2"/><rect x="47" y="37.6" width="6" height="3.4" rx="1.2"/></g><rect x="19.5" y="19.5" width="25" height="25" rx="5" fill="none" stroke="currentColor" strokeWidth="3.6"/><circle cx="32" cy="32" r="4.2" fill="currentColor"/></g>,
    laptop: <g><rect x="18" y="19" width="28" height="20" rx="2.5" fill="none" stroke="currentColor" strokeWidth="3.4"/><path d="M11 46H53L48.5 40.5H15.5Z" fill="currentColor"/></g>,
    network: <g><g stroke="currentColor" strokeWidth="3.2" strokeLinecap="round"><path d="M32 32L32 18"/><path d="M32 32L19 45"/><path d="M32 32L45 45"/></g><circle cx="32" cy="32" r="5.2" fill="currentColor"/><g fill="currentColor"><circle cx="32" cy="16" r="4"/><circle cx="18" cy="46" r="4"/><circle cx="46" cy="46" r="4"/></g></g>,
    book: <g fill="none" stroke="currentColor" strokeWidth="3" strokeLinejoin="round" strokeLinecap="round"><path d="M32 22C27 19 19 19 13 21V46C19 44 27 44 32 47C37 44 45 44 51 46V21C45 19 37 19 32 22Z"/><path d="M32 22V47"/></g>,
    cap: <g fill="none" stroke="currentColor" strokeWidth="3" strokeLinejoin="round" strokeLinecap="round"><path d="M32 18L54 27L32 36L10 27Z"/><path d="M20 31V42C20 44.8 25.4 47 32 47C38.6 47 44 44.8 44 42V31"/></g>,
  };
  return <svg width={size} height={size} viewBox="0 0 64 64" style={{ color, flex: "none" }} aria-hidden="true">{g[name] || null}</svg>;
}

function catById(id) { return window.TTS_FORUM.categories.find((c) => c.id === id); }

/* ---- Vote control ---- */
function Votes({ count, vertical = true }) {
  const [v, setV] = React.useState(0); // -1, 0, 1
  const total = count + v;
  const btn = (dir, icon) => (
    <button onClick={() => setV(v === dir ? 0 : dir)} style={{
      border: "none", background: "transparent", cursor: "pointer", padding: 2, display: "flex",
      color: v === dir ? "var(--color-ember-500)" : "var(--text-muted)",
    }}><FIcon name={icon} size={18} color="currentColor" /></button>
  );
  return (
    <div style={{ display: "flex", flexDirection: vertical ? "column" : "row", alignItems: "center", gap: 2 }}>
      {btn(1, "chevron-up")}
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 700, color: "var(--text-primary)" }}>{total}</span>
      {btn(-1, "chevron-down")}
    </div>
  );
}

/* ---- Question row (feed) ---- */
function QuestionRow({ q, go, mobile }) {
  const cat = catById(q.cat);
  return (
    <Card padding={0} interactive onClick={() => go("question", q.id)} style={{ display: "flex" }}>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12, padding: "18px 14px", borderRight: "1px solid var(--color-line)", minWidth: 64, background: "var(--color-stone-50)" }}>
        <div style={{ textAlign: "center" }}>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, lineHeight: 1 }}>{q.votes}</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.08em", color: "var(--text-muted)", marginTop: 3 }}>VOTES</div>
        </div>
        <div style={{ textAlign: "center" }}>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, lineHeight: 1, color: q.solved ? "var(--color-growth-600)" : "var(--text-secondary)" }}>{q.answers}</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.08em", color: "var(--text-muted)", marginTop: 3 }}>ANS</div>
        </div>
      </div>
      <div style={{ flex: 1, padding: "16px 18px", minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8, flexWrap: "wrap" }}>
          {q.solved && <Badge tone="success" variant="soft" dot>Solved</Badge>}
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-secondary)" }}>
            <FBrand name={cat.icon} size={14} color="var(--color-ember-600)" /> {cat.name}
          </span>
          {q.course && <Tag>{q.course}</Tag>}
        </div>
        <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 16 : 18, letterSpacing: "-0.01em", margin: "0 0 6px", lineHeight: 1.2, color: "var(--text-primary)" }}>{q.title}</h3>
        {!mobile && <p style={{ fontFamily: "var(--font-sans)", fontSize: 13.5, color: "var(--text-secondary)", margin: "0 0 12px", lineHeight: 1.5, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{q.body}</p>}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {q.tags.map((t) => <Tag key={t} tone="neutral">#{t}</Tag>)}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>
            <Avatar name={q.author} size={22} shape="circle" /> {q.author} · {q.time}
          </div>
        </div>
      </div>
    </Card>
  );
}

/* ---- Forum home ---- */
function ForumHome({ go, mobile, activeCat, setActiveCat }) {
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const F = window.TTS_FORUM;
  const [sort, setSort] = React.useState("Newest");
  let qs = activeCat === "all" ? F.questions : F.questions.filter((q) => q.cat === activeCat);
  qs = [...qs].sort((a, b) => sort === "Top" ? b.votes - a.votes : sort === "Unanswered" ? a.answers - b.answers : b.id - a.id);

  const Rail = () => (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      <button onClick={() => setActiveCat("all")} style={catBtn(activeCat === "all")}>
        <FIcon name="layers" size={18} color={activeCat === "all" ? "var(--color-ember-600)" : "var(--text-secondary)"} />
        <span style={{ flex: 1, textAlign: "left" }}>All topics</span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>{F.questions.length}</span>
      </button>
      {F.categories.map((c) => (
        <button key={c.id} onClick={() => setActiveCat(c.id)} style={catBtn(activeCat === c.id)}>
          <FBrand name={c.icon} size={18} color={activeCat === c.id ? "var(--color-ember-600)" : "var(--text-secondary)"} />
          <span style={{ flex: 1, textAlign: "left" }}>{c.name}</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>{c.count}</span>
        </button>
      ))}
    </div>
  );

  return (
    <div style={{ maxWidth: 1180, margin: "0 auto", padding: mobile ? "24px 16px 72px" : "32px 20px 72px", display: "grid", gridTemplateColumns: mobile ? "1fr" : "248px 1fr", gap: 28, alignItems: "start" }}>
      {!mobile && <aside style={{ position: "sticky", top: 88 }}><Rail /></aside>}

      <div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, marginBottom: 18, flexWrap: "wrap" }}>
          <div>
            <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 26 : 32, letterSpacing: "-0.02em", margin: 0 }}>
              {activeCat === "all" ? "All questions" : catById(activeCat).name}
            </h1>
            <p style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-secondary)", margin: "4px 0 0" }}>{qs.length} questions{activeCat !== "all" ? ` · ${catById(activeCat).blurb}` : ""}</p>
          </div>
          <Button onClick={() => go("ask")} leftIcon={<FIcon name="plus" size={18} />}>Ask a question</Button>
        </div>

        {mobile && (
          <div style={{ display: "flex", gap: 8, overflowX: "auto", paddingBottom: 12, marginBottom: 8 }}>
            {[{ id: "all", name: "All" }, ...F.categories].map((c) => (
              <button key={c.id} onClick={() => setActiveCat(c.id)} style={{
                flex: "none", border: "1px solid var(--color-line)", borderRadius: "var(--radius-pill)", padding: "7px 14px",
                background: activeCat === c.id ? "var(--color-ink)" : "var(--bg-surface)", color: activeCat === c.id ? "#fff" : "var(--text-secondary)",
                fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, cursor: "pointer", whiteSpace: "nowrap",
              }}>{c.name}</button>
            ))}
          </div>
        )}

        <div style={{ display: "flex", gap: 6, marginBottom: 16 }}>
          {["Newest", "Top", "Unanswered"].map((s) => (
            <button key={s} onClick={() => setSort(s)} style={{
              border: "1px solid", borderColor: sort === s ? "var(--color-ember-300)" : "var(--color-line)",
              background: sort === s ? "var(--color-ember-50)" : "var(--bg-surface)", color: sort === s ? "var(--color-ember-700)" : "var(--text-secondary)",
              borderRadius: "var(--radius-sm)", padding: "7px 14px", fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, cursor: "pointer",
            }}>{s}</button>
          ))}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {qs.length === 0 ? (
            <div style={{ textAlign: "center", padding: "48px 24px", border: "1px dashed var(--color-line-strong)", borderRadius: "var(--radius-lg)", background: "var(--bg-surface)" }}>
              <FIcon name="search-x" size={28} color="var(--text-muted)" />
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18, margin: "12px 0 4px" }}>No questions here yet</div>
              <p style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)", margin: "0 0 16px" }}>
                {activeCat === "all" ? "Nothing matches this filter." : "Be the first to ask in " + catById(activeCat).name + "."}
              </p>
              <Button onClick={() => go("ask")} leftIcon={<FIcon name="plus" size={16} />}>Ask a question</Button>
            </div>
          ) : qs.map((q) => <QuestionRow key={q.id} q={q} go={go} mobile={mobile} />)}
        </div>
      </div>
    </div>
  );
}

function catBtn(active) {
  return {
    display: "flex", alignItems: "center", gap: 11, width: "100%", padding: "10px 12px",
    border: "none", borderRadius: "var(--radius-md)", cursor: "pointer",
    background: active ? "var(--color-ember-50)" : "transparent",
    color: active ? "var(--color-ember-700)" : "var(--text-primary)",
    fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600,
  };
}

Object.assign(window, { useForumMobile, FIcon, FBrand, catById, Votes, ForumHome });
