import type { CategorySlice } from '../lib/api';
import { translations, getLang } from '../lib/i18n';

interface Props {
  byCategory: CategorySlice[];
  totalMinor: number;
  onSelect?: (categoryId: number | null) => void;
  selectedCategoryId?: number | null;
}

/**
 * Yatay yığılmış kategori şeridi. %3 altındaki kategoriler "Diğer"e toplanır.
 * Dilime dokununca o kategoriye filtreler.
 */
export function CategoryStrip({ byCategory, totalMinor, onSelect, selectedCategoryId }: Props) {
  const lang = getLang();
  const t = translations[lang];

  if (totalMinor <= 0 || byCategory.length === 0) return null;

  const main = byCategory.filter((c) => c.share >= 0.03);
  const rest = byCategory.filter((c) => c.share < 0.03);
  const restTotal = rest.reduce((a, c) => a + c.totalMinor, 0);
  const segments = [...main];
  if (rest.length > 0) {
    segments.push({
      categoryId: null,
      slug: null,
      nameTr: t.categoryOther,
      nameEn: 'Other',
      emoji: '📦',
      color: '#9CA3AF',
      totalMinor: restTotal,
      count: rest.reduce((a, c) => a + c.count, 0),
      share: totalMinor > 0 ? restTotal / totalMinor : 0,
    });
  }

  return (
    <div className="w-full">
      <div className="flex h-8 w-full overflow-hidden rounded-md bg-[var(--tg-secondary-bg)]">
        {segments.map((seg, i) => (
          <button
            key={seg.categoryId ?? `other-${i}`}
            type="button"
            onClick={() => onSelect?.(seg.categoryId)}
            aria-label={seg.nameTr ?? ''}
            title={seg.nameTr ?? ''}
            className={`strip-seg ${selectedCategoryId === seg.categoryId ? 'ring-1 ring-[var(--kurus-brass-deep)]' : ''}`}
            style={{
              width: `${Math.max(seg.share * 100, 2)}%`,
              backgroundColor: seg.color ?? '#9CA3AF',
            }}
          />
        ))}
      </div>
    </div>
  );
}
