// FOOTPASS Messenger v2 · APPEL DE SALON (groupe)
// Pendant un appel à plusieurs :
//  • mode salon : tous les membres visibles en tuiles, indicateur de parole
//  • notes prises directement sur l'écran d'appel (texte + photo + doc + mémo transcrit)
//  • accès immédiat aux notes existantes : vue de lecture riche présentée par Passi
//    (photos, documents, transcription du mémo visible d'un coup d'œil)
// Les notes écrites ici vont dans window.FP_NOTES (ev = id du salon) → elles
// se retrouvent dans le bloc Notes de la carte salon (onglet Appels), et vice-versa.
const { useState: useStateSL, useEffect: useEffectSL, useRef: useRefSL } = React;

const slcRoleColor = (p) => {
  const byRole = { Joueur: 'joueur', Agent: 'agent', Juriste: 'reseau' };
  const fam = (p && (p.fam || byRole[p.role])) || 'staff';
  return window.m4RoleColor ? window.m4RoleColor(fam) : '#8E8E96';
};
const slcLines = (t) => {
  const ls = String(t || '').split('\n').map((x) => x.trim()).filter(Boolean);
  return { title: ls[0] || '', rest: ls.slice(1) };
};
const slcFmtT = (s) => Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');

const SlcCam = ({ s = 14 }) => (
  <svg width={s} height={s} viewBox="0 0 20 20" fill="none">
    <path d="M2 6.2A2.2 2.2 0 014.2 4h1.6l1.3-1.7h5.8L14.2 4h1.6A2.2 2.2 0 0118 6.2v8.6a2.2 2.2 0 01-2.2 2.2H4.2A2.2 2.2 0 012 14.8V6.2z" stroke="currentColor" strokeWidth="1.5"></path>
    <circle cx="10" cy="10.3" r="3.2" stroke="currentColor" strokeWidth="1.5"></circle>
  </svg>
);

// ── Tuile participant ──
function SlcTile({ p, you, speaking, muted }) {
  return (
    <div className={`slc-tile ${speaking ? 'speaking' : ''}`}>
      <span className="slc-tile-av">
        <FPAvatar size={64} initials={p.initials} src={p.photo} />
      </span>
      <span className="slc-tile-name">{you ? 'Vous' : window.fpUpperLast(p.name)}</span>
      <span className="slc-tile-role" style={{ color: you ? 'rgba(255,255,255,0.4)' : slcRoleColor(p) }}>
        {you ? 'Organisateur' : p.role + (p.org ? ' · ' + p.org : '')}
      </span>
      <span className="slc-tile-st">
        {muted ? (
          <span className="mut"><FPIcon.MicOff c="rgba(255,255,255,0.45)" s={11} /> Muet</span>
        ) : speaking ? (
          <span className="slc-wave" aria-label="Parle">
            {[10, 12, 7, 11].map((h, i) => (
              <i key={i} style={{ height: h + 'px', animationDelay: i * 140 + 'ms' }}></i>
            ))}
          </span>
        ) : (
          <span className="quiet">En ligne</span>
        )}
      </span>
    </div>
  );
}

