/* TTS Forum — question detail (answers, accepted/verified, reply) + ask composer. */
const { Card, Badge, Tag, Button, Avatar, Input, Select } = window.TTSTechnicalTradeSchoolDesignSystem_281306;

function AnswerBlock({ a, mobile }) {
  return (
    <div style={{ display: "flex", gap: mobile ? 12 : 18, padding: "22px 0", borderTop: "1px solid var(--color-line)" }}>
      <div style={{ flex: "none" }}><Votes count={a.votes} /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 10, flexWrap: "wrap" }}>
          {a.accepted && <Badge tone="success" variant="soft"><FIcon name="check" size={13} color="currentColor" /> Accepted answer</Badge>}
          {a.verified && <Badge tone="ember" variant="soft" dot>Instructor verified</Badge>}
        </div>
        <p style={{ fontFamily: "var(--font-sans)", fontSize: 15, color: "var(--text-primary)", lineHeight: 1.65, margin: "0 0 16px" }}>{a.body}</p>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 14, fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)" }}>
            <button style={linkBtn}><FIcon name="message-square" size={14} color="currentColor" /> Reply</button>
            <button style={linkBtn}><FIcon name="share-2" size={14} color="currentColor" /> Share</button>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
            <Avatar name={a.author} size={30} shape="circle" />
            <div>
              <div style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 700, display: "flex", alignItems: "center", gap: 5 }}>
                {a.author}{a.verified && <FIcon name="badge-check" size={14} color="var(--color-ember-500)" />}
              </div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>{a.role} · {a.time}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function QuestionView({ go, qid, mobile }) {
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const q = window.TTS_FORUM.questions.find((x) => x.id === qid) || window.TTS_FORUM.questions[0];
  const cat = catById(q.cat);
  const [reply, setReply] = React.useState("");
  const [, bump] = React.useReducer((x) => x + 1, 0);
  const postAnswer = () => { if (!reply.trim()) return; window.TTSForumStore.addAnswer(q.id, reply.trim()); setReply(""); bump(); };
  const sorted = [...q.answerList].sort((a, b) => (b.accepted ? 1 : 0) - (a.accepted ? 1 : 0) || b.votes - a.votes);

  return (
    <div style={{ maxWidth: 860, margin: "0 auto", padding: mobile ? "20px 16px 72px" : "32px 20px 72px" }}>
      <a href="#" onClick={(e) => { e.preventDefault(); go("home"); }} 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 questions
      </a>

      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12, 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: 12, color: "var(--text-secondary)" }}>
          <FBrand name={cat.icon} size={15} color="var(--color-ember-600)" /> {cat.name}
        </span>
        {q.course && <Tag>{q.course}</Tag>}
      </div>

      <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: mobile ? 24 : 32, letterSpacing: "-0.02em", margin: "0 0 12px", lineHeight: 1.15 }}>{q.title}</h1>
      <div style={{ display: "flex", gap: 16, fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)", marginBottom: 22, flexWrap: "wrap" }}>
        <span>Asked {q.time}</span><span>{q.views} views</span><span>{q.answers} answers</span>
      </div>

      {/* question body */}
      <div style={{ display: "flex", gap: mobile ? 12 : 18 }}>
        <div style={{ flex: "none" }}><Votes count={q.votes} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <p style={{ fontFamily: "var(--font-sans)", fontSize: 15.5, color: "var(--text-primary)", lineHeight: 1.7, margin: "0 0 16px" }}>{q.body}</p>
          <div style={{ display: "flex", 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: 9 }}>
              <Avatar name={q.author} size={30} shape="circle" />
              <div><div style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 700 }}>{q.author}</div><div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)" }}>{q.role}</div></div>
            </div>
          </div>
        </div>
      </div>

      {/* answers */}
      <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, letterSpacing: "-0.01em", margin: "36px 0 0", paddingTop: 8 }}>{q.answerList.length} answers</h2>
      <div>{sorted.map((a, i) => <AnswerBlock key={i} a={a} mobile={mobile} />)}</div>

      {/* reply composer */}
      <Card padding={20} style={{ marginTop: 28 }}>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 17, marginBottom: 12 }}>Your answer</div>
        <textarea value={reply} onChange={(e) => setReply(e.target.value)} placeholder="Share what you know — be specific, cite the standard or the step." rows={4}
          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, color: "var(--text-primary)", 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)" }}>Answering as {window.TTS_FORUM.me.name}</span>
          <Button disabled={!reply.trim()} onClick={postAnswer}>Post answer</Button>
        </div>
      </Card>
    </div>
  );
}

