"use client";

import { useTranslations } from "next-intl";

import { formatMetricValue, getCwvStatus } from "@/lib/scoring";

type MetricKey = "fcp" | "si" | "lcp" | "tbt" | "cls";
type TimingKey = "ttfb" | "domInteractive" | "domContentLoaded" | "fullyLoaded";

const METRICS: { key: MetricKey; weight: number; sublabel: string }[] = [
  { key: "fcp", weight: 10, sublabel: "FCP" },
  { key: "si", weight: 10, sublabel: "SI" },
  { key: "lcp", weight: 25, sublabel: "LCP" },
  { key: "tbt", weight: 30, sublabel: "TBT" },
  { key: "cls", weight: 25, sublabel: "CLS" },
];

const BROWSER_TIMINGS: TimingKey[] = ["ttfb", "domInteractive", "domContentLoaded", "fullyLoaded"];

// Lighthouse official colors
function lhBarColor(score: number, metric: string) {
  const status = getCwvStatus(metric, score);
  if (status === "good") return "bg-[#0cce6b]";
  if (status === "needs-improvement") return "bg-[#ffa400]";
  return "bg-[#ff4e42]";
}

function lhTextColor(metric: string, value: number) {
  const status = getCwvStatus(metric, value);
  if (status === "good") return "text-[#0cce6b]";
  if (status === "needs-improvement") return "text-[#ffa400]";
  return "text-[#ff4e42]";
}

interface Props {
  metrics: Record<string, number | null>;
}

export function PerformanceMetrics({ metrics }: Props) {
  const t = useTranslations("PerformanceMetrics");
  return (
    <div className="space-y-12">
      {/* Lighthouse Performance Metrics */}
      <div>
        <h3 className="mb-6 font-[family-name:var(--font-manrope)] text-lg font-bold">
          {t("title")}
        </h3>
        <div className="space-y-4">
          {METRICS.map(({ key, weight, sublabel }) => {
            const value = metrics[key];
            if (value == null) return null;

            const maxes: Record<string, number> = {
              fcp: 6000,
              si: 8000,
              lcp: 8000,
              tbt: 1200,
              cls: 0.5,
            };
            const max = maxes[key] ?? 5000;
            const pct = Math.min(100, (value / max) * 100);
            const label = t(`metrics.${key}`);

            return (
              <div
                key={key}
                className="rounded-xl border border-[#45464d]/10 bg-surface-container p-6"
              >
                <div className="mb-3 flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <span className="text-sm font-bold text-foreground" title={sublabel}>
                      {label}
                    </span>
                    <span className="rounded bg-surface-container-high px-2 py-0.5 text-[10px] font-bold text-muted-foreground">
                      {weight}%
                    </span>
                  </div>
                  <span
                    className={`font-[family-name:var(--font-manrope)] text-lg font-black ${lhTextColor(key, value)}`}
                  >
                    {formatMetricValue(key, value)}
                  </span>
                </div>
                <div className="h-2 w-full overflow-hidden rounded-full bg-surface-container-highest">
                  <div
                    className={`h-full rounded-full transition-all duration-700 ${lhBarColor(value, key)}`}
                    style={{ width: `${Math.max(3, pct)}%` }}
                  />
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Browser Timings */}
      <div>
        <h3 className="mb-6 font-[family-name:var(--font-manrope)] text-lg font-bold">
          {t("browserTimings")}
        </h3>
        <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
          {BROWSER_TIMINGS.map((key) => {
            const value = metrics[key];
            const label = t(`timings.${key}`);
            return (
              <div
                key={key}
                className="rounded-xl border-t border-primary/10 bg-surface-container-low p-5"
              >
                <p className="mb-2 text-[10px] font-bold tracking-widest text-muted-foreground uppercase">
                  {label}
                </p>
                <p className="font-[family-name:var(--font-manrope)] text-xl font-bold text-foreground">
                  {value != null ? formatMetricValue("lcp", value) : "--"}
                </p>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
