// -----------------------------------------------------------------------------
// Immo-Ka — Agrégateur de propriétés à vendre (province de Québec)
// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
// pages/Listing.tsx : fiche complète d'une propriété
//   galerie + lightbox · specs · caractéristiques (details) · pièces ·
//   inclusions · description · historique de prix · courtier · mini-carte
// -----------------------------------------------------------------------------
import { Suspense, lazy, useEffect, useRef, useState } from "react";
import { Link, useParams } from "react-router-dom";
import {
  Listing, Room, fetchListing, fetchSources, fmtArea, fmtDate, fmtPrice,
  registerSourceNames, sourceName,
} from "../api";

const PropertyMap = lazy(() => import("../components/PropertyMap"));
import QuartierBlock from "../components/QuartierBlock";
import { Ico } 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 DETAIL_HIDDEN = new Set(["pieces", "price_from"]);

// icône de chaque tuile « spec » (Icons.tsx)
const SPEC_ICONS: Record<string, string> = {
  "Type": "home", "Chambres": "bed", "Salles de bain": "bath",
  "Salles d'eau": "drop", "Superficie": "area", "Terrain": "land",
  "Année": "calendar", "MLS / Centris": "tag",
};

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

  useEffect(() => {
    fetchSources().then((r) => registerSourceNames(r.sources)).catch(() => {});
    if (!uid) return;
    setL(null); setError(null);
    fetchListing(uid).then(setL).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>Propriété introuvable</h2>
        <p>{error}</p>
        <Link className="btn btn-primary" to="/">Retour aux propriétés</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 specs: { k: string; v: string }[] = [];
  if (l.property_type) specs.push({ k: "Type", v: l.property_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.powder_rooms != null) specs.push({ k: "Salles d'eau", v: String(l.powder_rooms) });
  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 (l.mls) specs.push({ k: "MLS / Centris", v: l.mls });

  const rooms: Room[] = Array.isArray(l.details?.pieces) ? (l.details!.pieces as Room[]) : [];
  const detEntries = Object.entries(l.details ?? {})
    .filter(([k, v]) => !DETAIL_HIDDEN.has(k) && (typeof v === "string" || typeof v === "number") && String(v).trim());

  const hist = (l.price_history ?? []).filter((h) => h.price != null);
  const baisse = hist.length >= 2 && hist[0].price !== hist[1].price
    ? { de: hist[1].price!, a: hist[0].price! } : null;
  const updated = l.updated_at ? fmtDate(l.updated_at) : null;

  return (
    <div className="container detail">
      <nav className="crumbs" aria-label="Fil d'Ariane">
        <Link to="/">Propriétés</Link> ›
        {l.city && <span>{l.city}</span>} ›
        <span>{l.address || l.title}</span>
      </nav>

      <div className="fiche">
        {/* -------- colonne gauche : galerie, description, caractéristiques ---- */}
        <div className="f-col">
          <section className="f-bloc f-galerie" aria-label="Photos">
            <Galerie images={l.images ?? []} titre={l.address || l.title} />
          </section>

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

          {detEntries.length > 0 && (
            <section className="f-bloc" id="caracteristiques">
              <h2>Caractéristiques</h2>
              <div className="dtable">
                {detEntries.map(([k, v]) => (
                  <div className="drow" key={k}><span>{k}</span><b>{String(v)}</b></div>
                ))}
              </div>
            </section>
          )}

          {rooms.length > 0 && (
            <section className="f-bloc" id="pieces">
              <h2>Pièces</h2>
              <div className="rooms-wrap">
                <table className="rooms">
                  <thead><tr><th>Pièce</th><th>Niveau</th><th>Dimensions</th><th>Revêtement</th></tr></thead>
                  <tbody>
                    {rooms.map((r, i) => (
                      <tr key={i}>
                        <td>{r.nom || "—"}</td><td>{r.niveau || "—"}</td>
                        <td>{r.dimensions || "—"}</td><td>{r.revetement || "—"}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>
          )}

          {l.features && l.features.length > 0 && (
            <section className="f-bloc" id="inclusions">
              <h2>Inclusions</h2>
              <div className="amenity-row">
                {l.features.map((f, i) => <span className="amenity" key={i}><Ico name="check" size={13} /> {f}</span>)}
              </div>
            </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}
                    deal={l.price != null && l.vraiprix?.value != null
                          && l.price <= l.vraiprix.value * 0.95}
                  />
                </Suspense>
              </div>
            </section>
          )}

        </div>

        {/* -------- colonne droite : synthèse, specs, courtier ---------------- */}
        <div className="f-col">
          <section className="f-bloc f-hero">
            <div className="price">{fmtPrice(l.price, l.price_label)}</div>
            {l.property_type && <div className="deal-badge deal-ok">{l.property_type}{l.details?.price_from ? " · à partir de" : ""}</div>}
            <h1>{l.address || l.title}</h1>
            <div className="loc">{[l.sector, l.city, l.region].filter(Boolean).join(" · ")}</div>

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

            {baisse && (
              <div className={`prix-histo ${baisse.a < baisse.de ? "down" : ""}`}>
                <Ico name={baisse.a < baisse.de ? "trenddown" : "trendup"} size={16} /> Prix passé de {fmtPrice(baisse.de)} à <b>{fmtPrice(baisse.a)}</b>
              </div>
            )}

            {l.vraiprix && l.vraiprix.value != null && (
              <div className="vraiprix">
                <div className="vp-head">
                  <span className="vp-logo">Vrai‑Prix</span>
                  {l.vraiprix.confidence && (
                    <span className={`vp-conf vp-conf-${l.vraiprix.confidence}`}>
                      confiance {l.vraiprix.confidence}
                    </span>
                  )}
                </div>
                <div className="vp-k">Valeur marchande estimée</div>
                <div className="vp-value">{fmtPrice(l.vraiprix.value)}</div>
                {l.vraiprix.low != null && l.vraiprix.high != null && (
                  <div className="vp-range">
                    fourchette {fmtPrice(l.vraiprix.low)} – {fmtPrice(l.vraiprix.high)}
                  </div>
                )}
                {l.price != null && (
                  (() => {
                    const diff = l.price - (l.vraiprix!.value as number);
                    const pct = Math.round((diff / (l.vraiprix!.value as number)) * 100);
                    const cls = diff > 0 ? "over" : "under";
                    const txt = diff > 0
                      ? `Prix demandé ${pct}% au-dessus de l'estimation`
                      : `Prix demandé ${Math.abs(pct)}% sous l'estimation`;
                    return Math.abs(pct) >= 1
                      ? <div className={`vp-delta vp-${cls}`}>{diff > 0 ? "▲" : "▼"} {txt}</div>
                      : <div className="vp-delta vp-fair">≈ Prix aligné sur l'estimation</div>;
                  })()
                )}
                <a className="vp-link" href={l.vraiprix.url} target="_blank" rel="noopener noreferrer">
                  Voir l'analyse détaillée ↗
                </a>
              </div>
            )}

            {(l.broker_name || l.broker_phone) && (
              <div className="broker">
                <div className="broker-k">Courtier</div>
                {l.broker_name && <div className="broker-name">{l.broker_name}</div>}
                {l.broker_phone && <a className="broker-tel" href={`tel:${l.broker_phone.replace(/\s/g, "")}`}><Ico name="phone" size={14} /> {l.broker_phone}</a>}
              </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 Immo-Ka — {sourceName(l.source)}{updated ? ` · synchronisé le ${updated}` : ""}.
            </div>
          </section>
        </div>
      </div>

      {/* quartier : pleine largeur, APRÈS les infos de propriété (ordre mobile correct) */}
      {l.quartier && <QuartierBlock q={l.quartier} />}

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

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