// FOOTPASS Final · PANNEAU DE GESTION DE STRUCTURE (sous-page plein écran, pattern PgPage)
// 5 lots validés : invitations en 3 temps · bandeau Équipe & sièges · fiche personne ·
// thème or (liseré + bandeau « casquette ») · coffre filtré structure.
// Une seule vérité de démo (STP_STAFF / STP_MEMBERS) ; chaque compteur s'en déduit.
// Vocabulaire : « autorisation » jamais « mandat » · « Suisse » jamais « Europe » · l'or en touche, jamais en aplat.
const { useState: useStateStp, useEffect: useEffectStp } = React;
const stpTX = (s) => (typeof TX === 'function' ? TX(s) : s);
const stpSlug = (n) => ((n || '').toUpperCase().replace(/[^A-Z]/g, '').slice(0, 4) || 'FTPS');
const stpOrd = (n) => `${n}e`;

// ── Icônes locales (vocabulaire trait 1.3, comme le reste de l'app) ──
const StpChev = () => <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M5 3l4 4-4 4" stroke="#A1A1AA" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path></svg>;
const StpCheck = ({ s = 11 }) => <svg width={s} height={s} viewBox="0 0 16 16" fill="none"><path d="M2.8 8.6L6.2 12L13.2 4.4" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"></path></svg>;
// ── Icônes de la grappe d'en-tête · alignées au pixel sur les piliers (Coffre-fort / Autorisations) ──
const StpInsights = () => <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M3 10.5v2M8 6v6.5M13 3v9.5"></path></svg>;
const StpPersonPlus = () => <svg width="17" height="17" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="6.8" cy="6" r="2.7"></circle><path d="M2.4 15.2c.35-3 2.3-4.8 4.4-4.8.8 0 1.5.17 2.2.5"></path><path d="M13.4 10.4v4.9M11 12.9h4.8"></path></svg>;
const StpPlus = () => <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round"><path d="M8 3v10M3 8h10"></path></svg>;
const StpI = {
  People: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><circle cx="5.8" cy="5.4" r="2.4" stroke="currentColor" strokeWidth="1.3"></circle><path d="M1.8 13c.4-2.4 2-3.7 4-3.7s3.6 1.3 4 3.7" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"></path><path d="M10.6 3.4a2.4 2.4 0 010 4.4M12 9.6c1.2.5 2 1.6 2.3 3.2" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"></path></svg>,
  Mail: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><rect x="2" y="3.5" width="12" height="9" rx="1.6" stroke="currentColor" strokeWidth="1.3"></rect><path d="M3 5l5 3.6L13 5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"></path></svg>,
  Shield: ({ check }) => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M8 2.2l5 2V8c0 3.1-2.1 4.8-5 5.8C5.1 12.8 3 11.1 3 8V4.2l5-2z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"></path>{check ? <path d="M5.8 8l1.6 1.6L10.5 6.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"></path> : null}</svg>,
  Lock: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><rect x="3" y="7" width="10" height="6.4" rx="1.6" stroke="currentColor" strokeWidth="1.3"></rect><path d="M5.5 7V5.2a2.5 2.5 0 015 0V7" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"></path></svg>,
  Grid: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><rect x="2.5" y="2.5" width="4.6" height="4.6" rx="1.2" stroke="currentColor" strokeWidth="1.3"></rect><rect x="8.9" y="2.5" width="4.6" height="4.6" rx="1.2" stroke="currentColor" strokeWidth="1.3"></rect><rect x="2.5" y="8.9" width="4.6" height="4.6" rx="1.2" stroke="currentColor" strokeWidth="1.3"></rect><rect x="8.9" y="8.9" width="4.6" height="4.6" rx="1.2" stroke="currentColor" strokeWidth="1.3"></rect></svg>,
  Card: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><rect x="2" y="3.5" width="12" height="9" rx="1.6" stroke="currentColor" strokeWidth="1.3"></rect><path d="M2 6.5h12" stroke="currentColor" strokeWidth="1.3"></path></svg>,
  Gear: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="2.2" stroke="currentColor" strokeWidth="1.3"></circle><path d="M8 1.8v2M8 12.2v2M1.8 8h2M12.2 8h2M3.6 3.6l1.4 1.4M11 11l1.4 1.4M12.4 3.6L11 5M5 11l-1.4 1.4" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"></path></svg>,
  Clock: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="5.6" stroke="currentColor" strokeWidth="1.3"></circle><path d="M8 5v3.2l2.2 1.4" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"></path></svg>,
  Doc: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M4 2h6l3 3v9H4V2z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"></path><path d="M10 2v3h3" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"></path></svg>,
  Chart: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M3 13V9.5M8 13V6M13 13V2.8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"></path></svg>,
  Heart: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M8 13.2S2.6 10 2.6 6.4A2.9 2.9 0 018 4.5a2.9 2.9 0 015.4 1.9C13.4 10 8 13.2 8 13.2z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"></path></svg>,
  Portal: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M6.5 2.5h5a2 2 0 012 2v7a2 2 0 01-2 2h-5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"></path><path d="M2.5 8h7M7 5.2L9.8 8 7 10.8" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"></path></svg>,
  Pen: () => <svg width="15" height="15" viewBox="0 0 16 16" fill="none"><path d="M3 11.2L10.2 4l1.8 1.8L4.8 13H3v-1.8z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"></path></svg>,
  Eye: () => <svg width="12" height="12" viewBox="0 0 16 16" fill="none"><path d="M2.5 8c1.5-3 3.3-4.5 5.5-4.5S12 5 13.5 8c-1.5 3-3.3 4.5-5.5 4.5S4 11 2.5 8z" stroke="currentColor" strokeWidth="1.3"></path><circle cx="8" cy="8" r="1.8" stroke="currentColor" strokeWidth="1.3"></circle></svg>,
};
const stpDosIc = (k) => k === 'shieldc' ? <StpI.Shield check /> : k === 'shield' ? <StpI.Shield /> : k === 'pen' ? <StpI.Pen /> : k === 'clock' ? <StpI.Clock /> : k === 'lock' ? <StpI.Lock /> : <StpI.Doc />;

// ── Marques de pass (cibles exactes de la référence) ──
const STP_PASS = {
  pro: { label: 'PassPRO', lie: true, price: '19,99', full: '29,99' },
  start: { label: 'PassSTART', price: '9,99' },
  staff: { label: 'PassSTAFF', price: '1,99' },
};
const StpPB = ({ brand }) => { const p = STP_PASS[brand] || STP_PASS.pro; return <span className={`stp-pb ${brand}`}>{p.label}{p.lie ? <i>lié</i> : null}</span>; };
// Libellés payeur uniques et neutres (référence · point 3)
const STP_PAY = { included: ['inc', 'Siège inclus'], structure: ['st', 'Par la structure'], self: ['self', 'À sa charge'] };
const StpPay = ({ pay }) => { const [c, l] = STP_PAY[pay] || STP_PAY.self; return <span className={`stp-pay ${c}`}>{stpTX(l)}</span>; };

