// Page 2 — Alerts

function AlertCard({ alert, expanded, onToggle, onDismiss, onCopy }) {
  return (
    <div className={"card " + (alert.severity === "critical" && alert.status === "active" ? "pulse-crit" : "")} style={{ display: "flex", overflow: "hidden", marginBottom: 12 }}>
      <SeverityBar severity={alert.severity} />
      <div style={{ flex: 1, padding: "16px 20px" }}>
        <div style={{ display: "flex", alignItems: "flex-start", gap: 16 }}>
          <div style={{ flex: 1 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
              <SeverityChip severity={alert.severity} />
              <span className="mono muted" style={{ fontSize: 11 }}>{alert.rule}</span>
              {alert.status === "resolved" && <span className="pill ok">resolved</span>}
              {alert.status === "dismissed" && <span className="pill neutral">dismissed</span>}
            </div>
            <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 4 }}>{alert.ruleTitle}</div>
            <div style={{ fontSize: 13, color: "var(--text-dim)", marginBottom: 10 }}>{alert.text}</div>

            <div style={{ display: "flex", flexWrap: "wrap", gap: 16, fontSize: 12, color: "var(--text-muted)" }}>
              <Meta label="Время">{fmtDateTime(alert.ts)} <span className="dim">({fmtAgo(alert.ts)})</span></Meta>
              <Meta label="Задача"><span className="mono" style={{ color: "var(--accent)" }}>PB-{alert.seq}</span> · {alert.title}</Meta>
              {alert.agent && (
                <Meta label="Агент">
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <Avatar agentId={alert.agent} size={18} />
                    {teamById(alert.agent)?.name}
                  </span>
                </Meta>
              )}
              <Meta label="Длительность"><span className="mono">{fmtDuration(alert.durationMin)}</span></Meta>
            </div>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-end" }}>
            {alert.status === "active" && (
              <button className="btn" onClick={onDismiss}>Скрыть</button>
            )}
            <button className="btn btn-primary">К задаче ↗</button>
            <button className="btn btn-ghost" onClick={onToggle}>
              {expanded ? "Свернуть ↑" : "Детали ↓"}
            </button>
          </div>
        </div>

        {expanded && (
          <div style={{ marginTop: 16, paddingTop: 16, borderTop: "1px dashed var(--border-soft)", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 24 }}>
            <div>
              <div className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 6 }}>Пункт инструкции</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--accent)", marginBottom: 8 }}>{alert.claudeMdRef}</div>
              <blockquote style={{
                margin: 0, padding: "10px 14px",
                background: "var(--bg-elev)", borderLeft: "3px solid var(--accent)",
                fontSize: 13, lineHeight: 1.55, color: "var(--text)",
                borderRadius: "0 6px 6px 0",
              }}>
                {alert.claudeMdQuote}
              </blockquote>
            </div>
            <div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
                <span className="muted" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.05em" }}>Промпт для Виктора</span>
                <button className="btn" style={{ padding: "3px 8px", fontSize: 11 }} onClick={onCopy}>📋 Копировать</button>
              </div>
              <pre style={{
                margin: 0, padding: "10px 14px",
                background: "var(--bg-elev)", border: "1px solid var(--border-soft)",
                fontSize: 12, lineHeight: 1.55, color: "var(--text)",
                borderRadius: 6, fontFamily: "var(--font-mono)",
                whiteSpace: "pre-wrap",
              }}>{alert.promptDraft}</pre>
              <button className="btn btn-primary" style={{ marginTop: 8 }}>Обсудить с Виктором →</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function Meta({ label, children }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
      <span className="muted" style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.05em" }}>{label}</span>
      <span style={{ fontSize: 12, color: "var(--text)" }}>{children}</span>
    </div>
  );
}

