/* global React, CR_UI, CR_API */
const { useState, useEffect, useCallback } = React;
const { Icons, Btn } = CR_UI;

function StatCard({ label, value, sub }) {
  return (
    <div style={{
      background: "var(--bg-card)",
      border: "1px solid var(--border)",
      borderRadius: 6,
      padding: "16px 20px",
    }}>
      <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>{label}</div>
      <div style={{ fontSize: 28, fontWeight: 700, fontFamily: "Geometria, sans-serif", color: "var(--fg-primary)", lineHeight: 1 }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

function StatusDot({ status }) {
  const colors = {
    ok: "var(--status-approved-fg)",
    approved: "var(--status-approved-fg)",
    needs_revision: "var(--status-warning-fg)",
    failed: "var(--status-rejected-fg)",
    timeout: "var(--status-rejected-fg)",
    killed: "var(--fg-muted)",
    running: "var(--status-info-fg)",
  };
  return (
    <span style={{
      display: "inline-block", width: 7, height: 7, borderRadius: 999,
      background: colors[status] || "var(--fg-muted)",
      marginRight: 5, verticalAlign: "middle",
    }} />
  );
}

function CouncilCard({ review }) {
  const [open, setOpen] = useState(false);
  const verdict = review.verdict || {};
  const gpt = review.reviews?.gpt || {};
  const gemini = review.reviews?.gemini || {};
  const decision = verdict.decision || "—";

  return (
    <div style={{ border: "1px solid var(--border)", borderRadius: 6, overflow: "hidden", marginBottom: 8 }}>
      <div
        style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", cursor: "pointer", background: "var(--bg-card)" }}
        onClick={() => setOpen((v) => !v)}
      >
        <StatusDot status={decision} />
        <span style={{ fontWeight: 600, flex: 1, fontSize: 13 }}>{review.topic_id}</span>
        <span style={{ fontSize: 12, color: "var(--fg-muted)" }}>
          GPT: {gpt.score ?? "—"} · Gemini: {gemini.score ?? "—"}
        </span>
        <span style={{
          fontSize: 11, fontWeight: 600, padding: "2px 8px", borderRadius: 4,
          background: decision === "approved" ? "var(--status-approved-bg)" : decision === "failed" ? "var(--status-rejected-bg)" : "var(--status-warning-bg)",
          color: decision === "approved" ? "var(--status-approved-fg)" : decision === "failed" ? "var(--status-rejected-fg)" : "var(--status-warning-fg)",
        }}>
          {decision === "approved" ? "Одобрено" : decision === "failed" ? "Ошибка" : "Нужны правки"}
        </span>
        <Icons.ChevronDown size={14} style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform 0.15s" }} />
      </div>
      {open && (
        <div style={{ padding: "12px 14px", borderTop: "1px solid var(--border)", background: "var(--bg-page)", display: "flex", flexDirection: "column", gap: 12 }}>
          {[["GPT", gpt], ["Gemini", gemini]].map(([name, r]) => (
            <div key={name}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 4 }}>
                {name} · {r.model} · Оценка: <strong style={{ color: "var(--fg-primary)" }}>{r.score ?? "—"}</strong>
              </div>
              {r.error && <div style={{ color: "var(--status-rejected-fg)", fontSize: 12 }}>Ошибка: {r.error}</div>}
              {r.summary && <div style={{ fontSize: 13, marginBottom: 6 }}>{r.summary}</div>}
              {r.issues?.length > 0 && (
                <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12, color: "var(--fg-muted)" }}>
                  {r.issues.map((s, i) => <li key={i}>{s}</li>)}
                </ul>
              )}
            </div>
          ))}
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 4 }}>
              {verdict.model || "Судья"} · Финальное решение
            </div>
            {verdict.error && <div style={{ color: "var(--status-rejected-fg)", fontSize: 12 }}>Ошибка: {verdict.error}</div>}
            {verdict.reasoning && <div style={{ fontSize: 13, marginBottom: 6 }}>{verdict.reasoning}</div>}
            {verdict.final_suggestions?.length > 0 && (
              <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12, color: "var(--fg-muted)" }}>
                {verdict.final_suggestions.map((s, i) => <li key={i}>{s}</li>)}
              </ul>
            )}
          </div>
          <div style={{ fontSize: 11, color: "var(--fg-muted)" }}>
            {review.created_at ? new Date(review.created_at).toLocaleString("ru-RU") : ""}
          </div>
        </div>
      )}
    </div>
  );
}

