import { useState } from 'react';
import type { Site } from '../types/site';
import { getFaviconUrl } from '../utils/favicon';

interface SiteCardProps {
  site: Site;
}

/** 导航卡片：外链、favicon、占位字母 */
export function SiteCard({ site }: SiteCardProps) {
  const [imgFailed, setImgFailed] = useState(false);

  const firstLetter = site.name.charAt(0).toUpperCase();
  const faviconUrl = site.url ? getFaviconUrl(site.url) : '';

  const tagsText = site.tags?.length ? site.tags.join('、') : '';
  const clickCount = typeof site.clicks === 'number' ? site.clicks : 0;

  return (
    <a
      href={site.url}
      target="_blank"
      rel="noreferrer"
      className="site-card"
      data-url={site.url}
      data-site-id={site.id}
    >
      <span className="site-card-clicks" title="访问次数">
        {clickCount}
      </span>
      <div className="site-icon">
        {faviconUrl && !imgFailed ? (
          <img src={faviconUrl} alt={`${site.name}图标`} onError={() => setImgFailed(true)} />
        ) : (
          <div className="favicon-placeholder">{firstLetter}</div>
        )}
      </div>
      <div className="site-card-body">
        <div className="site-name" title={site.name}>
          {site.name}
        </div>
        <div className="site-description" title={site.description || ''}>
          {site.description || ''}
        </div>
      </div>
      <div className="site-tags" title={tagsText}>
        {site.tags?.map((tag) => (
          <span key={tag} className="tag">
            {tag}
          </span>
        ))}
      </div>
    </a>
  );
}
