// -----------------------------------------------------------------------------
// Auto-Ka — Agrégateur de voitures usagées à vendre (province de Québec)
// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
// Vehicle.tsx : fiche véhicule — galerie, specs, historique de prix, similaires
// -----------------------------------------------------------------------------
import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { VehicleDetail, fetchVehicle, fmtDate, fmtKm, fmtPrice } from "../api";
import VehicleCard from "../components/VehicleCard";

export default function VehiclePage() {
  const { uid } = useParams<{ uid: string }>();
  const [v, setV] = useState<VehicleDetail | null>(null);
  const [error, setError] = useState(false);
  const [img, setImg] = useState(0);

  useEffect(() => {
    setV(null); setError(false); setImg(0);
    if (uid) fetchVehicle(uid).then(setV).catch(() => setError(true));
    window.scrollTo(0, 0);
  }, [uid]);

  if (error)
    return (
      <div className="notice container">
        <div className="big">🚗</div>
        <h2>Véhicule introuvable</h2>
        <p>Il a peut-être été vendu — l'inventaire évolue chaque jour.</p>
        <p><Link to="/" className="btn ghost">← Retour à la recherche</Link></p>
      </div>
    );

  if (!v)
    return (
      <div className="container vdetail">
        <div className="skeleton" style={{ height: 60, marginBottom: 20 }} />
        <div className="vd-cols">
          <div className="skeleton" style={{ height: 460 }} />
          <div className="skeleton" style={{ height: 460 }} />
        </div>
      </div>
    );

  const prevPrice = v.price_history.find(
    (h) => h.price != null && v.price != null && h.price !== v.price
  )?.price;

  const specs: [string, string][] = [
    ["Année", v.year ? String(v.year) : "—"],
    ["Kilométrage", fmtKm(v.mileage_km)],
    ["Transmission", v.transmission || "—"],
    ["Carburant", v.fuel || "—"],
    ["Motricité", v.drivetrain || "—"],
    ["Carrosserie", v.body_type || "—"],
    ["Moteur", v.engine || "—"],
    ["Couleur ext.", v.exterior_color || "—"],
    ["Couleur int.", v.interior_color || "—"],
    ["Portes", v.doors ? String(v.doors) : "—"],
    ["Places", v.seats ? String(v.seats) : "—"],
    ["NIV (VIN)", v.vin || "—"],
    ["No de stock", v.stock_number || "—"],
  ].filter(([, val]) => val !== "—") as [string, string][];

  return (
    <div className="container vdetail">
      <p style={{ marginTop: 0 }}>
        <Link to="/" className="mono" style={{ fontSize: 12 }}>← Retour à la recherche</Link>
      </p>
      <div className="vd-head">
        <div>
          <span className="kicker">{v.dealer_name || v.source} — {v.city}{v.region ? ` · ${v.region}` : ""}</span>
          <h1>{v.title}</h1>
        </div>
        <div className="vd-price">
          <div className="p">{fmtPrice(v.price)}</div>
          {prevPrice != null && v.price != null && prevPrice > v.price && (
            <div className="was">{fmtPrice(prevPrice)}</div>
          )}
        </div>
      </div>

      <div className="vd-cols">
        <div>
          <div className="gallery">
            <div className="main">
              {v.images.length > 0 ? (
                <a href={v.images[img]} target="_blank" rel="noreferrer">
                  <img src={v.images[img]} alt={v.title} />
                </a>
              ) : (
                <div className="nopic" style={{ display: "grid", placeItems: "center", height: "100%", fontSize: 60 }}>🚗</div>
              )}
            </div>
            {v.images.length > 1 && (
              <div className="thumbs">
                {v.images.map((u, i) => (
                  <img
                    key={u}
                    src={u}
                    alt={`photo ${i + 1}`}
                    loading="lazy"
                    className={i === img ? "sel" : ""}
                    onClick={() => setImg(i)}
                  />
                ))}
              </div>
            )}
          </div>

          {v.description && (
            <div className="panel" style={{ marginTop: 18 }}>
              <h3>📝 Description du concessionnaire</h3>
              <div className="desc">{v.description}</div>
            </div>
          )}
        </div>

        <div>
          <div className="panel">
            <h3>🔧 Caractéristiques</h3>
            <table className="spec-table">
              <tbody>
                {specs.map(([k, val]) => (
                  <tr key={k}>
                    <td>{k}</td>
                    <td>{val}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            <a className="cta-source" href={v.url} target="_blank" rel="noreferrer">
              Voir chez {v.dealer_name || "le concessionnaire"} →
            </a>
            {v.carfax_url && (
              <a
                className="cta-source"
                style={{ background: "var(--surface)", color: "var(--ink)", marginTop: 10 }}
                href={v.carfax_url}
                target="_blank"
                rel="noreferrer"
              >
                📋 Rapport Carfax
              </a>
            )}
            <div className="cta-note">
              annonce originale — prix et disponibilité confirmés à la source
            </div>
          </div>

          {v.features.length > 0 && (
            <div className="panel">
              <h3>✨ Équipements ({v.features.length})</h3>
              <div className="feat-list">
                {v.features.map((f) => (
                  <span key={f} className="spec-chip">{f}</span>
                ))}
              </div>
            </div>
          )}

          {v.price_history.length > 1 && (
            <div className="panel">
              <h3>📉 Historique de prix</h3>
              <div className="price-history">
                {v.price_history.map((h, i) => {
                  const next = v.price_history[i + 1];
                  const dir =
                    next?.price != null && h.price != null
                      ? h.price < next.price ? "down" : h.price > next.price ? "up" : ""
                      : "";
                  return (
                    <div key={h.ts} className="row">
                      <span>{fmtDate(h.ts)}</span>
                      <span className={dir}>{fmtPrice(h.price)}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          <div className="panel">
            <h3>ℹ️ Suivi Auto-Ka</h3>
            <table className="spec-table">
              <tbody>
                <tr><td>Repéré le</td><td>{fmtDate(v.first_seen)}</td></tr>
                <tr><td>Vérifié le</td><td>{fmtDate(v.updated_at)}</td></tr>
                <tr><td>Statut</td><td>{v.active ? "En vente" : "Retiré / vendu"}</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {v.similar.length > 0 && (
        <section style={{ marginTop: 40 }}>
          <span className="kicker">Comparer</span>
          <h2 style={{ margin: "8px 0 18px" }}>
            {v.make} {v.model} similaires au Québec
          </h2>
          <div className="vgrid">
            {v.similar.map((s) => (
              <VehicleCard key={s.uid} v={s} />
            ))}
          </div>
        </section>
      )}
    </div>
  );
}
