import React from 'react';

import { faviconUrlFor } from './helpers';

interface NewCompetitorEntry {
  domain?: string | null;
  name?: string | null;
  share_of_voice?: number | null;
  [key: string]: unknown;
}

interface NewCompetitorsBannerProps {
  newCompetitors: Record<string, unknown>[] | undefined | null;
}

const CompetitorChip = ({
  entry,
}: {
  entry: NewCompetitorEntry;
}): JSX.Element => {
  const domain = (entry.domain || '').trim();
  const name = (entry.name || '').trim() || domain;
  const sov =
    typeof entry.share_of_voice === 'number' &&
    Number.isFinite(entry.share_of_voice)
      ? entry.share_of_voice
      : null;

  return (
    <span className="inline-flex items-center gap-1.5 pl-1.5 pr-2.5 py-0.5 bg-white border border-gray-200 rounded-full">
      <img
        src={faviconUrlFor(domain, 16)}
        alt=""
        width={16}
        height={16}
        loading="lazy"
        onError={event => {
          (event.currentTarget as HTMLImageElement).style.visibility = 'hidden';
        }}
        style={{ borderRadius: 3 }}
      />
      <span className="text-xs font-semibold text-gray-900">{name}</span>
      {sov !== null && (
        <span className="text-xs text-gray-500">{`${sov}%`}</span>
      )}
    </span>
  );
};

/**
 * Warning banner that surfaces competitors which entered the weekly
 * leaderboard for the first time. Renders nothing when there are no new
 * competitors for the selected week.
 */
const NewCompetitorsBanner = ({
  newCompetitors,
}: NewCompetitorsBannerProps): JSX.Element | null => {
  if (!Array.isArray(newCompetitors) || newCompetitors.length === 0)
    return null;

  const entries: NewCompetitorEntry[] = newCompetitors
    .filter(
      (raw): raw is Record<string, unknown> => !!raw && typeof raw === 'object'
    )
    .map(raw => raw as NewCompetitorEntry)
    .filter(
      entry => typeof entry.domain === 'string' && entry.domain.trim() !== ''
    );

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

  return (
    <div className="rounded-xl border border-yellow-200 bg-yellow-50 p-4">
      <p className="text-sm font-semibold text-yellow-800">
        {entries.length} new competitor{entries.length === 1 ? '' : 's'} entered
        your leaderboard this week
      </p>
      <div className="mt-2 flex flex-wrap items-center gap-2">
        {entries.map((entry, idx) => (
          <CompetitorChip key={`${entry.domain}-${idx}`} entry={entry} />
        ))}
      </div>
    </div>
  );
};

export default NewCompetitorsBanner;
