/**
 * earth-now.co
 * Author:  Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * File:    apps/web/app/methodology/page.tsx
 * Purpose: Public methodology page (product commitment) — per-metric source, license, cadence, model family/version, last observation, uncertainty
 */

import Link from "next/link";
import { formatValue } from "@earth-now/counter";
import { fetchMetrics, type MetricSummary } from "@/lib/api";
import {
  DEFAULT_LOCALE,
  formatDateUtc,
  isLocale,
  translate,
  type MessageKey,
} from "@/lib/messages";

export const dynamic = "force-dynamic";

const PERCENT_HINTS = { decimals: 0, unit: "%" } as const;

function levelLabel(metric: MetricSummary): string {
  const level = typeof metric.level === "number" ? `L${metric.level}` : metric.level.toUpperCase();
  const version = metric.modelVersion !== undefined ? ` · ${metric.modelVersion}` : "";
  return `${level} · ${metric.model}${version}`;
}

export default async function MethodologyPage({
  searchParams,
}: {
  searchParams?: { lang?: string };
}) {
  const langParam = searchParams?.lang;
  const locale = isLocale(langParam) ? langParam : DEFAULT_LOCALE;
  const t = (key: MessageKey) => translate(locale, key);

  let metrics: MetricSummary[] = [];
  let offline = false;
  try {
    metrics = await fetchMetrics();
  } catch {
    offline = true;
  }

  return (
    <div className="mx-auto max-w-6xl px-4 py-10">
      <Link href="/" className="text-xs text-accent hover:opacity-80">
        {t("methodology.back")}
      </Link>
      <h1 className="mt-3 text-2xl font-semibold tracking-tight text-ink">
        {t("methodology.title")}
      </h1>
      <p className="mt-3 max-w-3xl text-sm leading-relaxed text-ink2">
        {t("methodology.intro")}
      </p>

      {offline ? (
        <p className="mt-8 text-sm text-ink2">{t("offline.body")}</p>
      ) : (
        <div className="mt-8 overflow-x-auto">
          <table className="w-full min-w-[900px] border-collapse text-left text-xs">
            <thead>
              <tr className="border-b border-line text-ink2">
                <th className="py-2 pr-3 font-medium">{t("methodology.metric")}</th>
                <th className="py-2 pr-3 font-medium">{t("methodology.domain")}</th>
                <th className="py-2 pr-3 font-medium">{t("methodology.kind")}</th>
                <th className="py-2 pr-3 font-medium">{t("methodology.model")}</th>
                <th className="py-2 pr-3 font-medium">{t("methodology.source")}</th>
                <th className="py-2 pr-3 font-medium">{t("methodology.license")}</th>
                <th className="py-2 pr-3 font-medium">{t("methodology.cadence")}</th>
                <th className="py-2 pr-3 font-medium">{t("methodology.observed")}</th>
                <th className="py-2 pr-3 font-medium">{t("methodology.uncertainty")}</th>
                <th className="py-2 font-medium">{t("methodology.note")}</th>
              </tr>
            </thead>
            <tbody>
              {metrics.map((metric) => {
                const source = metric.sources[0];
                return (
                  <tr key={metric.id} className="border-b border-line align-top text-ink2">
                    <td className="py-2 pr-3 font-medium text-ink">
                      {metric.name[locale]}
                      {metric.stale && (
                        <span className="ml-2 rounded border border-warn/50 px-1.5 py-0.5 text-[10px] uppercase text-ink2">
                          {t("chip.stale")}
                        </span>
                      )}
                    </td>
                    <td className="py-2 pr-3">
                      {t(`domain.${metric.domain}` as MessageKey)}
                    </td>
                    <td className="py-2 pr-3">{t(`kind.${metric.kind}` as MessageKey)}</td>
                    <td className="py-2 pr-3 tabular-nums">{levelLabel(metric)}</td>
                    <td className="py-2 pr-3">
                      {source !== undefined ? (
                        <a
                          href={source.url}
                          target="_blank"
                          rel="noreferrer"
                          className="text-accent underline decoration-accent/40 hover:opacity-80"
                        >
                          {source.name}
                        </a>
                      ) : (
                        "—"
                      )}
                    </td>
                    <td className="py-2 pr-3">{source?.license ?? "—"}</td>
                    <td className="py-2 pr-3">{source?.cadence ?? "—"}</td>
                    <td className="py-2 pr-3">
                      {metric.observedAt !== undefined
                        ? formatDateUtc(metric.observedAt, locale)
                        : "—"}
                    </td>
                    <td className="py-2 pr-3 tabular-nums">
                      {metric.uncertaintyFraction !== undefined
                        ? `± ${formatValue(metric.uncertaintyFraction * 100, PERCENT_HINTS, {
                            locale,
                          })} % (${t("chip.estimate")})`
                        : "—"}
                    </td>
                    <td className="py-2 text-ink2">
                      {metric.editorialNote !== undefined ? metric.editorialNote[locale] : ""}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
