// Page 5 — Agents Instructions

function InstructionsPage({ pushToast }) {
  const [activeRole, setActiveRole] = useState("coder");
  const [proposalOpen, setProposalOpen] = useState(false);
  const [proposal, setProposal] = useState({ pt: "", quote: "", suggestion: "", reason: "" });

  const agent = TEAM.find(t => t.role === activeRole);
  const doc = AGENT_DOCS[activeRole] || "";

  // Calculate which points have active rules / recent alerts
  const highlights = useMemo(() => {
    const h = {};
    // Map rules to points by claudeMdRef
    RULES.forEach((r) => {
      if (r.role !== activeRole && r.role !== "any") return;
      // Extract "§ 3.1" or "§ 3" or "§ 5"
      const m = r.claudeMdRef.match(/§\s+([\d.]+)/);
      if (m) h[m[1]] = "active";
    });
    // Alerts in last 24h
    ALERTS.forEach((a) => {
      const m = a.claudeMdRef.match(/agents\/([\w-]+)\/CLAUDE.md\s*§\s+([\d.]+)/);
      if (m && m[1] === activeRole) h[m[2]] = "alert";
    });
    return h;
  }, [activeRole]);

  const rulesForRole = RULES.filter(r => r.role === activeRole || r.role === "any");
  const alertsForRole = ALERTS.filter(a => {
    const m = a.claudeMdRef.match(/agents\/([\w-]+)\/CLAUDE.md/);
    return m && m[1] === activeRole;
  });

  const openProposal = (pt) => {
    // Extract a snippet of text for pt
    const lines = doc.split("\n");
    let quote = "";
    let collecting = false;
    let captured = [];
    for (const ln of lines) {
      if (ln.startsWith("##") || ln.startsWith("###")) {
        const m = ln.match(/(\d+(?:\.\d+)?)/);
        if (m && m[1] === pt) { collecting = true; continue; }
        else if (collecting) break;
      }
      if (collecting) captured.push(ln);
    }
    quote = captured.join("\n").trim().slice(0, 400);
    setProposal({ pt, quote, suggestion: quote, reason: "" });
    setProposalOpen(true);
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Инструкции агентов</h1>
          <div className="page-sub">Read-only: <span className="mono">agents/&lt;role&gt;/CLAUDE.md</span>. Зелёным — пункты, на которые ссылается активное правило. Жёлтым — пункты, по которым недавно сработал алерт.</div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "240px 1fr 320px", gap: 16 }}>
        {/* Left — role list */}
        <div className="card" style={{ alignSelf: "flex-start" }}>
          <div className="card-hd"><h3>Роли</h3></div>
          <div style={{ padding: "6px 6px" }}>
            {TEAM.map((t) => (
              <button
                key={t.id}
                onClick={() => setActiveRole(t.role)}
                style={{
                  width: "100%", display: "flex", alignItems: "center", gap: 10,
                  padding: "8px 10px", borderRadius: 6, border: "none",
                  background: t.role === activeRole ? "var(--surface-hi)" : "transparent",
                  color: "inherit", cursor: "pointer",
                  borderLeft: t.role === activeRole ? "2px solid var(--accent)" : "2px solid transparent",
                }}
              >
                <Avatar agentId={t.id} size={26} />
                <div style={{ textAlign: "left", flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{t.name}</div>
                  <div className="mono muted" style={{ fontSize: 10 }}>{t.role}</div>
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* Center — markdown */}
        <div className="card">
          <div className="card-hd">
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <h3>agents / {activeRole} / CLAUDE.md</h3>
              <span className="mono muted" style={{ fontSize: 11 }}>read-only</span>
            </div>
            <div style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 11 }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                <span style={{ width: 12, height: 8, borderRadius: 2, background: "rgba(34,197,94,0.4)" }} />
                <span className="muted">правило активно</span>
              </span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                <span style={{ width: 12, height: 8, borderRadius: 2, background: "rgba(234,179,8,0.55)" }} />
                <span className="muted">алерт за 24ч</span>
              </span>
            </div>
          </div>
          <div className="card-bd" style={{ padding: "8px 24px 24px" }}>
            <Md src={doc} highlights={highlights} />
          </div>
        </div>

        {/* Right — bindings + propose */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="card">
            <div className="card-hd"><h3>Связи правило ↔ пункт</h3></div>
            <div style={{ padding: "8px 14px 14px" }}>
              {rulesForRole.length === 0 ? (
                <div className="muted" style={{ fontSize: 13, padding: 8 }}>Нет правил.</div>
              ) : rulesForRole.map((r) => {
                const ptMatch = r.claudeMdRef.match(/§\s+([\d.]+)/);
                const pt = ptMatch ? ptMatch[1] : "?";
                const hadAlert = highlights[pt] === "alert";
                return (
                  <div key={r.name} style={{ padding: "8px 0", borderBottom: "1px dashed var(--border-soft)" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <SeverityChip severity={r.severity} />
                      {hadAlert && <span className="pill warn">сработал</span>}
                    </div>
                    <div className="mono" style={{ fontSize: 11, marginTop: 4, color: r.active ? "var(--text)" : "var(--text-muted)" }}>{r.name}</div>
                    <div style={{ fontSize: 11, color: "var(--text-muted)", marginTop: 2 }}>
                      → § {pt}
                      <button
                        onClick={() => openProposal(pt)}
                        className="btn btn-ghost"
                        style={{ marginLeft: 8, padding: "1px 6px", fontSize: 10 }}
                      >править</button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="card">
            <div className="card-hd"><h3>Алерты за 24ч</h3></div>
            <div style={{ padding: "8px 14px 14px" }}>
              {alertsForRole.length === 0 ? (
                <div className="muted" style={{ fontSize: 13, padding: 8 }}>Нет.</div>
              ) : alertsForRole.map((a) => (
                <div key={a.id} style={{ padding: "8px 0", borderBottom: "1px dashed var(--border-soft)", fontSize: 12 }}>
                  <div className="mono" style={{ color: "var(--accent)" }}>PB-{a.seq}</div>
                  <div className="dim">{a.ruleTitle}</div>
                  <div className="mono muted" style={{ fontSize: 10 }}>{fmtAgo(a.ts)}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <SidePanel open={proposalOpen} onClose={() => setProposalOpen(false)} title={`Предложить правку — § ${proposal.pt}`}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div>
            <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 6 }}>Текущая версия</div>
            <pre style={{
              margin: 0, padding: 12, background: "var(--bg)", border: "1px solid var(--border-soft)",
              borderRadius: 6, fontSize: 12, lineHeight: 1.55, whiteSpace: "pre-wrap", fontFamily: "var(--font-mono)",
              color: "var(--text-dim)",
            }}>{proposal.quote}</pre>
          </div>
          <div>
            <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 6 }}>Предложенная версия</div>
            <textarea
              className="input mono"
              value={proposal.suggestion}
              onChange={(e) => setProposal({ ...proposal, suggestion: e.target.value })}
              style={{ width: "100%", minHeight: 160, resize: "vertical", fontSize: 12, lineHeight: 1.55 }}
            />
          </div>
          <div>
            <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 6 }}>Почему</div>
            <textarea
              className="input"
              value={proposal.reason}
              onChange={(e) => setProposal({ ...proposal, reason: e.target.value })}
              placeholder="Что не так в текущей версии и зачем правка?"
              style={{ width: "100%", minHeight: 80, resize: "vertical", fontSize: 13 }}
            />
          </div>
          <button
            className="btn btn-primary"
            onClick={() => {
              pushToast("Создана задача для Виктора (workflow-lead)", "ok");
              setProposalOpen(false);
            }}
          >Отправить → создать задачу для Виктора</button>
        </div>
      </SidePanel>
    </div>
  );
}

window.InstructionsPage = InstructionsPage;
