'use client';

import { useQuery } from '@tanstack/react-query';
import * as React from 'react';
import { listingsApi } from '@/lib/listings-api';

interface SparklineProps {
  listingId: string;
  width?: number;
  height?: number;
}

/**
 * Inline SVG sparkline showing 30-day price history.
 * Fetches data lazily when the component mounts (used in table hover/visible rows).
 */
export function Sparkline({ listingId, width = 64, height = 20 }: SparklineProps) {
  const { data, isLoading } = useQuery({
    queryKey: ['listings', 'price-history', listingId],
    queryFn: () => listingsApi.getPriceHistory(listingId),
    staleTime: 5 * 60 * 1000,
  });

  if (isLoading) {
    return (
      <span
        className="inline-block animate-pulse rounded bg-background-surface"
        style={{ width, height }}
      />
    );
  }

  if (!data || data.length < 2) {
    return <span className="text-[11px] text-foreground-dim">—</span>;
  }

  const prices = data.map((d) => Number(d.newPrice));
  const min = Math.min(...prices);
  const max = Math.max(...prices);
  const range = max - min || 1;

  const points = prices
    .map((p, i) => {
      const x = (i / (prices.length - 1)) * width;
      const y = height - ((p - min) / range) * (height - 4) - 2;
      return `${x.toFixed(1)},${y.toFixed(1)}`;
    })
    .join(' ');

  // Color based on trend direction
  const trending = prices[prices.length - 1]! >= prices[0]!;
  const strokeColor = trending ? 'var(--color-signal-up)' : 'var(--color-signal-down)';

  return (
    <svg
      width={width}
      height={height}
      viewBox={`0 0 ${width} ${height}`}
      className="inline-block"
      aria-label="Biểu đồ giá 30 ngày"
    >
      <polyline
        points={points}
        fill="none"
        stroke={strokeColor}
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}
