"use client";

import { useRouter } from "next/navigation";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useT } from "@/shared/i18n/client";
import { ROUTES } from "@/shared/constants";
import { TierDot } from "./components/tier";
import type { HealthTier } from "@/domain/entities/health";

/**
 * SCRUM-303 global chrome for the health module: the WATCHLIST — the most
 * fragile accounts kept one click away on every screen. Clients with score
 * below the at-risk cut-off, worst first, top 4; hidden when none qualify.
 */
export default function HealthLayout({ children }: { children: React.ReactNode }) {
  return (
    <>
      <Watchlist />
      {children}
    </>
  );
}

function Watchlist() {
  const t = useT();
  const router = useRouter();
  const c = useRepositories();

  const { data } = useApiQuery(
    () => c.healthRepository.getClients({ tier: "at_risk", order_by: "health", order: "ASC", per_page: 4, page: 1 }),
    { deps: [] }
  );

  const items = data?.items ?? [];
  if (items.length === 0) return null;

  return (
    <div className="px-6 pt-4 -mb-2">
      <div className="flex items-center gap-2 flex-wrap rounded-xl border border-border bg-card px-3 py-2 shadow-sm">
        <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground mr-1">
          {t.health.watchlist}
        </span>
        {items.map((row) => (
          <button
            key={row.company_user_id}
            onClick={() => router.push(`${ROUTES.healthClients}/${row.company_user_id}`)}
            className="inline-flex items-center gap-2 rounded-full border border-border bg-background px-2.5 py-1 text-xs font-medium hover:bg-muted/60 transition-colors"
          >
            <TierDot tier={row.tier as HealthTier} />
            <span className="max-w-[140px] truncate">{row.company}</span>
            <span className="font-mono font-bold" style={{ color: "var(--chart-5)" }}>{row.health}</span>
          </button>
        ))}
      </div>
    </div>
  );
}
