import React from 'react'
import { formatClubPercent, formatSkillWeight, kpiRowsFromSummary } from '../../utils/skillProfileListHelpers'

/**
 * Kleine KPI-Kacheln: je Unterkategorie die Top-Fähigkeit (Listen/Karten).
 */
export default function SkillProfileCompact({
  summary,
  loading = false,
  emptyText = 'Keine Fähigkeiten',
  displayLimit = 24,
  highlightSkillIds = [],
}) {
  if (loading) {
    return (
      <div className="skill-kpi-grid skill-kpi-grid--loading" aria-busy="true">
        <span className="form-sub">…</span>
      </div>
    )
  }

  const rows = kpiRowsFromSummary(summary, { limit: displayLimit })
  const highlight = new Set((highlightSkillIds || []).map(String))

  if (!rows.length) {
    return summary ? <p className="form-sub skill-kpi-grid--empty">{emptyText}</p> : null
  }

  return (
    <ul className="skill-kpi-grid" aria-label="Fähigkeiten je Kategorie">
      {rows.map((row) => {
        const highlighted = highlight.has(String(row.skill_id))
        const isBest = row.is_club_best_for_skill || row.universal_percent >= 100
        return (
          <li
            key={`${row.category_name}-${row.skill_id}`}
            className={
              'skill-kpi-tile' +
              (highlighted ? ' skill-kpi-tile--highlight' : '') +
              (isBest ? ' skill-kpi-tile--best' : '')
            }
            title={`${row.category_name}: ${row.skill_name} — Gewicht ${formatSkillWeight(row.weight ?? row.score)}, ${formatClubPercent(row.universal_percent)} vom Vereins-Maximum`}
          >
            <span className="skill-kpi-tile__cat">{row.category_name}</span>
            <span className="skill-kpi-tile__name">{row.skill_name}</span>
            <span className="skill-kpi-tile__score">{formatSkillWeight(row.weight ?? row.score)}</span>
            <span className="skill-kpi-tile__pct">
              {isBest ? '★ ' : ''}
              {formatClubPercent(row.universal_percent)}
            </span>
          </li>
        )
      })}
    </ul>
  )
}
