// components/diagnostics.jsx — Orchestrator for the "Tests" tab.
// Sub-components loaded from diagnostics/*.jsx (helpers, DiagInfrastructure, DiagConfig, DiagExtensions, DiagAgent).
// Backend: /tests/status (runs all 8 checks in parallel)

function DiagnosticsPanel() {
  const [results, setResults] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const runTests = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const r = await fetch(`${_api()}/tests/status`, { headers: _headers() });
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      setResults(await r.json());
    } catch (e) { setError(e.message); }
    finally { setLoading(false); }
  }, []);

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

  const find = (svc) => results?.tests?.find(t => t.service === svc);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold text-gray-900">Testy diagnostyczne</h2>
          {results && (
            <p className="text-sm text-gray-500 mt-0.5">
              {results.passed}/{results.total} testów OK
              {results.failed > 0 && <span className="text-red-600 ml-1">({results.failed} problemów)</span>}
            </p>
          )}
        </div>
        <button onClick={runTests} disabled={loading}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2">
          {loading ? <><span className="animate-spin inline-block">⟳</span> Testowanie...</> : "▶ Uruchom testy"}
        </button>
      </div>

      {/* Overall status */}
      {results && (
        <div className={`px-4 py-3 rounded-lg text-sm font-medium ${
          results.overall_status === "healthy"
            ? "bg-emerald-50 text-emerald-800 border border-emerald-200"
            : "bg-amber-50 text-amber-800 border border-amber-200"
        }`}>
          {results.overall_status === "healthy"
            ? "✓ Wszystkie testy przeszły pomyślnie"
            : `⚠ ${results.failed} test${results.failed > 1 ? "ów" : ""} wymaga uwagi`}
        </div>
      )}

      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-lg text-sm text-red-800">
          Błąd: {error}
        </div>
      )}

      {/* Test sections */}
      {results && (
        <>
          {/* Row 1: Infrastructure */}
          <div>
            <h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Infrastruktura</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <DiagVSCode t={find("vscode")} />
              <DiagProxy t={find("llm_proxy")} />
            </div>
          </div>

          {/* Row 2: Configuration */}
          <div>
            <h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Konfiguracja</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <DiagRooConfig t={find("roo_cline")} />
              <DiagProviders t={find("providers")} />
            </div>
          </div>

          {/* Row 3: Extensions */}
          <div>
            <h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Rozszerzenia</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <DiagExtensions t={find("extensions")} />
              <DiagCopilot t={find("copilot_conflict")} />
            </div>
          </div>

          {/* Row 4: Agent */}
          <div>
            <h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Agent AI</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <DiagAgentSetup t={find("agent_setup")} />
              <DiagAgentTest t={find("agent_test")} />
            </div>
          </div>
        </>
      )}

      {/* Connection info footer */}
      {results && (
        <div className="p-4 bg-gray-50 rounded-lg border border-gray-200">
          <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Dane dostępowe</h3>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs font-mono text-gray-700">
            <div><span className="text-gray-400">VS Code:</span> localhost:8080</div>
            <div><span className="text-gray-400">Proxy API:</span> {_api().replace(/^https?:\/\//, '')}</div>
            <div><span className="text-gray-400">Dashboard:</span> /dashboard-ui</div>
          </div>
        </div>
      )}
    </div>
  );
}