const ReportScreen = ({ brand }) => {
  const [report, setReport] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const load = useCallback(() => {
    if (!brand) return;
    setLoading(true);
    setError(null);
    CR_API.getReport(brand)
      .then((r) => { setReport(r); setLoading(false); })
      .catch((e) => { setError(e.message); setLoading(false); });
  }, [brand]);

  useEffect(() => { load(); }, [load]);

  if (!brand) {
    return (
      <div className="screen">
        <div style={{ padding: 40, color: "var(--fg-muted)" }}>Выберите бренд</div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="screen">
        <div style={{ padding: 40, display: "flex", gap: 10, alignItems: "center", color: "var(--fg-muted)" }}>
          <Icons.Spinner size={18} /> Загрузка отчёта…
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="screen">
        <div style={{ padding: 40 }}>
          <div className="error-banner">
            <Icons.AlertTriangle size={18} />
            <div style={{ flex: 1 }}><div className="error-banner__title">Ошибка</div><div className="error-banner__body">{error}</div></div>
            <Btn kind="primary" size="sm" onClick={load}>Повторить</Btn>
          </div>
        </div>
      </div>
    );
  }

  if (!report) return null;

  const { pipeline = {}, jobs: jobsData = {}, council_reviews = [], bootstrap } = report;
  const topics = pipeline.topics || {};
  const posts = pipeline.posts || {};
  const council = pipeline.council || {};
  const research = pipeline.research || {};

  return (
    <div className="screen">
      <div className="screen__header">
        <div className="screen__header-row">
          <div style={{ flex: 1 }}>
            <div className="section-label" style={{ marginBottom: 6 }}>Аналитика · {brand}</div>
            <h1 className="screen__title">Отчёт по пайплайну</h1>
            <div className="screen__subtitle">Статус всех этапов: от поиска тем до публикации</div>
          </div>
          <Btn kind="ghost" size="sm" icon={<Icons.Refresh size={13} />} onClick={load}>Обновить</Btn>
        </div>
      </div>

      <div style={{ padding: "0 24px 32px", flex: 1, overflowY: "auto" }}>

        {/* Pipeline stats */}
        <div style={{ marginBottom: 24 }}>
          <div className="section-label" style={{ marginBottom: 12 }}>Пайплайн</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(160px, 1fr))", gap: 12 }}>
            <StatCard label="Тем найдено" value={topics.total ?? "—"} sub={`одобрено ${topics.approved ?? 0} · откл. ${topics.rejected ?? 0}`} />
            <StatCard label="Исследовано" value={research.topics_researched ?? "—"} sub={`${research.total_versions ?? 0} версий`} />
            <StatCard label="Черновиков" value={posts.drafts ?? "—"} sub={`опубликовано ${posts.published ?? 0}`} />
            <StatCard label="Консилиумов" value={council.total ?? "—"} sub={`одобр. ${council.approved ?? 0} · правки ${council.needs_revision ?? 0} · ошибки ${council.failed ?? 0}`} />
            <StatCard label="Всего задач" value={jobsData.total ?? "—"} sub={`${(jobsData.total_tokens || 0).toLocaleString("ru-RU")} токенов`} />
          </div>
        </div>

        {/* Bootstrap quality */}
        {bootstrap && (
          <div style={{ marginBottom: 24 }}>
            <div className="section-label" style={{ marginBottom: 12 }}>Bootstrap</div>
            <div style={{ background: "var(--bg-card)", border: "1px solid var(--border)", borderRadius: 6, padding: "14px 18px" }}>
              <div style={{ display: "flex", gap: 16, alignItems: "center", flexWrap: "wrap" }}>
                <span style={{ fontSize: 13 }}>
                  <StatusDot status={bootstrap.status === "ok" ? "ok" : "failed"} />
                  {bootstrap.channel} · {bootstrap.status}
                </span>
                {bootstrap.quality_blockers > 0 && (
                  <span style={{ color: "var(--status-rejected-fg)", fontSize: 12, fontWeight: 600 }}>
                    ⛔ {bootstrap.quality_blockers} блокер(а)
                  </span>
                )}
                {bootstrap.quality_warnings > 0 && (
                  <span style={{ color: "var(--status-warning-fg)", fontSize: 12, fontWeight: 600 }}>
                    ⚠️ {bootstrap.quality_warnings} предупреждение(й)
                  </span>
                )}
              </div>
              {bootstrap.quality_issues?.length > 0 && (() => {
                const CODE_LABELS = {
                  truncated_title: "Заголовок обрезан",
                  truncated_summary: "Описание обрезано",
                  placeholder_glyphs: "Нетипичные эмодзи",
                  few_new_sources: "Мало новых источников",
                  own_channel_as_source: "Собственный канал в источниках",
                };
                // Strip leading "filename.md: " from message
                const stripFile = (msg) => msg.replace(/^[^\s:]+\.md:\s*/, "");

                const blockers = bootstrap.quality_issues.filter((i) => i.level === "BLOCKER");
                const warnings = bootstrap.quality_issues.filter((i) => i.level !== "BLOCKER");

                // Warnings: grouped by code with count
                const warnGroups = {};
                warnings.forEach((iss) => {
                  const key = iss.code || "other";
                  if (!warnGroups[key]) warnGroups[key] = 0;
                  warnGroups[key]++;
                });

                return (
                  <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 4, fontSize: 12 }}>
                    {blockers.map((iss, i) => (
                      <div key={i} style={{ display: "flex", alignItems: "flex-start", gap: 6 }}>
                        <span style={{ color: "var(--status-rejected-fg)", flexShrink: 0 }}>⛔</span>
                        <span style={{ color: "var(--fg-primary)" }}>{stripFile(iss.message)}</span>
                      </div>
                    ))}
                    {Object.entries(warnGroups).map(([code, count]) => (
                      <div key={code} style={{ display: "flex", alignItems: "flex-start", gap: 6 }}>
                        <span style={{ color: "var(--status-warning-fg)", flexShrink: 0 }}>⚠️</span>
                        <span style={{ color: "var(--fg-muted)" }}>
                          <strong style={{ color: "var(--fg-secondary, var(--fg-muted))" }}>{count}×</strong>{" "}
                          {CODE_LABELS[code] || code}
                        </span>
                      </div>
                    ))}
                  </div>
                );
              })()}
            </div>
          </div>
        )}

        {/* Jobs breakdown */}
        {jobsData.total > 0 && (
          <div style={{ marginBottom: 24 }}>
            <div className="section-label" style={{ marginBottom: 12 }}>Задачи по типам</div>
            <div style={{ background: "var(--bg-card)", border: "1px solid var(--border)", borderRadius: 6, overflow: "hidden" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
                <thead>
                  <tr style={{ borderBottom: "1px solid var(--border)" }}>
                    {["Тип", "Всего", "OK", "Failed", "Timeout"].map((h) => (
                      <th key={h} style={{ textAlign: "left", padding: "8px 14px", fontWeight: 600, color: "var(--fg-muted)", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em" }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {Object.entries(jobsData.by_kind || {}).map(([kind, count]) => {
                    const ks = jobsData.by_kind_status?.[kind] || {};
                    return (
                      <tr key={kind} style={{ borderBottom: "1px solid var(--border)" }}>
                        <td style={{ padding: "8px 14px" }}><code style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 12 }}>{kind}</code></td>
                        <td style={{ padding: "8px 14px", fontWeight: 600 }}>{count}</td>
                        <td style={{ padding: "8px 14px", color: "var(--status-approved-fg)" }}>{ks.ok ?? 0}</td>
                        <td style={{ padding: "8px 14px", color: "var(--status-rejected-fg)" }}>{ks.failed ?? 0}</td>
                        <td style={{ padding: "8px 14px", color: "var(--fg-muted)" }}>{ks.timeout ?? 0}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Recent jobs */}
        {jobsData.recent?.length > 0 && (
          <div style={{ marginBottom: 24 }}>
            <div className="section-label" style={{ marginBottom: 12 }}>Последние задачи</div>
            <div style={{ background: "var(--bg-card)", border: "1px solid var(--border)", borderRadius: 6, overflow: "hidden" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
                <thead>
                  <tr style={{ borderBottom: "1px solid var(--border)" }}>
                    {["Задача", "Статус", "Запущена", "Длительность", "Токены"].map((h) => (
                      <th key={h} style={{ textAlign: "left", padding: "7px 12px", fontWeight: 600, color: "var(--fg-muted)", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.07em" }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {jobsData.recent.map((j) => (
                    <tr key={j.id} style={{ borderBottom: "1px solid var(--border)" }}>
                      <td style={{ padding: "7px 12px" }}>
                        <code style={{ fontFamily: "JetBrains Mono, monospace" }}>{j.kind}</code>
                        <span style={{ color: "var(--fg-muted)", marginLeft: 6 }}>{j.id}</span>
                      </td>
                      <td style={{ padding: "7px 12px" }}><StatusDot status={j.status} />{j.status}</td>
                      <td style={{ padding: "7px 12px", color: "var(--fg-muted)" }}>{new Date(j.started_at).toLocaleString("ru-RU")}</td>
                      <td style={{ padding: "7px 12px" }}>{j.duration_s != null ? `${Math.round(j.duration_s)}с` : "—"}</td>
                      <td style={{ padding: "7px 12px" }}>{j.cost_tokens != null ? j.cost_tokens.toLocaleString("ru-RU") : "—"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* Council reviews */}
        {council_reviews.length > 0 && (
          <div>
            <div className="section-label" style={{ marginBottom: 12 }}>Консилиум · Результаты</div>
            {council_reviews.map((r) => (
              <CouncilCard key={r.topic_id} review={r} />
            ))}
          </div>
        )}

        {council_reviews.length === 0 && jobsData.total === 0 && !bootstrap && (
          <div style={{ textAlign: "center", paddingTop: 60, color: "var(--fg-muted)" }}>
            <Icons.Info size={28} style={{ marginBottom: 12 }} />
            <div>Нет данных. Запустите bootstrap и создайте несколько постов.</div>
          </div>
        )}
      </div>
    </div>
  );
};

window.CR_REPORT = { ReportScreen };
