// FOOTPASS Messenger v2 · ACCUEIL v3 (HMHomeV3) · le poste de pilotage, version rapide
// Retours du 11 juillet (5e passe) · moins d'infos, une ligne par sujet :
//  • À traiter : UNE ligne par sujet (titre + repère de date) · le détail et
//    les actions ne vivent que dans le dépliage
//  • AGENDA : heure + titre, rien d'autre
//  • « Mes joueurs » : remonté sous l'Agenda, en cartes à balayer (swipe
//    horizontal) · valeur marchande sur la carte (réglable via Tweaks)
//  • Coffre-fort : très privé · une seule entrée verrouillée TOUT EN BAS,
//    AUCUN nom de document sur l'Accueil, Face ID simulé avant d'ouvrir
//  • pas de « Négociation en cours », pas de « Conversations récentes », pas de Passi
// Tout est dérivé des stores réels · chaque tuile mène à l'endroit réel de l'app.

const { useState: useStateA3, useEffect: useEffectA3 } = React;

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

// Coche (état « tout est traité »)
const A3Check = ({ s = 15 }) => (
  <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" strokeLinecap="round" strokeLinejoin="round"></path>
  </svg>
);
// Tendance (valeur marchande)
const A3Trend = ({ s = 9 }) => (
  <svg width={s} height={s} viewBox="0 0 10 10" fill="none">
    <path d="M1.5 8.5L5 5l2 2 1.5-4.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"></path>
  </svg>
);
// Plus (nouvelle autorisation)
const A3Plus = ({ s = 15 }) => (
  <svg width={s} height={s} viewBox="0 0 16 16" fill="none">
    <path d="M8 3v10M3 8h10" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"></path>
  </svg>
);
// Glyphe Face ID (cadre + visage, traits simples)
const A3FaceId = ({ s = 16, c = 'currentColor' }) => (
  <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
    <path d="M3 8V6a3 3 0 013-3h2"></path>
    <path d="M16 3h2a3 3 0 013 3v2"></path>
    <path d="M21 16v2a3 3 0 01-3 3h-2"></path>
    <path d="M8 21H6a3 3 0 01-3-3v-2"></path>
    <path d="M8.5 9.3v1.2"></path>
    <path d="M15.5 9.3v1.2"></path>
    <path d="M12 9.3v3.4a1 1 0 01-1 1"></path>
    <path d="M8.8 16.1a4.6 4.6 0 006.4 0"></path>
  </svg>
);

// Valeur marchande des joueurs représentés (démo · cohérent avec FP_DEALS)
const A3_VALUES = {
  lucas: { v: '95 M€', t: '+2,8 %' },
  mathis: { v: '850 K€', t: '+15 %' },
};

