interface CountyDistribution {
  county: string;
  contracts: number;
  total_value: number;
}

interface Props {
  data: CountyDistribution[];
  limit?: number;
  side: 'authority' | 'supplier';
}

function formatRON(value: number): string {
  if (!Number.isFinite(value) || value <= 0) return '0';
  if (value >= 1_000_000_000) return `${(value / 1_000_000_000).toFixed(1)} mld`;
  if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)} mil`;
  if (value >= 1_000) return `${(value / 1_000).toFixed(0)}K`;
  return Math.round(value).toString();
}

export function CountyBars({ data, limit = 15, side }: Props) {
  const visible = data.slice(0, limit);
  const max = visible.length > 0 ? Number(visible[0].total_value) : 1;

  if (visible.length === 0) {
    return <div className="profile-county-empty">Nicio distribuție geografică disponibilă.</div>;
  }

  const label = side === 'authority' ? 'Județ furnizor' : 'Județ cumpărător';

  return (
    <div className="profile-county-bars">
      <div className="profile-county-header">
        <span>{label}</span>
        <span>Valoare totală</span>
      </div>
      {visible.map((c) => {
        const pct = max > 0 ? (Number(c.total_value) / max) * 100 : 0;
        return (
          <a
            key={c.county}
            href={`/judet/${encodeURIComponent(c.county)}`}
            className="profile-county-row"
          >
            <span className="profile-county-name">{c.county}</span>
            <div className="profile-county-bar-track">
              <div className="profile-county-bar-fill" style={{ width: `${pct}%` }} />
            </div>
            <span className="profile-county-value tabular-nums">
              {formatRON(Number(c.total_value))}
              <span className="profile-county-count"> · {c.contracts}</span>
            </span>
          </a>
        );
      })}
    </div>
  );
}