// ── Vue de lecture · la note présentée en entier (photos, docs, transcription) ──
function SlcNoteView({ n, room, onBack, onEdit }) {
  const { title, rest } = slcLines(n.text);
  const p = !n.ev && n.who ? FP_PEERS[n.who] : null;
  const att = n.att || [];
  const imgs = att.filter((a) => a.k === 'img');
  const docs = att.filter((a) => a.k === 'doc');
  const auds = att.filter((a) => a.k === 'aud');
  const bits = [];
  if (imgs.length) bits.push(imgs.length + ' photo' + (imgs.length > 1 ? 's' : ''));
  if (docs.length) bits.push(docs.length + ' document' + (docs.length > 1 ? 's' : ''));
  if (auds.length) bits.push('mémo transcrit');
  return (
    <div className="slc-view" data-screen-label="Lecture de note (appel)">
      <div className="slc-view-head">
        <button className="slc-view-back" onClick={onBack}>
          <svg width="9" height="15" viewBox="0 0 12 20" fill="none"><path d="M10 2L2 10l8 8" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"></path></svg>
          Notes
        </button>
        <span className="sp"></span>
        <button className="slc-view-edit" onClick={() => onEdit(n)}><FPIcon.Pen c="currentColor" s={11} /> Modifier</button>
      </div>
      <div className="slc-view-scroll">
        <div className="slc-presenter">
          <span className="slc-presenter-ic"><PassiIcon s={13} /></span>
          <span className="slc-presenter-txt">
            <b>Passi vous la présente</b>
            <em>{bits.length ? bits.join(' · ') : 'Note texte'} · {p ? 'dossier ' + p.name.split(' ')[0] : 'liée à ce salon'}</em>
          </span>
        </div>
        <div className="slc-view-title">{title || 'Note'}</div>
        <div className="slc-view-meta">
          {p ? <FPAvatar size={16} initials={p.initials} src={p.photo} /> : <span className="ndot" style={{ background: n.call ? 'var(--acc-bright, #00C49A)' : 'rgba(255,255,255,0.35)' }}></span>}
          <span>{n.ts}{n.call ? ' · prise en appel' : ''}</span>
        </div>
        {rest.length ? (
          <div className="slc-view-body">
            {rest.map((l, i) => <p key={i}>{l}</p>)}
          </div>
        ) : null}
        {imgs.length ? (
          <div className="slc-photos">
            {imgs.map((a, i) => (
              <div key={i} className="slc-photo">
                <SlcCam s={16} />
                <em>{(a.name || 'Photo').split(' · ').pop()}</em>
              </div>
            ))}
          </div>
        ) : null}
        {docs.map((a, i) => (
          <div key={i} className="slc-docrow">
            <span className="ic"><FPIcon.Doc s={13} /></span>
            <span className="tx"><b>{a.name}</b>{a.size ? <em>{a.size}</em> : null}</span>
          </div>
        ))}
        {auds.map((a, i) => (
          <div key={i} className="slc-audblock">
            {window.NtAudio ? <NtAudio a={{ ...a, tr: null }} /> : (
              <div className="slc-docrow"><span className="ic"><FPIcon.Mic s={10} /></span><span className="tx"><b>Mémo audio</b><em>{a.dur}</em></span></div>
            )}
            {a.tr ? (
              <div className="slc-tr">
                <span className="slc-tr-lbl"><FPIcon.Mic s={8} /> Transcription</span>
                <p>« {a.tr} »</p>
              </div>
            ) : null}
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Feuille NOTES · composer complet + notes du salon, sans quitter l'appel ──
function SlcNotes({ room, secs, speakingPid, muted, onClose, showToast }) {
  const evObj = { id: room.id, who: room.pids[0], whos: room.pids, theme: 'admin', kindLabel: 'Ce salon' };
  const [draft, setDraft] = useStateSL('');
  const [att, setAtt] = useStateSL([]);
  const [editing, setEditing] = useStateSL(null); // id de note en cours d'édition
  const [viewing, setViewing] = useStateSL(null); // note ouverte en lecture
  const [rec, setRec] = useStateSL(null); // null | { t, wi }
  const [expandedG, setExpandedG] = useStateSL({}); // groupes dépliés au-delà de 3 notes
  const [, force] = useStateSL(0);
  const taRef = useRefSL(null);
  useEffectSL(() => { if (taRef.current) taRef.current.focus(); }, []);

  const notes = (window.fpNotesFor ? window.fpNotesFor(evObj) : []);

  // Mémo audio · transcription en direct (simulation) pendant l'appel
  const first = (FP_PEERS[room.pids[0]] || {}).name || '';
  const trFull = 'Confirmer avec ' + first.split(' ')[0] + ' les points évoqués pendant l\u2019appel, préparer les documents et recaler un point avant le prochain rendez-vous.';
  const trWords = trFull.split(' ');
  useEffectSL(() => {
    if (!rec) return undefined;
    const w = setInterval(() => setRec((r) => (r && r.wi < trWords.length ? { ...r, wi: r.wi + 1 } : r)), 300);
    const t = setInterval(() => setRec((r) => (r ? { ...r, t: r.t + 1 } : r)), 1000);
    return () => { clearInterval(w); clearInterval(t); };
  }, [!!rec]);
  const stopRec = () => {
    setAtt((a) => [...a, { k: 'aud', dur: slcFmtT(Math.max(rec.t, 2)), tr: trWords.slice(0, Math.max(rec.wi, 6)).join(' ') }]);
    setRec(null);
  };
  const nImg = att.filter((a) => a.k === 'img').length;
  const addPhoto = () => setAtt((a) => [...a, { k: 'img', name: 'Photo · IMG_08' + (24 + nImg) + '.jpg', size: '1,8 Mo' }]);
  const addDoc = () => setAtt((a) => [...a, { k: 'doc', name: 'Document · ' + room.name + '.pdf', size: '340 Ko' }]);

  const reset = () => { setDraft(''); setAtt([]); setEditing(null); setRec(null); };
  const save = () => {
    const t = draft.trim();
    if (!t && !att.length) return;
    if (editing) {
      window.FP_NOTES = window.FP_NOTES.map((n) => (n.id === editing ? { ...n, text: t, att: att.length ? att : undefined } : n));
      if (showToast) showToast('Note mise à jour');
    } else {
      window.FP_NOTES = [
        { id: 'n' + Date.now(), text: t, ev: room.id, who: room.pids[0], ts: 'Pendant l\u2019appel · ' + fmtDur(secs), call: true, att: att.length ? att : undefined },
        ...window.FP_NOTES,
      ];
      if (showToast) showToast('Note enregistrée dans le salon');
    }
    if (window.fpSaveNotes) window.fpSaveNotes();
    reset(); force((x) => x + 1);
  };
  const del = () => {
    window.FP_NOTES = window.FP_NOTES.filter((n) => n.id !== editing);
    if (window.fpSaveNotes) window.fpSaveNotes();
    reset(); force((x) => x + 1);
    if (showToast) showToast('Note supprimée');
  };
  const startEdit = (n) => {
    setViewing(null);
    setEditing(n.id); setDraft(n.text || ''); setAtt(n.att ? n.att.slice() : []);
    setTimeout(() => { if (taRef.current) taRef.current.focus(); }, 50);
  };

  const viewed = viewing ? notes.find((n) => n.id === viewing) : null;

  return (
    <div className="slc-notes" data-screen-label="Notes pendant l'appel">
      <div className="slc-notes-grab" onClick={onClose} role="button" aria-label="Fermer les notes"><i></i></div>
      <div className="slc-notes-head">
        <b>Notes · {room.name}</b>
        <span className="tmr"><span className="dot"></span>{fmtDur(secs)}</span>
        <button className="slc-notes-close" onClick={onClose} aria-label="Fermer">✕</button>
      </div>

      {/* Le salon reste sous les yeux pendant la prise de notes */}
      <div className="slc-strip">
        {room.pids.map((pid) => {
          const p = FP_PEERS[pid];
          return (
            <span key={pid} className={`slc-strip-p ${speakingPid === pid ? 'speaking' : ''}`}>
              <FPAvatar size={28} initials={p.initials} src={p.photo} />
            </span>
          );
        })}
        <span className="slc-strip-p">
          <FPAvatar size={28} initials="AD" />
          {muted ? <span className="mut"><FPIcon.MicOff c="currentColor" s={7} /></span> : null}
        </span>
        <span className="slc-strip-lbl">
          <b>{speakingPid && FP_PEERS[speakingPid] ? FP_PEERS[speakingPid].name.split(' ')[0] + ' parle…' : 'Appel en cours'}</b>
          L&rsquo;appel continue pendant vos notes
        </span>
      </div>

      <div className="slc-comp">
        <textarea
          ref={taRef} value={draft}
          onChange={(e) => setDraft(e.target.value)}
          placeholder="Notez pendant l'appel… la première ligne devient le titre"
        ></textarea>
        {att.length ? (
          <div className="slc-atts">
            {att.map((a, i) => (
              <span key={i} className="slc-attchip">
                {a.k === 'img' ? <SlcCam s={11} /> : a.k === 'aud' ? <FPIcon.Mic s={8} /> : <FPIcon.Doc s={10} />}
                <em>{a.k === 'aud' ? 'Mémo · ' + a.dur : (a.name || '').split(' · ').pop()}</em>
                <button onClick={() => setAtt(att.filter((_, j) => j !== i))} aria-label="Retirer">×</button>
              </span>
            ))}
          </div>
        ) : null}
        {rec ? (
          <div className="slc-rec">
            <div className="slc-rec-top"><span className="dot"></span><b>Enregistrement…</b><em>{slcFmtT(rec.t)}</em>
              <span className="sp"></span>
              <button className="slc-rec-stop" onClick={stopRec}>Terminer</button>
            </div>
            <div className="slc-rec-tr">
              {rec.wi ? trWords.slice(0, rec.wi).join(' ') : <i>Parlez, le texte s&rsquo;écrit en direct…</i>}
              <span className="slc-caret"></span>
            </div>
          </div>
        ) : (
          <div className="slc-comp-foot">
            <button className="slc-tool" onClick={addPhoto} aria-label="Ajouter une photo"><SlcCam s={13} /></button>
            <button className="slc-tool" onClick={addDoc} aria-label="Joindre un document"><FPIcon.Doc s={12} /></button>
            <button className="slc-tool mic" onClick={() => setRec({ t: 0, wi: 0 })} aria-label="Mémo audio transcrit"><FPIcon.Mic s={9} /></button>
            <span className="at">{editing ? 'Modification' : fmtDur(secs)}</span>
            <span className="sp"></span>
            {editing ? <button className="slc-comp-del" onClick={del}>Supprimer</button> : null}
            <button className="slc-comp-save" disabled={!draft.trim() && !att.length} onClick={save}>
              {editing ? 'Mettre à jour' : 'Enregistrer'}
            </button>
          </div>
        )}
      </div>

      <div className="slc-nlist">
        <div className="slc-nlist-h">Vos notes · salon &amp; participants</div>
        {notes.length ? (window.fpGroupNotes ? window.fpGroupNotes(notes, evObj) : [{ key: 'all', label: '', items: notes }]).map((g, gi, arr) => {
          const showHead = arr.length > 1 || g.items.length > 3;
          const items = expandedG[g.key] ? g.items : g.items.slice(0, 3);
          return (
            <React.Fragment key={g.key}>
              {showHead ? <div className="slc-ngroup"><span>{g.label}</span><em>{g.items.length}</em></div> : null}
              {items.map((n) => {
          const { title, rest } = slcLines(n.text);
          const p = !n.ev && n.who ? FP_PEERS[n.who] : null;
          const a = n.att || [];
          const aud = a.find((x) => x.k === 'aud');
          const nDoc = a.filter((x) => x.k === 'doc').length;
          const nImgs = a.filter((x) => x.k === 'img').length;
          return (
            <button key={n.id} className={`slc-nrow ${editing === n.id ? 'on' : ''}`} onClick={() => setViewing(n.id)}>
              {p ? <FPAvatar size={18} initials={p.initials} src={p.photo} />
                 : <span className="ndot" style={{ background: n.call ? 'var(--acc-bright, #00C49A)' : 'rgba(255,255,255,0.3)' }}></span>}
              <span className="ntxt">
                <b>{title || (aud ? 'Note audio' : 'Pièces jointes')}</b>
                <em>{n.ts}{rest.length ? ' · ' + rest.join(' · ') : (aud && aud.tr ? ' · ' + aud.tr : '')}</em>
                {(a.length || p) ? (
                  <span className="nminis">
                    {nImgs ? <i><SlcCam s={9} /> {nImgs}</i> : null}
                    {nDoc ? <i><FPIcon.Doc s={9} /> {nDoc}</i> : null}
                    {aud ? <i className="aud"><FPIcon.Mic s={7} /> {aud.dur}</i> : null}
                    {p ? <i>Dossier {p.name.split(' ')[0]}</i> : null}
                  </span>
                ) : null}
              </span>
              {n.call ? <span className="live">Appel</span> : null}
            </button>
          );
              })}
              {g.items.length > 3 && !expandedG[g.key] ? (
                <button className="slc-nmore" onClick={() => setExpandedG({ ...expandedG, [g.key]: true })}>
                  + {g.items.length - 3} autres notes
                </button>
              ) : null}
            </React.Fragment>
          );
        }) : (
          <div className="slc-nempty">Aucune note pour ce salon.<br />Écrivez ci-dessus : tout reste rattaché au salon.</div>
        )}
      </div>

      {viewed ? <SlcNoteView n={viewed} room={room} onBack={() => setViewing(null)} onEdit={startEdit} /> : null}
    </div>
  );
}

// ── ÉCRAN · appel de salon ──
function SalonCall({ lang, room, onEnd, showToast }) {
  const r = room || (window.CL2_ROOMS && window.CL2_ROOMS[0]);
  const [secs, setSecs] = useStateSL(0);
  const [muted, setMuted] = useStateSL(false);
  const [speaker, setSpeaker] = useStateSL(true);
  const [notesOpen, setNotesOpen] = useStateSL(false);
  const [spIdx, setSpIdx] = useStateSL(0);
  const [, force] = useStateSL(0);

  useEffectSL(() => {
    const id = setInterval(() => setSecs((s) => s + 1), 1000);
    return () => clearInterval(id);
  }, []);
  // Tour de parole simulé entre les membres du salon
  useEffectSL(() => {
    const id = setInterval(() => setSpIdx((i) => (i + 1) % r.pids.length), 3200);
    return () => clearInterval(id);
  }, [r.pids.length]);

  const speakingPid = r.pids[spIdx];
  const nNotes = window.fpNotesFor
    ? window.fpNotesFor({ id: r.id, who: r.pids[0], whos: r.pids }).length
    : 0;

  return (
    <div className="callscreen salon" data-screen-label="Appel de salon">
      <div className="call-bg"></div>
      <FPStatusBar light />

      <div className="slc-top">
        <span className="slc-chip"><span className="dot"></span>{fmtDur(secs)}</span>
        <div className="slc-title">{r.name}</div>
        <div className="slc-sub">
          <FPIcon.Shield s={9} />
          <span>{r.pids.length + 1} en ligne · chiffré de bout en bout</span>
        </div>
      </div>

      {/* Mode salon · tous les membres visibles */}
      <div className="slc-grid">
        {r.pids.map((pid) => (
          <SlcTile key={pid} p={FP_PEERS[pid]} speaking={!notesOpen && speakingPid === pid} />
        ))}
        <SlcTile p={{ initials: 'AD', name: 'Vous' }} you muted={muted} />
      </div>

      <div className="call-controls">
        <CallBtn icon={<FPIcon.MicOff c="#fff" s={22} />} label="Muet" on={muted} onClick={() => setMuted((m) => !m)} />
        <CallBtn icon={<FPIcon.SpeakerOn c="#fff" s={22} />} label="HP" on={speaker} onClick={() => setSpeaker((s) => !s)} />
        <div className="callbtn-wrap">
          <button className={`callbtn ${notesOpen ? 'on' : ''}`} onClick={() => setNotesOpen((o) => !o)} aria-label="Notes">
            <FPIcon.Pen c={notesOpen ? '#0F0F0F' : '#fff'} s={20} />
          </button>
          {nNotes ? <span className="slc-badge">{nNotes}</span> : null}
          <span className="callbtn-label">Notes</span>
        </div>
        <CallBtn icon={<FPIcon.PhoneDown c="#fff" s={28} />} label="Raccrocher" danger onClick={() => onEnd(secs)} />
      </div>

      {notesOpen ? (
        <SlcNotes room={r} secs={secs} speakingPid={speakingPid} muted={muted}
          onClose={() => { setNotesOpen(false); force((x) => x + 1); }} showToast={showToast} />
      ) : null}
    </div>
  );
}

Object.assign(window, { SalonCall });
