// -----------------------------------------------------------------------------
// Author: Simon-Pierre Boucher
// Contact: contact@spboucher.ai
// Project: Toit-Ka
// pages/Home.tsx : accueil — LE commutateur Louer/Acheter, héros, filtres
//   adaptés à l'univers, grille + carte. L'accent du site suit le toggle.
// -----------------------------------------------------------------------------
import { Suspense, lazy, useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "react-router-dom";
import {
  Facets, Listing, ListingFilters, Stats, Tx,
  fetchFacets, fetchListings, fetchStats, setDocTitle, setMode, sourceName,
} from "../api";
import ListingCard from "../components/ListingCard";
import { Ico } from "../components/Icons";

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

const PRICE_STEPS: Record<Tx, number[]> = {
  louer: [500, 700, 900, 1100, 1300, 1500, 1800, 2200, 2600, 3000, 4000],
  acheter: [100000, 200000, 300000, 400000, 500000, 600000, 750000, 1000000, 1500000, 2000000, 3000000],
};
const AREA_STEPS = [500, 800, 1000, 1500, 2000, 3000];
const PAGE = 12;

const fmtStep = (n: number, tx: Tx) =>
  tx === "acheter"
    ? (n >= 1_000_000 ? `${n / 1_000_000} M$` : `${Math.round(n / 1000)} k$`)
    : `${n.toLocaleString("fr-CA")} $`;

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;
}

/** Valeur retardée : évite une requête API à chaque frappe de recherche. */
function useDebounced<T>(value: T, delayMs = 300): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setDebounced(value), delayMs);
    return () => clearTimeout(t);
  }, [value, delayMs]);
  return debounced;
}