function AskForm({ go, mobile }) {
  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });
  const [posted, setPosted] = React.useState(false);
  const [title, setTitle] = React.useState("");
  const [body, setBody] = React.useState("");
  const [catName, setCatName] = React.useState(window.TTS_FORUM.categories[0].name);
  const [course, setCourse] = React.useState("None");
  const [tags, setTags] = React.useState("");
  const submit = () => {
    if (!title.trim()) return;
    const cat = window.TTS_FORUM.categories.find((c) => c.name === catName) || window.TTS_FORUM.categories[0];
    window.TTSForumStore.addQuestion({
      cat: cat.id, title: title.trim(), body: body.trim() || title.trim(),
      course: course === "None" ? null : course,
      tags: tags.split(",").map((t) => t.trim()).filter(Boolean),
    });
    setPosted(true);
  };
  return (
    <div className="tts-blueprint-light" style={{ minHeight: "calc(100vh - 64px)" }}>
      <div style={{ maxWidth: 720, margin: "0 auto", padding: mobile ? "24px 16px 64px" : "40px 20px 72px" }}>
        <a href="#" onClick={(e) => { e.preventDefault(); go("home"); }} 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 questions
        </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" }}>Question posted</h1>
            <p style={{ fontFamily: "var(--font-sans)", fontSize: 15, color: "var(--text-secondary)", margin: "0 auto 24px", maxWidth: 360, lineHeight: 1.6 }}>The community and instructors get notified. Verified instructor answers are flagged so you know what to trust.</p>
            <Button onClick={() => go("home")}>Back to questions</Button>
          </Card>
        ) : (
          <Card padding={mobile ? 24 : 36}>
            <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, letterSpacing: "-0.02em", margin: "0 0 6px" }}>Ask the community</h1>
            <p style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--text-secondary)", margin: "0 0 24px" }}>Be specific. A good title and the standard or step you're stuck on gets you a faster, better answer.</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <Input label="Title" placeholder="e.g. Landing a shielded drain wire — one end or both?" value={title} onChange={(e) => setTitle(e.target.value)} />
              <div>
                <label style={{ display: "block", fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, marginBottom: 6 }}>Details</label>
                <textarea rows={5} value={body} onChange={(e) => setBody(e.target.value)} placeholder="What are you trying to do, what have you tried, and what's the exact sticking point?"
                  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: "grid", gridTemplateColumns: mobile ? "1fr" : "1fr 1fr", gap: 14 }}>
                <Select label="Category" value={catName} onChange={(e) => setCatName(e.target.value)} options={window.TTS_FORUM.categories.map((c) => c.name)} />
                <Select label="Related course (optional)" value={course} onChange={(e) => setCourse(e.target.value)} options={["None", "BAS-101", "BAS-201", "BAS-320", "DEV-310", "DEV-330"]} />
              </div>
              <Input label="Tags" placeholder="shielding, grounding, NEC" value={tags} onChange={(e) => setTags(e.target.value)} hint="Comma-separated. Helps the right people find it." />
              <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
                <Button variant="ghost" onClick={() => go("home")}>Cancel</Button>
                <Button disabled={!title.trim()} onClick={submit}>Post question</Button>
              </div>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}

const linkBtn = { 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, { QuestionView, AskForm });
