/**
 * llmindex.io — provider brand logo with monogram fallback
 * Author:  Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * License: Proprietary — © Simon-Pierre Boucher, all rights reserved
 *
 * Brand glyphs come from the Simple Icons CDN (tiny SVGs, brand colors).
 * Providers without a glyph — or any load failure — fall back to a colored
 * monogram chip, so the UI never shows a broken image.
 */
'use client';

import { useState, type ReactElement } from 'react';

interface Brand {
  slug?: string;
  color: string; // hex without '#'
  label: string;
}

const BRANDS: Record<string, Brand> = {
  anthropic: { slug: 'claude', color: 'D97757', label: 'A' },
  openai: { slug: 'openai', color: '111111', label: 'O' },
  google: { slug: 'googlegemini', color: '4796E3', label: 'G' },
  'x-ai': { slug: 'xai', color: '111111', label: 'X' },
  deepseek: { slug: 'deepseek', color: '4D6BFE', label: 'D' },
  qwen: { slug: 'qwen', color: '615CED', label: 'Q' },
  'meta-llama': { slug: 'meta', color: '0467DF', label: 'M' },
  mistralai: { slug: 'mistralai', color: 'FA520F', label: 'M' },
  moonshotai: { slug: 'moonshotai', color: '16181C', label: 'K' },
  'z-ai': { slug: 'zai', color: '1F2937', label: 'Z' },
  minimax: { slug: 'minimax', color: 'FF4040', label: 'MM' },
  nvidia: { slug: 'nvidia', color: '76B900', label: 'N' },
  amazon: { slug: 'amazonwebservices', color: 'FF9900', label: 'A' },
  cohere: { slug: 'cohere', color: 'D18EE2', label: 'C' },
};

export function ProviderLogo({
  provider,
  size = 18,
}: {
  provider: string;
  size?: number;
}): ReactElement {
  const [failed, setFailed] = useState(false);
  const brand = BRANDS[provider] ?? {
    color: '52525B',
    label: (provider[0] ?? '?').toUpperCase(),
  };

  if (failed || !brand.slug) {
    return (
      <span
        aria-hidden="true"
        title={provider}
        className="inline-flex shrink-0 items-center justify-center rounded-md font-bold"
        style={{
          width: size,
          height: size,
          fontSize: Math.max(8, size * 0.45),
          color: `#${brand.color}`,
          backgroundColor: `#${brand.color}22`,
          border: `1px solid #${brand.color}44`,
        }}
      >
        {brand.label}
      </span>
    );
  }

  return (
    // eslint-disable-next-line @next/next/no-img-element -- tiny external brand SVG; next/image adds no value and can't optimize SVGs
    <img
      src={`https://cdn.simpleicons.org/${brand.slug}/${brand.color}`}
      alt={`${provider} logo`}
      title={provider}
      width={size}
      height={size}
      loading="lazy"
      className="shrink-0"
      onError={() => setFailed(true)}
    />
  );
}
