"use client";

import { AreaChart } from "@/components/charts/area-chart";

type DataPoint = { date: string; clicks: number; impressions: number; sessions: number };

export function PortalCharts({
  data,
  showClicks,
  showImpressions,
  showSessions,
}: {
  data: DataPoint[];
  showClicks: boolean;
  showImpressions: boolean;
  showSessions: boolean;
}) {
  const series: Array<{ key: string; label: string; color: string; axis: "left" | "right" }> = [];
  if (showClicks) {
    series.push({ key: "clicks", label: "Clics", color: "#fbbf24", axis: "left" });
  }
  if (showSessions) {
    series.push({ key: "sessions", label: "Sessions", color: "#6b8e6f", axis: "left" });
  }
  if (showImpressions) {
    // Impressions ont une magnitude 10-100x plus grande que clics/sessions.
    // Axe droit dedie si une autre serie est presente, sinon axe gauche seul.
    const hasOther = showClicks || showSessions;
    series.push({
      key: "impressions",
      label: "Impressions",
      color: "#c2410c",
      axis: hasOther ? "right" : "left",
    });
  }

  // Resume textuel a11y : totaux + plage temporelle.
  const ariaSummary = (() => {
    if (!data.length) return "Graphique de trafic vide";
    const first = data[0];
    const last = data[data.length - 1];
    const parts: string[] = [];
    if (showClicks) {
      const total = data.reduce((s, d) => s + d.clicks, 0);
      parts.push(`${total.toLocaleString("fr-FR")} clics organiques cumules`);
    }
    if (showImpressions) {
      const total = data.reduce((s, d) => s + d.impressions, 0);
      parts.push(`${total.toLocaleString("fr-FR")} impressions cumulees`);
    }
    if (showSessions) {
      const total = data.reduce((s, d) => s + d.sessions, 0);
      parts.push(`${total.toLocaleString("fr-FR")} sessions cumulees`);
    }
    return `Trafic du ${first.date} au ${last.date} : ${parts.join(", ")}`;
  })();

  return (
    <AreaChart
      data={data}
      xKey="date"
      series={series}
      height={280}
      ariaLabel={ariaSummary}
      formatX={(v) => {
        const d = new Date(String(v));
        if (isNaN(d.getTime())) return String(v);
        return d.toLocaleDateString("fr-FR", { day: "2-digit", month: "short" });
      }}
      formatY={(n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n))}
      formatYRight={(n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n))}
      formatTooltipValue={(v) => v.toLocaleString("fr-FR")}
    />
  );
}
