// -----------------------------------------------------------------------------
// Forma-Ka — Agrégateur de formations (province de Québec)
// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
// pages/Formation.tsx : fiche d'une formation — l'accent est mis sur les
//   DÉTAILS (le prix est souvent absent, p. ex. cours universitaires) :
//   description → objectifs → plan de cours → préalables → clientèle →
//   infos pratiques. Colonne droite : synthèse, dates offertes, CTA source,
//   formations similaires. CTA sticky en bas d'écran (mobile).
// -----------------------------------------------------------------------------
import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import {
  Formation, MODE_ICONS, fetchFormation, fetchSources, fmtDate, fmtHours,
  fmtPrice, registerSourceNames, sourceName,
} from "../api";

const NBSP = " ";

export default function FormationPage() {
  const { uid } = useParams<{ uid: string }>();
  const [f, setF] = useState<Formation | null>(null);
  const [error, setError] = useState<string | null>(null);
  // re-rendu quand le registre des noms de sources est chargé
  const [, setSourcesReady] = useState(false);

  useEffect(() => {
    fetchSources()
      .then((r) => { registerSourceNames(r.sources); setSourcesReady(true); })
      .catch(() => {});
    if (!uid) return;
    fetchFormation(uid).then(setF).catch((e) => setError(String(e)));
    window.scrollTo(0, 0);
  }, [uid]);

  if (error)
    return (
      <div className="notice container">
        <div className="big">⚠️</div>
        <h2>Formation introuvable</h2>
        <p>{error}</p>
        <Link className="btn btn-primary" to="/">Retour aux formations</Link>
      </div>
    );

  if (!f)
    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 updated = f.updated_at
    ? new Date(f.updated_at * 1000).toLocaleDateString("fr-CA", {
        day: "numeric", month: "long", year: "numeric" }) : null;

  // chips clés — tout ce qui décrit la formation d'un coup d'œil
  const chips: string[] = [];
  if (f.training_type) chips.push(f.training_type);
  if (f.mode) chips.push(`${MODE_ICONS[f.mode] ?? ""} ${f.mode}`.trim());
  const dur = f.duration || fmtHours(f.duration_hours);
  if (dur) chips.push(dur);
  if (f.credits) chips.push(f.credits);
  if (f.level) chips.push(`Niveau ${f.level}`);
  if (f.language) chips.push(f.language === "fr" ? "Français" : f.language === "en" ? "Anglais" : f.language);
  if (f.city) chips.push(f.city);
  if (f.code) chips.push(f.code);

  const sessions = (f.sessions ?? []).filter(Boolean);
  const img = f.images && f.images.length > 0 ? f.images[0] : null;

  return (
    <div className="container detail">
      <nav className="crumbs" aria-label="Fil d'Ariane">
        <Link to="/">Formations</Link> ›
        {f.category && <span>{f.category}</span>} ›
        <span>{f.title}</span>
      </nav>

      <div className="fiche">
        {/* ------- colonne gauche (desktop) : les DÉTAILS de la formation ---- */}
        <div className="f-col">
          {img && (
            <section className="f-bloc f-galerie" aria-label="Visuel">
              <div className="carousel">
                <div className="carousel-track">
                  <img src={img} alt={f.title} loading="eager" />
                </div>
              </div>
            </section>
          )}

          <section className="f-bloc f-desc" id="description">
            <h2>Description</h2>
            {f.description
              ? f.description.split(/\n{2,}/).map((p, i) => (
                  <p key={i} style={{ color: "var(--ink-2)" }}>{p}</p>
                ))
              : <p className="fine">La source ne fournit pas de description pour cette formation.</p>}
          </section>

          {f.objectives.length > 0 && (
            <section className="f-bloc" id="objectifs">
              <h2>Objectifs d'apprentissage</h2>
              <div className="amenity-row">
                {f.objectives.map((o) => (
                  <span className="amenity confirmed" key={o}>✓ {o}</span>
                ))}
              </div>
            </section>
          )}

          {f.program.length > 0 && (
            <section className="f-bloc" id="plan">
              <h2>Plan de la formation</h2>
              <ol style={{ color: "var(--ink-2)", lineHeight: 1.7, paddingLeft: 22, margin: 0 }}>
                {f.program.map((p, i) => (
                  <li key={i}>{p}</li>
                ))}
              </ol>
            </section>
          )}

          {(f.prerequisites || f.audience) && (
            <section className="f-bloc" id="admission">
              <h2>Admission</h2>
              <div className="kv">
                {f.prerequisites && (
                  <div className="cell"><div className="k">Préalables</div><div className="v">{f.prerequisites}</div></div>
                )}
                {f.audience && (
                  <div className="cell"><div className="k">Clientèle visée</div><div className="v">{f.audience}</div></div>
                )}
              </div>
            </section>
          )}

          <section className="f-bloc f-pratique" id="pratique">
            <h2>Infos pratiques</h2>
            <div className="kv">
              <div className="cell"><div className="k">Établissement</div><div className="v">{sourceName(f.source)}</div></div>
              {f.code && (
                <div className="cell"><div className="k">Sigle</div><div className="v">{f.code}</div></div>
              )}
              {f.credential && (
                <div className="cell"><div className="k">Reconnaissance</div><div className="v">{f.credential}</div></div>
              )}
              {f.credits && (
                <div className="cell"><div className="k">Crédits / UEC</div><div className="v">{f.credits}</div></div>
              )}
              {dur && (
                <div className="cell"><div className="k">Durée</div><div className="v">{dur}</div></div>
              )}
              {f.instructor && (
                <div className="cell"><div className="k">Formateur·trice</div><div className="v">{f.instructor}</div></div>
              )}
              {f.price_label && (
                <div className="cell"><div className="k">Prix affiché</div><div className="v">{f.price_label}</div></div>
              )}
              {f.schedule_label && (
                <div className="cell"><div className="k">Horaire affiché</div><div className="v">{f.schedule_label}</div></div>
              )}
              {updated && (
                <div className="cell"><div className="k">Synchronisé</div><div className="v">{updated}</div></div>
              )}
            </div>
          </section>
        </div>

        {/* ------- colonne droite (desktop) : synthèse, dates, similaires ---- */}
        <div className="f-col">
          <section className="f-bloc f-hero">
            <div className="price">
              {f.price === 0 || f.is_free ? (
                "Gratuit"
              ) : f.price != null ? (
                <>{fmtPrice(f.price, f.price_label)}</>
              ) : (
                <span style={{ fontSize: ".72em" }}>Prix non affiché par la source</span>
              )}
            </div>
            <h1>{f.title}</h1>
            <div className="loc">
              {[f.category, f.city].filter(Boolean).join(" · ")}
            </div>
            <div className="chips-scroll" role="list" aria-label="Caractéristiques clés">
              {chips.map((c) => <span className="chip-key" role="listitem" key={c}>{c}</span>)}
            </div>
            <nav className="ancres" aria-label="Sections de la fiche">
              <a href="#description">Description</a>
              {f.objectives.length > 0 && <a href="#objectifs">Objectifs</a>}
              {f.program.length > 0 && <a href="#plan">Plan</a>}
              <a href="#pratique">Infos pratiques</a>
            </nav>
            <a className="cta cta-desktop" href={f.url}
               target="_blank" rel="noopener noreferrer">
              Voir chez {sourceName(f.source)} ↗
            </a>
          </section>

          {sessions.length > 0 && (
            <section className="f-bloc" id="dates">
              <h2>Dates offertes</h2>
              <div className="amenity-row">
                {sessions.map((s) => (
                  <span className="amenity confirmed" key={s}>📅 {fmtDate(s) ?? s}</span>
                ))}
              </div>
            </section>
          )}

          {f.tags.length > 0 && (
            <section className="f-bloc">
              <h2>Thèmes</h2>
              <div className="amenity-row">
                {f.tags.map((t) => (
                  <span className="amenity unconfirmed" key={t}>{t}</span>
                ))}
              </div>
            </section>
          )}

          {(f.similar ?? []).length > 0 && (
            <section className="f-bloc">
              <h2>Formations similaires</h2>
              <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "grid", gap: 10 }}>
                {(f.similar ?? []).map((s) => (
                  <li key={s.uid}>
                    <Link to={`/formation/${encodeURIComponent(s.uid)}`}
                          style={{ color: "var(--ink)", fontWeight: 600 }}>
                      {s.title}
                    </Link>
                    <div className="fine">
                      {[s.training_type, s.mode, s.duration,
                        s.price != null ? fmtPrice(s.price) : "",
                        sourceName(s.source)].filter(Boolean).join(" · ")}
                    </div>
                  </li>
                ))}
              </ul>
            </section>
          )}
        </div>
      </div>

      <div className="fine f-foot">
        {updated && <>Dernière synchronisation : {updated}. </>}
        Les prix, dates et détails sont ceux affichés par la source — chaque fiche
        renvoie à la page originale de la formation.
      </div>

      {/* CTA sticky mobile — toujours visible */}
      <div className="cta-sticky">
        <span className="cta-sticky-prix">
          {f.price === 0 || f.is_free ? "Gratuit"
            : f.price != null ? fmtPrice(f.price, f.price_label)
            : (f.credits || "Détails")}
        </span>
        <a className="cta" href={f.url} target="_blank" rel="noopener noreferrer">
          Voir chez {sourceName(f.source)} ↗
        </a>
      </div>
    </div>
  );
}
