import type { AmazonData } from './types';

function StarRating({ rating }: { rating: number }) {
  const full = Math.floor(rating);
  const half = rating - full >= 0.5;
  const stars: string[] = [];
  for (let i = 0; i < full; i++) stars.push('\u2605');
  if (half) stars.push('\u2606');
  return <span className="text-amber-400" style={{ fontSize: 10 }}>{stars.join('')} {rating.toFixed(1)}</span>;
}

export function AmazonProductsCard({ data, onExpand }: { data: AmazonData; onExpand: () => void }) {
  const { query, products } = data;

  return (
    <div className="bg-slate-50 border border-slate-200 rounded-xl p-4 my-2 not-prose" style={{ maxWidth: 600 }}>
      {/* Header */}
      <div className="flex items-center gap-2 mb-3">
        <span className="text-sm">&#128722;</span>
        <span className="font-semibold text-slate-700" style={{ fontSize: 13 }}>Amazon 検索結果: 「{query}」</span>
        <span className="text-slate-400 ml-auto" style={{ fontSize: 11 }}>{products.length}件</span>
      </div>

      {/* Horizontal scroll cards */}
      <div className="flex gap-3 overflow-x-auto pb-1">
        {products.slice(0, 5).map((p) => (
          <a
            key={p.asin}
            href={p.productUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="bg-white border border-slate-200 rounded-lg p-2 cursor-pointer hover:border-blue-300 hover:shadow-sm transition-all flex-shrink-0 no-underline"
            style={{ minWidth: 160, maxWidth: 160 }}
          >
            <div className="w-full h-20 bg-slate-100 rounded flex items-center justify-center mb-2 overflow-hidden">
              {p.imageUrl ? (
                <img src={p.imageUrl} alt={p.title} className="max-h-full max-w-full object-contain" />
              ) : (
                <span className="text-2xl">&#128190;</span>
              )}
            </div>
            <div className="font-semibold text-slate-800 leading-tight mb-1 line-clamp-2" style={{ fontSize: 11 }}>
              {p.title}
            </div>
            {p.price && (
              <div className="font-bold text-red-600" style={{ fontSize: 13 }}>{p.price}</div>
            )}
            {p.rating != null && (
              <StarRating rating={p.rating} />
            )}
          </a>
        ))}
      </div>

      {/* Expand button */}
      <div className="text-center mt-2">
        <button
          onClick={onExpand}
          className="text-blue-500 hover:text-blue-700 cursor-pointer bg-transparent border-none"
          style={{ fontSize: 11 }}
        >
          &#9660; 詳細を表示
        </button>
      </div>
    </div>
  );
}
