'use client';

import {
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import {CHART} from './palette';
import {ChartTooltip} from './ChartTooltip';

/**
 * The axis/grid/tooltip furniture every cartesian chart shares.
 *
 * Centralising it is what stops nine charts across four modules from drifting
 * into nine slightly different tick sizes and grid weights. Every value here
 * is a token — nothing is a literal colour.
 */

export const AXIS_TICK = {
  fill: '#e4e4e7',
  fontSize: 12,
  fontWeight: 500,
} as const;

export function chartFurniture({
  xKey,
  xFormat,
  yFormat,
  isBare,
}: {
  xKey: string;
  xFormat?: (v: string | number) => string;
  yFormat?: (v: number) => string;
  isBare?: boolean;
}) {
  if (isBare) return null;
  return (
    <>
      <CartesianGrid
        stroke={CHART.grid}
        strokeDasharray="3 3"
        vertical={false}
      />
      <XAxis
        dataKey={xKey}
        tick={AXIS_TICK}
        tickLine={false}
        axisLine={{stroke: CHART.axisLine}}
        tickFormatter={xFormat}
        minTickGap={24}
      />
      <YAxis
        tick={AXIS_TICK}
        tickLine={false}
        axisLine={false}
        width={54}
        tickFormatter={yFormat ? (v: number) => yFormat(v) : undefined}
      />
      <Tooltip
        cursor={{fill: CHART.cursor, stroke: CHART.axisLine}}
        content={
          <ChartTooltip labelFormat={xFormat} valueFormat={yFormat} />
        }
      />
    </>
  );
}

export function ChartFrame({
  height = 260,
  children,
}: {
  height?: number | `${number}%`;
  children: React.ReactElement;
}) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      {children}
    </ResponsiveContainer>
  );
}
