"use client";

import { cn } from "@/shared/lib/utils";
import { useT } from "@/shared/i18n/client";
import type { HealthTier } from "@/domain/entities/health";

// Tier → chart CSS var (healthy = blue, attention = amber, at_risk = red).
export const TIER_VAR: Record<HealthTier, string> = {
  healthy: "var(--chart-1)",
  attention: "var(--chart-3)",
  at_risk: "var(--chart-5)",
};

// StatsCard accent per tier.
export const TIER_ACCENT: Record<HealthTier, "blue" | "amber" | "red"> = {
  healthy: "blue",
  attention: "amber",
  at_risk: "red",
};

export function tierFromScore(score: number, healthyCut = 75, atRiskCut = 50): HealthTier {
  if (score >= healthyCut) return "healthy";
  if (score >= atRiskCut) return "attention";
  return "at_risk";
}

const TIER_CLASSES: Record<HealthTier, string> = {
  healthy: "bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-950/40 dark:text-blue-300 dark:border-blue-900",
  attention: "bg-amber-100 text-amber-700 border-amber-200 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-900",
  at_risk: "bg-red-100 text-red-700 border-red-200 dark:bg-red-950/40 dark:text-red-300 dark:border-red-900",
};

export function TierDot({ tier, className }: { tier: HealthTier; className?: string }) {
  return (
    <span
      className={cn("inline-block w-2 h-2 rounded-full flex-shrink-0", className)}
      style={{ backgroundColor: TIER_VAR[tier] }}
    />
  );
}

export function TierBadge({ tier, className }: { tier: HealthTier; className?: string }) {
  const t = useT();
  return (
    <span
      className={cn(
        "inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-xs font-semibold whitespace-nowrap",
        TIER_CLASSES[tier],
        className
      )}
    >
      <span className="w-1.5 h-1.5 rounded-full" style={{ backgroundColor: TIER_VAR[tier] }} />
      {t.health.tiers[tier]}
    </span>
  );
}

// A compact score + tier bar used in the client list Health column.
export function ScoreBar({ score, tier }: { score: number; tier: HealthTier }) {
  return (
    <div className="flex items-center gap-2 min-w-[92px]">
      <span className="font-mono font-bold text-sm w-7 text-right" style={{ color: TIER_VAR[tier] }}>
        {score}
      </span>
      <div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden">
        <div
          className="h-full rounded-full"
          style={{ width: `${Math.max(2, Math.min(100, score))}%`, backgroundColor: TIER_VAR[tier] }}
        />
      </div>
    </div>
  );
}