export default function Home() {
  const [params, setParams] = useSearchParams();
  const [tx, setTx] = useState<Tx>(params.get("tx") === "acheter" ? "acheter" : "louer");
  // le toggle est LE geste central : il bascule aussi l'identité du site
  useEffect(() => { setMode(tx); setDocTitle(
    tx === "louer" ? "Logements à louer au Québec" : "Propriétés à vendre au Québec");
  }, [tx]);
  useEffect(() => {
    const urlTx = params.get("tx") === "acheter" ? "acheter" : "louer";
    setTx(urlTx);
  }, [params]);

  const [listings, setListings] = useState<Listing[] | null>(null);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(Number(params.get("page")) || 1);
  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 [q, setQ] = useState(params.get("q") ?? "");
  const [city, setCity] = useState(params.get("city") ?? "");
  const [sector, setSector] = useState(params.get("sector") ?? "");
  const [type, setType] = useState(params.get("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 [pets, setPets] = useState(params.get("pets") ?? "");
  const [furnished, setFurnished] = useState(params.get("furnished") ?? "");
  const [sort, setSort] = useState(params.get("sort") ?? "recent");

  const [sheetOpen, setSheetOpen] = useState(false);
  const [advOpen, setAdvOpen] = useState(false);
  const activeFilters = [q, city, sector, type, source, priceMin, priceMax,
    bedsMin, bathsMin, areaMin, pets, furnished].filter(Boolean).length;
  const advCount = [bedsMin, bathsMin, areaMin, source, sector, pets, furnished].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 qDebounced = useDebounced(q);
  const filters: ListingFilters = useMemo(() => ({
    tx, q: qDebounced, city, sector, type, source,
    price_min: priceMin, price_max: priceMax,
    bedrooms_min: bedsMin, bathrooms_min: bathsMin, area_min: areaMin,
    pets, furnished, sort,
  }), [tx, qDebounced, city, sector, type, source, priceMin, priceMax,
       bedsMin, bathsMin, areaMin, pets, furnished, sort]);

  // sélection carte <-> liste
  const [mapSelectedUid, setMapSelectedUid] = useState<string | null>(null);
  const [mapHoveredUid, setMapHoveredUid] = useState<string | null>(null);
  const mapListRef = useRef<HTMLDivElement | null>(null);
  useEffect(() => {
    if (!mapSelectedUid) return;
    mapListRef.current
      ?.querySelector(`[data-uid="${CSS.escape(mapSelectedUid)}"]`)
      ?.scrollIntoView({ behavior: "smooth", block: "nearest" });
  }, [mapSelectedUid]);

  useEffect(() => {
    fetchStats().then(setStats).catch(() => {});
  }, []);

  // les facettes (villes, types, sources) dépendent de l'univers
  useEffect(() => {
    fetchFacets(tx).then(setFacets).catch(() => {});
  }, [tx]);

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

  // changer d'univers : purge les filtres propres à l'autre univers
  const switchTx = (next: Tx) => {
    if (next === tx) return;
    setTx(next);
    setType(""); setSource(""); setSector("");
    setPriceMin(""); setPriceMax("");
    setPets(""); setFurnished(""); setBedsMin(""); setBathsMin("");
    setPage(1);
  };

  const firstRender = useRef(true);
  useEffect(() => {
    if (firstRender.current) { firstRender.current = false; return; }
    setPage(1);
  }, [filters]);

  // synchroniser filtres + page + tri + vue dans l'URL
  useEffect(() => {
    const p = new URLSearchParams();
    const set = (k: string, v: string) => { if (v) p.set(k, v); };
    p.set("tx", tx);
    set("q", q); set("city", city); set("sector", sector);
    set("type", type); set("source", source);
    set("price_min", priceMin); set("price_max", priceMax);
    set("bedrooms_min", bedsMin); set("bathrooms_min", bathsMin);
    set("area_min", areaMin); set("pets", pets); set("furnished", furnished);
    if (sort && sort !== "recent") p.set("sort", sort);
    if (view === "carte") p.set("view", "carte");
    if (page > 1) p.set("page", String(page));
    setParams(p, { replace: true });
  }, [filters, page, view, tx, q, city, sector, type, source, priceMin, priceMax,
      bedsMin, bathsMin, areaMin, pets, furnished, sort, setParams]);

  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(""); setType(""); setSource("");
    setPriceMin(""); setPriceMax(""); setBedsMin(""); setBathsMin("");
    setAreaMin(""); setPets(""); setFurnished("");
  };

  const louer = tx === "louer";
  const txStats = stats ? stats[tx] : null;

  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 (type) pills.push({ label: type, clear: () => setType("") });
  if (priceMin) pills.push({ label: `≥ ${fmtStep(Number(priceMin), tx)}`, clear: () => setPriceMin("") });
  if (priceMax) pills.push({ label: `≤ ${fmtStep(Number(priceMax), tx)}`, 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 (pets) pills.push({ label: "animaux acceptés", clear: () => setPets("") });
  if (furnished) pills.push({ label: furnished === "1" ? "meublé" : "non meublé", clear: () => setFurnished("") });
  if (source) pills.push({ label: sourceName(source), clear: () => setSource("") });

  const topTypes = (facets?.types ?? []).slice(0, 8).map((t) => t.type);
  const priceSteps = PRICE_STEPS[tx];

  return (
    <div className="container">
      <section className="hero">
        <span className="kicker">Lou-Ka × Immo-Ka — la fusion</span>
        <h1>
          Un <span className="outline">toit</span> au Québec.<br />
          <span className="hl">{louer ? "Louer" : "Acheter"}</span>, un seul endroit.
        </h1>
        <p className="lede">
          {louer
            ? "Toit-Ka rassemble les logements à louer affichés par les gestionnaires immobiliers, courtiers et plateformes du Québec — mis à jour automatiquement, avec un lien direct vers l'annonce originale."
            : "Toit-Ka rassemble les propriétés à vendre affichées par les agences de courtage et plateformes du Québec — RE/MAX, Sutton, Via Capitale, Proprio Direct et plus — avec un lien direct vers l'annonce originale."}
        </p>

        <div style={{ marginTop: 24 }}>
          <div className="tx-toggle" role="tablist" aria-label="Louer ou acheter">
            <button role="tab" aria-selected={louer} className={louer ? "on" : ""}
                    onClick={() => switchTx("louer")}>
              <span className="tt-dot louer" aria-hidden="true" /> Louer
            </button>
            <button role="tab" aria-selected={!louer} className={!louer ? "on" : ""}
                    onClick={() => switchTx("acheter")}>
              <span className="tt-dot acheter" aria-hidden="true" /> Acheter
            </button>
          </div>
        </div>

        <div className="stat-row">
          <span className="stat-chip"><span className="pulse" /> Synchronisé en continu</span>
          {txStats && (
            <>
              <span className="stat-chip"><b>{txStats.total.toLocaleString("fr-CA")}</b> annonces</span>
              <span className="stat-chip"><b>{txStats.cities.toLocaleString("fr-CA")}</b> villes</span>
              <span className="stat-chip"><b>{txStats.sources}</b> sources</span>
              {txStats.avg_price != null && (
                <span className="stat-chip">{louer ? "loyer moyen" : "prix moyen"}{" "}
                  <b>{Math.round(txStats.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">
            <Ico name="search" size={15} />
            <input id="f-q" placeholder={louer ? "Adresse, ville, quartier…" : "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.city} value={c.city}>{c.city} ({c.n})</option>
              ))}
            </select>
          </label>
          <label className="f-ctl">
            <span>Type</span>
            <select value={type} onChange={(e) => setType(e.target.value)}>
              <option value="">Tous</option>
              {(facets?.types ?? []).map((t) => (
                <option key={t.type} value={t.type}>{t.type} ({t.n})</option>
              ))}
            </select>
          </label>
          <div className="f-ctl">
            <span>{louer ? "Loyer" : "Prix"}</span>
            <div className="range-pair">
              <select aria-label="Prix minimum" value={priceMin} onChange={(e) => setPriceMin(e.target.value)}>
                <option value="">Min</option>
                {priceSteps.map((p) => (
                  <option key={p} value={p} disabled={!!priceMax && p >= Number(priceMax)}>{fmtStep(p, tx)}</option>
                ))}
              </select>
              <span className="range-sep">—</span>
              <select aria-label="Prix maximum" value={priceMax} onChange={(e) => setPriceMax(e.target.value)}>
                <option value="">Max</option>
                {priceSteps.map((p) => (
                  <option key={p} value={p} disabled={!!priceMin && p <= Number(priceMin)}>{fmtStep(p, tx)}</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>
            {louer ? (
              <>
                <div className="f-group">
                  <label>Animaux</label>
                  <div className="seg" role="group">
                    <button className={pets === "" ? "on" : ""} onClick={() => setPets("")}>Peu importe</button>
                    <button className={pets === "oui" ? "on" : ""} onClick={() => setPets(pets === "oui" ? "" : "oui")}>Acceptés</button>
                  </div>
                </div>
                <div className="f-group">
                  <label>Meublé</label>
                  <div className="seg" role="group">
                    <button className={furnished === "" ? "on" : ""} onClick={() => setFurnished("")}>Peu importe</button>
                    <button className={furnished === "1" ? "on" : ""} onClick={() => setFurnished(furnished === "1" ? "" : "1")}>Meublé</button>
                    <button className={furnished === "0" ? "on" : ""} onClick={() => setFurnished(furnished === "0" ? "" : "0")}>Non meublé</button>
                  </div>
                </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>Source</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 ${type === t ? "on" : ""}`} onClick={() => setType(type === 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>{louer ? "Logements à louer" : "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">{louer ? "Loyer" : "Prix"} ↑</option>
              <option value="price_desc">{louer ? "Loyer" : "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"><Ico name="alert" size={40} /></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"><Ico name="search" size={40} /></div>
          <h2>Aucune annonce 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" ref={mapListRef}>
            {(listings ?? []).map((l) => (
              <div
                key={l.uid}
                data-uid={l.uid}
                className={`map-card${mapSelectedUid === l.uid ? " map-card-sel" : ""}`}
                onMouseEnter={() => setMapHoveredUid(l.uid)}
                onMouseLeave={() => setMapHoveredUid((h) => (h === l.uid ? null : h))}
              >
                <ListingCard l={l} />
              </div>
            ))}
          </div>
          <Suspense fallback={<div className="mapview map-loading">Chargement de la carte…</div>}>
            <MapView
              filters={filters}
              selectedUid={mapSelectedUid}
              hoveredUid={mapHoveredUid}
              onSelect={setMapSelectedUid}
            />
          </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>
  );
}
