// src/components/keywords/keyword-modal-trend.tsx — « Tendance du volume ·
// N mois » card: SVG area chart with gradient, last-point dot, month labels.
// N reflects the actual displayed window (≤ 12) rather than a hardcoded « 12 ».
"use client";

import { useId } from "react";
import type { Keyword, KeywordSource } from "@/lib/keywords/types";
import { cn } from "@/lib/utils";
import {
  activeMetrics,
  monthLabelFr,
  SOURCE_LABELS,
  trendDeltaPct,
  trendFor,
} from "./keyword-modal-utils";

const W = 600;
const H = 120;
const PAD = 6;

export function KeywordModalTrend({
  keyword,
  source,
}: {
  keyword: Keyword;
  /** Active toolbar « Source » view — sparkline shows this source's série. */
  source?: KeywordSource | "";
}) {
  const gradId = useId();
  const primary = activeMetrics(keyword, source);
  const points = trendFor(
    keyword,
    primary?.source ?? keyword.primarySource,
  ).slice(-12);
  const srcLabel = primary ? SOURCE_LABELS[primary.source] : null;
  // delta derived from the very points the chart displays — the native
  // Mangools growthPct covers a different window and would lie next to it
  const growth = trendDeltaPct(points);
  const hasData = points.length >= 2;
  // ELEVA-83 legacy data: Semrush rows imported before the import-side scaling
  // stored the RELATIVE trend (0..1) as-is. If every point is ≤ 1 while the
  // keyword's volume clearly isn't (> 10), the absolute « Recherches
  // mensuelles » number would be garbage — hide it (chart shape + delta stay).
  const isLegacyRelative =
    hasData &&
    points.every((p) => p.volume <= 1) &&
    (primary?.metrics.volume ?? 0) > 10;

  let linePath = "";
  let areaPath = "";
  let last: { x: number; y: number } | null = null;
  if (hasData) {
    const max = Math.max(...points.map((p) => p.volume), 1) * 1.25;
    const x = (i: number) => PAD + (i * (W - PAD * 2)) / (points.length - 1);
    const y = (v: number) => H - PAD - (v / max) * (H - PAD * 2);
    linePath = points
      .map(
        (p, i) =>
          `${i ? "L" : "M"}${x(i).toFixed(1)} ${y(p.volume).toFixed(1)}`,
      )
      .join(" ");
    areaPath = `${linePath} L${x(points.length - 1).toFixed(1)} ${H - PAD} L${x(
      0,
    ).toFixed(1)} ${H - PAD} Z`;
    last = { x: x(points.length - 1), y: y(points.at(-1)?.volume ?? 0) };
  }

  return (
    <section className="rounded-2xl border border-border/70 bg-card px-4.5 py-4">
      <div className="mb-1.5 flex items-start justify-between gap-3.5">
        <div className="flex min-w-0 flex-col gap-1">
          <h3 className="whitespace-nowrap font-semibold text-[13.5px]">
            Tendance du volume · {points.length} mois
          </h3>
          <p className="text-[11.5px] text-muted-foreground">
            Recherches mensuelles{srcLabel ? ` · ${srcLabel}` : ""}
          </p>
        </div>
        {hasData ? (
          <div className="flex items-baseline gap-2">
            {!isLegacyRelative ? (
              <b className="font-semibold text-[22px] tabular-nums tracking-tight">
                {points.at(-1)?.volume.toLocaleString("fr-FR")}
              </b>
            ) : null}
            {growth !== null && growth !== 0 ? (
              <span
                className={cn(
                  "inline-flex items-center gap-0.5 rounded-md px-1.5 py-0.5 font-semibold text-xs tabular-nums",
                  growth > 0
                    ? "bg-emerald-500/10 text-emerald-400"
                    : "bg-rose-500/10 text-rose-400",
                )}
              >
                <svg
                  width="11"
                  height="11"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="3"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className={growth < 0 ? "rotate-180" : undefined}
                  aria-hidden="true"
                >
                  <path d="M5 12l7-7 7 7M12 19V5" />
                </svg>
                {growth > 0 ? "+" : ""}
                {growth}%
              </span>
            ) : null}
          </div>
        ) : null}
      </div>

      {hasData ? (
        <>
          <svg
            viewBox={`0 0 ${W} ${H}`}
            preserveAspectRatio="none"
            className="mt-2 block h-[100px] w-full overflow-visible"
            role="img"
            aria-label="Tendance du volume de recherche sur 12 mois"
          >
            <defs>
              <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#3d5afe" stopOpacity="0.32" />
                <stop offset="100%" stopColor="#3d5afe" stopOpacity="0" />
              </linearGradient>
            </defs>
            <line
              x1={PAD}
              y1={H - PAD}
              x2={W - PAD}
              y2={H - PAD}
              className="stroke-border/70"
              strokeWidth="1"
            />
            <line
              x1={PAD}
              y1={H / 2}
              x2={W - PAD}
              y2={H / 2}
              className="stroke-border/40"
              strokeWidth="1"
              strokeDasharray="3 5"
            />
            <path d={areaPath} fill={`url(#${gradId})`} />
            <path
              d={linePath}
              fill="none"
              stroke="#6c7bff"
              strokeWidth="2.4"
              strokeLinejoin="round"
              strokeLinecap="round"
            />
            {last ? (
              <circle
                cx={last.x}
                cy={last.y}
                r="4.5"
                className="fill-card"
                stroke="#6c7bff"
                strokeWidth="2.4"
              />
            ) : null}
          </svg>
          <div className="mt-2 flex justify-between px-0.5">
            {points.map((p) => (
              <span
                key={p.month}
                className="font-medium text-[10px] text-muted-foreground/70"
              >
                {monthLabelFr(p.month)}
              </span>
            ))}
          </div>
        </>
      ) : (
        <div className="mt-2 flex h-[100px] items-center justify-center rounded-xl border border-border/50 border-dashed">
          <span className="text-muted-foreground/70 text-xs">
            — Aucune donnée de tendance
          </span>
        </div>
      )}
    </section>
  );
}
