// src/components/content/stats/stats-columns.tsx
"use client";

import type { ColumnDef } from "@tanstack/react-table";
import Link from "next/link";
import { Sparkline } from "@/components/keywords/sparkline";
import { Badge } from "@/components/ui/badge";
import type { PageStatRow } from "@/lib/content/stats";

/** Variation % vs période précédente — « — » quand prev manquant ou nul. */
function deltaPct(cur: number | null, prev: number | null): number | null {
  if (cur == null || prev == null || prev === 0) return null;
  return ((cur - prev) / prev) * 100;
}

function fmtDelta(d: number | null): string {
  if (d == null) return "—";
  return `${d > 0 ? "+" : ""}${d.toFixed(1)} %`;
}

function pathnameOf(page: string): string {
  try {
    return new URL(page).pathname;
  } catch {
    return page;
  }
}

export const statsColumns: ColumnDef<PageStatRow>[] = [
  {
    id: "page",
    accessorFn: (r) => pathnameOf(r.page),
    header: "Page",
    cell: ({ row }) => (
      <span
        className="inline-block max-w-[24rem] truncate align-middle font-medium"
        title={row.original.page}
      >
        {pathnameOf(row.original.page)}
      </span>
    ),
  },
  {
    accessorKey: "clicks",
    header: "Clics",
    enableGlobalFilter: false,
    meta: { align: "right" },
    cell: ({ row }) => {
      const d = deltaPct(row.original.clicks, row.original.prevClicks);
      return (
        <span className="tabular-nums">
          {row.original.clicks.toLocaleString("fr-FR")}{" "}
          <span className="text-muted-foreground text-xs">{fmtDelta(d)}</span>
        </span>
      );
    },
  },
  {
    accessorKey: "impressions",
    header: "Impressions",
    enableGlobalFilter: false,
    meta: { align: "right" },
    cell: ({ row }) => {
      const d = deltaPct(
        row.original.impressions,
        row.original.prevImpressions,
      );
      return (
        <span className="tabular-nums">
          {row.original.impressions.toLocaleString("fr-FR")}{" "}
          <span className="text-muted-foreground text-xs">{fmtDelta(d)}</span>
        </span>
      );
    },
  },
  {
    id: "ctr",
    accessorFn: (r) => r.ctr ?? undefined,
    header: "CTR",
    enableGlobalFilter: false,
    sortUndefined: "last",
    meta: { align: "right" },
    cell: ({ row }) => (
      <span className="tabular-nums">
        {row.original.ctr != null
          ? `${(row.original.ctr * 100).toFixed(1)} %`
          : "—"}
      </span>
    ),
  },
  {
    id: "position",
    accessorFn: (r) => r.position ?? undefined,
    header: "Position",
    enableGlobalFilter: false,
    sortUndefined: "last",
    meta: { align: "right" },
    cell: ({ row }) => {
      const { position, prevPosition } = row.original;
      // Position : une baisse du chiffre est une amélioration → couleur inversée.
      const d = deltaPct(position, prevPosition);
      const cls =
        d == null || d === 0
          ? "text-muted-foreground"
          : d < 0
            ? "text-emerald-600"
            : "text-red-600";
      return (
        <span className="tabular-nums">
          {position?.toFixed(1) ?? "—"}{" "}
          <span className={`text-xs ${cls}`}>{fmtDelta(d)}</span>
        </span>
      );
    },
  },
  {
    id: "trend",
    header: "Tendance",
    enableGlobalFilter: false,
    enableSorting: false,
    cell: ({ row }) => <Sparkline values={row.original.spark} />,
  },
  {
    id: "signal",
    header: "Signal",
    enableGlobalFilter: false,
    enableSorting: false,
    filterFn: (row, _id, v) => !v || row.original.dropping,
    cell: ({ row }) =>
      row.original.dropping ? (
        <Badge variant="destructive">📉 Décrochage</Badge>
      ) : null,
  },
  {
    id: "article",
    header: "Article",
    enableGlobalFilter: false,
    enableSorting: false,
    cell: ({ row }) =>
      row.original.contentItemId ? (
        <Link href="/content/planning" onClick={(e) => e.stopPropagation()}>
          <Badge
            variant="secondary"
            className="max-w-[12rem] truncate"
            title={row.original.contentTitle ?? undefined}
          >
            {row.original.contentTitle}
          </Badge>
        </Link>
      ) : null,
  },
];