// ── Aperçu public : la page structure telle que les autres la voient (rendue par FPStructSheet) ──
const stpPublicStruct = (st) => ({
  mine: true,
  name: st.name,
  initials: ((st.name || 'S').replace(/[^A-Za-zÀ-ÿ0-9 ]/g, '').split(/\s+/).filter(Boolean).map((w) => w[0]).slice(0, 2).join('') || 'ST').toUpperCase(),
  type: st.type || 'Agence',
  roster: [
    { initials: 'LF', name: 'Lucas FERREIRA', id2: 'Joueur pro · AS Monaco', fam: 'joueur', pid: 'lucas', passNo: 'FP-2847-9921-LF', cp: 'Alexandre DA COSTA', terr: 'Monde' },
    { initials: 'MR', name: 'Mathis RENARD', id2: 'Joueur pro · FC Nantes', fam: 'joueur', pid: 'mathis', passNo: 'FP-7741-0265-MR', cp: 'Alexandre DA COSTA', terr: 'Europe' },
    { initials: 'RB', name: 'Rayan BELKACEM', id2: 'Joueur U17 · centre de formation', fam: 'joueur', passNo: 'FP-5521-9080-RB', cp: 'Alexandre DA COSTA', terr: 'France' },
  ],
  privCount: 2,
  team: [
    { initials: 'AD', name: 'Alexandre DA COSTA', id2: 'Agent · Monde', fam: 'agent', me: true, passNo: '2480 1196 0049' },
    { initials: 'NR', name: 'Nadia ROUSSEAU', id2: 'Juridique', fam: 'reseau', passNo: 'FP-2204-6612-NR' },
    { initials: 'TB', name: 'Théo BLANC', id2: 'Agent · France', fam: 'agent', passNo: 'FP-3310-4471-TB' },
  ],
});

// ── Vérité de démo · pay : 'included' (couvert par le forfait) | 'structure' (pris en charge en +) | 'self' (à sa charge) ──
const STP_STAFF = [
  { id: 'me', pole: 'Direction', role: 'Administrateur', brand: 'pro', pay: 'included', admin: true, cls: 'g' },
  { id: 'nadia', name: 'Nadia Rousseau', ini: 'NR', photo: (window.STP_PHOTOS||{}).nadia, pole: 'Juridique', role: 'Gestion déléguée', brand: 'pro', pay: 'included', cls: 'b', passNo: 'FP-2204-6612-NR', since: 'avril 2026' },
  { id: 'theo', name: 'Théo Blanc', ini: 'TB', photo: (window.STP_PHOTOS||{}).theo, pole: 'Sportif', role: 'Agent', brand: 'pro', pay: 'self', cls: 'v', passNo: 'FP-3310-4471-TB', since: 'mars 2026' },
  { id: 'marc', name: 'Marc Keller', ini: 'MK', photo: (window.STP_PHOTOS||{}).marc, pole: 'Scouting', role: 'Scout', brand: 'pro', pay: 'structure', invited: '48 h' },
];
const STP_MEMBERS = [
  { id: 'lucas', peer: 'lucas', brand: 'pro', pay: 'self', role: 'Joueur pro', club: 'AS Monaco' },
  { id: 'mathis', peer: 'mathis', brand: 'pro', pay: 'self', role: 'Joueur pro', club: 'FC Nantes' },
  { id: 'rayan', name: 'Rayan Belkacem', ini: 'RB', photo: (window.STP_PHOTOS||{}).rayan, cls: 'o', brand: 'start', pay: 'structure', role: 'Joueur U17', club: 'U17 · centre de formation', passNo: 'FP-5521-9080-RB', price: '9,99' },
  { id: 'helene', name: 'Hélène Renard', ini: 'HR', photo: (window.STP_PHOTOS||{}).helene, cls: 'r', brand: 'staff', pay: 'structure', role: 'Parent', club: '·', passNo: 'FP-7742-1130-HR', price: '1,99' },
];
// Dossier complet par membre du staff : autorisations, dossiers du pôle (par statut), accès documentaires, tâches
const STP_DOSSIERS = {
  nadia: {
    chips: { atr: 2, cours: 3, traite: 14, signe: 8 },
    auths: [
      { ic: 'shieldc', cls: 'green', t: 'Délégation · Espace Juridique', e: 'Active · gestion des accès du pôle · émise par la structure' },
      { ic: 'pen', t: 'Relecture · Convention', e: 'N. Krstić · Information · expire 20 juil.' },
    ],
    dossiers: [
      { st: 'atr', cls: 'amber', t: 'Convention · N. Krstić', e: 'Relecture demandée · échéance 18 juil.', pill: ['warn', 'À TRAITER'] },
      { st: 'cours', t: 'Avenant · L. Ferreira', e: 'v2.1 en rédaction · avec Théo Blanc', pill: ['', 'EN COURS'] },
      { st: 'traite', t: 'Bail · bureaux Genève', e: 'Classé · 2 juin 2026', pill: ['', 'TRAITÉ'] },
      { st: 'signe', cls: 'green', t: 'Statuts de la structure', e: 'Administratif · 12 mars 2026', pill: ['ok', 'SIGNÉ'] },
    ],
    access: [
      { ic: 'lock', cls: 'gold', t: 'Tout le Juridique · via catégorie', e: 'documents à venir compris', rts: ['Consulter'] },
      { ic: 'doc', t: 'Convention · N. Krstić', e: 'droits par document', rts: ['Consulter', 'Réviser', 'Signer'] },
    ],
    tasks: [
      { t: 'Relire la convention N. Krstić', e: 'échéance 18 juil. · rappel la veille' },
      { t: 'Préparer l’avenant · L. Ferreira', e: 'avec Théo Blanc · pôle Sportif' },
    ],
  },
  theo: {
    chips: { atr: 1, cours: 2, traite: 12, signe: 6 },
    auths: [
      { ic: 'shieldc', cls: 'green', t: 'Sous-autorisation · mondiale exclusive', e: 'Rayan Belkacem · émise par A. Da Costa · publique' },
      { ic: 'shield', t: 'Représentation via la structure', e: 'Lucas Ferreira · expire janv. 2027 · publique' },
      { ic: 'clock', cls: 'amber', t: 'Délégation demandée', e: 'Mathis Renard · 12 juil. · votre accord requis' },
    ],
    dossiers: [
      { st: 'atr', cls: 'amber', t: 'Contrat image · R. Belkacem', e: 'À valider · échéance 14 juil.', pill: ['warn', 'À TRAITER'] },
      { st: 'cours', t: 'Prolongation · L. Ferreira', e: 'Négociation · avec Nadia Rousseau', pill: ['', 'EN COURS'] },
      { st: 'traite', t: 'Bon de transfert · saison 25-26', e: 'Classé · 30 juin 2026', pill: ['', 'TRAITÉ'] },
      { st: 'signe', cls: 'green', t: 'Prolongation · précédente', e: 'Signé · 2 juil. 2026', pill: ['ok', 'SIGNÉ'] },
    ],
    access: [
      { ic: 'doc', t: 'Prolongation · L. Ferreira', e: 'droits par document', rts: ['Consulter', 'Réviser'] },
      { ic: 'lock', cls: 'gold', t: 'Clips & data · R. Belkacem', e: 'Performance', rts: ['Consulter'] },
    ],
    tasks: [
      { t: 'Finaliser la prolongation L. Ferreira', e: 'échéance 15 juil.' },
      { t: 'Valider le contrat image R. Belkacem', e: 'avec Communication' },
    ],
  },
};
const STP_POLES = [
  { n: 'Direction', r: 'A. Da Costa', c: 1 },
  { n: 'Sportif', r: 'Théo Blanc', c: 2 },
  { n: 'Juridique', r: 'Nadia Rousseau · gestion déléguée', c: 1 },
  { n: 'Scouting', r: 'Marc Keller · en attente d’arrivée', c: 1 },
  { n: 'Communication', r: 'À pourvoir · déléguer à un membre', c: 0 },
];
const STP_INV_POLES = ['Direction', 'Sportif', 'Juridique', 'Scouting', 'Communication'];
const STP_MEM_STATUS = [['all', 'Tous'], ['atr', 'À traiter'], ['cours', 'En cours'], ['traite', 'Traités'], ['signe', 'Signés']];
const STP_TEAM_FILTERS = [['pro', 'PassPRO'], ['start', 'PassSTART'], ['staff', 'PassSTAFF'], ['pay-st', 'Par la structure'], ['pay-self', 'À sa charge']];

