import React from 'react';

import type { CompetitorSnapshot } from '../../service/visibility/visibility.interface';

import { faviconUrlFor } from './helpers';

const TOP_N = 3;

interface TopCompetitorsHighlightProps {
  competitors: CompetitorSnapshot[];
}

/**
 * Hero strip for the top {@link TOP_N} competitors of the week. Renders
 * each as a card with a favicon, name, domain, and SOV badge.
 */
const TopCompetitorsHighlight = ({
  competitors,
}: TopCompetitorsHighlightProps): JSX.Element | null => {
  const top = competitors.slice(0, TOP_N);
  if (top.length === 0) {
    return null;
  }

  return (
    <div className="flex flex-col gap-2">
      <h3 className="text-base font-semibold text-gray-900">
        Top competitors this week
      </h3>
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
        {top.map(competitor => {
          const displayName =
            competitor.competitor_name || competitor.competitor_domain;

          return (
            <div
              key={competitor.competitor_domain}
              className="bg-white rounded-xl border border-gray-200 p-4"
            >
              <div className="flex items-center gap-3">
                <img
                  src={faviconUrlFor(competitor.competitor_domain)}
                  alt=""
                  width={48}
                  height={48}
                  loading="lazy"
                  style={{
                    borderRadius: 8,
                    background: '#f1f5f9',
                    flexShrink: 0,
                  }}
                  onError={event => {
                    (event.currentTarget as HTMLImageElement).style.visibility =
                      'hidden';
                  }}
                />
                <div className="flex flex-col gap-0.5 min-w-0">
                  <span className="text-sm font-semibold text-gray-900 truncate">
                    {displayName}
                  </span>
                  <span className="text-xs text-gray-500 truncate">
                    {competitor.competitor_domain}
                  </span>
                  <span className="text-sm font-bold text-gray-900">
                    {competitor.share_of_voice}% SOV
                  </span>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default TopCompetitorsHighlight;
