/**
 * @file ErrorPropagationMap.tsx
 * @description A React component that visualizes error propagation across agent hierarchies in a workflow system. It displays the distribution of errors by hierarchy depth, identifies error-prone agent types, and highlights API and session errors. The component uses horizontal bars to represent error counts at different depths and types, providing an intuitive overview of where errors are occurring within the agent structure.
 * @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
 */
/* =============================================================================
 * MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
 * =============================================================================
 * **Purpose:** Workflow analytics visualization built on D3; consumes aggregated session/run metrics from the workflows API.
 *
 * ## Design constraints
 * - Local-first: no telemetry leaves the machine unless the user configures webhooks.
 * - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
 *   philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
 * - Destructive flows stay behind explicit confirmation modals and server-side gates.
 * - Internationalization: user-visible strings belong in i18n JSON, not literals here.
 *
 * ## Remote data & SSH
 * Remote Data Sources let operators aggregate multiple machines. SSH entries describe
 * how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
 * scoped GET via `?sources=`. Health checks and import history surface in Settings.
 *
 * ## Internal dependencies
 * - `../../lib/types`
 *
 * ## Public surface
 * - `ErrorPropagationMapProps` — exported API; see TSDoc on the symbol for behavior.
 * - `ErrorPropagationMap` — exported API; see TSDoc on the symbol for behavior.
 *
 * ## Testing pointers
 * - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
 * - Server contract changes require `npm run test:server` and OpenAPI sync.
 * - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`.
 *
 * ## Related docs
 * - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
 * - `docs/API.md` — REST reference.
 * - `.claude/skills/file-headers/` — mandatory `@author` header policy.
 * ============================================================================= */
/* -----------------------------------------------------------------------------
 * EXPORT CATALOG — quick index of symbols defined below (documentation only).
 * -----------------------------------------------------------------------------
 * **ErrorPropagationMapProps**
 *   Part of this module's public contract. Downstream imports should treat
 *   the signature and return type as stable unless release notes say otherwise.
 *   When behavior changes, update the `@file` overview and relevant tests.
 *
 * **ErrorPropagationMap**
 *   Part of this module's public contract. Downstream imports should treat
 *   the signature and return type as stable unless release notes say otherwise.
 *   When behavior changes, update the `@file` overview and relevant tests.
 *
 * ----------------------------------------------------------------------------- */

import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { ErrorPropagationData } from "../../lib/types";

const DEPTH_COLORS = ["#ef4444", "#f97316", "#eab308", "#a855f7"];

// ── Component ─────────────────────────────────────────────────────────────────

export interface ErrorPropagationMapProps {
  data: ErrorPropagationData;
}