function HMHomeV3({ lang, onOpenChat, onTab, onOpenSub, onOpenEvent, onConfirmEvent, events, hasUnreadNotifs }) {
  const cal = window.FP_CAL;
  const TH = window.FP_EV_THEMES;
  const [openTodo, setOpenTodo] = useStateA3(null); // ligne « À traiter » dépliée

  // Le coffre s'ouvre sur son arrivée dédiée (porte + plaque, v2/coffre-arrivee-v2.jsx) · plus de scan simulé ici

  // ── Options (tweaks · lues à chaque rendu, le panneau force un re-render) ──
  const passStyle = (() => { try { const v = localStorage.getItem('fp_home_pass'); return v === 'chip' || v === 'card' ? v : 'none'; } catch (e) { return 'none'; } })();
  const showVal = (() => { try { return localStorage.getItem('fp_home_val') !== '0'; } catch (e) { return true; } })();

  // ── Agenda · les deux prochains événements (jour / semaine / mois) ──
  const upcoming = (events || []).filter((e) => !window.fpEvIsPast(e)).sort(window.fpEvSort);
  const next2 = upcoming.slice(0, 2);

  // ── À traiter · dérivé des stores réels. Chaque ligne se déplie : détail + action. ──
  const todos = [];
  upcoming.filter((e) => e.status === 'pending' && e.d - cal.todayD <= 3).forEach((e) => {
    const peer = FP_PEERS[e.who];
    todos.push({
      id: 'ev' + e.id, tint: TH[e.theme].c, icon: <HMI.Calendar s={16} />,
      title: a3TX(e.title),
      hint: window.fpEvDayLabel(e.d, e.m),
      detail: e.time + ' · ' + e.dur + ' · ' + a3TX(e.place) + (peer ? ' · ' + a3TX('avec') + ' ' + window.fpUpperLast(peer.name) : ''),
      actions: [
        { label: a3TX('Confirmer ma présence'), primary: true, run: () => onConfirmEvent && onConfirmEvent(e.id) },
        { label: a3TX('Voir la fiche'), run: () => onOpenEvent(e) },
      ],
    });
  });
  (window.FP_DOCS || []).filter((d) => d.state === 'pending' && d.chat && FP_PEERS[d.chat]).forEach((d) => {
    todos.push({
      id: 'doc' + d.id, tint: '#E2B248', icon: <HMI.Pen s={15} />,
      title: a3TX(d.title),
      hint: a3TX('à signer'),
      detail: a3TX(d.meta) + ' · ' + d.size,
      actions: [{ label: a3TX('Ouvrir la conversation'), primary: true, run: () => onOpenChat(d.chat) }],
    });
  });
  (window.FP_MANDATES || []).filter((m) => m.status === 'pending').forEach((m) => {
    todos.push({
      id: 'mand' + m.id, tint: '#A07CEA', icon: <HMI.Mandate s={17} />,
      title: a3TX('Accès dossier') + ' · ' + m.title,
      hint: (String(m.until).match(/(\d+)\s*jour/) || [null, null])[1] ? String(m.until).match(/(\d+)\s*jour/)[1] + ' j' : '',
      detail: a3TX(m.sub) + ' · ' + a3TX(m.scope),
      actions: [{ label: a3TX('Examiner la demande'), primary: true, run: () => onOpenSub('mandates') }],
    });
  });

  // ── Joueurs représentés (autorisations actives) ──
  const players = (window.FP_MANDATES || []).filter((m) => m.pid && FP_PEERS[m.pid] && FP_PEERS[m.pid].role === 'Joueur' && m.status === 'active');
  const mandYear = (m) => { const y = String(m.until || '').match(/(20\d\d)/); return y ? a3TX('Autorisation') + ' · ' + y[1] : a3TX('Autorisation active'); };

  return (
    <div className="hm-page" data-screen-label="Accueil">
      <div className="hm-apphead">
        <img className="hm-logo" src="assets/logotype_white.png" alt="FOOTPASS®" />
        <div className="hm-apphead-actions">
          <button className="hm-iconbtn" onClick={() => onOpenSub('notifs')} aria-label="Notifications">
            <HMI.Bell />
            {hasUnreadNotifs ? <span className="hm-dot"></span> : null}
          </button>
          <button className="hm-avatarbtn" onClick={() => onTab('menu')} aria-label="Profil"><img src={FP_ME.photo} alt="AD" /></button>
        </div>
      </div>

      <div className="hm-scroll">
        {/* Salut + date · puce Pass ID optionnelle (Tweaks) */}
        <div className="a3-hello">
          <div className="a3-hello-txt">
            <h1 className="hm-h1">{a3TX('Bonjour') + ', ' + ((FP_ME.name || 'Alexandre').trim().split(/\s+/)[0])}</h1>
            <span className="ac-date">{a3TX(cal.todayLabel)}</span>
          </div>
          {passStyle === 'chip' ? (
            <button className="a3-pass" onClick={() => onOpenSub('passid')} aria-label="Pass ID">
              <HMI.Card s={13} />
              <span>PASS ID</span>
              <i><A3Check s={9} /></i>
            </button>
          ) : null}
        </div>
        {passStyle === 'card' ? (
          <button className="hm-pass" onClick={() => onOpenSub('passid')}>
            <span className="hm-pass-ic"><HMI.Card s={20} /></span>
            <span className="hm-pass-txt">
              <b>PASS ID · VERIFIED</b>
              <em>2480 1196 0049 · {a3TX('Agent')}</em>
            </span>
            <span className="hm-pass-chev"><HMI.Chevron /></span>
          </button>
        ) : null}

        {/* Audit R-05 · retour d'absence : récap factuel, jamais dramatisé */}
        {window.FPAbsenceRecap ? <FPAbsenceRecap onTab={onTab} onOpenSub={onOpenSub} /> : null}
        {/* Audit R-02 · « Bien démarrer » : les 3 gestes d'activation, refermable */}
        {window.FPStartChecklist ? <FPStartChecklist onTab={onTab} onOpenSub={onOpenSub} /> : null}
        {/* Votre structure · créer ou rejoindre (promesse de l'inscription) · s'affichera sur le Pass ID */}
        {window.FPStructureCard ? <FPStructureCard /> : null}

        {/* À traiter · dépliable : confirmer, signer, examiner · sur place */}
        <div className="hm-sechead">
          <span>{a3TX('À traiter')}{todos.length ? <i className="ac-count">{todos.length}</i> : null}</span>
        </div>
        {todos.length ? (
          <div className="hm-cardlist">
            {todos.map((t) => (
              <div key={t.id} className={`a3-todo ${openTodo === t.id ? 'open' : ''}`}>
                <button className="hm-row" onClick={() => setOpenTodo(openTodo === t.id ? null : t.id)} aria-expanded={openTodo === t.id}>
                  <span className="hm-row-ic" style={{ background: `color-mix(in srgb, ${t.tint} 13%, transparent)`, color: t.tint }}>{t.icon}</span>
                  <span className="hm-row-txt"><b>{t.title}</b></span>
                  {t.hint ? <span className="a3-hint">{t.hint}</span> : null}
                  <span className="a3-fold"><HMI.Chevron c="#A1A1AA" /></span>
                </button>
                {openTodo === t.id ? (
                  <div className="a3-todo-body">
                    <p>{t.detail}</p>
                    <div className="a3-todo-acts">
                      {t.actions.map((a) => (
                        <button key={a.label} className={`a3-act ${a.primary ? 'pri' : ''}`} onClick={a.run}>{a.label}</button>
                      ))}
                    </div>
                  </div>
                ) : null}
              </div>
            ))}
          </div>
        ) : (
          <div className="ac-done">
            <span className="ac-done-ic"><A3Check /></span>
            {a3TX('Tout est traité. Rien ne vous attend.')}
          </div>
        )}

        {/* Agenda · les deux prochains événements (jour / semaine / mois) */}
        {next2.length ? (
          <React.Fragment>
            <div className="hm-sechead">
              <span>{a3TX('Agenda')}</span>
              <button className="hm-seclink" onClick={() => onTab('agenda')}>{a3TX('Tout voir')}</button>
            </div>
            <div className="hm-cardlist">
              {next2.map((e) => (
                <button key={e.id} className="hm-event a3-ev" onClick={() => onOpenEvent(e)}>
                  <span className="hm-event-when" style={{ background: `color-mix(in srgb, ${TH[e.theme].c} 12%, transparent)` }}>
                    <b>{e.time}</b>
                    <em>{window.fpEvDayLabel(e.d, e.m)}</em>
                  </span>
                  <span className="hm-row-txt"><b>{a3TX(e.title)}</b></span>
                </button>
              ))}
            </div>
          </React.Fragment>
        ) : null}

        {/* Mes autorisations · cartes à balayer (swipe horizontal) */}
        {players.length ? (
          <React.Fragment>
            <div className="hm-sechead">
              <span>{a3TX('Mes autorisations')}</span>
              <button className="hm-seclink" onClick={() => onOpenSub('mandates')}>{a3TX('Tout voir')}</button>
            </div>
            <div className="ac-players">
              {players.map((m) => {
                const p = FP_PEERS[m.pid];
                const val = A3_VALUES[m.pid];
                return (
                  <button key={m.id} className="ac-player" onClick={() => onOpenChat(m.pid)}>
                    <FPAvatar size={44} initials={p.initials} src={p.photo} />
                    <b>{window.fpUpperLast(p.name)}</b>
                    <em>{p.org}</em>
                    {showVal && val ? (
                      <span className="a3-cardval"><b>{val.v}</b><em><A3Trend /> {val.t}</em></span>
                    ) : (
                      <span className="ac-mand"><FPIcon.Shield s={9} /> {mandYear(m)}</span>
                    )}
                  </button>
                );
              })}
              <button className="ac-player add" onClick={() => onOpenSub('mandates')}>
                <span className="ac-addic">+</span>
                <b>{a3TX('Nouvelle autorisation')}</b>
                <em>{a3TX('Représenter un joueur')}</em>
              </button>
            </div>
          </React.Fragment>
        ) : null}

        {/* Coffre-fort · très privé, tout en bas : une ligne, aucun détail · l'arrivée (porte + plaque) gère Face ID */}
        <button className="a3-vault" onClick={() => onOpenSub('vault')}>
          <span className="a3-vault-ic"><HMI.Vault s={18} /></span>
          <span className="hm-row-txt"><b>{a3TX('Coffre-fort')}</b></span>
          <span className="a3-fid-mini"><A3FaceId s={17} /></span>
        </button>

        <div className="hm-listfoot"><FPIcon.Shield s={10} /> {a3TX('Chiffré de bout en bout · identités vérifiées PASS ID')}</div>
      </div>
    </div>
  );
}

Object.assign(window, { HMHomeV3 });