const stpNum = (p) => parseFloat(String(p).replace(/\s/g, '').replace(',', '.')) || 0;
const stpFmt = (n) => { const s = n.toFixed(2).replace('.', ','); const i = s.indexOf(','); return i > 3 ? s.slice(0, i - 3) + ' ' + s.slice(i - 3) : s; };
const StpAv = ({ p, size }) => {
  const peer = p.peer && window.FP_PEERS ? FP_PEERS[p.peer] : null;
  const me = p.id === 'me' ? window.FP_ME : null;
  const src = p.photo || (me ? me.photo : peer ? peer.photo : null);
  const st = size ? { width: size, height: size, fontSize: size * 0.32 } : null;
  return <span className={`stp-av ${p.invited ? 'dash' : p.cls || ''}`} style={st}>{src ? <img src={src} alt="" /> : (p.ini || (peer ? peer.initials : 'FP'))}</span>;
};
const stpName = (p) => (p.id === 'me' ? FP_ME.name : p.name || (window.FP_PEERS && p.peer && FP_PEERS[p.peer] ? FP_PEERS[p.peer].name : ''));
const StpSech = ({ label, link, onLink }) => (
  <div className="hm-sechead"><span>{label}</span>{link ? <button className="hm-seclink" onClick={onLink}>{link}</button> : null}</div>
);
const StpRow = ({ ic, cls, av, b, em, pill, chev, onClick }) => (
  <button className="hm-row" onClick={onClick}>
    {av ? <StpAv p={av} /> : <span className={`hm-row-ic ${cls || ''}`}>{ic}</span>}
    <span className="hm-row-txt"><b>{b}</b>{em ? <em>{em}</em> : null}</span>
    {pill ? <span className={`pg-pill ${pill[0]}`}>{pill[1]}</span> : null}
    {chev ? <StpChev /> : null}
  </button>
);