export function ErrorPropagationMap({ data }: ErrorPropagationMapProps) {
  const { t } = useTranslation("workflows");
  const [hoveredDepth, setHoveredDepth] = useState<number | null>(null);

  function depthLabel(depth: number): string {
    const keys = [
      t("errorPropagation.depthLabels.sessionMain"),
      t("errorPropagation.depthLabels.directSubagent"),
      t("errorPropagation.depthLabels.nested"),
      t("errorPropagation.depthLabels.deep"),
    ];
    return keys[depth] ?? `${t("common:depth")} ${depth}`;
  }

  const hasErrors =
    data.byDepth.some((d) => d.count > 0) ||
    data.byType.some((t) => t.count > 0) ||
    (data.eventErrors && data.eventErrors.length > 0) ||
    data.sessionsWithErrors > 0;

  if (!hasErrors) {
    return (
      <div className="flex flex-col items-center justify-center py-16 gap-3">
        <div className="w-12 h-12 rounded-full bg-status-success/10 border border-status-success/20 flex items-center justify-center">
          <svg
            width="24"
            height="24"
            viewBox="0 0 24 24"
            fill="none"
            stroke="#10b981"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
            <polyline points="22 4 12 14.01 9 11.01" />
          </svg>
        </div>
        <span className="text-sm text-status-success font-medium">
          {t("errorPropagation.noErrors")}
        </span>
        <span className="text-xs text-fg-muted">{t("errorPropagation.allSuccess")}</span>
      </div>
    );
  }

  const errorRatePct = data.errorRate;
  const totalErrors = data.byDepth.reduce((s, d) => s + d.count, 0);
  const maxDepthCount = Math.max(...data.byDepth.map((d) => d.count), 1);
  const topTypes = [...data.byType].sort((a, b) => b.count - a.count).slice(0, 6);
  const hasDepthData = data.byDepth.some((d) => d.count > 0);

  return (
    <div className="flex flex-col gap-4">
      {/* Error rate summary bar */}
      <div className="flex items-center gap-3 p-3 rounded-xl bg-status-danger/5 border border-status-danger/15">
        <div className="flex-shrink-0 min-w-[2.75rem] h-10 px-2 rounded-lg bg-status-danger/10 border border-status-danger/20 flex items-center justify-center">
          <span className="text-[13px] font-bold text-status-danger tabular-nums whitespace-nowrap">
            {errorRatePct}%
          </span>
        </div>
        <div className="min-w-0 flex-1">
          <p className="text-xs font-medium text-status-danger">
            {t("errorPropagation.sessionsErrorSummary", {
              errorSessions: data.sessionsWithErrors,
              totalSessions: data.totalSessions,
            })}
          </p>
          <p className="text-[11px] text-fg-muted mt-0.5">
            {totalErrors > 0
              ? `${totalErrors}${t("errorPropagation.agentErrors")}`
              : t("errorPropagation.sessionErrorsOnly")}
          </p>
        </div>
      </div>

      {/* Errors by depth - horizontal bars */}
      {hasDepthData && (
        <div>
          <p className="text-[10px] font-medium text-fg-muted uppercase tracking-wider mb-2.5">
            {t("errorPropagation.errorsByDepth")}
          </p>
          <div className="flex flex-col gap-1.5">
            {data.byDepth
              .filter((d) => d.count > 0)
              .map((d) => {
                const pct = (d.count / maxDepthCount) * 100;
                const color = DEPTH_COLORS[d.depth] ?? DEPTH_COLORS[DEPTH_COLORS.length - 1];
                const isHovered = hoveredDepth === d.depth;
                return (
                  <div
                    key={d.depth}
                    className="flex items-center gap-2.5 group"
                    onMouseEnter={() => setHoveredDepth(d.depth)}
                    onMouseLeave={() => setHoveredDepth(null)}
                  >
                    <span className="text-[11px] text-fg-muted w-24 flex-shrink-0 text-right truncate">
                      {depthLabel(d.depth)}
                    </span>
                    <div className="flex-1 h-5 bg-surface-3 rounded overflow-hidden relative">
                      <div
                        className="h-full rounded transition-all duration-300"
                        style={{
                          width: `${Math.max(pct, 4)}%`,
                          backgroundColor: color,
                          opacity: isHovered ? 1 : 0.75,
                        }}
                      />
                    </div>
                    <span
                      className="text-xs font-semibold tabular-nums w-7 text-right transition-colors"
                      style={{ color: isHovered ? color : "#9ca3af" }}
                    >
                      {d.count}
                    </span>
                  </div>
                );
              })}
          </div>
        </div>
      )}

      {/* Error-prone agent types */}
      {topTypes.length > 0 && (
        <div>
          <p className="text-[10px] font-medium text-fg-muted uppercase tracking-wider mb-2.5">
            {t("errorPropagation.errorProneTypes")}
          </p>
          <div className="flex flex-col gap-1">
            {topTypes.map((t, i) => {
              const maxCount = topTypes[0]?.count ?? 1;
              const pct = (t.count / maxCount) * 100;
              return (
                <div
                  key={t.subagent_type}
                  className="flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg hover:bg-surface-3/50 transition-colors"
                >
                  <span
                    className="w-1.5 h-1.5 rounded-full flex-shrink-0"
                    style={{ backgroundColor: DEPTH_COLORS[Math.min(i, DEPTH_COLORS.length - 1)] }}
                  />
                  <span className="text-xs text-fg-secondary truncate flex-1 min-w-0">
                    {t.subagent_type}
                  </span>
                  <div className="w-16 h-1.5 bg-surface-4 rounded-full overflow-hidden flex-shrink-0">
                    <div
                      className="h-full rounded-full bg-status-danger/60"
                      style={{ width: `${Math.max(pct, 8)}%` }}
                    />
                  </div>
                  <span className="text-[11px] font-semibold text-status-danger tabular-nums w-5 text-right flex-shrink-0">
                    {t.count}
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* API & session errors */}
      {data.eventErrors && data.eventErrors.length > 0 && (
        <div>
          <p className="text-[10px] font-medium text-fg-muted uppercase tracking-wider mb-2.5">
            {t("errorPropagation.apiSessionErrors")}
          </p>
          <div className="flex flex-col gap-1">
            {data.eventErrors.map((e) => (
              <div
                key={e.summary}
                className="flex items-center gap-2.5 px-2.5 py-2 rounded-lg bg-status-warning/5 border border-status-warning/10 hover:border-status-warning/20 transition-colors"
              >
                <svg
                  width="14"
                  height="14"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="#f59e0b"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="flex-shrink-0"
                >
                  <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
                  <line x1="12" y1="9" x2="12" y2="13" />
                  <line x1="12" y1="17" x2="12.01" y2="17" />
                </svg>
                <span
                  className="text-xs text-fg-secondary truncate flex-1 min-w-0"
                  title={e.summary}
                >
                  {e.summary}
                </span>
                <span className="flex-shrink-0 text-[11px] font-semibold text-status-warning tabular-nums">
                  {e.count}x
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
