// src/components/keywords/keyword-modal-kpis.tsx — KPI strip of the keyword
// detail modal: Volume / KD donut / CPC / Position / Clics / Impressions.
"use client";

import { RingGauge } from "@/components/ui/ring-gauge";
import type { Keyword, KeywordSource } from "@/lib/keywords/types";
import { cn } from "@/lib/utils";
import { activeMetrics, kdLevel, SOURCE_LABELS } from "./keyword-modal-utils";

function SrcTag({ children }: { children: React.ReactNode }) {
  return (
    <span className="rounded-[5px] border border-border/60 bg-muted/50 px-1.5 py-px font-semibold text-[9px] text-muted-foreground uppercase tracking-wider">
      {children}
    </span>
  );
}

function Kpi({
  label,
  children,
  sub,
}: {
  label: string;
  children: React.ReactNode;
  sub?: React.ReactNode;
}) {
  return (
    <div className="flex min-h-[88px] flex-col gap-1.5 bg-card p-3.5">
      <div className="text-[11px] text-muted-foreground">{label}</div>
      {children}
      {sub ? (
        <div className="mt-auto flex items-center gap-1.5 font-medium text-[10.5px] text-muted-foreground/70">
          {sub}
        </div>
      ) : null}
    </div>
  );
}

function Val({
  value,
  unit,
  muted,
}: {
  value: React.ReactNode;
  unit?: string;
  muted?: boolean;
}) {
  return (
    <div
      className={cn(
        "flex items-baseline gap-1 font-semibold text-2xl tabular-nums leading-none tracking-tight",
        muted && "text-muted-foreground/60",
      )}
    >
      {value}
      {unit ? (
        <small className="font-medium text-[13px] text-muted-foreground">
          {unit}
        </small>
      ) : null}
    </div>
  );
}

export function KeywordModalKpis({
  keyword,
  source,
}: {
  keyword: Keyword;
  /** Active toolbar « Source » view — KPIs show this source (else primary). */
  source?: KeywordSource | "";
}) {
  const primary = activeMetrics(keyword, source);
  const srcLabel = primary ? SOURCE_LABELS[primary.source] : null;
  const kd = primary?.metrics.kd ?? null;
  const level = kdLevel(kd);
  const gsc = keyword.gsc;

  // shrink-0: this strip is a flex item in the modal's flex-col scroll body. Its
  // `overflow-hidden` makes the flex `min-height:auto` resolve to 0, so the column
  // would otherwise squeeze the strip to a single line and clip every value.
  return (
    <div className="grid shrink-0 grid-cols-2 gap-px overflow-hidden rounded-[14px] border border-border/70 bg-border/70 sm:grid-cols-3 lg:grid-cols-6">
      <Kpi label="Volume" sub={srcLabel ? <SrcTag>{srcLabel}</SrcTag> : null}>
        {primary ? (
          <Val
            value={primary.metrics.volume.toLocaleString("fr-FR")}
            unit="/mo"
          />
        ) : (
          <Val value="N/A" muted />
        )}
      </Kpi>

      <div className="flex min-h-[88px] items-center gap-3 bg-card p-3.5">
        <RingGauge
          fraction={(kd ?? 0) / 100}
          color={level.color}
          size={40}
          stroke={3.5}
          title={kd === null ? "KD inconnu" : `KD ${kd}`}
        />
        <div className="flex flex-col gap-1">
          <div className="text-[11px] text-muted-foreground">KD</div>
          <div
            className={cn(
              "font-semibold text-[22px] tabular-nums leading-none tracking-tight",
              kd === null && "text-muted-foreground/60",
            )}
          >
            {kd ?? "N/A"}
          </div>
          {/* No chip for unknown KD (null or coerced-0) — a green « Facile »
              chip on missing data would lie; the muted donut + number suffice. */}
          {!level.unknown ? (
            <span
              className={cn(
                "w-fit rounded-[5px] px-1.5 py-px font-semibold text-[10px]",
                level.chipClass,
              )}
            >
              {level.label}
            </span>
          ) : null}
        </div>
      </div>

      <Kpi label="CPC" sub={srcLabel ? <SrcTag>{srcLabel}</SrcTag> : null}>
        {primary ? (
          <Val value={`$${primary.metrics.cpc.toFixed(2)}`} />
        ) : (
          <Val value="N/A" muted />
        )}
      </Kpi>

      {/* gsc.position is the GLOBAL position; no country flag here — pairing the
          first gscByCountry key with a global number was misleading (ELEVA-86). */}
      <Kpi label="Position" sub={gsc ? <SrcTag>GSC</SrcTag> : null}>
        {gsc ? (
          <Val value={gsc.position.toFixed(1)} />
        ) : (
          <Val value="—" muted />
        )}
      </Kpi>

      <Kpi label="Clics" sub={gsc ? "28 derniers jours" : null}>
        {gsc ? (
          <Val
            value={gsc.clicks.toLocaleString("fr-FR")}
            muted={gsc.clicks === 0}
          />
        ) : (
          <Val value="—" muted />
        )}
      </Kpi>

      <Kpi label="Impressions" sub={gsc ? "28 derniers jours" : null}>
        {gsc ? (
          <Val
            value={gsc.impressions.toLocaleString("fr-FR")}
            muted={gsc.impressions === 0}
          />
        ) : (
          <Val value="—" muted />
        )}
      </Kpi>
    </div>
  );
}
