// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
"use client";
import { useState } from "react";
import { CountUp } from "./MetricViz";
import { useLang } from "./LangContext";

export interface ProvStats {
  generated: string;
  unites: number;
  valeur_totale_2026: number;
  valeur_role_totale: number;
  valeur_mediane_2026: number;
  croissance_2021_2026_pct: number;
  logements: number;
  aire_etages_km2: number;
  terrain_km2: number;
  municipalites: number;
  totaux_annee: { year: number; total: number; n: number }[];
  par_type: { type: string; n: number; total: number; mediane: number | null }[];
  par_ville: { ville: string; n: number; total: number; mediane: number | null }[];
}

const POP_QC = 9_111_000; // population du Québec (2026, ISQ)
const BUDGET_QC = 165_800_000_000; // dépenses budget QC 2026-2027 (approx.)
const PIB_QC = 640_000_000_000; // PIB nominal QC (approx. 2025)

const money = (v: number, lang: string, frac = 0) =>
  new Intl.NumberFormat(lang === "fr" ? "fr-CA" : "en-CA", {
    style: "currency",
    currency: "CAD",
    maximumFractionDigits: frac,
  }).format(v);

const compact = (v: number, lang: string) => {
  const fr = lang === "fr";
  if (v >= 1e12) return `${(v / 1e12).toLocaleString(fr ? "fr-CA" : "en-CA", { maximumFractionDigits: 2 })} ${fr ? "billions $" : "T$"}`;
  if (v >= 1e9) return `${(v / 1e9).toLocaleString(fr ? "fr-CA" : "en-CA", { maximumFractionDigits: 1 })} G$`;
  if (v >= 1e6) return `${(v / 1e6).toLocaleString(fr ? "fr-CA" : "en-CA", { maximumFractionDigits: 1 })} M$`;
  return money(v, lang);
};

const num = (v: number, lang: string) =>
  v.toLocaleString(lang === "fr" ? "fr-CA" : "en-CA");

