import { formatInteger, formatPercent } from "@/lib/utils";

type Props = {
  coverage: number;
  eventsWithDates: number;
  eventsInScope: number;
  clmCallDatesAvailable: boolean;
  className?: string;
};

// CLM source exports are known to be patchy on dates. Showing our own coverage
// bar means figures get read with the right confidence rather than being taken
// as gospel and later picked apart.
export function DataConfidence({
  coverage,
  eventsWithDates,
  eventsInScope,
  clmCallDatesAvailable,
  className,
}: Props) {
  if (eventsInScope === 0) return null;

  // Full coverage with call dates present means there's nothing to caveat —
  // the banner only earns its place when confidence is actually reduced.
  if (coverage >= 0.995 && clmCallDatesAvailable) return null;

  const tone =
    coverage >= 0.95
      ? { bar: "bg-emerald-500", text: "text-emerald-700", chip: "border-emerald-200 bg-emerald-50" }
      : coverage >= 0.8
        ? { bar: "bg-[#F7993A]", text: "text-[#a35e1c]", chip: "border-[#f3d9b8] bg-[#fffaf3]" }
        : { bar: "bg-rose-500", text: "text-rose-700", chip: "border-rose-200 bg-rose-50" };

  const missing = eventsInScope - eventsWithDates;

  return (
    <div className={`rounded-2xl border px-4 py-3 print:break-inside-avoid ${tone.chip} ${className ?? ""}`}>
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div className="min-w-0">
          <p className="caption text-[10px] uppercase tracking-[0.16em] text-slate-500">Data confidence</p>
          <p className="mt-0.5 text-sm text-slate-700">
            <span className={`font-bold ${tone.text}`}>{formatPercent(coverage)}</span> of clickstream records
            have usable dates
            {missing > 0 ? (
              <span className="text-slate-500">
                {" "}
                &middot; {formatInteger(missing)} of {formatInteger(eventsInScope)} undated and excluded from
                time-based views
              </span>
            ) : null}
          </p>
          {!clmCallDatesAvailable ? (
            <p className="mt-1 text-xs text-slate-500">
              CLM call dates are unavailable in this export — deck timelines are derived from clickstream only.
            </p>
          ) : null}
        </div>
        <div className="h-2 w-full max-w-[160px] shrink-0 overflow-hidden rounded-full bg-white/70">
          <div
            className={`h-full rounded-full ${tone.bar}`}
            style={{ width: `${Math.max(2, Math.round(coverage * 100))}%` }}
          />
        </div>
      </div>
    </div>
  );
}