// ═══════ Page · panneau complet ═══════
function StructurePanelPage({ onBack, showToast, onOpenSub }) {
  const [, bump] = useStateStp(0);
  useEffectStp(() => { const f = () => bump((n) => n + 1); window.addEventListener('fp:growth', f); return () => window.removeEventListener('fp:growth', f); }, []);
  const [view, setViewRaw] = useStateStp('home'); // home | team | member | billing | invites | spaces | params
  // Pile de navigation interne : « Retour » revient à l'écran précédent DANS la structure ; on ne quitte le panneau que depuis le hub.
  const navRef = React.useRef([]);
  const setView = (v) => { if (v !== view) navRef.current.push(view); setViewRaw(v); };
  const [showStats, setShowStats] = useStateStp(true); // résumé (3 compteurs) · masquable comme Autorisations / Coffre
  const [pubOpen, setPubOpen] = useStateStp(false); // aperçu de la page structure publique
  const [mem, setMem] = useStateStp(null);
  const [teamSeg, setTeamSeg] = useStateStp('all');
  const [teamFilter, setTeamFilter] = useStateStp(null);
  const [teamSearch, setTeamSearch] = useStateStp(false); // recherche Équipe & sièges · même déclencheur d'en-tête que les piliers
  const [teamQ, setTeamQ] = useStateStp('');
  const [memStatus, setMemStatus] = useStateStp('all');
  const [tiersOpen, setTiersOpen] = useStateStp(false);
  // Invitation en 3 temps (LOT 1)
  const [invFirst, setInvFirst] = useStateStp('Marc');
  const [invLast, setInvLast] = useStateStp('Keller');
  const [invPole, setInvPole] = useStateStp('Scouting');
  const [invPass, setInvPass] = useStateStp('pro');
  const [invPayer, setInvPayer] = useStateStp('structure');
  const [invGen, setInvGen] = useStateStp(false);
  const resetGen = () => { if (invGen) setInvGen(false); };

  const st = window.fpGetStructure ? fpGetStructure() : null;
  const tiers = window.FP_ST_TIERS || [];
  const t = tiers.find((x) => x.id === (st && st.tier)) || tiers[0] || { id: 'Small', staff: '1–5', price: '499,99', inc: 2 };
  const tNext = tiers[tiers.indexOf(t) + 1];
  const copy = (s, msg) => { try { if (navigator.clipboard) navigator.clipboard.writeText(s); } catch (e) { /* ignore */ } showToast(msg || stpTX('Lien copié')); };
  const demo = (m) => () => showToast(stpTX(m));
  if (!st) return <PgPage title="Ma structure" onBack={onBack}><p className="stp-foot" style={{ marginTop: 24 }}>{stpTX('Aucune structure enregistrée.')}</p></PgPage>;

  // ── Compteurs dérivés de la vérité de démo ──
  const activeStaff = STP_STAFF.filter((m) => !m.invited);
  const pending = STP_STAFF.filter((m) => m.invited);
  const seatsActive = activeStaff.length;                       // 3
  const incUsed = Math.min(seatsActive, t.inc);                 // 2
  const seatsExtra = Math.max(0, seatsActive - t.inc);          // 1 (Théo)
  const seatsExtraStr = activeStaff.filter((m) => m.pay === 'structure').length; // sièges suppl. facturés à la structure = 0
  const linked = seatsActive + STP_MEMBERS.length;              // 7 (une invitation ne compte pas)
  const coveredMembers = STP_MEMBERS.filter((m) => m.pay === 'structure'); // Rayan, Hélène
  const coveredCost = coveredMembers.reduce((s, m) => s + stpNum(m.price), 0); // 11,98
  const totalYear = stpNum(t.price) + seatsExtraStr * 239.99;   // 499,99 aujourd'hui
  const passCount = { pro: 0, start: 0, staff: 0 };
  activeStaff.concat(STP_MEMBERS).forEach((m) => { passCount[m.brand] = (passCount[m.brand] || 0) + 1; });
  const stInitials = st.logo ? null : (st.name || 'ST').trim().split(/\s+/).slice(0, 2).map((w) => w[0]).join('').toUpperCase();

  // ── Bandeau de synthèse admin (LOT 2) · révélé par l'icône insights, réutilisé sur Équipe & sièges ET Invitations ──
  const seatSegs = activeStaff.map((m) => (m.pay === 'included' ? 'inc' : 'sup')).concat(pending.map(() => 'inv'));
  const seatText = `${seatsActive} ${seatsActive > 1 ? stpTX('sièges') : stpTX('siège')} · ${incUsed} ${stpTX('inclus dans')} ${t.id}${seatsExtra > 0 ? ` + ${seatsExtra} ${seatsExtra > 1 ? stpTX('supplémentaires') : stpTX('supplémentaire')}` : ` · ${stpTX('tous inclus')}`}`;
  const seatNote = pending.length ? `${pending.length} ${pending.length > 1 ? stpTX('invitations en attente') : stpTX('invitation en attente')}` : null;
  const marc = pending.find((m) => m.pay === 'structure');
  const synth = (
    <div className="stp-syn">
      <div className="stp-syn-hd">
        <span className="stp-syn-cap">{stpTX('Sièges du staff')}</span>
        {seatNote ? <span className="stp-syn-note">{seatNote}</span> : null}
      </div>
      <b className="stp-syn-seat">{seatsActive} {seatsActive > 1 ? stpTX('personnes au staff') : stpTX('personne au staff')}</b>
      <p className="stp-syn-lead">{incUsed} {incUsed > 1 ? stpTX('sièges compris dans votre palier') : stpTX('siège compris dans votre palier')} {t.id}</p>
      <div className="stp-syn-rows">
        <div className="stp-syn-block">
          <span className="stp-syn-k">{stpTX('Répartition des pass')}</span>
          <span className="stp-syn-l2">{['pro', 'start', 'staff'].filter((b) => passCount[b]).map((b) => <span key={b} className={`stp-pb ${b}`}>{STP_PASS[b].label} <i>× {passCount[b]}</i></span>)}</span>
        </div>
        <div className="stp-syn-row">
          <span className="stp-syn-k">{stpTX('Payé par la structure')}</span>
          <span className="stp-syn-v"><b className="gd">{stpFmt(coveredCost)} CHF/{stpTX('mois')}</b> · {coveredMembers.length} {coveredMembers.length > 1 ? stpTX('membres') : stpTX('membre')}</span>
        </div>
        {marc ? (
          <div className="stp-syn-row">
            <span className="stp-syn-k">{stpTX('À l’arrivée de')} {stpName(marc).split(' ')[0]}</span>
            <span className="stp-syn-v gd">+ 19,99 CHF/{stpTX('mois')}</span>
          </div>
        ) : null}
      </div>
      <div className="stp-syn-vis"><StpI.Eye /> {stpTX('Visible par vous (admin)')}</div>
    </div>
  );
  // « Nouvelle invitation » · relance le flux en 3 temps depuis un formulaire vierge
  const newInvite = () => { setInvFirst(''); setInvLast(''); setInvPole('Scouting'); setInvPass('pro'); setInvPayer('structure'); setInvGen(false); try { const sc = document.querySelector('.pg-scroll'); if (sc) sc.scrollTop = 0; } catch (e) {} showToast(stpTX('Nouvelle invitation')); };

  const openMember = (p) => { if (p.id === 'me') { onOpenSub('passid'); return; } if (p.invited) { setView('invites'); return; } setMem(p); setMemStatus('all'); setView('member'); };
  const openVaultStructure = () => { window.__fpVaultFilter = st.name; window.dispatchEvent(new CustomEvent('fp:vault-filter', { detail: { structure: st.name } })); onOpenSub('vault'); };

  const TITLES = { home: 'Ma structure', team: 'Équipe & sièges', member: mem ? stpName(mem) : 'Fiche personne', billing: 'Facturation', invites: 'Invitations', spaces: 'Espaces & rôles', params: 'Paramètres' };
  const memberSub = mem && (mem.pole ? `${stpTX(mem.role || mem.pole)} · ${stpTX('Pôle')} ${stpTX(mem.pole)} · ${stpTX('depuis')} ${mem.since || 'mars 2026'}` : `${stpTX(mem.role || 'Joueur')} · ${stpTX(mem.club || '·')}`);
  const back = () => { if (navRef.current.length) setViewRaw(navRef.current.pop()); else onBack(); };
  // ── Grappe d'en-tête · patron des piliers : boutons ronds 44 px, insights en tête dans son anneau, puis actions de l'écran ──
  const insightsBtn = (
    <button className={`hm-iconbtn ${showStats ? 'on' : ''}`} onClick={() => setShowStats(!showStats)} aria-label={stpTX('Statistiques')} aria-pressed={showStats}><StpInsights /></button>
  );
  const action = view === 'home' ? (
    <div className="pg-headacts2">
      {insightsBtn}
      <button className="hm-iconbtn" onClick={demo('Identité de la structure · nom, couleur et logo (démo)')} aria-label={stpTX('Modifier la structure')}><HMI.Pen s={16} /></button>
    </div>
  ) : view === 'team' ? (
    <div className="pg-headacts2">
      {insightsBtn}
      <button className={`hm-iconbtn ${teamSearch ? 'on' : ''}`} onClick={() => setTeamSearch((s) => { if (s) setTeamQ(''); return !s; })} aria-label={stpTX('Rechercher')} aria-pressed={teamSearch}><HMI.Search s={17} /></button>
      <button className="hm-iconbtn stp-acc" onClick={() => setView('invites')} aria-label={stpTX('Inviter')}><StpPersonPlus /></button>
    </div>
  ) : view === 'invites' ? (
    <div className="pg-headacts2">
      {insightsBtn}
      <button className="hm-iconbtn stp-acc" onClick={newInvite} aria-label={stpTX('Nouvelle invitation')}><StpPlus /></button>
    </div>
  ) : view === 'member' ? (
    <div className="pg-headacts2">
      <button className="hm-iconbtn" onClick={demo('Modification du rôle et du pôle · démo')} aria-label={stpTX('Modifier')}><HMI.Pen s={16} /></button>
    </div>
  ) : null;

  // Bandeau « casquette » (LOT 4) · sur tous les écrans structure
  const gband = (
    <React.Fragment>
      <div className="stp-gline"></div>
      <div className="stp-gband"><span className="stp-gm">{st.logo ? <img src={st.logo} alt="" /> : stInitials}</span><span>{stpTX('Vous agissez au nom de')} {st.name} <em>· {stpTX('vos gestes sont consignés au journal')}</em></span></div>
    </React.Fragment>
  );

  const idHead = (extraPill) => (
    <div className="stp-idh">
      <span className="st-orgav" style={st.color ? { background: `color-mix(in oklab, ${st.color} 16%, transparent)`, color: st.color === '#52525B' ? '#A1A1AA' : st.color } : null}>{st.logo ? <img src={st.logo} alt="" /> : stInitials}</span>
      <span className="stp-idh-txt"><b>{st.name}</b><em>{stpTX(st.type || 'Agence')}</em></span>
      {extraPill}
    </div>
  );

  const body = (() => {
    if (view === 'home') {
      const all = window.fpListStructures ? fpListStructures() : [];
      return (
        <React.Fragment>
          {all.length > 1 ? (
            <div className="st-chips stp-chiprow">
              {all.map((x) => <button key={x.name} className={`st-chip ${st.name === x.name ? 'on' : ''}`} onClick={() => { fpSetStructure(x); setView('home'); }}>{x.name}</button>)}
              <button className="st-chip" onClick={() => window.dispatchEvent(new CustomEvent('fp:growth', { detail: { kind: 'sheet', sheet: 'structure' } }))}>+</button>
            </div>
          ) : null}
          {idHead(<span className="stp-tierpill"><span className="stp-tierdot"></span>{stpTX('Palier')} {t.id}</span>)}
          {showStats ? (
          <div className="stp-stats">
            <button className="stp-stat" onClick={() => setView('team')}><b>{linked}</b><span>{stpTX('Personnes liées')}</span></button>
            <button className="stp-stat" onClick={() => setView('billing')}><b>{seatsActive}</b><span>{stpTX('Sièges staff')}</span></button>
            <div className="stp-stat warn"><b>2</b><span>{stpTX('À traiter')}</span></div>
          </div>
          ) : null}
          <StpSech label={stpTX('À traiter')} />
          <div className="hm-cardlist">
            <StpRow cls="amber" ic={<StpI.Shield />} b={stpTX('Demande d’autorisation')} em={stpTX('Nenad Krstić · représentation · à approuver')} chev onClick={() => onOpenSub('mandates')} />
            <StpRow cls="amber" ic={<StpI.Clock />} b={stpTX('1 invitation expire bientôt')} em={stpTX('Marc Keller · lien 72 h à usage unique')} chev onClick={() => setView('invites')} />
          </div>
          <StpSech label={stpTX('Équipe')} />
          <div className="hm-cardlist">
            <StpRow ic={<StpI.People />} b={stpTX('Équipe & sièges')} em={`${seatsActive} ${stpTX('staff permanent')} · ${STP_MEMBERS.length} ${stpTX('joueurs & membres')}`} chev onClick={() => setView('team')} />
            <StpRow ic={<StpI.Mail />} b={stpTX('Invitations')} em={stpTX('1 en attente · staff ou Pass lié')} chev onClick={() => setView('invites')} />
          </div>
          <StpSech label={stpTX('Accès & délégations')} />
          <div className="hm-cardlist">
            <StpRow ic={<StpI.Shield check />} b={stpTX('Autorisations')} em={stpTX('Représentation, délégations · 1 à traiter')} chev onClick={() => onOpenSub('mandates')} />
            <StpRow cls="gold" ic={<StpI.Lock />} b={stpTX('Documents & permissions')} em={stpTX('S’ouvre dans le coffre-fort · filtre structure')} chev onClick={openVaultStructure} />
            <StpRow ic={<StpI.Grid />} b={stpTX('Espaces & rôles')} em={`5 ${stpTX('pôles · qui accède à quoi')}`} chev onClick={() => setView('spaces')} />
          </div>
          <StpSech label={stpTX('Page publique')} />
          <div className="hm-cardlist">
            <StpRow ic={<StpI.Eye />} b={stpTX('Aperçu de ma page structure')} em={stpTX('Ce que les autres voient de vous')} chev onClick={() => setPubOpen(true)} />
          </div>
          <StpSech label={stpTX('Compte')} />
          <div className="hm-cardlist">
            <StpRow cls="green" ic={<StpI.Card />} b={stpTX('Facturation & abonnement')} em={`${t.id} · ${t.price} CHF/${stpTX('an')} · ${stpTX('à jour')}`} chev onClick={() => setView('billing')} />
            <StpRow ic={<StpI.Gear />} b={stpTX('Paramètres')} em={stpTX('Identité, vérification, zone sensible')} chev onClick={() => setView('params')} />
          </div>
          <p className="stp-foot">{stpTX('La structure est la porte, pas le portefeuille : elle ne paie que son staff, chaque membre garde son propre Pass.')}</p>
        </React.Fragment>
      );
    }
    if (view === 'team') {
      const tq = teamQ.trim().toLowerCase();
      const matchQ = (m) => !tq || `${stpName(m)} ${stpTX(m.role || '')} ${stpTX(m.pole || '')} ${stpTX(m.club || '')}`.toLowerCase().includes(tq);
      const matchF = (m) => { if (!teamFilter) return true; if (teamFilter === 'pay-st') return m.pay !== 'self'; if (teamFilter === 'pay-self') return m.pay === 'self'; return m.brand === teamFilter; };
      const staffList = STP_STAFF.filter((m) => matchF(m) && matchQ(m));
      const memberList = STP_MEMBERS.filter((m) => matchF(m) && matchQ(m));
      const showStaff = teamSeg !== 'members' && staffList.length > 0;
      const showMembers = teamSeg !== 'staff' && memberList.length > 0;
      const memberRow = (m) => (
        <button key={m.id} className="hm-row" onClick={() => openMember(m)}>
          <StpAv p={m} />
          <span className="hm-row-txt"><b>{stpName(m)}</b><em>{m.invited ? `${stpTX(m.pole)} · ${stpTX('invité · expire dans')} ${m.invited}` : `${stpTX(m.pole || m.role)}${m.pole ? ` · ${stpTX(m.role)}` : m.club ? ` · ${stpTX(m.club)}` : ''}`}</em></span>
          <span className="stp-rtag"><StpPB brand={m.brand} /><StpPay pay={m.pay} /></span>
        </button>
      );
      return (
        <React.Fragment>
          {showStats ? synth : null}
          {teamSearch ? (
            <div className="hm-search">
              <HMI.Search />
              <input autoFocus value={teamQ} onChange={(e) => setTeamQ(e.target.value)} placeholder={stpTX('Nom, rôle, pôle, club…')} aria-label={stpTX('Rechercher')} />
              {teamQ ? <button className="hm-search-clear" onClick={() => setTeamQ('')} aria-label={stpTX('Effacer')}><svg width="13" height="13" viewBox="0 0 22 22" fill="none"><path d="M16 6L6 16M6 6l10 10" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"></path></svg></button> : null}
            </div>
          ) : null}
          <div className="pg-seg stp-seg">
            <button className={teamSeg === 'all' ? 'on' : ''} onClick={() => setTeamSeg('all')}>{stpTX('Tous')}</button>
            <button className={teamSeg === 'staff' ? 'on' : ''} onClick={() => setTeamSeg('staff')}>{stpTX('Staff')}</button>
            <button className={teamSeg === 'members' ? 'on' : ''} onClick={() => setTeamSeg('members')}>{stpTX('Membres')}</button>
          </div>
          <div className="stp-fchips">
            {STP_TEAM_FILTERS.map(([k, l]) => <button key={k} className={`stp-fchip fam-${k} ${teamFilter === k ? 'on' : ''}`} onClick={() => setTeamFilter(teamFilter === k ? null : k)}><span className="stp-fdot"></span>{stpTX(l)}</button>)}
          </div>
          {showStaff ? (
            <React.Fragment>
              <StpSech label={stpTX('Staff permanent · compte dans le palier')} />
              <div className="hm-cardlist">{staffList.map(memberRow)}</div>
            </React.Fragment>
          ) : null}
          {showMembers ? (
            <React.Fragment>
              <StpSech label={stpTX('Joueurs & membres · jamais dans le palier')} />
              <div className="hm-cardlist">{memberList.map(memberRow)}</div>
            </React.Fragment>
          ) : null}
          {!showStaff && !showMembers ? <p className="stp-hint" style={{ margin: '2px 2px 14px' }}>{stpTX(teamQ.trim() ? 'Aucune personne pour cette recherche.' : 'Aucune personne pour ce filtre.')}</p> : null}
          <p className="stp-foot" style={{ textAlign: 'left', margin: '2px 2px 14px' }}>{stpTX('Le compte appartient à la personne : si elle part, compte et historique restent, ses accès à la structure expirent automatiquement, son PassPRO repasse à 29,99 CHF/mois.')}</p>
        </React.Fragment>
      );
    }
    if (view === 'member' && mem) {
      const d = STP_DOSSIERS[mem.id];
      const isStaff = !!mem.pole;
      const memFam = /joueur/i.test(mem.role || '') ? 'joueur' : /agent/i.test(mem.role || '') ? 'agent' : /juri|avocat|médec|conseil/i.test((mem.role || '') + ' ' + (mem.pole || '')) ? 'reseau' : 'staff';
      const memRoleColor = window.m4RoleColor ? window.m4RoleColor(memFam) : null;
      const passNo = mem.passNo || (mem.peer && FP_PEERS[mem.peer] ? FP_PEERS[mem.peer].passNo : 'FP-····-····');
      const dossShown = d ? (memStatus === 'all' ? d.dossiers : d.dossiers.filter((x) => x.st === memStatus)) : [];
      return (
        <React.Fragment>
          <div className="stp-idh">
            <StpAv p={mem} size={40} />
            <span className="stp-idh-txt">
              <b>{stpName(mem)}<i className="stp-idh-v" title="Pass ID vérifié"><StpCheck s={8} /></i></b>
              <em className="stp-idh-role" style={memRoleColor ? { color: memRoleColor } : null}>{stpTX(mem.role || mem.pole || 'Membre')}{!mem.pole && mem.club && mem.club !== '·' ? ` · ${stpTX(mem.club)}` : ''}</em>
              <i className="pg-mono">{passNo}</i>
            </span>
            <span className="stp-rtag"><StpPB brand={mem.brand} /><StpPay pay={mem.pay} /></span>
          </div>
          {d ? (
            <React.Fragment>
              <div className="stp-fchips">
                {STP_MEM_STATUS.map(([k, l]) => <button key={k} className={`stp-fchip ${memStatus === k ? 'on' : ''}`} onClick={() => setMemStatus(k)}>{stpTX(l)}{k !== 'all' ? <span className="stp-fchip-n">{d.chips[k]}</span> : null}</button>)}
              </div>
              <p className="stp-hint">{stpTX('Compteurs filtrés sur son pôle :')} {stpTX(mem.pole)}. {stpTX('Ce sont des filtres de statut.')}</p>
              <StpSech label={stpTX('Autorisations')} link={stpTX('+ Ajouter')} onLink={demo('Ajouter une autorisation · démo')} />
              <div className="hm-cardlist">
                {d.auths.map((a, i) => (
                  <div key={i} className="hm-row static">
                    <span className={`hm-row-ic ${a.cls || ''}`}>{stpDosIc(a.ic)}</span>
                    <span className="hm-row-txt"><b>{stpTX(a.t)}</b><em>{stpTX(a.e)}</em></span>
                    <button className="stp-rvk" onClick={demo('Révocation · effet immédiat, consignée au journal (démo)')}>{stpTX('Révoquer')}</button>
                  </div>
                ))}
              </div>
              <StpSech label={`${stpTX('Dossiers · pôle')} ${stpTX(mem.pole)}`} link={stpTX('Tout voir')} onLink={openVaultStructure} />
              <div className="hm-cardlist">
                {dossShown.length ? dossShown.map((x, i) => (
                  <button key={i} className="hm-row" onClick={openVaultStructure}>
                    <span className={`hm-row-ic ${x.cls || ''}`}><StpI.Doc /></span>
                    <span className="hm-row-txt"><b>{stpTX(x.t)}</b><em>{stpTX(x.e)}</em></span>
                    <span className={`pg-pill ${x.pill[0]}`}>{x.pill[1]}</span>
                  </button>
                )) : <div className="hm-row static"><span className="hm-row-txt"><em>{stpTX('Aucun dossier pour ce statut dans l’aperçu.')}</em></span></div>}
              </div>
              <StpSech label={stpTX('Accès documentaires')} link={stpTX('Gérer dans le coffre')} onLink={openVaultStructure} />
              <div className="hm-cardlist">
                {d.access.map((a, i) => (
                  <div key={i} className="hm-row static">
                    <span className={`hm-row-ic ${a.cls || ''}`}>{stpDosIc(a.ic)}</span>
                    <span className="hm-row-txt"><b>{stpTX(a.t)}</b><em>{stpTX(a.e)}</em><span className="stp-rts">{a.rts.map((r, j) => <span key={j} className="stp-rt">{stpTX(r)}</span>)}</span></span>
                    <button className="stp-rvk" onClick={demo('Accès retiré · effet immédiat (démo)')}>{stpTX('Retirer')}</button>
                  </div>
                ))}
              </div>
              <StpSech label={stpTX('Tâches en cours')} />
              <div className="hm-cardlist">
                {d.tasks.map((x, i) => (
                  <div key={i} className="hm-row static"><span className="stp-ck"></span><span className="hm-row-txt"><b>{stpTX(x.t)}</b><em>{stpTX(x.e)}</em></span></div>
                ))}
              </div>
              <div className="stp-acts">
                <button className="pg-btn" onClick={demo('Gestion des accès · démo')}>{stpTX('Gérer les accès')}</button>
                <button className="pg-btn" onClick={demo('Changement de pôle · démo')}>{stpTX('Changer de pôle')}</button>
              </div>
            </React.Fragment>
          ) : (
            <React.Fragment>
              <div className="pg-info">
                <div className="pg-inforow"><span>{stpTX('Pass')}</span><b>{stpTX(mem.pass || (STP_PASS[mem.brand].label + (mem.brand === 'pro' ? ' lié' : '')))}</b></div>
                <div className="pg-inforow"><span>{stpTX('N° Pass')}</span><b className="pg-mono">{passNo}</b></div>
                <div className="pg-inforow"><span>{stpTX('Club')}</span><b>{stpTX(mem.club || '·')}</b></div>
              </div>
              <div className="hm-cardlist">
                <StpRow ic={<StpI.Shield check />} b={stpTX('Autorisations le concernant')} em={stpTX('Représentation, délégations')} chev onClick={() => onOpenSub('mandates')} />
                <StpRow cls="gold" ic={<StpI.Lock />} b={stpTX('Documents partagés')} em={stpTX('Dans le coffre · filtre structure')} chev onClick={openVaultStructure} />
              </div>
            </React.Fragment>
          )}
          <button className="stp-danger" onClick={demo('Retrait · confirmation requise · effet immédiat (démo)')}>{stpTX('Retirer de la structure · effet immédiat')}</button>
          <button className="stp-note" onClick={demo('Journal des consultations · démo')}>{stpTX('Dossier visible par vous (admin) et les responsables autorisés · chaque consultation est consignée au journal.')}</button>
        </React.Fragment>
      );
    }
    if (view === 'billing') {
      return (
        <React.Fragment>
          <div className="pg-info">
            <div className="pg-inforow"><span>{stpTX('Statut')}</span><b className="ok"><StpCheck /> {st.kind === 'request' ? stpTX('Vérification en cours · 24 h') : stpTX('Active · vérifiée')}</b></div>
            <div className="pg-inforow"><span>{stpTX('Palier')}</span><b>{`${t.id} · ${stpTX('staff')} ${t.staff}`}</b></div>
            <div className="pg-inforow"><span>{stpTX('Forfait annuel')}</span><b>{`${t.price} CHF`}</b></div>
            <div className="pg-inforow"><span>{stpTX('Prochaine échéance')}</span><b>{stpTX('12 mars 2027')}</b></div>
          </div>
          <StpSech label={stpTX('Sièges staff')} />
          <div className="pg-info">
            <div className="pg-inforow"><span>{`${stpTX('Inclus dans')} ${t.id}`}</span><b>{`${t.inc} ${stpTX('sièges')}`}</b></div>
            <div className="pg-inforow"><span>{stpTX('Supplémentaires')}</span><b>{seatsExtraStr ? `${seatsExtraStr} × 19,99 CHF/${stpTX('mois')}` : `${seatsExtra} ${stpTX('siège à sa charge · 0 CHF pour la structure')}`}</b></div>
            <div className="pg-inforow stp-inforow-tot"><span>{stpTX('Total structure / an')}</span><b>{`${stpFmt(totalYear)} CHF`}</b></div>
          </div>
          <p className="stp-hint">{stpTX('Aucun siège supplémentaire facturé à la structure aujourd’hui : le siège de Théo Blanc est à sa charge.')}</p>
          <StpSech label={stpTX('Palier suivant')} link={stpTX('Voir les 6 paliers')} onLink={() => setTiersOpen(true)} />
          <div className="hm-cardlist">
            {tNext ? <StpRow ic={<StpI.Chart />} b={`${tNext.id} · ${stpTX('dès')} ${(tNext.staff || '').split('–')[0]} ${stpTX('permanents')}`} em={`${tNext.price} CHF/${stpTX('an')} · ${tNext.inc} ${stpTX('sièges inclus · proposé, jamais imposé')}`} onClick={() => setTiersOpen(true)} /> : null}
          </div>
          <StpSech label={stpTX('Prise en charge · optionnelle')} />
          <div className="hm-cardlist">
            {coveredMembers.map((m) => <StpRow key={m.id} cls="green" ic={<StpI.Heart />} b={stpName(m)} em={`${STP_PASS[m.brand].label} · ${m.price} CHF/${stpTX('mois')} · ${stpTX('par la structure')}`} chev onClick={demo('Prise en charge par membre · démo')} />)}
          </div>
          <p className="stp-hint">{`${stpTX('Total pris en charge')} : ${coveredMembers.length} ${stpTX('membres')} · ${stpFmt(coveredCost)} CHF/${stpTX('mois')}. ${stpTX('Chaque membre paie son propre Pass ; la structure peut le prendre en charge, membre par membre.')}`}</p>
          <StpSech label={stpTX('Factures')} />
          <div className="hm-cardlist">
            <StpRow ic={<StpI.Doc />} b={stpTX('Forfait annuel') + ' ' + t.id} em={`12 ${stpTX('mars')} 2026 · ${t.price} CHF`} pill={['', 'PDF']} onClick={demo('Facture téléchargée (démo)')} />
            <StpRow ic={<StpI.Portal />} b={stpTX('Portail client')} em={stpTX('Moyen de paiement, TVA, reçus')} chev onClick={demo('Portail client · démo')} />
          </div>
          <button className="stp-danger" onClick={demo('Résiliation notée · active jusqu’à l’échéance annuelle')}>{stpTX('Résilier · effet à l’échéance annuelle')}</button>
          <p className="stp-foot">{stpTX('Aucune reconduction cachée : annuel = 12 × mensuel. Vos données restent exportables.')}</p>
          {tiersOpen ? (
            <PgSheet onClose={() => setTiersOpen(false)} title={stpTX('Les 6 paliers structurels')}>
              <div className="pg-info">
                {tiers.map((x) => (
                  <div key={x.id} className="pg-inforow"><span>{`${x.id} · ${stpTX('staff')} ${x.staff}`}</span><b className={x.id === t.id ? 'ok' : ''}>{x.id === t.id ? <StpCheck /> : null}{`${x.price} CHF/${stpTX('an')} · ${x.inc} ${stpTX('sièges')}`}</b></div>
                ))}
              </div>
              <p className="stp-hint" style={{ margin: '0 2px' }}>{stpTX('Palier selon le staff permanent uniquement. Jusqu’à Confirmed : paiement direct, essai 10 jours. Dès Established : sur demande, activation sous 24 h.')}</p>
            </PgSheet>
          ) : null}
        </React.Fragment>
      );
    }
    if (view === 'invites') {
      const slug = stpSlug(st.name);
      const p = STP_PASS[invPass];
      const passLabel = `${p.label}${p.lie ? ' lié' : ''}`;
      const payerLabel = invPayer === 'structure' ? stpTX('par la structure') : stpTX('à sa charge');
      const isSeat = invPass === 'pro';                 // un pôle + PassPRO = siège staff
      const seatAfter = seatsActive + 1;                // ce nouvel arrivant = 4e siège
      const extraAfter = Math.max(0, seatAfter - t.inc);// 2e au-delà des 2 inclus
      const covered = seatAfter <= t.inc;
      const link = `footpass.app/s/${slug}-${isSeat ? 'STAFF' : 'MEMBER'}-2201`;
      const canGen = invFirst.trim() && invLast.trim();
      const seatDetail = isSeat
        ? (covered ? stpTX('siège inclus, déjà couvert par le forfait') : `${stpOrd(seatAfter)} ${stpTX('siège staff')}, ${stpOrd(extraAfter)} ${stpTX('au-delà des')} ${t.inc} ${stpTX('inclus')} : +${p.price} CHF/${stpTX('mois')} ${stpTX('à son arrivée')}`)
        : (invPayer === 'structure' ? `${stpTX('pris en charge')} ${p.price} CHF/${stpTX('mois')}` : `${p.price} CHF/${stpTX('mois')} ${stpTX('à sa charge')}`);
      const structEm = isSeat
        ? (covered ? `${stpTX('Siège inclus · déjà couvert par le forfait')} · 0 CHF ${stpTX('en plus')}.` : `${stpOrd(seatAfter)} ${stpTX('siège staff')} · ${stpOrd(extraAfter)} ${stpTX('au-delà des')} ${t.inc} ${stpTX('inclus')} : +${p.price} CHF/${stpTX('mois')} ${stpTX('à son arrivée')}.`)
        : `${stpTX('Pris en charge par la structure')} · ${p.price} CHF/${stpTX('mois')}.`;
      const passCard = (k, sub) => {
        const pp = STP_PASS[k];
        return (
          <button className={`stp-rc ${invPass === k ? 'on' : ''}`} onClick={() => { setInvPass(k); resetGen(); }}>
            <span className="stp-rad"></span>
            <span className="stp-rc-tx"><b><span className={`stp-pb ${k}`}>{pp.label}{pp.lie ? <i>lié</i> : null}</span><u>{pp.price} CHF/{stpTX('mois')}</u></b><em>{sub}</em></span>
          </button>
        );
      };
      return (
        <React.Fragment>
          {showStats ? synth : null}
          <div className="stp-step first"><b>1</b><span>{stpTX('Qui')}</span></div>
          <div className="stp-fgrid">
            <label className="stp-fld"><span>{stpTX('Prénom')}</span><input value={invFirst} onChange={(e) => { setInvFirst(e.target.value); resetGen(); }} placeholder={stpTX('Prénom')} /></label>
            <label className="stp-fld"><span>{stpTX('Nom')}</span><input value={invLast} onChange={(e) => { setInvLast(e.target.value); resetGen(); }} placeholder={stpTX('Nom')} /></label>
          </div>
          <div className="stp-fchips">
            {STP_INV_POLES.map((po) => <button key={po} className={`stp-fchip ${invPole === po ? 'on' : ''}`} onClick={() => { setInvPole(po); resetGen(); }}>{stpTX(po)}</button>)}
          </div>
          <p className="stp-hint">{stpTX('Le prénom et le nom génèrent le lien personnel et la ligne « En attente ».')}</p>
          <div className="stp-step"><b>2</b><span>{stpTX('Quel pass')}</span></div>
          {passCard('pro', `${stpTX('Acteurs du football professionnel, joueurs pros compris')} · ${stpTX('staff : siège décompté du quota')} · 29,99 CHF/${stpTX('mois')} ${stpTX('hors structure')}.`)}
          {passCard('start', stpTX('Jeunes joueurs, parents, encadrants amateurs · prix fixe, jamais réduit, lié ou non.'))}
          {passCard('staff', stpTX('Membres occasionnels ou passifs · interne à la structure uniquement · n’existe que lié.'))}
          <div className="stp-step"><b>3</b><span>{stpTX('Qui paye')}</span></div>
          <div className="stp-pcs">
            <button className={`stp-pc ${invPayer === 'structure' ? 'on' : ''}`} onClick={() => { setInvPayer('structure'); resetGen(); }}><span className="stp-rad"></span><b>{stpTX('La structure prend en charge')}</b><em>{structEm}</em></button>
            <button className={`stp-pc ${invPayer === 'self' ? 'on' : ''}`} onClick={() => { setInvPayer('self'); resetGen(); }}><span className="stp-rad"></span><b>{stpTX('La personne paye elle-même')}</b><em>{p.price} CHF/{stpTX('mois')} {stpTX('à sa charge · rien pour la structure')}.</em></button>
          </div>
          <p className="stp-hint">{stpTX('Réglable pour chaque invitation · la prise en charge est une option, jamais une obligation.')}</p>
          <div className="stp-recap">
            <span className="stp-recap-cap">{stpTX('Récapitulatif')}</span>
            <b>{`${invFirst || '·'} ${invLast || ''} · ${stpTX(invPole)} · ${passLabel} · ${payerLabel}`}</b>
            <em>{`${stpTX('Lien personnel à usage unique · valable 72 h')} · ${seatDetail}`}</em>
          </div>
          {invGen ? (
            <div className="stp-linkbox">
              <div className="stp-linkurl">{link}</div>
              <div className="stp-acts">
                <button className="pg-btn" onClick={() => copy(link, stpTX('Lien copié'))}>{stpTX('Copier')}</button>
                <button className="pg-btn" onClick={demo('Partage du lien · démo')}>{stpTX('Partager')}</button>
              </div>
            </div>
          ) : (
            <button className="stp-btnp" disabled={!canGen} onClick={() => { if (!canGen) { showToast(stpTX('Prénom et nom requis')); return; } setInvGen(true); showToast(stpTX('Lien généré · valable 72 h')); }}>{stpTX('Générer le lien')}</button>
          )}
          <StpSech label={`${stpTX('En attente')} · ${pending.length}`} />
          <div className="hm-cardlist">
            {pending.map((m) => (
              <div key={m.id} className="hm-row static">
                <StpAv p={m} />
                <span className="hm-row-txt"><b>{m.name}</b><em>{stpTX(m.pole)} · {stpTX('lien 72 h · expire dans')} {m.invited}</em></span>
                <button className="stp-rvk" style={{ color: 'var(--acc-bright,#00C49A)' }} onClick={demo('Invitation renvoyée · nouveau lien 72 h')}>{stpTX('Renvoyer')}</button>
              </div>
            ))}
          </div>
          <p className="stp-foot" style={{ textAlign: 'left', margin: '2px 2px' }}>{stpTX('Une invitation acceptée devient un siège (staff) ou un Pass lié (joueurs & membres) · visible immédiatement dans Équipe & sièges.')}</p>
        </React.Fragment>
      );
    }
    if (view === 'spaces') {
      return (
        <React.Fragment>
          <div className="hm-cardlist">
            {STP_POLES.map((p) => (
              <StpRow key={p.n} ic={<StpI.Grid />} b={stpTX(p.n)} em={`${stpTX(p.r)}${p.c ? ' · ' + p.c + ' ' + stpTX(p.c > 1 ? 'personnes' : 'personne') : ''}`} chev onClick={demo('Gestion de l’espace · démo')} />
            ))}
          </div>
          <p className="stp-foot" style={{ textAlign: 'left', margin: '2px 2px' }}>{stpTX('Un espace = un pôle de votre structure. Déléguer sa gestion donne à un membre les droits d’y accueillir, retirer et autoriser · révocable en un geste.')}</p>
        </React.Fragment>
      );
    }
    // params
    return (
      <React.Fragment>
        {idHead()}
        <div className="pg-info">
          <div className="pg-inforow"><span>{stpTX('Nom')}</span><b>{st.name}</b></div>
          <div className="pg-inforow"><span>{stpTX('Type')}</span><b>{stpTX(st.type || 'Agence')}</b></div>
          <div className="pg-inforow"><span>{stpTX('Pays')}</span><b>{stpTX('Suisse')}</b></div>
          <div className="pg-inforow"><span>{stpTX('Vérification')}</span><b className="ok"><StpCheck /> {st.kind === 'request' ? stpTX('En cours · 24 h') : stpTX('Vérifiée par FOOTPASS')}</b></div>
        </div>
        <div className="hm-cardlist">
          <StpRow ic={<StpI.Pen />} b={stpTX('Logo & couleur')} em={stpTX('Identité visuelle de la structure')} chev onClick={demo('Logo & couleur · démo')} />
          <StpRow ic={<StpI.Doc />} b={stpTX('Documents de vérification')} em={stpTX('Registre du commerce, statuts')} chev onClick={demo('Documents de vérification · démo')} />
        </div>
        <StpSech label={stpTX('Zone sensible')} />
        <div className="pg-actions single" style={{ marginBottom: 10 }}>
          <button className="pg-btn danger" onClick={demo('Transférez d’abord le rôle d’admin à un membre du staff')}>{stpTX('Quitter la structure')}</button>
          <button className="pg-btn danger" onClick={demo('Suppression · confirmation par e-mail requise (démo)')}>{stpTX('Supprimer la structure')}</button>
        </div>
        <p className="stp-foot">{stpTX('La suppression libère tous les sièges à l’échéance ; chaque membre conserve son compte et son Pass.')}</p>
      </React.Fragment>
    );
  })();

  return <PgPage title={TITLES[view]} subtitle={view === 'member' ? memberSub : null} onBack={back} action={action} tabbar>{body}{pubOpen && window.FPStructSheet ? <FPStructSheet struct={stpPublicStruct(st)} onClose={() => setPubOpen(false)} /> : null}</PgPage>;
}

Object.assign(window, { StructurePanelPage });
