/**
 * llmindex.io — live-updating efficiency (Pareto) frontier table
 * Author:  Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * License: Proprietary — © Simon-Pierre Boucher, all rights reserved
 */
'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { formatUsd } from '@llmindex/ui';
import { ProviderLogo } from './ProviderLogo';

export interface EffPoint {
  model: string;
  name: string;
  score: number;
  cost_per_1k_items: number;
  on_frontier: boolean;
}

const POLL_MS = 15000;

export function EfficiencyLive({ initial }: { initial: EffPoint[] }) {
  const [points, setPoints] = useState<EffPoint[]>(initial);

  useEffect(() => {
    let cancelled = false;
    async function tick() {
      try {
        const res = await fetch('/api/v1/efficiency', { cache: 'no-store' });
        if (!res.ok || cancelled) return;
        const body = (await res.json()) as { points: EffPoint[] };
        if (body.points) setPoints(body.points);
      } catch {
        /* keep last state */
      }
    }
    const id = setInterval(tick, POLL_MS);
    tick();
    return () => {
      cancelled = true;
      clearInterval(id);
    };
  }, []);

  if (points.length === 0) return null;

  return (
    <section className="space-y-3">
      <div className="flex flex-wrap items-baseline justify-between gap-2">
        <h2 className="text-lg font-semibold text-zinc-900 sm:text-xl">Efficiency frontier</h2>
        <Link
          href="/frontier"
          className="rounded-full border border-emerald-300 bg-emerald-50 px-3 py-1 text-xs font-medium text-emerald-700 transition-colors hover:border-emerald-400"
        >
          Open the full interactive chart →
        </Link>
      </div>
      <p className="text-sm text-zinc-500">
        Score vs. measured cost per 1k items — refreshed live as models land. Frontier models are
        not dominated on both axes; never collapsed into a single blended number.
      </p>
      <div className="overflow-x-auto rounded-xl border border-zinc-200 bg-white">
        <table className="w-full min-w-[28rem] text-sm">
          <thead>
            <tr className="border-b border-zinc-200 text-left text-xs uppercase tracking-wide text-zinc-500">
              <th className="px-3 py-2">Model</th>
              <th className="px-3 py-2 text-right">Global Index</th>
              <th className="px-3 py-2 text-right">Cost / 1k items</th>
              <th className="px-3 py-2">Pareto</th>
            </tr>
          </thead>
          <tbody>
            {points.map((p) => (
              <tr key={p.model} className="border-b border-zinc-100 last:border-0">
                <td className="px-3 py-2">
                  <Link href={`/models/${p.model}`} className="flex items-center gap-2 hover:text-emerald-600">
                    <ProviderLogo provider={p.model.split('/')[0] ?? ''} size={16} />
                    {p.name}
                  </Link>
                </td>
                <td className="px-3 py-2 text-right tabular-nums">{p.score}</td>
                <td className="px-3 py-2 text-right tabular-nums">{formatUsd(p.cost_per_1k_items)}</td>
                <td className="px-3 py-2">
                  {p.on_frontier ? (
                    <span className="rounded-full bg-emerald-100 px-2 py-0.5 text-xs text-emerald-700">
                      frontier
                    </span>
                  ) : (
                    <span className="text-xs text-zinc-400">dominated</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}

export function HomeStats({
  initialCount,
  domains,
  version,
}: {
  initialCount: number;
  domains: number;
  version: string;
}) {
  const [count, setCount] = useState(initialCount);

  useEffect(() => {
    let cancelled = false;
    async function tick() {
      try {
        const res = await fetch('/api/v1/leaderboard?limit=200', { cache: 'no-store' });
        if (!res.ok || cancelled) return;
        const body = (await res.json()) as { entries?: unknown[] };
        if (body.entries) setCount(body.entries.length);
      } catch {
        /* keep last state */
      }
    }
    const id = setInterval(tick, POLL_MS);
    return () => {
      cancelled = true;
      clearInterval(id);
    };
  }, []);

  return (
    <div className="flex flex-wrap gap-x-6 gap-y-2 pt-2 text-sm">
      <span className="flex items-center gap-2 text-zinc-700">
        <span className="relative flex h-2 w-2">
          <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-60" />
          <span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-400" />
        </span>
        updates live
      </span>
      <span className="text-zinc-600">
        <span className="font-semibold text-zinc-900 tabular-nums">{count}</span> models scored
      </span>
      <span className="text-zinc-600">
        <span className="font-semibold text-zinc-900 tabular-nums">{domains}</span> domains
      </span>
      <span className="text-zinc-600">IRT 2PL · 95% CI · v{version}</span>
    </div>
  );
}