function AlertsPage({ alerts, dismissAlert, pushToast }) {
  const [tab, setTab] = useState("active");
  const [sev, setSev] = useState("all");
  const [rule, setRule] = useState("all");
  const [expanded, setExpanded] = useState(() => new Set([17]));

  const ruleList = useMemo(() => {
    const s = new Set(); alerts.forEach(a => s.add(a.rule));
    return Array.from(s);
  }, [alerts]);

  const filtered = useMemo(() => {
    return alerts.filter(a => {
      if (tab !== "all" && a.status !== tab) return false;
      if (sev !== "all" && a.severity !== sev) return false;
      if (rule !== "all" && a.rule !== rule) return false;
      return true;
    });
  }, [alerts, tab, sev, rule]);

  const counts = useMemo(() => ({
    active: alerts.filter(a => a.status === "active").length,
    dismissed: alerts.filter(a => a.status === "dismissed").length,
    resolved: alerts.filter(a => a.status === "resolved").length,
  }), [alerts]);

  const toggle = (id) => {
    setExpanded((prev) => {
      const n = new Set(prev);
      n.has(id) ? n.delete(id) : n.add(id);
      return n;
    });
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Алерты</h1>
          <div className="page-sub">Инциденты из правил watchdog'а. Разбирай по очереди и закрывай.</div>
        </div>
      </div>

      <div className="card" style={{ marginBottom: 16 }}>
        <div style={{ padding: "10px 16px", display: "flex", alignItems: "center", gap: 16, borderBottom: "1px solid var(--border-soft)" }}>
          <div className="tabs">
            <button className={`tab ${tab === "active" ? "active" : ""}`} onClick={() => setTab("active")}>
              Active <span className="ctr">{counts.active}</span>
            </button>
            <button className={`tab ${tab === "dismissed" ? "active" : ""}`} onClick={() => setTab("dismissed")}>
              Dismissed <span className="ctr">{counts.dismissed}</span>
            </button>
            <button className={`tab ${tab === "resolved" ? "active" : ""}`} onClick={() => setTab("resolved")}>
              Resolved <span className="ctr">{counts.resolved}</span>
            </button>
            <button className={`tab ${tab === "all" ? "active" : ""}`} onClick={() => setTab("all")}>
              Все <span className="ctr">{alerts.length}</span>
            </button>
          </div>
          <div style={{ width: 1, height: 20, background: "var(--border-soft)" }} />
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span className="muted" style={{ fontSize: 12 }}>Severity:</span>
            {["all","critical","warning","info"].map((s) => (
              <button
                key={s}
                className={`btn ${sev === s ? "" : "btn-ghost"}`}
                style={{ padding: "3px 10px", fontSize: 12, ...(sev === s ? { borderColor: s === "critical" ? "var(--crit)" : s === "warning" ? "var(--warn)" : s === "info" ? "var(--info)" : "var(--border)" } : {}) }}
                onClick={() => setSev(s)}
              >{s}</button>
            ))}
          </div>
          <div style={{ width: 1, height: 20, background: "var(--border-soft)" }} />
          <select className="input mono" style={{ fontSize: 12 }} value={rule} onChange={(e) => setRule(e.target.value)}>
            <option value="all">все правила</option>
            {ruleList.map(r => <option key={r} value={r}>{r}</option>)}
          </select>
          <div className="ml-auto muted" style={{ fontSize: 12 }}>Найдено: <span className="mono">{filtered.length}</span></div>
        </div>
      </div>

      {filtered.length === 0 ? (
        <div className="card">
          <div className="empty">
            <div className="big" style={{ color: "var(--ok)" }}>● Алертов нет</div>
            <div>Все хорошо. <a style={{ color: "var(--accent)", cursor: "pointer" }}>Посмотреть исторические алерты за неделю →</a></div>
          </div>
        </div>
      ) : (
        <div>
          {filtered.map((a) => (
            <AlertCard
              key={a.id}
              alert={a}
              expanded={expanded.has(a.id)}
              onToggle={() => toggle(a.id)}
              onDismiss={() => { dismissAlert(a.id); pushToast("Алерт скрыт", "info"); }}
              onCopy={() => { navigator.clipboard?.writeText(a.promptDraft); pushToast("Промпт скопирован", "ok"); }}
            />
          ))}
        </div>
      )}
    </div>
  );
}

window.AlertsPage = AlertsPage;
