// -----------------------------------------------------------------------------
// Author: Simon-Pierre Boucher
// Contact: contact@spboucher.ai
// Project: Toit-Ka
// pages/Category.tsx : pages programmatiques /louer/{ville}[/{type}],
//   /acheter/{ville}[/{type}] et /{tx}/type/{type} — mêmes URL que le rendu
//   SEO serveur (toitka/seo.py), le SPA prend le relais au montage.
// -----------------------------------------------------------------------------
import { useEffect, useState } from "react";
import { Link, useParams, useSearchParams } from "react-router-dom";
import { Listing, Tx, fetchListings, fmtPrice, resolveSeo, setDocTitle } from "../api";
import ListingCard from "../components/ListingCard";
import { Ico } from "../components/Icons";

const PAGE_SIZE = 48;   // aligné sur toitka/seo.py

export default function CategoryPage({ tx }: { tx: Tx }) {
  const { ville, type } = useParams<{ ville?: string; type?: string }>();
  const [params, setParams] = useSearchParams();
  const page = Math.max(1, Number(params.get("page")) || 1);
  const louer = tx === "louer";

  const [labels, setLabels] = useState<{ city?: string; type?: string } | null>(null);
  const [listings, setListings] = useState<Listing[] | null>(null);
  const [total, setTotal] = useState(0);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    setLabels(null); setListings(null); setError(null);
    resolveSeo(tx, ville, type)
      .then(setLabels)
      .catch(() => setError("Page introuvable."));
  }, [tx, ville, type]);

  useEffect(() => {
    if (!labels) return;
    setListings(null);
    fetchListings(
      { tx, city: labels.city, type: labels.type, sort: "price_asc" },
      PAGE_SIZE, (page - 1) * PAGE_SIZE)
      .then((r) => { setListings(r.listings); setTotal(r.total); })
      .catch((e) => setError(String(e)));
    window.scrollTo(0, 0);
  }, [tx, labels, page]);

  const verbe = louer ? "à louer" : "à vendre";
  const noun = louer ? "Logements" : "Propriétés";
  const h1 = labels
    ? labels.city && labels.type
      ? `${labels.type} ${verbe} à ${labels.city}`
      : labels.city
        ? `${noun} ${verbe} à ${labels.city}`
        : `${labels.type} ${verbe} au Québec`
    : "";
  useEffect(() => { if (h1) setDocTitle(h1); }, [h1]);

  if (error)
    return (
      <div className="notice container">
        <div className="big"><Ico name="alert" size={44} /></div>
        <h2>Page introuvable</h2>
        <p>{error}</p>
        <Link className="btn btn-primary" to="/">Toutes les annonces</Link>
      </div>
    );

  const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
  const refine = new URLSearchParams({ tx });
  if (labels?.city) refine.set("city", labels.city);
  if (labels?.type) refine.set("type", labels.type);

  return (
    <div className="container">
      <nav className="crumbs" aria-label="Fil d'Ariane" style={{ margin: "14px 0 4px" }}>
        <Link to={`/?tx=${tx}`}>Accueil</Link>
        {labels?.city && ville && <> › <Link to={`/${tx}/${ville}`}>{verbe.charAt(0).toUpperCase() + verbe.slice(1)} à {labels.city}</Link></>}
        {labels?.type && <> › <span>{labels.type}</span></>}
      </nav>
      <h1>{h1 || "Chargement…"}</h1>
      {listings && (
        <p style={{ opacity: 0.75, margin: "6px 0 14px" }}>
          <b>{total.toLocaleString("fr-CA")}</b> annonces
          {listings.length > 0 && listings[0].price != null && (
            <> · à partir de <b>{fmtPrice(listings[0].price, tx)}</b></>
          )}
          {" · "}
          <Link to={`/?${refine}`}>Affiner la recherche (carte, filtres)</Link>
        </p>
      )}
      {!listings && !error && (
        <div className="grid" aria-busy="true">
          {Array.from({ length: 8 }).map((_, i) => (
            <div key={i} className="card skel"><div className="sk-img" /><div className="sk-line" /></div>
          ))}
        </div>
      )}
      {listings && (
        <div className="grid">
          {listings.map((l) => <ListingCard key={l.uid} l={l} />)}
        </div>
      )}
      {pages > 1 && (
        <nav className="pager" aria-label="Pagination" style={{ margin: "18px 0" }}>
          {page > 1 && (
            <button className="btn" onClick={() => setParams(page === 2 ? {} : { page: String(page - 1) })}>
              ← Précédente
            </button>
          )}
          <span style={{ margin: "0 10px" }}>Page {page} de {pages}</span>
          {page < pages && (
            <button className="btn" onClick={() => setParams({ page: String(page + 1) })}>
              Suivante →
            </button>
          )}
        </nav>
      )}
    </div>
  );
}
