// features/accueil — page d'ensemble (compteurs, activité, chat)

const { useState: useStateHm } = React;

// ───────────────────────── Home ─────────────────────────
function Home({ go, openProfile, asstStyle, chatLocked, onUnlockRequest, homeLayout = 'classic', vigChart = false }) {
  const R = window.RESIDENTS;
  const [recentShown, setRecentShown] = useStateHm(4);
  const totalToday = R.reduce((n, r) => n + todayCallCount(r), 0);
  const inCall = R.filter((r) => r.inCall).length;
  // Taux d'apaisement : humeurs de fin analysées, sur les 7 derniers jours.
  // L'analyse lancée ici sert aussi aux courbes 7 jours des fiches résidents.
  const appels7j = React.useMemo(() => appels7jDe(R), [window.LIVANA_DATA_VERSION]);
  useAnalyseHumeurs(appels7j);
  const apaisement = tauxApaisement(R);
  const watch = R.filter(isWatch);

  // derniers appels effectués (à plat, plus récents d'abord)
  const recentCalls = [];
  R.forEach((r) => r.calls.forEach((c) => recentCalls.push({ ...c, resident: r })));
  const rank = (w) => w.startsWith("Aujourd'hui") || w.startsWith('Ce matin') ? 0 : w.startsWith('Hier') ? 1 : 2;
  recentCalls.sort((a, b) => rank(a.when) - rank(b.when));
  const allRecent = recentCalls.slice(0, 20);
  const lastCalls = allRecent.slice(0, recentShown);

  // Sur mobile la barre latérale est masquée : le logo réapparaît en tête
  // de la page d'accueil pour garder un repère de marque (masqué par le CSS
  // au-delà de 720 px, où le bandeau latéral le porte déjà).
  const logoMobile =
  <div className="home-mlogo">
      <img src="assets/livana-logo.png" alt="Livana" />
    </div>;


  const stat = (icon, val, label, foot) =>
  <div className="card stat-tile">
      <span className="stat-ic"><Icon name={icon} size={19} /></span>
      <div className="stat-val">{val}</div>
      <div className="stat-label">{label}</div>
      {foot && <div className="stat-foot">{foot}</div>}
    </div>;


  const miniStat = (icon, val, label, foot) =>
  <div className="card mini-stat">
      <span className="mini-stat-ic"><Icon name={icon} size={17} /></span>
      <div className="mini-stat-body">
        <div className="mini-stat-val">{val}</div>
        <div className="mini-stat-label">{label}</div>
      </div>
      {foot && <div className="mini-stat-foot">{foot}</div>}
    </div>;


  const recentPanel =
  <div className="card panel" style={{ marginTop: 16 }}>
      <div className="panel-head">
        <h3>Derniers appels</h3>
        <button className="link-btn" onClick={() => go('residents')}>Tous les résidents <Icon name="chevron-right" size={14} /></button>
      </div>
      <div className="recent-calls recent-calls-grid">
        {lastCalls.map((c) => {
        const m = window.moodOf(humeurFin(c));
        return (
          <button key={c.id} className="recent-call" style={{ '--mc': m.color }} onClick={() => openProfile(c.resident)}>
              <span className="feed-dot">{m.emoji}</span>
              <span className="recent-call-body">
                <span className="recent-call-head">
                  <span className="recent-call-name">{c.resident.firstName} {c.resident.lastName}</span>
                  <span className="recent-call-when">{c.when} · {c.duration}</span>
                </span>
                <span className={`recent-call-sum ${chatLocked ? 'locked' : ''}`}>{c.summary}</span>
              </span>
            </button>);

      })}
      </div>
      {allRecent.length > recentShown ?
    <button className="vig-more" style={{ marginTop: 12 }} onClick={() => setRecentShown((n) => Math.min(n + 6, 20))}>
          Afficher plus <Icon name="chevron-right" size={14} style={{ transform: 'rotate(90deg)' }} />
        </button> :
    recentShown > 4 &&
    <button className="vig-more" style={{ marginTop: 12 }} onClick={() => setRecentShown(4)}>
          Afficher moins <Icon name="chevron-left" size={14} style={{ transform: 'rotate(90deg)' }} />
        </button>
    }
    </div>;


  // ── Variante Tweak : chatbot plein écran (4 blocs en haut, vigilance dessous) ──
  if (homeLayout === 'fullchat') {
    return (
      <div className="page page-home home-novig fade-up">
        {logoMobile}
        <div className="home-grid">
          {stat('user', R.length, 'Résidents suivis')}
          {stat('phone', totalToday, "Appels aujourd'hui", <span className="trend up">↑ Activité en augmentation <span className="info-tip" data-tip="Basé sur les 7 derniers jours"><Icon name="info" size={13} /></span></span>)}
          {stat('check', apaisement ? apaisement.pourcent + '%' : '—', "Taux d'apaisement moyen", <span>{apaisement ? 'sur les 7 derniers jours' : 'analyse en cours…'}</span>)}
          {stat('message', inCall, 'Appels en cours', inCall ? <span className="in-call-pill"><span className="in-call-dot"></span>en direct</span> : <span>aucun pour l'instant</span>)}
        </div>
        <div style={{ marginTop: 16 }}>
          <VigilancePanel openProfile={openProfile} locked={chatLocked} onUnlockRequest={onUnlockRequest} withChart={vigChart} />
        </div>
        <div style={{ marginTop: 16 }}>
          <CallsEvolutionSection />
        </div>
        {recentPanel}
      </div>);

  }

  // ── Variante Tweak : tableau de bord (4 blocs + graphique appels + derniers appels) ──
  if (homeLayout === 'tableau') {
    return (
      <div className="page fade-up">
        {logoMobile}
        <div className="home-grid">
          {stat('user', R.length, 'Résidents suivis')}
          {stat('phone', totalToday, "Appels aujourd'hui", <span className="trend up">↑ Activité en augmentation <span className="info-tip" data-tip="Basé sur les 7 derniers jours"><Icon name="info" size={13} /></span></span>)}
          {stat('check', apaisement ? apaisement.pourcent + '%' : '—', "Taux d'apaisement moyen", <span>{apaisement ? 'sur les 7 derniers jours' : 'analyse en cours…'}</span>)}
          {stat('message', inCall, 'Appels en cours', inCall ? <span className="in-call-pill"><span className="in-call-dot"></span>en direct</span> : <span>aucun pour l'instant</span>)}
        </div>

        <div className="card panel" style={{ marginTop: 16 }}>
          <div className="panel-head">
            <h3>Appels acceptés &amp; refusés</h3>
            <span className="eyebrow">7 derniers jours</span>
          </div>
          <CallsChart data={window.CALL_STATS} />
        </div>

        <div style={{ marginTop: 16 }}>
          <VigilancePanel openProfile={openProfile} locked={chatLocked} onUnlockRequest={onUnlockRequest} withChart={vigChart} />
        </div>

        {recentPanel}
      </div>);

  }

  // ── Disposition classique (défaut) ──
  return (
    <div className="page fade-up">
      {logoMobile}
      <div className="home-grid">
        {stat('user', R.length, 'Résidents suivis')}
        {stat('phone', totalToday, "Appels aujourd'hui", <span className="trend up">↑ Activité en augmentation <span className="info-tip" data-tip="Basé sur les 7 derniers jours"><Icon name="info" size={13} /></span></span>)}
        {stat('check', apaisement ? apaisement.pourcent + '%' : '—', "Taux d'apaisement moyen", <span>{apaisement ? 'sur les 7 derniers jours' : 'analyse en cours…'}</span>)}
        {stat('message', inCall, 'Appels en cours', inCall ? <span className="in-call-pill"><span className="in-call-dot"></span>en direct</span> : <span>aucun pour l'instant</span>)}
      </div>

      <div className="home-assistant">
        <Assistant mode="page" pageStyle="chatgpt" asstStyle={asstStyle} onOpenProfile={openProfile} locked={chatLocked} onUnlockRequest={onUnlockRequest} suggestions={["Crée un tableau émotionnel de Marguerite Dubois", "De quoi parle Paul Bernard depuis les 7 derniers jours ?"]} />
      </div>

      <div style={{ marginTop: 16 }}>
        <VigilancePanel openProfile={openProfile} locked={chatLocked} onUnlockRequest={onUnlockRequest} withChart={vigChart} />
      </div>

      {recentPanel}
    </div>);

}

window.Home = Home;
