// src/components/keywords/research/research-columns.tsx
"use client";

import type { ColumnDef, RowData } from "@tanstack/react-table";
import { Flag } from "@/components/ui/flag";
import { gscBand, opportunityScore } from "@/lib/keywords/gsc-positioning";
import { coverageOf, type TargetsState } from "@/lib/keywords/targets";
import type { Keyword } from "@/lib/keywords/types";
import { columns as reservoirColumns } from "../columns";
import { TargetStatusBadge } from "./target-status-badge";

declare module "@tanstack/react-table" {
  interface TableMeta<TData extends RowData> {
    targets?: TargetsState;
    countries?: string[];
  }
}

const gscPositionColumn: ColumnDef<Keyword> = {
  id: "gscPosition",
  // Ancre du tutoriel posée sur l'intitulé de la colonne : c'est le seul
  // élément de la bande GSC qui existe même quand aucune ligne n'a de position.
  header: () => <span data-tour="research-gsc-columns">Pos. GSC</span>,
  accessorFn: (k) => k.gsc?.position ?? undefined,
  enableGlobalFilter: false,
  sortUndefined: "last",
  filterFn: (row, _id, value: string[]) =>
    !value?.length || value.includes(gscBand(row.original.gsc)),
  cell: ({ row }) => {
    const gsc = row.original.gsc;
    if (!gsc) return <span className="text-muted-foreground/50">—</span>;
    return (
      <span className="inline-flex items-center gap-1 tabular-nums">
        {gsc.position.toFixed(1)}
        {gscBand(gsc) === "quickwin" ? (
          <span role="img" title="Quick win (11–20)" aria-label="Quick win">
            ⚡
          </span>
        ) : null}
      </span>
    );
  },
};

// Hidden, sort-only column powering the "Trier par opportunité" toggle.
const gscOpportunityColumn: ColumnDef<Keyword> = {
  id: "gscOpportunity",
  header: () => null,
  accessorFn: (k) => opportunityScore(k.gsc),
  enableGlobalFilter: false,
  cell: () => null,
};

// The shared reservoir columns already render the flag, the inline GSC badge,
// and the copy/delete actions in the term cell — recherche just adds the GSC
// positioning columns and the per-country targeting column.
export const researchColumns: ColumnDef<Keyword>[] = [
  ...reservoirColumns,
  gscPositionColumn,
  gscOpportunityColumn,
  {
    id: "targets",
    header: "Pays ciblés",
    enableSorting: false,
    enableGlobalFilter: false,
    cell: ({ row, table }) => {
      const cov = coverageOf(
        table.options.meta?.targets ?? {},
        row.original.id,
        table.options.meta?.countries ?? [],
      );
      if (cov.length === 0)
        return <span className="text-muted-foreground">—</span>;
      return (
        <div className="flex flex-wrap gap-1">
          {cov.map((c) => (
            <TargetStatusBadge
              key={c.country}
              status={c.status}
              prefix={<Flag code={c.country} />}
            />
          ))}
        </div>
      );
    },
  },
];
