'use client';

import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from 'recharts';

export interface PriceAreaChartPoint {
  period: string;
  avgPriceM2: number;
}

interface PriceAreaChartProps {
  data: PriceAreaChartPoint[];
  height?: number;
  className?: string;
}

/**
 * 30-day price area chart using signal colors.
 * Green fill when latest > first point, red otherwise.
 */
export function PriceAreaChart({ data, height = 280, className }: PriceAreaChartProps) {
  const isUp =
    data.length >= 2 && data[data.length - 1]!.avgPriceM2 >= data[0]!.avgPriceM2;

  // CSS tokens are stored as raw HSL components (`--signal-up: 142 72% 50%`),
  // so they must be wrapped in `hsl(...)`. The previous `var(--color-signal-up)`
  // form referenced a non-existent variable, leaving recharts with `undefined`
  // and rendering an invisible line/area.
  const strokeColor = isUp ? 'hsl(var(--signal-up))' : 'hsl(var(--signal-down))';
  const fillColor = strokeColor;

  return (
    <div className={className}>
      <ResponsiveContainer width="100%" height={height}>
        <AreaChart data={data} margin={{ top: 8, right: 12, left: 0, bottom: 0 }}>
          <defs>
            <linearGradient id="priceGradient" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={fillColor} stopOpacity={0.3} />
              <stop offset="95%" stopColor={fillColor} stopOpacity={0.02} />
            </linearGradient>
          </defs>
          <CartesianGrid
            strokeDasharray="3 3"
            stroke="hsl(var(--border))"
            strokeOpacity={0.5}
          />
          <XAxis
            dataKey="period"
            tick={{ fontSize: 11, fill: 'hsl(var(--muted-foreground))' }}
            tickLine={false}
            axisLine={false}
          />
          <YAxis
            tick={{ fontSize: 11, fill: 'hsl(var(--muted-foreground))' }}
            tickLine={false}
            axisLine={false}
            tickFormatter={(v: number) =>
              v >= 1_000_000 ? `${(v / 1_000_000).toFixed(0)}tr` : `${Math.round(v / 1000)}k`
            }
          />
          <Tooltip
            contentStyle={{
              backgroundColor: 'hsl(var(--card))',
              border: '1px solid hsl(var(--border))',
              borderRadius: '0.375rem',
              fontSize: '0.75rem',
              fontFamily: 'var(--font-mono)',
            }}
            formatter={(value) => [
              `${(Number(value) / 1_000_000).toFixed(2)} tr/m²`,
              'Giá TB',
            ]}
          />
          <Area
            type="monotone"
            dataKey="avgPriceM2"
            stroke={strokeColor}
            strokeWidth={2}
            fill="url(#priceGradient)"
            dot={false}
            activeDot={{ r: 4, strokeWidth: 0 }}
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
}
