'use client';

import {useId} from 'react';
import {AreaChart, Area, ReferenceLine} from 'recharts';
import {ChartFrame, chartFurniture} from './ChartFrame';
import {useChartMotion} from './useChartMotion';
import {CHART, dashFor, defaultEncoding, strokeWidthFor} from './palette';
import type {ChartViewProps} from './types';

const TONE = {
  neutral: CHART.reference,
  positive: CHART.positive,
  negative: CHART.negative,
} as const;

/**
 * Areas fade to transparent rather than sitting as flat gray blocks — on a
 * near-black surface a solid fill swallows the gridlines and the series below.
 */
export function AreaChartView<T extends object>({
  data,
  xKey,
  series,
  height = 260,
  xFormat,
  yFormat,
  reference,
  isAnimated = true,
  isBare,
}: ChartViewProps<T>) {
  const motion = useChartMotion(isAnimated);
  const uid = useId().replace(/:/g, '');

  return (
    <ChartFrame height={height}>
      <AreaChart data={data} margin={{top: 8, right: 8, bottom: 0, left: 0}}>
        <defs>
          {series.map((s, i) => {
            const c = s.color ?? CHART.seriesAt(i);
            return (
              <linearGradient
                key={s.key}
                id={`fill-${uid}-${s.key}`}
                x1="0"
                y1="0"
                x2="0"
                y2="1"
              >
                <stop offset="0%" stopColor={c} stopOpacity={0.38} />
                <stop offset="100%" stopColor={c} stopOpacity={0.03} />
              </linearGradient>
            );
          })}
        </defs>
        {chartFurniture({xKey, xFormat, yFormat, isBare})}
        {reference ? (
          <ReferenceLine
            y={reference.y}
            stroke={TONE[reference.tone ?? 'neutral']}
            strokeDasharray="4 4"
            label={{
              value: reference.label,
              position: 'insideTopRight',
              fill: CHART.axis,
              fontSize: 11,
            }}
          />
        ) : null}
        {series.map((s, i) => (
          <Area
            key={s.key}
            type="monotone"
            dataKey={s.key}
            name={s.label}
            stroke={s.color ?? CHART.seriesAt(i)}
            strokeWidth={strokeWidthFor(i)}
            strokeDasharray={dashFor(s.encoding ?? defaultEncoding(i))}
            fill={`url(#fill-${uid}-${s.key})`}
            // recharts defaults Area to fillOpacity 0.6, which multiplies the
            // gradient stops and leaves the fill nearly invisible on a
            // near-black card. The gradient already carries the opacity ramp.
            fillOpacity={1}
            dot={false}
            activeDot={{r: 3}}
            {...motion}
          />
        ))}
      </AreaChart>
    </ChartFrame>
  );
}
