// -----------------------------------------------------------------------------
// Auto-Ka — Agrégateur de voitures usagées à vendre (province de Québec)
// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
// Home.tsx : recherche — hero, filtres auto, grille de véhicules, pagination
// -----------------------------------------------------------------------------
import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import {
  Facets, Vehicle, VehicleQuery, fetchFacets, fetchStats, fetchVehicles,
} from "../api";
import VehicleCard from "../components/VehicleCard";

const PAGE_SIZE = 24;

const SORTS = [
  { v: "price_asc", label: "Prix croissant" },
  { v: "price_desc", label: "Prix décroissant" },
  { v: "km_asc", label: "Kilométrage croissant" },
  { v: "year_desc", label: "Année récente" },
  { v: "recent", label: "Arrivages récents" },
];

const PRICE_STEPS = [5000, 10000, 15000, 20000, 25000, 30000, 40000, 50000, 75000, 100000];
const KM_STEPS = [20000, 40000, 60000, 80000, 100000, 130000, 160000, 200000];

const KIND_COPY: Record<string, { label: string; hero: string; sub: string }> = {
  auto: {
    label: "voitures usagées",
    hero: "voitures usagées",
    sub: "Auto-Ka visite les sites des concessionnaires et marchands d'occasion de toutes les régions, normalise chaque annonce et détecte les nouveautés, les ventes et les baisses de prix — automatiquement.",
  },
  moto: {
    label: "motos usagées",
    hero: "motos usagées",
    sub: "Les inventaires des concessionnaires moto du Québec — Harley-Davidson, Honda, Yamaha, Kawasaki, BMW et plus — agrégés à la source et tenus à jour automatiquement.",
  },
  scooter: {
    label: "scooters usagés",
    hero: "scooters usagés",
    sub: "Les scooters usagés des concessionnaires du Québec — Vespa, Honda, Yamaha, Kymco et plus — agrégés à la source et tenus à jour automatiquement.",
  },
};

