"use client";

import { cn } from "@/shared/lib/utils";
import { useT } from "@/shared/i18n/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/presentation/components/ui/card";
import type { HealthBenchmark } from "@/domain/entities/health";

export function BenchmarkTab({ benchmark }: { benchmark: HealthBenchmark }) {
  const t = useT();

  if (!benchmark.available) {
    return (
      <Card>
        <CardContent className="py-10 text-center text-sm text-muted-foreground">
          {t.health.profile.benchmarkUnavailable}
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base">{t.health.profile.benchmarkTitle}</CardTitle>
        {benchmark.peer_count != null && (
          <p className="text-xs text-muted-foreground">{t.health.profile.benchmarkAgainst(benchmark.peer_count)}</p>
        )}
      </CardHeader>
      <CardContent className="space-y-5">
        {benchmark.metrics.map((m) => {
          const max = Math.max(1, m.value, m.peer_avg);
          const above = m.diff_pct >= 0;
          return (
            <div key={m.key}>
              <div className="flex items-center justify-between mb-1.5">
                <span className="text-sm font-medium">{m.label}</span>
                <span className={cn("text-xs font-semibold", above ? "text-emerald-600" : "text-red-500")}>
                  {above ? "+" : "−"}
                  {Math.abs(m.diff_pct)}% {t.health.profile.vsPeers}
                </span>
              </div>
              <div className="relative h-3 rounded-full bg-muted overflow-hidden">
                <div
                  className="h-full rounded-full"
                  style={{ width: `${(m.value / max) * 100}%`, backgroundColor: above ? "var(--chart-2)" : "var(--chart-5)" }}
                />
                {/* Peer average marker */}
                <span
                  className="absolute top-[-2px] bottom-[-2px] w-0.5 bg-foreground/70"
                  style={{ left: `${(m.peer_avg / max) * 100}%` }}
                  title={`${t.health.profile.peerAvg}: ${m.peer_avg}`}
                />
              </div>
              <div className="flex items-center justify-between mt-1 text-xs text-muted-foreground">
                <span>{t.health.profile.thisClient}: <span className="font-mono font-medium text-foreground">{m.value}</span></span>
                <span>{t.health.profile.peerAvg}: <span className="font-mono">{m.peer_avg}</span></span>
              </div>
            </div>
          );
        })}

        <p className="text-sm text-muted-foreground pt-2 border-t border-border">
          {benchmark.below_peer_count === 0
            ? t.health.profile.benchmarkOutperforms
            : t.health.profile.benchmarkSummary(benchmark.below_peer_count)}
        </p>
      </CardContent>
    </Card>
  );
}
