// src/components/keywords/source-dots.tsx — pastilles rondes par source de
// données (logos de marque + tooltip). Cliquer une pastille bascule les colonnes
// du réservoir sur cette source (sélecteur de source actif par ligne).
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import type { Keyword, KeywordSource } from "@/lib/keywords/types";

type DotConfig =
  | { logo: string; name: string; cover?: boolean }
  | { color: string; name: string };

/** Per-provider dot: brand logo cropped in the circle, or a solid brand colour
 *  when no icon exists (SE Ranking). */
const SOURCE_DOT: Partial<Record<KeywordSource, DotConfig>> = {
  seranking: {
    logo: "/brands/seranking.webp",
    name: "SE Ranking",
    cover: true,
  },
  mangools: { logo: "/brands/mangools.svg", name: "Mangools" },
  semrush: { logo: "/brands/semrush.webp", name: "Semrush" },
  ahrefs: { logo: "/brands/ahrefs.svg", name: "Ahrefs", cover: true },
};

/** Stable display order, independent of the keyword's sources[] ordering. */
const ORDER: KeywordSource[] = ["seranking", "mangools", "semrush", "ahrefs"];

/** ISO date → « DD-MM-YY » for the per-source « MAJ » stamp; null if unparseable. */
function majDate(iso?: string): string | null {
  if (!iso) return null;
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return null;
  const dd = String(d.getDate()).padStart(2, "0");
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  return `${dd}-${mm}-${String(d.getFullYear()).slice(-2)}`;
}

const DOT_BASE = "size-[18px] shrink-0 overflow-hidden rounded-full";
const ringCls = (active?: boolean) =>
  active
    ? "ring-2 ring-blue-500 ring-offset-1 ring-offset-background"
    : "ring-1 ring-black/10 dark:ring-white/15";

function Dot({ cfg, active }: { cfg: DotConfig; active?: boolean }) {
  if ("logo" in cfg) {
    return (
      <span
        className={`${DOT_BASE} ${ringCls(active)} grid place-items-center bg-white`}
      >
        {/* biome-ignore lint/performance/noImgElement: 12px static brand mark, next/image is overkill */}
        <img
          src={cfg.logo}
          alt=""
          className={
            cfg.cover ? "size-full object-cover" : "size-[12px] object-contain"
          }
        />
      </span>
    );
  }
  return (
    <span
      className={`${DOT_BASE} ${ringCls(active)}`}
      style={{ backgroundColor: cfg.color }}
    />
  );
}

/** Round brand dots for every data source present on the keyword, plus a GSC
 *  dot when Search Console tracking exists. When `onSelect` is provided the
 *  provider dots are clickable: picking one makes it the row's active source. */
export function SourceDots({
  keyword,
  activeSource,
  onSelect,
  dataTour,
}: {
  keyword: Keyword;
  activeSource?: KeywordSource;
  onSelect?: (id: string, source: KeywordSource) => void;
  /** Ancre du tutoriel, posée sur UNE SEULE ligne par table (la première) :
   *  l'attribut n'apparaît que si des pastilles sont réellement rendues, donc
   *  jamais sur un groupe vide qui donnerait une cible de taille nulle. */
  dataTour?: string;
}) {
  const present = new Set(keyword.sources);
  const providers = ORDER.filter((s) => present.has(s) && SOURCE_DOT[s]);
  const gsc = keyword.gsc;
  if (providers.length === 0 && !gsc) return null;
  return (
    <TooltipProvider>
      <span data-tour={dataTour} className="flex shrink-0 items-center gap-1">
        {providers.map((s) => {
          const cfg = SOURCE_DOT[s];
          if (!cfg) return null;
          const m = keyword.metrics[s];
          const date = majDate(m?.updatedAt);
          const active = activeSource === s;
          const dot = <Dot cfg={cfg} active={active} />;
          return (
            <Tooltip key={s}>
              <TooltipTrigger asChild>
                {onSelect ? (
                  <button
                    type="button"
                    aria-label={`Voir les données ${cfg.name}`}
                    aria-pressed={active}
                    className="rounded-full"
                    onClick={(e) => {
                      e.stopPropagation();
                      onSelect(keyword.id, s);
                    }}
                  >
                    {dot}
                  </button>
                ) : (
                  <span>{dot}</span>
                )}
              </TooltipTrigger>
              <TooltipContent className="text-center">
                <span className="block font-semibold">{cfg.name}</span>
                {m ? (
                  <span className="block text-[11px] opacity-80">
                    Vol {m.volume.toLocaleString("fr-FR")} · KD{" "}
                    {Math.round(m.kd)} · CPC {m.cpc}
                  </span>
                ) : null}
                {date ? (
                  <span className="block text-[11px] opacity-70">
                    MAJ {date}
                  </span>
                ) : null}
              </TooltipContent>
            </Tooltip>
          );
        })}
        {gsc ? (
          <Tooltip>
            <TooltipTrigger asChild>
              <span
                className={`${DOT_BASE} ${ringCls(false)} grid place-items-center bg-[#4285f4] font-bold text-[6px] text-white leading-none tracking-[-0.04em]`}
              >
                GSC
              </span>
            </TooltipTrigger>
            <TooltipContent className="text-center">
              <span className="block font-semibold">Search Console</span>
              <span className="block text-[11px] opacity-80">
                Pos {gsc.position.toFixed(1)} · {gsc.clicks} clics ·{" "}
                {gsc.impressions} impr.
              </span>
              {majDate(gsc.updatedAt) ? (
                <span className="block text-[11px] opacity-70">
                  MAJ {majDate(gsc.updatedAt)}
                </span>
              ) : null}
            </TooltipContent>
          </Tooltip>
        ) : null}
      </span>
    </TooltipProvider>
  );
}
