// -----------------------------------------------------------------------------
// Author: Simon-Pierre Boucher
// Contact: contact@spboucher.ai
// Project: Toit-Ka
// pages/Listing.tsx : fiche complète d'une annonce — bi-univers.
//   galerie + lightbox · specs adaptées (loyer/animaux/meublé vs prix/MLS/
//   courtier) · description · mini-carte · CTA vers l'annonce originale.
// -----------------------------------------------------------------------------
import { Suspense, lazy, useEffect, useRef, useState } from "react";
import { Link, useParams } from "react-router-dom";
import {
  Listing, fetchListing, fmtArea, fmtDate, fmtPrice, setDocTitle, setMode,
  slugify, sourceName,
} from "../api";

const PropertyMap = lazy(() => import("../components/PropertyMap"));
import { useAccount } from "../account";
import { Ico, IcoHeart } from "../components/Icons";

// --- Galerie : balayage natif (scroll-snap) + vignettes + plein écran --------
function Galerie({ images, titre }: { images: string[]; titre: string }) {
  const [idx, setIdx] = useState(0);
  const [zoom, setZoom] = useState(false);
  const track = useRef<HTMLDivElement>(null);

  const onScroll = () => {
    const el = track.current;
    if (el) setIdx(Math.round(el.scrollLeft / el.clientWidth));
  };
  const goto = (i: number) =>
    track.current?.scrollTo({ left: i * track.current.clientWidth, behavior: "smooth" });

  useEffect(() => {
    if (!zoom) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setZoom(false);
      if (e.key === "ArrowLeft") setIdx((i) => Math.max(0, i - 1));
      if (e.key === "ArrowRight") setIdx((i) => Math.min(images.length - 1, i + 1));
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [zoom, images.length]);

  if (images.length === 0)
    return <div className="carousel"><div className="noimg carousel-empty"><Ico name="home" size={44} /></div></div>;

  return (
    <>
      <div className="carousel">
        <div className="carousel-track" ref={track} onScroll={onScroll}>
          {images.map((u, i) => (
            <img key={u} src={u} loading={i === 0 ? "eager" : "lazy"}
              alt={`${titre} — photo ${i + 1} de ${images.length}`} onClick={() => setZoom(true)} />
          ))}
        </div>
        <span className="carousel-count" aria-live="polite">{idx + 1}/{images.length}</span>
        {idx > 0 && <button className="carousel-nav prev" aria-label="Photo précédente" onClick={() => goto(idx - 1)}>‹</button>}
        {idx < images.length - 1 && <button className="carousel-nav next" aria-label="Photo suivante" onClick={() => goto(idx + 1)}>›</button>}
      </div>
      {images.length > 1 && (
        <div className="thumbs">
          {images.map((u, i) => (
            <button key={u} className={i === idx ? "on" : ""} onClick={() => goto(i)} aria-label={`Photo ${i + 1}`}>
              <img src={u} alt="" loading="lazy" />
            </button>
          ))}
        </div>
      )}
      {zoom && (
        <div className="lightbox" onClick={() => setZoom(false)} role="dialog" aria-label="Photo agrandie">
          <button className="lb-close" aria-label="Fermer" onClick={() => setZoom(false)}>✕</button>
          {idx > 0 && <button className="lb-nav prev" aria-label="Précédente" onClick={(e) => { e.stopPropagation(); setIdx(idx - 1); }}>‹</button>}
          <img src={images[idx]} alt="" onClick={(e) => e.stopPropagation()} />
          {idx < images.length - 1 && <button className="lb-nav next" aria-label="Suivante" onClick={(e) => { e.stopPropagation(); setIdx(idx + 1); }}>›</button>}
          <span className="lb-count">{idx + 1} / {images.length}</span>
        </div>
      )}
    </>
  );
}

const SPEC_ICONS: Record<string, string> = {
  "Type": "home", "Chambres": "bed", "Salles de bain": "bath",
  "Superficie": "area", "Terrain": "land", "Année": "calendar",
  "MLS / Centris": "tag", "Animaux": "paw", "Meublé": "sofa",
  "Disponibilité": "calendar", "Agence": "building",
};

export default function ListingPage() {
  const { uid } = useParams<{ uid: string }>();
  const [l, setL] = useState<Listing | null>(null);
  const [error, setError] = useState<string | null>(null);
  const { favs, toggleFav } = useAccount();

  useEffect(() => {
    if (!uid) return;
    setL(null); setError(null);
    fetchListing(uid)
      .then((d) => {
        setL(d);
        setMode(d.transaction_type);
        setDocTitle(`${d.address || d.title} — ${d.type || "Annonce"} ${
          d.transaction_type === "louer" ? "à louer" : "à vendre"}, ${d.city || "Québec"}`);
      })
      .catch((e) => setError(String(e)));
    window.scrollTo(0, 0);
  }, [uid]);

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

  if (!l)
    return (
      <div className="container detail">
        <div className="fiche" aria-busy="true">
          <div className="skel"><div className="sk-img" /></div>
          <div className="skel"><div className="sk-line" /><div className="sk-line" /><div className="sk-line short" /></div>
        </div>
      </div>
    );

  const louer = l.transaction_type === "louer";
  const tx = l.transaction_type;

  const specs: { k: string; v: string }[] = [];
  if (l.type) specs.push({ k: "Type", v: l.type });
  if (l.bedrooms != null) specs.push({ k: "Chambres", v: String(l.bedrooms) });
  if (l.bathrooms != null) specs.push({ k: "Salles de bain", v: String(l.bathrooms) });
  if (l.area_sqft != null) specs.push({ k: "Superficie", v: fmtArea(l.area_sqft)! });
  if (l.lot_sqft != null) specs.push({ k: "Terrain", v: fmtArea(l.lot_sqft)! });
  if (l.year_built != null) specs.push({ k: "Année", v: String(l.year_built) });
  if (louer && l.pets) specs.push({ k: "Animaux", v: l.pets });
  if (louer && l.furnished != null) specs.push({ k: "Meublé", v: l.furnished === 1 ? "oui" : "non" });
  if (louer && l.availability_date)
    specs.push({ k: "Disponibilité", v: l.availability_date === "now" ? "maintenant" : l.availability_date });
  if (l.mls) specs.push({ k: "MLS / Centris", v: l.mls });
  if (l.agency) specs.push({ k: "Agence", v: l.agency });

  const updated = l.updated_at ? fmtDate(l.updated_at) : null;
  const cityHref = l.city ? `/${tx}/${slugify(l.city)}` : "/";

  return (
    <div className="container detail">
      <nav className="crumbs" aria-label="Fil d'Ariane">
        <Link to={`/?tx=${tx}`}>{louer ? "À louer" : "À vendre"}</Link> ›
        {l.city && <Link to={cityHref}>{l.city}</Link>} ›
        <span>{l.address || l.title}</span>
      </nav>

      <div className="fiche">
        {/* -------- colonne gauche : galerie, description ---------------------- */}
        <div className="f-col">
          <section className="f-bloc f-galerie" aria-label="Photos" style={{ position: "relative" }}>
            <Galerie images={l.images ?? []} titre={l.address || l.title} />
            <button
              className={`fav-btn fav-fiche ${favs.has(l.uid) ? "on" : ""}`}
              aria-label={favs.has(l.uid) ? "Retirer des favoris" : "Ajouter aux favoris"}
              aria-pressed={favs.has(l.uid)}
              onClick={() => toggleFav(l)}
            >
              <IcoHeart size={19} filled={favs.has(l.uid)} />
            </button>
          </section>

          {l.description && (
            <section className="f-bloc f-desc" id="description">
              <h2>Description</h2>
              <p className="desc-text">{l.description}</p>
            </section>
          )}

          {l.lat != null && l.lng != null && (
            <section className="f-bloc" id="carte">
              <h2>Emplacement</h2>
              <div className="mini-map">
                <Suspense fallback={<div className="mapview map-loading">Chargement de la carte…</div>}>
                  <PropertyMap lat={l.lat} lng={l.lng} price={l.price} tx={tx} />
                </Suspense>
              </div>
            </section>
          )}
        </div>

        {/* -------- colonne droite : synthèse, specs, CTA ----------------------- */}
        <div className="f-col">
          <section className="f-bloc f-hero">
            <div className="price-kicker">{louer ? "Loyer demandé" : "Prix demandé"}</div>
            <div className="price-row">
              <div className="price">
                {l.price != null
                  ? <>{l.price.toLocaleString("fr-CA", { maximumFractionDigits: 0 })} $
                      {louer && <em> /mois</em>}</>
                  : (l.price_label || "Prix sur demande")}
              </div>
              {l.type && (
                <span className="type-chip">
                  <Ico name="home" size={13} /> {l.type}
                </span>
              )}
            </div>
            {!louer && l.price != null && l.area_sqft != null && l.area_sqft > 200 && (
              <div className="price-sub">{Math.round(l.price / l.area_sqft).toLocaleString("fr-CA")} $ / pi² habitable</div>
            )}
            <h1>{l.address || l.title}</h1>
            <div className="loc"><Ico name="pin" size={13} /> {[l.sector, l.city].filter(Boolean).join(" · ")}</div>

            <div className="spec-list">
              {specs.map((s) => (
                <div className="spec-row" key={s.k}>
                  <span className="spec-badge"><Ico name={SPEC_ICONS[s.k] ?? "tag"} size={15} /></span>
                  <span className="spec-k">{s.k}</span>
                  <b className="spec-v">{s.v}</b>
                </div>
              ))}
            </div>

            {(l.broker_name) && (
              <div className="broker">
                <div className="broker-k">Courtier</div>
                <div className="broker-name">{l.broker_name}</div>
              </div>
            )}

            <a className="cta" href={l.url} target="_blank" rel="noopener noreferrer">
              Voir l'annonce chez {sourceName(l.source)} <Ico name="external" size={15} />
            </a>
            <div className="fine">
              Agrégé par Toit-Ka — {sourceName(l.source)}{updated ? ` · synchronisé le ${updated}` : ""}.
            </div>
          </section>
        </div>
      </div>

      <div className="fine f-foot">
        Les {louer ? "loyers" : "prix"} et disponibilités sont ceux affichés par la source —
        chaque fiche renvoie à l'annonce originale.
      </div>

      <div className="cta-sticky">
        <span className="cta-sticky-prix">{fmtPrice(l.price, tx, l.price_label)}</span>
        <a className="cta" href={l.url} target="_blank" rel="noopener noreferrer">
          Voir chez {sourceName(l.source)} ↗
        </a>
      </div>
    </div>
  );
}
