// src/components/content/content-columns.tsx — table columns for the content table view.
"use client";

import type { ColumnDef } from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
import { Flag } from "@/components/ui/flag";
import { isOverdue } from "@/lib/content/board";
import type { ContentAnalysis, ContentItem } from "@/lib/content/types";
import { CONTENT_KIND_LABEL, CONTENT_STATUS_LABEL } from "@/lib/content/types";
import { ContentDot } from "./content-dot";

const dash = <span className="text-muted-foreground">—</span>;

function serpTooltip(s: ContentAnalysis["serp"]) {
  if (s.state === "none") return "Aucun export SERP";
  const parts = [`${s.count} concurrents`];
  if (s.features.length) parts.push(`features: ${s.features.join(", ")}`);
  if (s.medianBacklinks != null)
    parts.push(`médian backlinks ${s.medianBacklinks}`);
  if (s.medianAuthority != null) parts.push(`autorité ${s.medianAuthority}`);
  return parts.join(" · ");
}

function onpageTooltip(o: ContentAnalysis["onpage"]) {
  if (o.state === "none") return "Pas de SERP à crawler";
  if (o.state === "partial") return "SERP importé — pas encore crawlé";
  const parts = [
    `Crawlé le ${o.crawledAt ? new Date(o.crawledAt).toLocaleDateString("fr-FR") : "—"}`,
  ];
  if (o.avgImages != null) parts.push(`img moy ${o.avgImages}`);
  if (o.jsonLdPct != null) parts.push(`JSON-LD ${o.jsonLdPct}%`);
  return parts.join(" · ");
}

function briefDotState(
  s: ContentAnalysis["brief"]["state"],
): "ok" | "partial" | "none" {
  return s === "other-locale" ? "partial" : s;
}

function briefTooltip(b: ContentAnalysis["brief"]) {
  if (b.state === "none") return "Pas de brief";
  if (b.state === "other-locale")
    return `Brief dispo pour ${b.locale ?? "autre locale"} (≠ pays de l'article)`;
  const parts: string[] = [];
  if (b.intent) parts.push(`Intention: ${b.intent}`);
  if (b.subjects.length)
    parts.push(`sujets: ${b.subjects.slice(0, 4).join(", ")}`);
  parts.push(`${b.questions} questions`);
  if (b.entities.length)
    parts.push(`entités: ${b.entities.slice(0, 4).join(", ")}`);
  return parts.join(" · ");
}

export const contentColumns: ColumnDef<ContentItem>[] = [
  {
    accessorKey: "title",
    header: "Titre",
    cell: ({ row }) => (
      <span className="block max-w-[260px] truncate">{row.original.title}</span>
    ),
  },
  {
    accessorKey: "status",
    header: "Statut",
    cell: ({ row }) => (
      <Badge variant="secondary">
        {CONTENT_STATUS_LABEL[row.original.status]}
      </Badge>
    ),
  },
  {
    id: "kind",
    header: "Type",
    cell: ({ row }) => {
      const { kind, warnedPageUrl } = row.original;
      return (
        <span className="inline-flex items-center gap-1.5 whitespace-nowrap">
          {kind === "optimize" ? (
            <Badge variant="outline" className="font-normal">
              {CONTENT_KIND_LABEL.optimize}
            </Badge>
          ) : (
            <span className="text-muted-foreground text-xs">
              {CONTENT_KIND_LABEL.new}
            </span>
          )}
          {warnedPageUrl ? (
            <span
              role="img"
              aria-label="Cannibalisation possible"
              title={`Cannibalisation possible avec ${warnedPageUrl}`}
              className="text-destructive"
            >
              ⚠️
            </span>
          ) : null}
        </span>
      );
    },
  },
  {
    id: "keyword",
    header: "Mot-clé",
    cell: ({ row }) =>
      row.original.keywordTerm ? (
        <span className="whitespace-nowrap">
          <Flag code={row.original.keywordCountry} /> {row.original.keywordTerm}
        </span>
      ) : (
        dash
      ),
  },
  {
    accessorKey: "assignee",
    header: "Assigné",
    cell: ({ row }) => row.original.assignee ?? dash,
  },
  {
    accessorKey: "dueDate",
    header: "Échéance",
    cell: ({ row }) => {
      const d = row.original.dueDate;
      if (!d) return dash;
      const over =
        isOverdue(d, new Date().toISOString()) &&
        row.original.status !== "published";
      return (
        <span className={over ? "text-destructive" : ""}>
          {new Date(d).toLocaleDateString("fr-FR")}
        </span>
      );
    },
  },
  {
    id: "url",
    header: "URL",
    cell: ({ row }) =>
      row.original.url ? (
        <a
          href={row.original.url}
          target="_blank"
          rel="noopener noreferrer"
          onClick={(e) => e.stopPropagation()}
          aria-label="Ouvrir l'URL de l'article (nouvel onglet)"
          title="Ouvrir l'URL de l'article"
          className="text-primary hover:underline"
        >
          ↗
        </a>
      ) : (
        dash
      ),
  },
  {
    id: "serp",
    header: "SERP",
    cell: ({ row }) => (
      <ContentDot
        state={row.original.analysis.serp.state}
        tooltip={serpTooltip(row.original.analysis.serp)}
      />
    ),
  },
  {
    id: "onpage",
    header: "On-page",
    cell: ({ row }) => (
      <ContentDot
        state={row.original.analysis.onpage.state}
        tooltip={onpageTooltip(row.original.analysis.onpage)}
      />
    ),
  },
  {
    id: "brief",
    header: "Brief",
    cell: ({ row }) => (
      <ContentDot
        state={briefDotState(row.original.analysis.brief.state)}
        tooltip={briefTooltip(row.original.analysis.brief)}
      />
    ),
  },
];
