// FOOTPASS Messenger v2 · AGENDA complet (HMAgendaV2 + fiche + création)
// Calendrier intelligent du cahier des charges, version V2 (sans Rooms) :
//  • bande de jours (pastilles colorées par thème, aujourd'hui cerclé)
//  • filtres par thème (Mercato · Médical · Juridique · Sportif)
//  • liste groupée Aujourd'hui / Demain / … synchronisée avec les conversations
//  • fiche événement : participant → conversation, confirmer / proposer / annuler
//  • création : type, contact, jour, heure, lieu · l'invitation part « pending »
// Branché par FPShell (home.jsx) via window.HMAgendaV2 / EventSheetV2 / NewEventSheetV2.
const { useState: useStateG, useRef: useRefG, useEffect: useEffectG } = React;

const agTX = (s) => (typeof TX === 'function' ? TX(s) : s);

// ═══════ ÉCRAN AGENDA ═══════
function HMAgendaV2({ lang, events, onSheet, onOpenChat }) {
  const cal = window.FP_CAL;
  const TH = window.FP_EV_THEMES;
  const [selD, setSelD] = useStateG(null);   // jour sélectionné (null = tout)
  const [selM, setSelM] = useStateG(6);      // mois du jour sélectionné
  const [selTh, setSelTh] = useStateG(null); // thème sélectionné (null = tous)
  const [selWho, setSelWho] = useStateG(null); // contact sélectionné (null = tous)
  const [showSearch, setShowSearch] = useStateG(false);
  const [q, setQ] = useStateG('');
  const [showPast, setShowPast] = useStateG(false); // volet « rendez-vous passés »
  // Zoom façon calendrier iOS : liste (jour) ← pincer → mois ← pincer → année
  const [view, setView] = useStateG('list'); // 'list' | 'month' | 'year'
  const [viewM, setViewM] = useStateG(6);    // mois affiché en vue mois
  const [zoomDir, setZoomDir] = useStateG('in');
  const pageRef = useRefG(null);
  const stripRef = useRefG(null);
  const searchRef = useRefG(null);

  const goView = (v, dir) => { setZoomDir(dir); setView(v); if (v === 'month') setMvTight(false); };
  const zoomStep = (dir) => {
    // dir 'out' = élargir (liste → mois → année) · 'in' = rapprocher (année → mois → liste)
    setView((v) => {
      const next = dir === 'out' ? (v === 'list' ? 'month' : 'year') : (v === 'year' ? 'month' : 'list');
      if (next !== v) { setZoomDir(dir); if (v === 'list' && next === 'month') setViewM(selD != null ? selM : 6); }
      return next;
    });
  };
  useEffectG(() => {
    const el = pageRef.current;
    if (el) return window.agvBindPinch(el, zoomStep);
    return undefined;
  }, []);

  // La bande de jours démarre sur aujourd'hui · les jours passés restent accessibles en glissant à gauche.
  // Réessaie tant que la bande n'est pas mesurable (montage sous le splash, transitions d'onglet).
  useEffectG(() => {
    if (showSearch || view !== 'list') return undefined;
    let raf; let tries = 0; let total = 0;
    const go = () => {
      const el = stripRef.current;
      const t = el && el.querySelector('.ag-day.today');
      const measurable = el && t && el.clientWidth > 0 && el.scrollWidth > el.clientWidth;
      if (measurable) {
        el.scrollLeft = Math.max(0, t.offsetLeft - el.offsetLeft - 18);
        if (el.scrollLeft > 0) return;
        tries++;
      }
      if (++total < 600 && tries < 20) raf = requestAnimationFrame(go);
    };
    go();
    return () => cancelAnimationFrame(raf);
  }, [showSearch, view]);
  useEffectG(() => { if (showSearch && searchRef.current) searchRef.current.focus(); }, [showSearch]);
  const toggleSearch = () => setShowSearch((s) => { if (s) setQ(''); return !s; });

  const sorted = (events || []).slice().sort(window.fpEvSort);
  const themesUsed = Object.keys(TH).filter((k) => sorted.some((e) => e.theme === k));
  const whosUsed = [];
  sorted.forEach((e) => (e.whos || [e.who]).forEach((id) => { if (FP_PEERS[id] && !whosUsed.includes(id)) whosUsed.push(id); }));

  const isPast = window.fpEvIsPast;
  const agNorm = (s) => String(s || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
  const term = agNorm(q.trim());
  const searching = showSearch && term.length > 0;

  let list = sorted;
  if (searching) {
    // Recherche instantanée · titre, lieu, contacts, thème · sur tout l'agenda (passé compris)
    list = sorted.filter((e) => {
      const names = (e.whos || [e.who]).filter((id) => FP_PEERS[id]).map((id) => FP_PEERS[id].name).join(' ');
      return agNorm(agTX(e.title) + ' ' + agTX(e.place) + ' ' + names + ' ' + agTX(TH[e.theme].label)).includes(term);
    });
  } else {
    if (selD != null) list = list.filter((e) => e.d === selD && (e.m || 6) === selM);
    if (selTh) list = list.filter((e) => e.theme === selTh);
    if (selWho) list = list.filter((e) => (e.whos || [e.who]).includes(selWho));
  }

  // Groupes par jour (la liste est déjà triée) · clé mois+jour
  const mkGroups = (arr) => {
    const gs = [];
    arr.forEach((e) => {
      const k = (e.m || 6) * 100 + e.d;
      const g = gs[gs.length - 1];
      if (!g || g.k !== k) gs.push({ k, d: e.d, m: e.m || 6, items: [e] });
      else g.items.push(e);
    });
    return gs;
  };
  const pastList = list.filter(isPast);
  const upList = list.filter((e) => !isPast(e));
  // Passé déplié si : recherche active, jour passé sélectionné, ou volet ouvert
  const pastOpen = searching || (selD != null && selM === 6 && selD < cal.todayD) || (selD != null && selM < 6) || showPast;
  const pastGroups = pastOpen ? mkGroups(pastList) : [];
  const groups = mkGroups(upList);
  const visibleN = upList.length + (pastOpen ? pastList.length : 0);

  const pendingN = sorted.filter((e) => e.status === 'pending').length;
  // Création : ne jamais pré-remplir un jour passé
  const newEvDay = selD != null && selM === 6 && selD >= cal.todayD ? selD : null;
  const clearSel = () => { setSelD(null); setSelM(6); };
  // Un jour tapé en vue mois → la liste glisse jusqu'à ce jour (le calendrier reste)
  const [mvTight, setMvTight] = useStateG(false);
  const [mvPast, setMvPast] = useStateG(false); // volet « passés » de la vue mois
  const [mSlide, setMSlide] = useStateG(null);
  const mvListRef = useRefG(null);
  const mvFixedRef = useRefG(null);
  const mvSwipe = useRefG(null);
  const mvSwipedAt = useRefG(0);
  const mvProg = useRefG(0);   // horodatage d'un défilement programmatique (clic sur un jour)
  const goMonthRef = useRefG(null);
  const goMonth = (m, dir) => {
    if (m < 1 || m > 12) return;
    setMSlide(dir); setViewM(m); setMvTight(false); setMvPast(false);
    if (mvListRef.current) mvListRef.current.scrollTop = 0;
  };
  const onMvScroll = (e) => {
    if (Date.now() - mvProg.current < 700) return; // défilement déclenché par un clic : le calendrier ne se resserre pas
    const y = e.target.scrollTop;
    setMvTight((p) => (y > 10 ? true : y < 4 ? false : p));
  };
  const mvSwipeStart = (e) => { mvSwipe.current = { x: e.clientX, y: e.clientY }; };
  const mvSwipeEnd = (e) => {
    const s = mvSwipe.current; mvSwipe.current = null;
    if (!s) return;
    const el = e.currentTarget;
    const scale = (el.getBoundingClientRect().width / el.offsetWidth) || 1; // téléphone mis à l'échelle
    const dx = (e.clientX - s.x) / scale; const dy = (e.clientY - s.y) / scale;
    if (Math.abs(dx) > 34 && Math.abs(dx) > Math.abs(dy) * 1.2) {
      mvSwipedAt.current = Date.now();
      goMonth(viewM + (dx < 0 ? 1 : -1), dx < 0 ? 'r' : 'l');
    }
  };
  goMonthRef.current = (one) => goMonth(viewM + one, one > 0 ? 'r' : 'l');
  // Trackpad / molette horizontale → mois précédent / suivant
  useEffectG(() => {
    if (view !== 'month') return undefined;
    const el = mvFixedRef.current; if (!el) return undefined;
    let acc = 0; let cool = 0;
    const onWheel = (e) => {
      if (Math.abs(e.deltaX) <= Math.abs(e.deltaY) * 1.2) return;
      e.preventDefault();
      const t = Date.now();
      if (t - cool < 480) { acc = 0; return; }
      acc += e.deltaX;
      if (Math.abs(acc) > 50) { cool = t; const one = acc > 0 ? 1 : -1; acc = 0; if (goMonthRef.current) goMonthRef.current(one); }
    };
    el.addEventListener('wheel', onWheel, { passive: false });
    return () => el.removeEventListener('wheel', onWheel);
  }, [view]);
  const mvPickDay = (m, d) => {
    if (Date.now() - mvSwipedAt.current < 300) return; // fin de swipe, pas un tap
    if (selD === d && selM === m) { clearSel(); return; }
    const pastDay = m < 6 || (m === 6 && d < cal.todayD);
    const dayHasEvents = sorted.some((e) => (e.m || 6) === m && e.d === d);
    setSelD(d); setSelM(m);
    // Jour libre à venir → démarre un événement pré-rempli à cette date (à finir de remplir)
    if (!pastDay && !dayHasEvents) { onSheet({ kind: 'newevent', day: d, month: m }); return; }
    if (pastDay) setMvPast(true); // un jour passé déplie le volet « passés »
    const doScroll = () => {
      const list = mvListRef.current; if (!list) return;
      const k = m * 100 + d;
      const nodes = Array.prototype.slice.call(list.querySelectorAll('[data-agk]'));
      const hit = nodes.find((n) => +n.dataset.agk === k) || nodes.find((n) => +n.dataset.agk > k) || nodes[nodes.length - 1];
      if (hit) {
        const lr = list.getBoundingClientRect();
        const scale = lr.width / list.clientWidth || 1; // le téléphone est mis à l'échelle (transform)
        const top = (hit.getBoundingClientRect().top - lr.top) / scale + list.scrollTop - 6;
        mvProg.current = Date.now();            // le calendrier reste déplié : seul le bas glisse
        list.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
      }
    };
    if (pastDay) requestAnimationFrame(() => requestAnimationFrame(doScroll)); // attendre le rendu du volet
    else doScroll();
  };
  const headMonth = selD != null && selM !== 6 ? agTX(window.AGV_MONTHS[selM - 1].label) + ' 2026' : agTX(cal.monthLabel);

  const renderGroups = (gs, dim) => gs.map((g) => (
    <div key={(dim ? 'p' : 'u') + g.k} data-agk={g.k}>
      <div className="hm-sechead ag-sechead"><span>{window.fpEvDayLabel(g.d, g.m)}</span><em>{g.items.length}</em></div>
      <div className="hm-cardlist">
        {g.items.map((e) => {
          const whos = (e.whos || [e.who]).filter((id) => FP_PEERS[id]);
          return (
            <button key={e.id} className={`ag-ev ${dim ? 'past' : ''}`} style={{ '--tc': TH[e.theme].c }} onClick={() => onSheet({ kind: 'event', ev: e })}>
              <span className="ag-when"><b>{e.time}</b><em>{e.dur}</em></span>
              <span className="ag-bar"></span>
              <span className="hm-row-txt">
                <b>{agTX(e.title)}</b>
                <em>{agTX(e.place)}</em>
              </span>
              <span className="ag-right">
                <span className={`ag-tag ${e.status}`}>{window.fpEvStatusLabel(e.status)}</span>
                <span className="ag-faces">
                  {whos.slice(0, 3).map((id) => {
                    const pp = FP_PEERS[id];
                    return <FPAvatar key={id} size={18} initials={pp.initials} src={pp.photo} />;
                  })}
                  {whos.length > 3 ? <i className="ag-more">+{whos.length - 3}</i> : null}
                </span>
              </span>
            </button>
          );
        })}
      </div>
    </div>
  ));

  return (
    <div className="hm-page" data-screen-label="Agenda" ref={pageRef}>
      <div className="hm-pagehead">
        <h1 className="hm-h1">{agTX('Agenda')}</h1>
        <div className="ag-headr">
          {view === 'list' ? (
            <button className="ag-month zoomable" onClick={() => { setViewM(selD != null ? selM : 6); goView('month', 'out'); }} title={agTX('Vue mois · pincez pour dézoomer')}>
              {headMonth}
              <svg width="8" height="5" viewBox="0 0 9 6" fill="none"><path d="M1 1.2L4.5 4.8L8 1.2" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"></path></svg>
            </button>
          ) : view === 'month' ? (
            <button className="ag-month zoomable" onClick={() => goView('year', 'out')}>
              <svg width="5" height="9" viewBox="0 0 6 10" fill="none"><path d="M5 1L1.4 5L5 9" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"></path></svg>
              2026
            </button>
          ) : (
            <button className="ag-month zoomable" onClick={() => { clearSel(); goView('list', 'in'); }}>{agTX("Aujourd'hui")}</button>
          )}
          {view === 'list' ? <button className={`hm-iconbtn ${showSearch ? 'on' : ''}`} onClick={toggleSearch} aria-label="Rechercher"><HMI.Search s={17} /></button> : null}
          <button className="hm-iconbtn" onClick={() => onSheet({ kind: 'newevent', day: newEvDay })} aria-label="Nouvel événement"><HMI.Pen s={16} /></button>
        </div>
      </div>

      {view === 'year' ? (
        <div key="year" className={`hm-scroll ag-zoomview ${zoomDir === 'in' ? 'zin' : 'zout'}`}>
          <div className="ag-ytitle">2026</div>
          <div className="ag-yhint">{agTX('Touchez un mois · pincez pour zoomer')}</div>
          <YearGridV2 events={sorted} onMonth={(m) => { setViewM(m); goView('month', 'in'); }} />
          <div className="hm-listfoot"><FPIcon.Shield s={10} /> {agTX('Synchronisé avec vos conversations · les invitations acceptées apparaissent ici')}</div>
        </div>
      ) : view === 'month' ? (
        <div key="month" className={`ag-mv ag-zoomview ${zoomDir === 'in' ? 'zin' : 'zout'}`}>
          <div className={`ag-mv-fixed ${mvTight ? 'tight' : ''}`} ref={mvFixedRef}
            onPointerDown={mvSwipeStart} onPointerUp={mvSwipeEnd} onPointerCancel={() => { mvSwipe.current = null; }}>
            <div className="ag-mv-head">
              <b>{agTX(window.AGV_MONTHS[viewM - 1].label)} <em>2026</em></b>
              <span className="ag-mv-nav">
                <button onClick={() => goMonth(viewM - 1, 'l')} disabled={viewM === 1} aria-label="Mois précédent">
                  <svg width="6" height="10" viewBox="0 0 6 10" fill="none"><path d="M5 1L1.4 5L5 9" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"></path></svg>
                </button>
                <button onClick={() => goMonth(viewM + 1, 'r')} disabled={viewM === 12} aria-label="Mois suivant">
                  <svg width="6" height="10" viewBox="0 0 6 10" fill="none"><path d="M1 1L4.6 5L1 9" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"></path></svg>
                </button>
              </span>
            </div>
            <div key={viewM} className={`ag-mv-slide ${mSlide ? 's' + mSlide : ''}`}>
              <MonthGridV2 lang={lang} m={viewM} events={sorted} selD={selD} selM={selM} onDay={mvPickDay} />
            </div>
          </div>
          <div className="hm-scroll ag-mv-list" ref={mvListRef} onScroll={onMvScroll}>
            {(() => {
              const mEvs = sorted.filter((e) => (e.m || 6) === viewM);
              const monthPast = viewM < 6; // juin = mois courant
              if (!mEvs.length) {
                return (
                  <div className="ag-empty">
                    <span className="ag-empty-ic"><HMI.Calendar s={22} /></span>
                    <b>{agTX(monthPast ? 'Aucun rendez-vous ce mois-ci' : 'Rien de prévu ce mois-ci')}</b>
                    <em>{agTX(monthPast ? 'Ce mois est passé.' : 'Touchez un jour pour planifier.')}</em>
                  </div>
                );
              }
              const upEvs = mEvs.filter((e) => !isPast(e));
              const pastEvs = mEvs.filter((e) => isPast(e));
              const up = mkGroups(upEvs);
              return (
                <React.Fragment>
                  {pastEvs.length ? (
                    <button className={`ag-pastbtn ${mvPast ? 'open' : ''}`} onClick={() => setMvPast(!mvPast)}>
                      <HMI.Chevron s={11} />
                      {agTX(mvPast ? 'Masquer les rendez-vous passés' : 'Rendez-vous passés')}
                    </button>
                  ) : null}
                  {mvPast ? renderGroups(mkGroups(pastEvs), true) : null}
                  {up.length ? renderGroups(up) : (
                    <div className="ag-empty sm">
                      <b>{agTX('Rien à venir ce mois-ci')}</b>
                      <em>{agTX('Les rendez-vous passés restent consultables ci-dessus.')}</em>
                    </div>
                  )}
                </React.Fragment>
              );
            })()}
            <div className="ag-yhint">{agTX('Glissez le calendrier pour changer de mois · touchez un jour pour y aller')}</div>
          </div>
        </div>
      ) : (
      <React.Fragment>
      {showSearch ? (
        /* Recherche instantanée · titre, lieu, contact ou thème */
        <div className="ag-search">
          <HMI.Search s={15} />
          <input ref={searchRef} value={q} onChange={(e) => setQ(e.target.value)} placeholder={agTX('Contact, titre, lieu, thème…')} />
          {q ? <button className="ag-search-x" onClick={() => setQ('')} aria-label="Effacer">✕</button> : null}
        </div>
      ) : (
        <React.Fragment>
          {/* Bande de jours (les jours passés restent consultables à gauche) */}
          <div className="ag-strip" ref={stripRef}>
            {cal.days.map((day) => {
              const evs = sorted.filter((e) => e.d === day.d && (e.m || 6) === 6);
              const on = selD === day.d;
              return (
                <button key={day.d} className={`ag-day ${on ? 'on' : ''} ${day.d === cal.todayD ? 'today' : ''} ${day.d < cal.todayD ? 'past' : ''}`}
                  onClick={() => { setSelD(on ? null : day.d); setSelM(6); }}>
                  <em>{agTX(day.dow)}</em>
                  <b>{day.d}</b>
                  <span className="ag-dots">
                    {evs.slice(0, 3).map((e, i) => <i key={i} style={{ background: TH[e.theme].c }}></i>)}
                  </span>
                </button>
              );
            })}
          </div>

          {/* Filtres par thème (code couleur) puis par contact */}
          <div className="hm-chips ag-themes">
            <button className={`hm-chip ${!selTh && !selWho ? 'on' : ''}`} onClick={() => { setSelTh(null); setSelWho(null); }}>{agTX('Tous')}</button>
            {themesUsed.map((k) => (
              <button key={k} className={`hm-chip ${selTh === k ? 'on' : ''}`} onClick={() => setSelTh(selTh === k ? null : k)}>
                <span className="hm-chip-dot" style={{ background: TH[k].c }}></span>
                <span>{agTX(TH[k].label)}</span>
              </button>
            ))}
            <span className="ag-chipsep"></span>
            {whosUsed.map((id) => {
              const pp = FP_PEERS[id];
              return (
                <button key={id} className={`hm-chip ag-whochip ${selWho === id ? 'on' : ''}`} onClick={() => setSelWho(selWho === id ? null : id)}>
                  <FPAvatar size={17} initials={pp.initials} src={pp.photo} />
                  <span>{pp.name.split(' ')[0]}</span>
                </button>
              );
            })}
          </div>
        </React.Fragment>
      )}

      <div key="list" className={`hm-scroll ag-zoomview ${zoomDir === 'in' ? 'zin' : 'zout'}`}>
        {selM !== 6 && selD != null && !searching ? (
          <button className="ag-selchip" onClick={clearSel}>
            {window.fpEvDayLabel(selD, selM)} 2026 <i>✕</i>
          </button>
        ) : null}
        {searching ? (
          <div className="ag-results">{list.length} {agTX(list.length > 1 ? 'résultats' : 'résultat')} {agTX('pour')} « {q.trim()} »</div>
        ) : null}

        {!searching && pastList.length && !(selD != null && selD < cal.todayD) ? (
          <button className={`ag-pastbtn ${showPast ? 'open' : ''}`} onClick={() => setShowPast(!showPast)}>
            <HMI.Chevron s={11} />
            {agTX(showPast ? 'Masquer les rendez-vous passés' : 'Rendez-vous passés')}
          </button>
        ) : null}

        {renderGroups(pastGroups, true)}

        {!searching && selD == null && !selTh && !selWho && pendingN ? (
          <div className="ag-note">
            <span className="ag-note-dot"></span>
            {pendingN} {agTX(pendingN > 1 ? 'présences à confirmer' : 'présence à confirmer')}
          </div>
        ) : null}

        {renderGroups(groups)}

        {visibleN === 0 ? (
          searching ? (
            <div className="ag-empty">
              <span className="ag-empty-ic"><HMI.Search s={22} /></span>
              <b>{agTX('Aucun résultat')}</b>
              <em>{agTX('Essayez un contact, un lieu ou un thème.')}</em>
            </div>
          ) : (
            <div className="ag-empty">
              <span className="ag-empty-ic"><HMI.Calendar s={22} /></span>
              <b>{agTX('Rien de prévu ce jour')}</b>
              <em>{agTX('Votre agenda est libre à cette date.')}</em>
              <button className="pg-btn primary" onClick={() => onSheet({ kind: 'newevent', day: newEvDay })}>{agTX('Planifier un rendez-vous')}</button>
            </div>
          )
        ) : null}

        <div className="hm-listfoot"><FPIcon.Shield s={10} /> {agTX('Synchronisé avec vos conversations · les invitations acceptées apparaissent ici')}</div>
      </div>
      </React.Fragment>
      )}
    </div>
  );
}

// ═══════ FICHE ÉVÉNEMENT ═══════
function EventSheetV2({ ev, onClose, onConfirm, onRemove, onOpenChat, showToast }) {
  const TH = window.FP_EV_THEMES;
  const th = TH[ev.theme] || TH.deal;
  const p = FP_PEERS[ev.who];
  const first = p ? p.name.split(' ')[0] : '';
  const openChat = () => { onClose(); onOpenChat(ev.chat || ev.who); };
  const cancelBtn = (
    <button className="pg-btn danger" onClick={() => { onRemove(ev.id); showToast(agTX('Événement annulé · les participants sont notifiés')); onClose(); }}>
      {agTX("Annuler l'événement")}
    </button>
  );
  return (
    <PgSheet onClose={onClose}>
      <div className="pg-ev-head">
        <span className="pg-ev-date ag-evd" style={{ '--tc': th.c }}><b>{ev.d}</b><em>{agTX((window.FP_MONTHS_2026[ev.m || 6] || {}).badge || window.FP_CAL.monthShort)}</em></span>
        <span style={{ flex: 1, minWidth: 0 }}>
          <div className="pg-ev-name">{agTX(ev.title)}</div>
          <div className="pg-ev-sub">{window.fpEvDayLabel(ev.d, ev.m)} · {ev.time} · {ev.dur}</div>
        </span>
        <span className="ag-themepill" style={{ '--tc': th.c }}>{agTX(th.label)}</span>
      </div>
      <div className="pg-info">
        {(ev.whos || (p ? [ev.who] : [])).filter((id) => FP_PEERS[id]).map((id, i) => {
          const pp = FP_PEERS[id];
          return (
            <button key={id} className="pg-inforow ag-withrow" onClick={() => { onClose(); onOpenChat(id); }}>
              <span>{i === 0 ? agTX('Avec') : ''}</span>
              <b><FPAvatar size={20} initials={pp.initials} src={pp.photo} /> {window.fpUpperLast(pp.name)} <HMI.Chevron s={11} c="#71717A" /></b>
            </button>
          );
        })}
        <div className="pg-inforow"><span>{agTX('Lieu')}</span><b>{agTX(ev.place)}</b></div>
        <div className="pg-inforow"><span>{agTX('Statut')}</span>
          {ev.status === 'ok' ? <span className="pg-pill ok">{agTX('Confirmé')}</span>
            : ev.status === 'invited' ? <span className="pg-pill">{agTX('Invitation envoyée')}</span>
            : ev.status === 'done' ? <span className="pg-pill">{agTX('Passé')}</span>
            : <span className="pg-pill warn">{agTX('À confirmer')}</span>}
        </div>
        {ev.status !== 'done' ? <div className="pg-inforow"><span>{agTX('Rappel')}</span><b>{agTX(ev.remind || '30 min avant')}</b></div> : null}
      </div>
      <NotesBlockV2 ev={ev} showToast={showToast} />
      <div className="pg-sheet-actions">
        {ev.status === 'pending' ? (
          <React.Fragment>
            <button className="pg-btn primary" onClick={() => { onConfirm(ev.id); showToast(agTX('Présence confirmée · les participants sont notifiés')); onClose(); }}>{agTX('Confirmer ma présence')}</button>
            <button className="pg-btn" onClick={() => { showToast(agTX('Proposition envoyée à ') + first); onClose(); }}>{agTX('Proposer un autre créneau')}</button>
            {ev.chat ? <button className="pg-btn" onClick={openChat}>{agTX('Ouvrir la conversation')}</button> : null}
          </React.Fragment>
        ) : ev.status === 'invited' ? (
          <React.Fragment>
            <button className="pg-btn primary" onClick={() => { showToast(agTX('Rappel envoyé à ') + first); onClose(); }}>{agTX("Relancer l'invitation")}</button>
            {cancelBtn}
          </React.Fragment>
        ) : ev.status === 'done' ? (
          ev.chat ? <button className="pg-btn primary" onClick={openChat}>{agTX('Ouvrir la conversation')}</button> : null
        ) : (
          <React.Fragment>
            {ev.chat ? <button className="pg-btn primary" onClick={openChat}>{agTX('Ouvrir la conversation')}</button> : null}
            {cancelBtn}
          </React.Fragment>
        )}
      </div>
    </PgSheet>
  );
}

// ═══════ NOUVEL ÉVÉNEMENT ═══════
// Le type pilote les suggestions : rendez-vous d'équipe → personnes de ma structure,
// rendez-vous joueur → mes joueurs, prospection/club → contacts clubs vérifiés.
const AG_ALL = ['lucas', 'mathis', 'karim', 'amadou', 'sira', 'david', 'marco', 'mufc'];
const AG_TPL = [
  // Groupés par famille de couleur · la pastille du type = la catégorie de l'événement créé
  // Mercato (teal)
  { t: 'Appel vidéo', place: 'Appel vidéo FOOTPASS', theme: 'deal', dur: '30 min', sug: AG_ALL, visio: true, hint: 'Contacts vérifiés', kw: ['visio'] },
  { t: 'Rencontre', place: 'À définir', theme: 'deal', dur: '45 min', sug: AG_ALL, hint: 'Contacts vérifiés', kw: ['rencontrer'] },
  { t: 'Prospection', place: 'Siège du club', theme: 'deal', dur: '1 h', sug: ['david', 'karim', 'marco', 'mufc'], hint: 'Contacts clubs vérifiés' },
  { t: 'Rendez-vous club', place: 'Siège du club', theme: 'deal', dur: '1 h', sug: ['karim', 'david', 'marco', 'mufc'], hint: 'Contacts clubs vérifiés' },
  // Admin (ambre)
  { t: 'Café', place: 'À définir', theme: 'admin', dur: '45 min', sug: AG_ALL, hint: 'Contacts vérifiés', kw: ['cafe', 'dejeuner', 'diner', 'petit dej'] },
  { t: 'Réunion', place: 'À définir', theme: 'admin', dur: '1 h', sug: AG_ALL, hint: 'Contacts vérifiés', kw: ['point hebdo', 'debrief'] },
  { t: "Rendez-vous d'équipe", place: 'Classico Sport, Genève', theme: 'admin', dur: '1 h', sug: ['amadou', 'sira'], all: true, hint: 'Personnes liées à votre structure' },
  // Sportif (bleu)
  { t: 'Rendez-vous joueur', place: 'À définir', theme: 'sport', dur: '1 h', sug: ['lucas', 'mathis'], hint: 'Vos joueurs représentés' },
  { t: 'Match', place: 'Stade', theme: 'sport', dur: '2 h', sug: ['lucas', 'mathis', 'marco'], hint: 'Vos joueurs et le staff', kw: ['stade'] },
  // Médical (rose) · Juridique (violet)
  { t: 'Visite médicale', place: 'Centre médical', theme: 'medical', dur: '45 min', sug: ['lucas', 'mathis', 'karim'], hint: 'Vos joueurs et le club' },
  { t: 'Signature', place: 'Visioconférence sécurisée', theme: 'legal', dur: '1 h', sug: ['sira', 'amadou', 'lucas'], visio: true, hint: 'Juriste, co-agent et signataires', kw: ['signer', 'contrat'] },
];
// Étapes : mois → jour (mini-calendrier) → matinée / après-midi / soir → horaires
const AG_PERIODS = [
  { id: 'am', label: 'Matinée', hours: ['08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30'] },
  { id: 'pm', label: 'Après-midi', hours: ['12:30', '14:00', '15:00', '16:00', '16:30', '17:30'] },
  { id: 'ev', label: 'Soir', hours: ['18:00', '18:30', '19:00', '20:00', '20:30'] },
];
// Lieux suggérés (recherche façon plan) · lieux déjà utilisés dans les conversations
const AG_PLACES = [
  'Classico Sport, Genève', 'La Jonelière, Nantes', 'Stade de la Beaujoire, Nantes',
  'Valdebebas, Madrid', 'Siège du club', 'Centre médical', 'Café Kléber, Paris',
];

// NewEventSheetV2 vit dans agenda-new-event.jsx (chargé juste après ce fichier).
Object.assign(window, { HMAgendaV2, EventSheetV2, AG_ALL, AG_TPL, AG_PERIODS, AG_PLACES });
