// src/features/charts/TopDeals.tsx
import React, { useMemo } from 'react';
import type { FlyerItem } from '../../types';
import { TrophyIcon } from '../../components/icons/TrophyIcon';
interface TopDealsProps {
  items: FlyerItem[];
}

export const TopDeals: React.FC<TopDealsProps> = ({ items }) => {
  const topDeals = useMemo(() => {
    // Use a type guard in the filter to inform TypeScript that price_in_cents is non-null
    // in subsequent operations. This allows removing the redundant nullish coalescing in sort.
    return [...items]
      .filter(
        (item): item is FlyerItem & { price_in_cents: number } => item.price_in_cents !== null,
      )
      .sort((a, b) => a.price_in_cents - b.price_in_cents)
      .slice(0, 10);
  }, [items]);

  if (topDeals.length === 0) return null;

  return (
    <div className="bg-brand-light dark:bg-brand-dark/20 border border-brand-primary/50 rounded-lg p-4">
      <h3 className="text-lg font-bold text-brand-dark dark:text-brand-light flex items-center mb-3">
        <TrophyIcon className="w-6 h-6 mr-2" />
        Top 10 Deals Across All Flyers
      </h3>
      <ul className="space-y-2">
        {topDeals.map((item, index) => (
          <li
            key={index}
            className="grid grid-cols-3 gap-2 items-center text-sm bg-white dark:bg-gray-800 p-2 rounded"
          >
            <span className="font-semibold text-gray-800 dark:text-gray-200 col-span-2 truncate">
              {item.item}
            </span>
            <span className="font-bold text-brand-primary text-right">{item.price_display}</span>
            <span className="text-xs text-gray-500 dark:text-gray-400 col-span-3 truncate italic">
              (Qty: {item.quantity})
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
};
