/**
 * Tag cloud display component.
 * Renders tags with font sizes proportional to usage count.
 */

import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { EmptyState } from '@/components/ui/EmptyState';
import type { Tag } from '@/api/tags';

export interface TagCloudProps {
  tags: Tag[];
  onTagClick?: (tag: Tag) => void;
  loading?: boolean;
}

export function TagCloud({ tags, onTagClick, loading = false }: TagCloudProps) {
  const { t } = useTranslation();

  const tagsWithSize = useMemo(() => {
    if (tags.length === 0) return [];
    const maxCount = Math.max(...tags.map((tag) => tag.usage_count || 0), 1);
    const minCount = Math.min(...tags.map((tag) => tag.usage_count || 0), 0);
    const range = maxCount - minCount || 1;

    return tags.map((tag) => {
      const count = tag.usage_count || 0;
      const ratio = (count - minCount) / range;
      const sizeClass =
        ratio > 0.75 ? 'text-2xl' :
        ratio > 0.5 ? 'text-xl' :
        ratio > 0.25 ? 'text-lg' :
        'text-base';
      return { tag, sizeClass };
    });
  }, [tags]);

  if (loading) {
    return (
      <div className="flex flex-wrap gap-3 items-center justify-center py-8" data-testid="tag-cloud-loading">
        {[1, 2, 3, 4, 5].map((i) => (
          <div key={i} className="h-6 bg-secondary-100 rounded animate-pulse" style={{ width: `${60 + i * 20}px` }} />
        ))}
      </div>
    );
  }

  if (tags.length === 0) {
    return (
      <div data-testid="tag-cloud-empty">
        <EmptyState title={t('tags.noTags')} />
      </div>
    );
  }

  return (
    <div className="flex flex-wrap gap-3 items-center justify-center py-8" data-testid="tag-cloud" role="list">
      {tagsWithSize.map(({ tag, sizeClass }) => (
        <button
          key={tag.id}
          onClick={() => onTagClick?.(tag)}
          className={`${sizeClass} font-medium text-secondary-700 hover:text-primary-600 motion-safe:transition-colors min-h-touch px-2 py-1 rounded`}
          aria-label={`${tag.name} (${tag.usage_count || 0} ${t('tags.usageCount')})`}
        >
          <span
            className="inline-block w-3 h-3 rounded-full mr-1 align-middle"
            style={{ backgroundColor: tag.color }}
            aria-hidden="true"
          />
          {tag.name}
        </button>
      ))}
    </div>
  );
}
