// features/appels — page « Appels récents » (tous résidents, paginée)

const { useState: useStateRc } = React;

// ───────────────────────── Appels récents ─────────────────────────
function RecentCalls({ openProfile, openCall }) {
  const PAGE = 10;
  const all = React.useMemo(() => {
    const liste = [];
    window.RESIDENTS.forEach((r) => r.calls.forEach((c) => liste.push({ ...c, resident: r })));
    // tri chronologique réel (les dates viennent de Firebase)
    liste.sort((a, b) => (b.date || 0) - (a.date || 0));
    return liste;
  }, [window.LIVANA_DATA_VERSION]);

  // Pagination : on n'analyse que les appels affichés. Ceux déjà qualifiés
  // ailleurs (fiche résident, graphique) sont repris du cache, sans doublon.
  const [nbAffiches, setNbAffiches] = useStateRc(PAGE);
  const visibles = all.slice(0, nbAffiches);
  const analyseEnCours = useAnalyseHumeurs(visibles);

  return (
    <div className="page fade-up">
      <div className="recentpage-list">
        {visibles.map((c) => {
          return (
            <button key={c.id} className="card recentpage-item" onClick={() => openCall(c.resident, c)}>
              <Avatar first={c.resident.firstName} last={c.resident.lastName} mood={humeurFin(c)} size={44} />
              <div className="recentpage-body">
                <div className="recentpage-head">
                  <span className="recentpage-name">{c.resident.firstName} {c.resident.lastName}</span>
                  <span className="recentpage-when">{c.when} · {c.duration}</span>
                </div>
                <div className="recentpage-flow">
                  <MoodFlow call={c} />
                  <span className="lock-badge" style={{ marginLeft: 'auto' }}><Icon name="lock" size={12} /> Résumé protégé</span>
                </div>
                <div className="recentpage-sum locked">{c.summary}</div>
              </div>
              <span className="res-open"><Icon name="chevron-right" size={16} /></span>
            </button>);

        })}
        {all.length > nbAffiches &&
        <button className="call-more" onClick={() => setNbAffiches((n) => n + PAGE)}>
          {analyseEnCours ? 'Analyse en cours…' : `Afficher ${Math.min(PAGE, all.length - nbAffiches)} appels de plus`}
          {' '}<span className="eyebrow">({nbAffiches}/{all.length})</span>
        </button>}
      </div>
    </div>);

}

window.RecentCalls = RecentCalls;