export default function StatsView({ s }: { s: ProvStats }) {
  const { lang } = useLang();
  const fr = lang === "fr";
  const [q, setQ] = useState("");

  const maxYear = Math.max(...s.totaux_annee.map((x) => x.total));
  const maxType = Math.max(...s.par_type.map((x) => x.total));
  const top10 = s.par_ville.slice(0, 10);
  const maxVille = Math.max(...top10.map((x) => x.total));
  const villes = s.par_ville.filter((v) =>
    v.ville.toLowerCase().includes(q.trim().toLowerCase())
  );

  return (
    <div className="pb-6 pt-10 sm:pt-14">
      {/* ---- LE CHIFFRE ---- */}
      <section>
        <span className="kicker">{fr ? "Juste pour le show" : "Just for the show"}</span>
        <h1 className="vp-display mt-3 text-[clamp(26px,4.6vw,46px)] font-bold uppercase leading-[1.02] tracking-[-0.03em]">
          {fr ? (
            <>
              Tous les plex du Québec valent,
              <br />
              <span className="hl">au dollar près</span>…
            </>
          ) : (
            <>
              All Québec plexes are worth,
              <br />
              <span className="hl">to the dollar</span>…
            </>
          )}
        </h1>
        <div className="rise mt-6 rounded-[10px] border-[1.5px] border-ink bg-ink p-6 shadow-[10px_10px_0_rgba(20,24,20,0.25)] sm:p-10">
          <p className="vp-display break-all text-[clamp(30px,6.2vw,76px)] font-bold leading-none tracking-[-0.03em] text-lime">
            <CountUp
              value={s.valeur_totale_2026}
              duration={2600}
              format={(v) => money(v, lang)}
            />
          </p>
          <p className="vp-mono mt-4 text-[11.5px] uppercase tracking-[0.1em] text-[rgba(255,159,69,0.75)]">
            {fr
              ? `≈ ${compact(s.valeur_totale_2026, lang)} · ${num(s.unites, lang)} plex · ${num(s.municipalites, lang)} municipalités · millésime 2026`
              : `≈ ${compact(s.valeur_totale_2026, lang)} · ${num(s.unites, lang)} plexes · ${num(s.municipalites, lang)} municipalities · 2026 vintage`}
          </p>
          <div className="mt-6 flex flex-wrap gap-2.5">
            {(
              [
                [fr ? "par Québécois·e" : "per Quebecer", money(s.valeur_totale_2026 / POP_QC, lang)],
                [fr ? "budgets annuels du Québec" : "annual Québec budgets", `× ${(s.valeur_totale_2026 / BUDGET_QC).toFixed(1)}`],
                [fr ? "fois le PIB du Québec" : "× Québec GDP", `× ${(s.valeur_totale_2026 / PIB_QC).toFixed(1)}`],
                [fr ? "depuis 2021 (périmètre constant)" : "since 2021 (constant perimeter)", `+${s.croissance_2021_2026_pct.toLocaleString(fr ? "fr-CA" : "en-CA")} %`],
              ] as [string, string][]
            ).map(([k, v]) => (
              <span key={k} className="stat-chip !border-[rgba(255,159,69,0.5)] !bg-transparent !text-[rgba(245,243,238,0.85)] !shadow-none">
                <b className="!text-lime">{v}</b> {k}
              </span>
            ))}
          </div>
        </div>
        <p className="vp-mono mt-3 text-[10.5px] uppercase tracking-[0.06em] text-ink-3">
          {fr
            ? "Somme des 393 867 estimations ValoPlex (modèle hédonique plex, rôle 2026). Évaluation municipale totale correspondante : "
            : "Sum of 393,867 ValoPlex estimates (plex hedonic model, 2026 roll). Corresponding total municipal assessment: "}
          {compact(s.valeur_role_totale, lang)}.
        </p>
        <a href="/api/report/stats" className="btn btn-primary mt-5" download>
          {fr
            ? "Télécharger le rapport statistique provincial (PDF)"
            : "Download the provincial statistics report (PDF)"}{" "}
          ↓
        </a>
      </section>

      {/* ---- tuiles physiques ---- */}
      <section className="mt-10">
        <div className="grid grid-cols-2 gap-3.5 sm:grid-cols-4">
          {(
            [
              [fr ? "Valeur médiane" : "Median value", money(s.valeur_mediane_2026, lang), true],
              [fr ? "Portes (logements)" : "Doors (dwellings)", num(s.logements, lang), false],
              [fr ? "Plancher bâti" : "Built floor area", `${num(s.aire_etages_km2, lang)} km²`, false],
              [fr ? "Terrains privés" : "Private land", `${num(s.terrain_km2, lang)} km²`, false],
            ] as [string, string, boolean][]
          ).map(([k, v, hero], i) => (
            <div key={k} className={`vp-card vp-card-hover rise p-4 ${hero ? "!bg-ink" : ""}`} style={{ animationDelay: `${i * 70}ms` }}>
              <p className={`vp-display text-[clamp(19px,2.4vw,27px)] font-bold tracking-[-0.03em] ${hero ? "text-lime" : ""}`}>{v}</p>
              <p className={`vp-mono mt-1.5 text-[10px] font-bold uppercase tracking-[0.1em] ${hero ? "text-[rgba(255,159,69,0.7)]" : "text-ink-3"}`}>{k}</p>
            </div>
          ))}
        </div>
      </section>

      {/* ---- valeur provinciale par année ---- */}
      <section className="mt-12">
        <span className="kicker">2021 → 2026</span>
        <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">
          {fr ? "La province, année par année" : "The province, year by year"}
        </h2>
        <div className="vp-card rise mt-4 p-5 sm:p-6">
          <div className="flex flex-col gap-2">
            {s.totaux_annee.map((h, i) => {
              const prev = i > 0 ? s.totaux_annee[i - 1].total : null;
              const yoy = prev ? ((h.total / prev - 1) * 100) : null;
              return (
                <div key={h.year} className="hbar-row grid grid-cols-[44px_1fr_auto] items-center gap-2 sm:grid-cols-[52px_1fr_auto] sm:gap-3">
                  <span className="vp-mono text-[12px] font-bold">{h.year}</span>
                  <span className="hbar-track !h-[24px]">
                    <span
                      className="hbar-fill grow-x !rounded-r-[6px]"
                      style={{
                        width: `${(h.total / maxYear) * 100}%`,
                        animationDelay: `${i * 90}ms`,
                        background: h.year === 2026 ? "var(--ink)" : undefined,
                      }}
                    />
                  </span>
                  <span className="vp-mono flex items-center justify-end gap-2 text-[12px] font-bold">
                    {compact(h.total, lang)}
                    {yoy != null && (
                      <span className={`rounded-[4px] border border-ink px-1 py-px text-[9px] ${yoy >= 0 ? "bg-lime-soft text-green-deep" : "bg-[var(--danger-soft)] text-[var(--danger)]"}`}>
                        {yoy >= 0 ? "+" : ""}{yoy.toFixed(1)} %
                      </span>
                    )}
                  </span>
                </div>
              );
            })}
          </div>
          <p className="vp-mono mt-3 text-[10px] uppercase tracking-[0.05em] text-ink-3">
            {fr
              ? "Sommes des unités estimées chaque millésime — le parc s'agrandit d'année en année (nouvelles constructions incluses)."
              : "Sums of units estimated each vintage — the stock grows every year (new construction included)."}
          </p>
        </div>
      </section>

      {/* ---- par type ---- */}
      <section className="mt-12">
        <span className="kicker">{fr ? "Répartition" : "Breakdown"}</span>
        <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">
          {fr ? "Valeur par taille de plex" : "Value by plex size"}
        </h2>
        <div className="vp-card rise mt-4 p-5 sm:p-6">
          <div className="flex flex-col gap-2.5">
            {s.par_type.map((tp, i) => (
              <div key={tp.type} className="hbar-row grid grid-cols-[110px_1fr_auto] items-center gap-2 sm:grid-cols-[150px_1fr_auto] sm:gap-3">
                <span className="vp-display truncate text-[13px] font-bold">{tp.type}</span>
                <span className="hbar-track !h-[22px]">
                  <span
                    className="hbar-fill grow-x"
                    style={{ width: `${(tp.total / maxType) * 100}%`, animationDelay: `${i * 80}ms` }}
                  />
                </span>
                <span className="vp-mono text-right text-[11.5px] font-bold">
                  {compact(tp.total, lang)}
                  <span className="block text-[9.5px] font-normal text-ink-3">
                    {num(tp.n, lang)} · {fr ? "méd." : "med."} {tp.mediane ? compact(tp.mediane, lang) : "—"}
                  </span>
                </span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ---- par ville ---- */}
      <section className="mt-12">
        <span className="kicker">{fr ? "Palmarès" : "Ranking"}</span>
        <h2 className="vp-display mt-2 text-[22px] font-bold uppercase tracking-[-0.02em]">
          {fr ? "Valeur par municipalité" : "Value by municipality"}
        </h2>
        {/* top 10 en barres */}
        <div className="vp-card rise mt-4 p-5 sm:p-6">
          <div className="flex flex-col gap-2">
            {top10.map((v, i) => (
              <div key={v.ville} className="hbar-row grid grid-cols-[24px_96px_1fr_auto] items-center gap-2 sm:grid-cols-[28px_150px_1fr_auto] sm:gap-3">
                <span className={`vp-mono inline-flex h-6 w-6 items-center justify-center rounded-full border-[1.5px] border-ink text-[10.5px] font-bold ${i < 3 ? "bg-ink text-lime" : "bg-surface text-ink"}`}>
                  {i + 1}
                </span>
                <span className="vp-display truncate text-[13px] font-bold">{v.ville}</span>
                <span className="hbar-track !h-[22px]">
                  <span
                    className="hbar-fill grow-x"
                    style={{ width: `${(v.total / maxVille) * 100}%`, animationDelay: `${i * 70}ms`, background: i === 0 ? "var(--ink)" : undefined }}
                  />
                </span>
                <span className="vp-mono text-right text-[11.5px] font-bold">{compact(v.total, lang)}</span>
              </div>
            ))}
          </div>
        </div>
        {/* table complète filtrable */}
        <div className="mt-4">
          <input
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder={fr ? "Filtrer parmi les 200 plus grandes municipalités…" : "Filter the 200 largest municipalities…"}
            className="vp-input max-w-md"
          />
          <div className="src-wrap mt-3 max-h-[460px] overflow-y-auto">
            <table className="src-table">
              <thead className="sticky top-0 z-10">
                <tr>
                  <th>#</th>
                  <th>{fr ? "Municipalité" : "Municipality"}</th>
                  <th className="text-right">{fr ? "Propriétés" : "Properties"}</th>
                  <th className="text-right">{fr ? "Valeur totale" : "Total value"}</th>
                  <th className="text-right">{fr ? "Valeur médiane" : "Median value"}</th>
                </tr>
              </thead>
              <tbody>
                {villes.map((v) => {
                  const rank = s.par_ville.indexOf(v) + 1;
                  return (
                    <tr key={v.ville}>
                      <td className="vp-mono text-[11px] font-bold text-ink-3">{rank}</td>
                      <td className="font-semibold">{v.ville}</td>
                      <td className="vp-mono text-right text-[12px]">{num(v.n, lang)}</td>
                      <td className="vp-display text-right font-bold">{compact(v.total, lang)}</td>
                      <td className="vp-mono text-right text-[12px]">{v.mediane ? money(v.mediane, lang) : "—"}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          <p className="vp-mono mt-2 text-[10px] uppercase tracking-[0.05em] text-ink-3">
            {fr
              ? `Top 200 des ${num(s.municipalites, lang)} municipalités, par valeur totale estimée (millésime 2026). Généré le ${s.generated}.`
              : `Top 200 of ${num(s.municipalites, lang)} municipalities by total estimated value (2026 vintage). Generated ${s.generated}.`}
          </p>
        </div>
      </section>
    </div>
  );
}