export default function Home({ kind = "auto" }: { kind?: string }) {
  const [params, setParams] = useSearchParams();
  const [facets, setFacets] = useState<Facets | null>(null);
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [heroStats, setHeroStats] = useState<{ total: number; sources: number; regions: number } | null>(null);

  const query: VehicleQuery = useMemo(() => {
    const g = (k: string) => params.get(k) || undefined;
    const gn = (k: string) => (params.get(k) ? Number(params.get(k)) : undefined);
    return {
      kind,
      make: g("make"), model: g("model"), body_type: g("body"),
      fuel: g("fuel"), transmission: g("trans"), region: g("region"),
      source: g("source"), year_min: gn("ymin"), year_max: gn("ymax"),
      price_max: gn("pmax"), km_max: gn("kmax"), q: g("q"),
      sort: g("sort") || "price_asc",
      limit: PAGE_SIZE,
      offset: (Math.max(1, gn("page") || 1) - 1) * PAGE_SIZE,
    };
  }, [params, kind]);

  const page = Math.max(1, Number(params.get("page") || 1));
  const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  useEffect(() => {
    fetchFacets(params.get("make") || undefined, kind).then(setFacets).catch(() => {});
  }, [params.get("make"), kind]);

  useEffect(() => {
    fetchStats()
      .then((s) => setHeroStats({ total: s.total, sources: s.sources, regions: s.regions }))
      .catch(() => {});
  }, []);

  useEffect(() => {
    setLoading(true);
    fetchVehicles(query)
      .then((r) => { setVehicles(r.vehicles); setTotal(r.total); })
      .catch(() => { setVehicles([]); setTotal(0); })
      .finally(() => setLoading(false));
  }, [query]);

  const setFilter = (key: string, value: string) => {
    const next = new URLSearchParams(params);
    if (value) next.set(key, value);
    else next.delete(key);
    if (key !== "page") next.delete("page");
    if (key === "make") next.delete("model");   // le modèle dépend de la marque
    setParams(next, { replace: false });
  };

  const clearAll = () => setParams(new URLSearchParams(), { replace: false });

  const years: number[] = [];
  const yb = facets?.years?.[0];
  if (yb?.y_min && yb?.y_max) {
    for (let y = yb.y_max; y >= yb.y_min; y--) years.push(y);
  }

  return (
    <div className="container">
      <section className="hero">
        <span className="kicker">Agrégateur indépendant — direct des concessionnaires</span>
        <h1>
          {kind === "scooter" ? "Tous les " : "Toutes les "}
          <em>{KIND_COPY[kind]?.hero ?? "véhicules"}</em> à vendre au Québec.
          Un seul endroit.
        </h1>
        <p className="sub">{KIND_COPY[kind]?.sub}</p>
        {kind === "auto" && heroStats && (
          <div className="hero-stats">
            <div className="hstat"><b>{heroStats.total.toLocaleString("fr-CA")}</b> véhicules en vente</div>
            <div className="hstat"><b>{heroStats.sources}</b> concessionnaires</div>
            <div className="hstat"><b>{heroStats.regions}</b> régions couvertes</div>
          </div>
        )}
      </section>

      <section className="filters" aria-label="Filtres de recherche">
        <div className="f-field full">
          <label htmlFor="f-q">Recherche</label>
          <input
            id="f-q"
            type="search"
            placeholder="Marque, modèle, concessionnaire, ville…"
            defaultValue={params.get("q") || ""}
            onKeyDown={(e) => {
              if (e.key === "Enter") setFilter("q", (e.target as HTMLInputElement).value);
            }}
          />
        </div>
        <div className="f-field">
          <label htmlFor="f-make">Marque</label>
          <select id="f-make" value={params.get("make") || ""} onChange={(e) => setFilter("make", e.target.value)}>
            <option value="">Toutes</option>
            {facets?.makes.map((m) => (
              <option key={m.make} value={m.make}>{m.make} ({m.n})</option>
            ))}
          </select>
        </div>
        <div className="f-field">
          <label htmlFor="f-model">Modèle</label>
          <select id="f-model" value={params.get("model") || ""} onChange={(e) => setFilter("model", e.target.value)}>
            <option value="">Tous</option>
            {facets?.models.map((m) => (
              <option key={m.model} value={m.model}>{m.model} ({m.n})</option>
            ))}
          </select>
        </div>
        <div className="f-field">
          <label htmlFor="f-region">Région</label>
          <select id="f-region" value={params.get("region") || ""} onChange={(e) => setFilter("region", e.target.value)}>
            <option value="">Toutes</option>
            {facets?.regions.map((r) => (
              <option key={r.region} value={r.region}>{r.region} ({r.n})</option>
            ))}
          </select>
        </div>
        <div className="f-field">
          <label htmlFor="f-body">Carrosserie</label>
          <select id="f-body" value={params.get("body") || ""} onChange={(e) => setFilter("body", e.target.value)}>
            <option value="">Toutes</option>
            {facets?.body_types.map((b) => (
              <option key={b} value={b}>{b}</option>
            ))}
          </select>
        </div>
        <div className="f-field">
          <label htmlFor="f-fuel">Carburant</label>
          <select id="f-fuel" value={params.get("fuel") || ""} onChange={(e) => setFilter("fuel", e.target.value)}>
            <option value="">Tous</option>
            {facets?.fuels.map((f) => (
              <option key={f} value={f}>{f}</option>
            ))}
          </select>
        </div>
        <div className="f-field">
          <label htmlFor="f-trans">Transmission</label>
          <select id="f-trans" value={params.get("trans") || ""} onChange={(e) => setFilter("trans", e.target.value)}>
            <option value="">Toutes</option>
            <option value="Automatique">Automatique</option>
            <option value="Manuelle">Manuelle</option>
          </select>
        </div>
        <div className="f-field">
          <label htmlFor="f-ymin">Année min</label>
          <select id="f-ymin" value={params.get("ymin") || ""} onChange={(e) => setFilter("ymin", e.target.value)}>
            <option value="">—</option>
            {years.map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </div>
        <div className="f-field">
          <label htmlFor="f-pmax">Prix max</label>
          <select id="f-pmax" value={params.get("pmax") || ""} onChange={(e) => setFilter("pmax", e.target.value)}>
            <option value="">—</option>
            {PRICE_STEPS.map((p) => (
              <option key={p} value={p}>{p.toLocaleString("fr-CA")} $</option>
            ))}
          </select>
        </div>
        <div className="f-field">
          <label htmlFor="f-kmax">KM max</label>
          <select id="f-kmax" value={params.get("kmax") || ""} onChange={(e) => setFilter("kmax", e.target.value)}>
            <option value="">—</option>
            {KM_STEPS.map((k) => (
              <option key={k} value={k}>{k.toLocaleString("fr-CA")} km</option>
            ))}
          </select>
        </div>
        <div className="f-actions">
          <button className="btn ghost" onClick={clearAll}>Réinitialiser</button>
        </div>
      </section>

      <div className="result-bar">
        <h2>
          <span className="count">{total.toLocaleString("fr-CA")}</span>{" "}
          véhicule{total !== 1 ? "s" : ""} trouvé{total !== 1 ? "s" : ""}
        </h2>
        <div className="sort-box">
          <label htmlFor="f-sort">Trier</label>
          <select id="f-sort" value={params.get("sort") || "price_asc"} onChange={(e) => setFilter("sort", e.target.value)}>
            {SORTS.map((s) => (
              <option key={s.v} value={s.v}>{s.label}</option>
            ))}
          </select>
        </div>
      </div>

      {loading ? (
        <div className="vgrid">
          {Array.from({ length: 8 }).map((_, i) => (
            <div key={i} className="skeleton" style={{ height: 360 }} />
          ))}
        </div>
      ) : vehicles.length === 0 ? (
        <div className="notice">
          <div className="big">🔍</div>
          <h2>Aucun véhicule ne correspond</h2>
          <p>Essayez d'élargir vos filtres — l'inventaire évolue chaque jour.</p>
        </div>
      ) : (
        <>
          <div className="vgrid">
            {vehicles.map((v) => (
              <VehicleCard key={v.uid} v={v} />
            ))}
          </div>
          {pages > 1 && (
            <div className="pager">
              <button
                className="btn ghost"
                disabled={page <= 1}
                onClick={() => { setFilter("page", String(page - 1)); window.scrollTo(0, 0); }}
              >
                ← Précédent
              </button>
              <span className="mono">page {page} / {pages}</span>
              <button
                className="btn ghost"
                disabled={page >= pages}
                onClick={() => { setFilter("page", String(page + 1)); window.scrollTo(0, 0); }}
              >
                Suivant →
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}
