"use client";

import { useLocale } from "@/i18n/LocaleProvider";
import { DailyEarning } from "@/lib/api";

/**
 * Single-series daily-earnings bar chart. One brand hue (no legend needed, the card title names
 * the series); labels use text tokens, only the bars carry the brand color. Rounded tops, a 2px
 * surface gap between bars, a recessive baseline. The page renders a full table beside it, which
 * is the accessible/detailed view.
 */
export function EarningsChart({
  data,
  currency,
}: {
  data: DailyEarning[];
  currency: string;
}) {
  const { locale } = useLocale();
  const max = Math.max(1, ...data.map((d) => d.amount));

  const money = (n: number) =>
    new Intl.NumberFormat(locale === "ar" ? "ar-SA" : "en-GB", {
      style: "currency",
      currency,
      maximumFractionDigits: 0,
    }).format(n);

  const dayLabel = (iso: string) =>
    new Date(iso).toLocaleDateString(locale === "ar" ? "ar-SA" : "en-GB", {
      day: "numeric",
      month: "short",
    });

  const ticks =
    data.length <= 1
      ? data
      : [data[0], data[Math.floor(data.length / 2)], data[data.length - 1]];

  return (
    <div>
      {/* y-axis max marker */}
      <div className="mb-1 text-xs text-muted">{money(max)}</div>

      <div className="flex h-48 items-end gap-[2px] border-b border-line">
        {data.map((d) => (
          <div key={d.day} className="group relative flex-1">
            <div
              className="w-full rounded-t bg-brand-deep transition-colors group-hover:bg-brand dark:bg-brand-soft"
              style={{ height: `${Math.max((d.amount / max) * 100, d.amount > 0 ? 2 : 0)}%` }}
            />
            {/* hover tooltip */}
            <div className="pointer-events-none absolute -top-9 start-1/2 z-10 hidden -translate-x-1/2 whitespace-nowrap rounded-md border border-line bg-surface px-2 py-1 text-xs shadow-card group-hover:block rtl:translate-x-1/2">
              <div className="font-semibold">{money(d.amount)}</div>
              <div className="text-muted">{dayLabel(d.day)}</div>
            </div>
          </div>
        ))}
      </div>

      {/* sparse x-axis ticks */}
      <div className="mt-2 flex justify-between text-xs text-muted">
        {ticks.map((d) => (
          <span key={d.day}>{dayLabel(d.day)}</span>
        ))}
      </div>
    </div>
  );
}
