/**
 * earth-now.co
 * Author:  Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * File:    apps/web/components/CountryRanking.tsx
 * Purpose: Top-10 countries by population — live re-ranked list, ticking values, single-hue magnitude bars (length encodes, not color)
 */

"use client";

import { useEffect, useState } from "react";
import { counterValue, formatRate, formatValue, rateAt, type CounterModel } from "@earth-now/counter";
import type { MetricSummary } from "@/lib/api";
import { useI18n } from "@/lib/i18n";

const FLAGS: Record<string, string> = {
  country_population_india: "🇮🇳",
  country_population_china: "🇨🇳",
  country_population_usa: "🇺🇸",
  country_population_indonesia: "🇮🇩",
  country_population_pakistan: "🇵🇰",
  country_population_nigeria: "🇳🇬",
  country_population_brazil: "🇧🇷",
  country_population_bangladesh: "🇧🇩",
  country_population_russia: "🇷🇺",
  country_population_mexico: "🇲🇽",
  continent_population_asia: "🌏",
  continent_population_africa: "🌍",
  continent_population_europe: "🌍",
  continent_population_latam: "🌎",
  continent_population_north_america: "🌎",
  continent_population_oceania: "🌏",
};

interface Row {
  metric: MetricSummary;
  value: number;
  perSecond: number;
}

export interface CountryRankingProps {
  metrics: MetricSummary[];
  models: Record<string, CounterModel>;
}

export default function CountryRanking({ metrics, models }: CountryRankingProps) {
  const { locale } = useI18n();
  const [rows, setRows] = useState<Row[]>([]);

  useEffect(() => {
    const compute = () => {
      const now = Date.now();
      const next: Row[] = [];
      for (const metric of metrics) {
        const model = models[metric.id];
        if (model === undefined) continue;
        const value = counterValue(model, now);
        if (!Number.isFinite(value)) continue;
        next.push({ metric, value, perSecond: rateAt(model, now) });
      }
      next.sort((a, b) => b.value - a.value);
      setRows(next);
    };
    compute();
    const interval = window.setInterval(compute, 1_000);
    return () => window.clearInterval(interval);
  }, [metrics, models]);

  if (rows.length === 0) return null;
  const max = rows[0]!.value;

  return (
    <ol className="divide-y divide-line rounded-2xl border bg-surface">
      {rows.map((row, index) => {
        const hints = {
          decimals: row.metric.display.decimals,
          unit: row.metric.display.unit[locale],
          ...(row.metric.display.scale !== undefined ? { scale: row.metric.display.scale } : {}),
        };
        return (
          <li key={row.metric.id} className="flex min-w-0 items-center gap-3 px-4 py-2.5 transition-colors hover:bg-page/60">
            <span className="w-5 shrink-0 text-right text-xs text-muted tabular-nums">
              {index + 1}
            </span>
            <span aria-hidden className="shrink-0 text-base leading-none">
              {FLAGS[row.metric.id] ?? "🌍"}
            </span>
            <span className="w-28 shrink-0 truncate text-sm text-ink sm:w-36">
              {row.metric.name[locale]}
            </span>
            <span className="hidden flex-1 sm:block" aria-hidden>
              {/* Magnitude bar: single hue, length encodes the value (4px rounded ends). */}
              <span className="block h-1.5 w-full rounded-full bg-line">
                <span
                  className="block h-1.5 rounded-full bg-accent transition-[width] duration-1000 ease-linear"
                  style={{ width: `${Math.max(2, (row.value / max) * 100)}%` }}
                />
              </span>
            </span>
            <span className="ml-auto min-w-0 shrink text-right text-sm font-medium text-ink tabular-nums">
              {formatValue(row.value, hints, { locale, applySigFigs: false })}
            </span>
            <span className="hidden w-20 shrink-0 text-right text-xs text-ink2 tabular-nums sm:block">
              {row.perSecond >= 0 ? "+" : ""}
              {formatRate(row.perSecond, hints, { locale })}
            </span>
          </li>
        );
      })}
    </ol>
  );
}
