// -----------------------------------------------------------------------------
// Immo-Ka — Agrégateur de propriétés à vendre (province de Québec)
// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
// pages/Home.tsx : accueil — héro, statistiques, filtres avancés, grille + carte
// -----------------------------------------------------------------------------
import { Suspense, lazy, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import {
  Facets, Listing, ListingFilters, Stats,
  fetchFacets, fetchListings, fetchSources, fetchStats,
  registerSourceNames, sourceName,
} from "../api";
import ListingCard from "../components/ListingCard";

const MapView = lazy(() => import("../components/MapView"));

const PRICE_STEPS = [100000, 200000, 300000, 400000, 500000, 600000, 750000, 1000000, 1500000, 2000000, 3000000];
const AREA_STEPS = [800, 1000, 1500, 2000, 3000];
const PAGE = 12;

const fmtK = (n: number) =>
  n >= 1_000_000 ? `${n / 1_000_000} M$` : `${Math.round(n / 1000)} k$`;

// fenêtre de pagination : 1 … (p-1) p (p+1) … N
function pageNumbers(p: number, n: number): (number | "…")[] {
  if (n <= 7) return Array.from({ length: n }, (_, i) => i + 1);
  const out: (number | "…")[] = [1];
  const lo = Math.max(2, p - 1), hi = Math.min(n - 1, p + 1);
  if (lo > 2) out.push("…");
  for (let i = lo; i <= hi; i++) out.push(i);
  if (hi < n - 1) out.push("…");
  out.push(n);
  return out;
}

export default function Home() {
  const [listings, setListings] = useState<Listing[] | null>(null);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);   // pagination 12/page
  const [facets, setFacets] = useState<Facets | null>(null);
  const [sectors, setSectors] = useState<string[]>([]);
  const [stats, setStats] = useState<Stats | null>(null);
  const [error, setError] = useState<string | null>(null);

  const [params] = useSearchParams();
  const [q, setQ] = useState(params.get("q") ?? "");
  const [city, setCity] = useState(params.get("city") ?? "");
  const [sector, setSector] = useState(params.get("sector") ?? "");
  const [ptype, setPtype] = useState(params.get("property_type") ?? "");
  const [source, setSource] = useState(params.get("source") ?? "");
  const [priceMin, setPriceMin] = useState(params.get("price_min") ?? "");
  const [priceMax, setPriceMax] = useState(params.get("price_max") ?? "");
  const [bedsMin, setBedsMin] = useState(params.get("bedrooms_min") ?? "");
  const [bathsMin, setBathsMin] = useState(params.get("bathrooms_min") ?? "");
  const [areaMin, setAreaMin] = useState(params.get("area_min") ?? "");
  const [sort, setSort] = useState(params.get("sort") ?? "recent");

  const [sheetOpen, setSheetOpen] = useState(false);
  const [advOpen, setAdvOpen] = useState(false);
  const activeFilters = [q, city, sector, ptype, source, priceMin, priceMax, bedsMin, bathsMin, areaMin].filter(Boolean).length;
  const advCount = [bedsMin, bathsMin, areaMin, source, sector].filter(Boolean).length;

  const [view, setView] = useState<"liste" | "carte">(params.get("view") === "carte" ? "carte" : "liste");
  useEffect(() => { setView(params.get("view") === "carte" ? "carte" : "liste"); }, [params]);

  const filters: ListingFilters = useMemo(() => ({
    q, city, sector, region: "", property_type: ptype, source,
    price_min: priceMin, price_max: priceMax,
    bedrooms_min: bedsMin, bathrooms_min: bathsMin, area_min: areaMin, sort,
  }), [q, city, sector, ptype, source, priceMin, priceMax, bedsMin, bathsMin, areaMin, sort]);

  useEffect(() => {
    fetchSources().then((r) => registerSourceNames(r.sources)).catch(() => {});
    fetchFacets().then(setFacets).catch(() => {});
    fetchStats().then(setStats).catch(() => {});
  }, []);

  useEffect(() => {
    fetchFacets(city || undefined).then((f) => setSectors(f.sectors)).catch(() => setSectors([]));
  }, [city]);

  // revenir à la page 1 quand les filtres changent
  useEffect(() => { setPage(1); }, [filters]);

  // charger la page courante (12 annonces) — remplace la grille
  useEffect(() => {
    let cancelled = false;
    setListings(null); setError(null);
    fetchListings(filters, PAGE, (page - 1) * PAGE)
      .then((r) => { if (!cancelled) { setListings(r.listings); setTotal(r.total); } })
      .catch((e) => !cancelled && setError(String(e)));
    return () => { cancelled = true; };
  }, [filters, page]);

  const totalPages = Math.max(1, Math.ceil(total / PAGE));
  const gotoPage = (p: number) => {
    setPage(Math.min(Math.max(1, p), totalPages));
    document.getElementById("results-top")?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  const resetAll = () => {
    setQ(""); setCity(""); setSector(""); setPtype(""); setSource("");
    setPriceMin(""); setPriceMax(""); setBedsMin(""); setBathsMin(""); setAreaMin("");
  };

  const pills: { label: string; clear: () => void }[] = [];
  if (q) pills.push({ label: `« ${q} »`, clear: () => setQ("") });
  if (city) pills.push({ label: city, clear: () => { setCity(""); setSector(""); } });
  if (sector) pills.push({ label: sector, clear: () => setSector("") });
  if (ptype) pills.push({ label: ptype, clear: () => setPtype("") });
  if (priceMin) pills.push({ label: `≥ ${fmtK(Number(priceMin))}`, clear: () => setPriceMin("") });
  if (priceMax) pills.push({ label: `≤ ${fmtK(Number(priceMax))}`, clear: () => setPriceMax("") });
  if (bedsMin) pills.push({ label: `${bedsMin}+ ch.`, clear: () => setBedsMin("") });
  if (bathsMin) pills.push({ label: `${bathsMin}+ sdb`, clear: () => setBathsMin("") });
  if (areaMin) pills.push({ label: `≥ ${areaMin} pi²`, clear: () => setAreaMin("") });
  if (source) pills.push({ label: sourceName(source), clear: () => setSource("") });

  const topTypes = (facets?.property_types ?? []).slice(0, 7);

  return (
    <div className="container">
      <section className="hero">
        <span className="kicker">Agrégateur — Toutes les agences du Québec</span>
        <h1>
          Toutes les propriétés <span className="outline">à vendre</span>,<br />
          <span className="hl">un seul</span> endroit.
        </h1>
        <p className="lede">
          Immo-Ka rassemble les propriétés à vendre affichées par les agences de courtage
          immobilier du Québec — RE/MAX, Sutton, Via Capitale, Proprio Direct, Barnes et plus —
          mises à jour automatiquement, avec toutes les photos, les détails complets et un lien
          direct vers l'annonce originale.
        </p>
        <div className="stat-row">
          <span className="stat-chip"><span className="pulse" /> Données synchronisées en continu</span>
          {stats && (
            <>
              <span className="stat-chip"><b>{stats.total.toLocaleString("fr-CA")}</b> propriétés</span>
              <span className="stat-chip"><b>{stats.sources}</b> agences</span>
              <span className="stat-chip"><b>{stats.cities?.toLocaleString("fr-CA")}</b> villes</span>
              {stats.avg_price != null && (
                <span className="stat-chip">prix moyen <b>{Math.round(stats.avg_price).toLocaleString("fr-CA")} $</b></span>
              )}
            </>
          )}
        </div>
      </section>

      {sheetOpen && <div className="sheet-backdrop" onClick={() => setSheetOpen(false)} aria-hidden="true" />}
      <section className={`filterbar ${sheetOpen ? "open" : ""}`} aria-label="Filtres">
        <div className="sheet-head">
          <span>Filtres</span>
          <button className="sheet-close" onClick={() => setSheetOpen(false)} aria-label="Fermer les filtres">✕</button>
        </div>

        <div className="f-primary">
          <div className="f-search">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" aria-hidden="true">
              <circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" />
            </svg>
            <input id="f-q" placeholder="Adresse, ville, n° MLS…" value={q}
              onChange={(e) => setQ(e.target.value)} aria-label="Recherche" />
            {q && <button className="f-clear" onClick={() => setQ("")} aria-label="Effacer la recherche">✕</button>}
          </div>
          <label className="f-ctl">
            <span>Ville</span>
            <select value={city} onChange={(e) => { setCity(e.target.value); setSector(""); }}>
              <option value="">Toutes</option>
              {(facets?.cities ?? []).map((c) => <option key={c} value={c}>{c}</option>)}
            </select>
          </label>
          <label className="f-ctl">
            <span>Type</span>
            <select value={ptype} onChange={(e) => setPtype(e.target.value)}>
              <option value="">Tous</option>
              {(facets?.property_types ?? []).map((t) => <option key={t} value={t}>{t}</option>)}
            </select>
          </label>
          <div className="f-ctl">
            <span>Prix</span>
            <div className="range-pair">
              <select aria-label="Prix minimum" value={priceMin} onChange={(e) => setPriceMin(e.target.value)}>
                <option value="">Min</option>
                {PRICE_STEPS.map((p) => (
                  <option key={p} value={p} disabled={!!priceMax && p >= Number(priceMax)}>{fmtK(p)}</option>
                ))}
              </select>
              <span className="range-sep">—</span>
              <select aria-label="Prix maximum" value={priceMax} onChange={(e) => setPriceMax(e.target.value)}>
                <option value="">Max</option>
                {PRICE_STEPS.map((p) => (
                  <option key={p} value={p} disabled={!!priceMin && p <= Number(priceMin)}>{fmtK(p)}</option>
                ))}
              </select>
            </div>
          </div>
          <button className={`f-more ${advOpen || advCount > 0 ? "on" : ""}`} onClick={() => setAdvOpen(!advOpen)} aria-expanded={advOpen}>
            Plus de filtres{advCount > 0 ? ` · ${advCount}` : ""} {advOpen ? "▴" : "▾"}
          </button>
        </div>

        {(advOpen || sheetOpen) && (
          <div className="f-adv">
            <div className="f-group">
              <label>Quartier / secteur</label>
              <select className="f-native" value={sector} onChange={(e) => setSector(e.target.value)}>
                <option value="">Tous</option>
                {sectors.map((s) => <option key={s} value={s}>{s}</option>)}
              </select>
            </div>
            <div className="f-group">
              <label>Chambres (min.)</label>
              <div className="seg" role="group">
                <button className={bedsMin === "" ? "on" : ""} onClick={() => setBedsMin("")}>Toutes</button>
                {["1", "2", "3", "4", "5"].map((n) => (
                  <button key={n} className={bedsMin === n ? "on" : ""} onClick={() => setBedsMin(n)}>{n}+</button>
                ))}
              </div>
            </div>
            <div className="f-group">
              <label>Salles de bain (min.)</label>
              <div className="seg" role="group">
                <button className={bathsMin === "" ? "on" : ""} onClick={() => setBathsMin("")}>Toutes</button>
                {["1", "2", "3"].map((n) => (
                  <button key={n} className={bathsMin === n ? "on" : ""} onClick={() => setBathsMin(n)}>{n}+</button>
                ))}
              </div>
            </div>
            <div className="f-group">
              <label>Superficie minimale</label>
              <div className="seg" role="group">
                <button className={areaMin === "" ? "on" : ""} onClick={() => setAreaMin("")}>Peu importe</button>
                {AREA_STEPS.map((a) => (
                  <button key={a} className={areaMin === String(a) ? "on" : ""} onClick={() => setAreaMin(String(a))}>{a}+</button>
                ))}
              </div>
            </div>
            <div className="f-group">
              <label>Agence</label>
              <select className="f-native" value={source} onChange={(e) => setSource(e.target.value)}>
                <option value="">Toutes</option>
                {(facets?.sources ?? []).map((s) => (
                  <option key={s.source} value={s.source}>{sourceName(s.source)} ({s.n})</option>
                ))}
              </select>
            </div>
            <div className="f-group f-group-end">
              <button className="btn btn-ghost" onClick={resetAll} disabled={activeFilters === 0}>
                Tout réinitialiser{activeFilters > 0 ? ` (${activeFilters})` : ""}
              </button>
            </div>
          </div>
        )}

        <button className="btn btn-primary sheet-apply" onClick={() => setSheetOpen(false)}>
          Voir les résultats {listings ? `(${total})` : ""}
        </button>
      </section>

      <div className="chips" role="group" aria-label="Filtres rapides">
        {topTypes.map((t) => (
          <button key={t} className={`chip ${ptype === t ? "on" : ""}`} onClick={() => setPtype(ptype === t ? "" : t)}>
            {t}
          </button>
        ))}
      </div>

      {pills.length > 0 && (
        <div className="pills" aria-label="Filtres actifs">
          {pills.map((p) => (
            <button key={p.label} className="pill" onClick={p.clear} aria-label={`Retirer le filtre ${p.label}`}>
              {p.label} <span className="pill-x">✕</span>
            </button>
          ))}
          <button className="pill pill-clear" onClick={resetAll}>Tout effacer</button>
        </div>
      )}

      <div className="results-head" id="results-top">
        <h2>Propriétés à vendre</h2>
        <div className="results-tools">
          {listings && <span>{total.toLocaleString("fr-CA")} résultat{total > 1 ? "s" : ""}</span>}
          <label className="sort-ctl">
            <select value={sort} onChange={(e) => setSort(e.target.value)} aria-label="Trier">
              <option value="recent">Plus récents</option>
              <option value="price_asc">Prix ↑</option>
              <option value="price_desc">Prix ↓</option>
            </select>
          </label>
          <div className="view-toggle" role="tablist" aria-label="Mode d'affichage">
            <button role="tab" aria-selected={view === "liste"} className={view === "liste" ? "on" : ""} onClick={() => setView("liste")}>☰ Liste</button>
            <button role="tab" aria-selected={view === "carte"} className={view === "carte" ? "on" : ""} onClick={() => setView("carte")}>◈ Carte</button>
          </div>
        </div>
      </div>

      {error && (
        <div className="notice">
          <div className="big">⚠️</div>
          <h2>Impossible de charger les annonces</h2>
          <p>{error}</p>
          <button className="btn btn-primary" onClick={() => window.location.reload()}>Réessayer</button>
        </div>
      )}

      {!error && view === "liste" && listings === null && (
        <div className="grid" aria-busy="true">
          {Array.from({ length: 8 }).map((_, i) => (
            <div className="skel" key={i}><div className="sk-img" /><div className="sk-line" /><div className="sk-line short" /></div>
          ))}
        </div>
      )}

      {!error && view === "liste" && listings !== null && listings.length === 0 && (
        <div className="notice">
          <div className="big">🔍</div>
          <h2>Aucune propriété ne correspond</h2>
          <p>Essayez d'élargir vos critères
            {activeFilters > 0 && <> — ou <button className="link-btn" onClick={resetAll}>retirez les {activeFilters} filtres actifs</button></>}.</p>
        </div>
      )}

      {!error && view === "carte" && (
        <div className="map-split">
          <div className="map-list" aria-label="Résultats en liste">
            {(listings ?? []).map((l) => <ListingCard key={l.uid} l={l} />)}
          </div>
          <Suspense fallback={<div className="mapview map-loading">Chargement de la carte…</div>}>
            <MapView filters={filters} />
          </Suspense>
        </div>
      )}

      {!error && view === "liste" && listings !== null && listings.length > 0 && (
        <>
          <div className="grid">
            {listings.map((l) => <ListingCard key={l.uid} l={l} />)}
          </div>
          {totalPages > 1 && (
            <nav className="pager" aria-label="Pagination">
              <button className="pager-btn" onClick={() => gotoPage(page - 1)} disabled={page <= 1}>‹ Préc.</button>
              {pageNumbers(page, totalPages).map((p, i) =>
                p === "…"
                  ? <span key={`e${i}`} className="pager-gap">…</span>
                  : <button key={p} className={`pager-btn ${p === page ? "on" : ""}`}
                            onClick={() => gotoPage(p as number)}>{p}</button>
              )}
              <button className="pager-btn" onClick={() => gotoPage(page + 1)} disabled={page >= totalPages}>Suiv. ›</button>
              <span className="pager-info">Page {page} / {totalPages}</span>
            </nav>
          )}
        </>
      )}

      <button className="fab" onClick={() => setSheetOpen(true)} aria-label="Ouvrir les filtres">
        ⚙ Filtres{activeFilters > 0 ? ` · ${activeFilters}` : ""}
      </button>
    </div>
  );
}
