// FOOTPASS Messenger v2 · business cards (contract, agenda, player, PASS ID, location, contact)
const { useState: useStateC, useEffect: useEffectC } = React;

// Wrapper: positions a card like a bubble (sent/received) with meta
function CardMsg({ side, time, status, children, ephemeral }) {
  return (
    <div className={`msg ${side}`} data-time={time}>
      <div className={`bubble ${side} card-bubble ${ephemeral ? 'ephemeral' : ''}`}>
        {children}
        {time && (
          <div className="card-foot">
            {ephemeral && <span className="eph-flag"><FPIcon.Timer c="currentColor" s={11} /></span>}
            <span className="bubble-time">{time}</span>
            {side === 'sent' && <Ticks status={status} />}
          </div>
        )}
      </div>
    </div>
  );
}

// Read receipts: sent (1 gray) → delivered (2 gray) → read (2 accent)
function Ticks({ status = 'read' }) {
  if (status === 'sent') return <FPIcon.SingleCheck cls="tick-gray" />;
  if (status === 'delivered') return <FPIcon.DoubleCheck cls="tick-gray" />;
  return <FPIcon.DoubleCheck cls="tick-read" />;
}

// ── CONTRACT · document + signature workflow ──
function ContractCard({ side, time, status, lang, signState = 'signed', title, onOpen, peerName }) {
  const t = (k) => fpT(lang, k);
  const signed = signState === 'signed';
  const signedLabel = t('signedBy').replace('{name}', peerName || 'Lucas Ferreira');
  return (
    <CardMsg side={side} time={time} status={status}>
      <div className="fpcard contract">
        <div className="fpcard-row">
          <div className="fpcard-icon doc-icon"><FPIcon.Doc c="currentColor" s={20} /></div>
          <div className="fpcard-main">
            <div className="fpcard-title">{title || t('contractTitle')}</div>
            <div className="fpcard-meta">{t('contractMeta')}</div>
          </div>
        </div>
        <div className={`contract-status ${signed ? 'ok' : 'pending'}`}>
          {signed ? (
            <>
              <svg className="sig-check" width="13" height="13" viewBox="0 0 14 14" fill="none">
                <circle cx="7" cy="7" r="6.3" strokeWidth="1.3"></circle>
                <path className="sig-check-mark" d="M4.2 7.2L6.2 9.2L9.9 5.1" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"></path>
              </svg>
              <span>{signedLabel}</span>
            </>
          ) : (
            <>
              <span className="pending-dot"></span>
              <FPIcon.Pen c="currentColor" s={12} />
              <span>{t('awaitingSignature')}</span>
            </>
          )}
        </div>
        <button className="fpcard-action" onClick={() => onOpen && onOpen()}>{t('open')}</button>
      </div>
    </CardMsg>
  );
}

// ── AUTORISATION · preuve de représentation envoyée dans le fil ──
// L'émetteur (celui qui autorise) → le bénéficiaire (moi). Vérifiable à l'instant par le destinataire.
const fpAuthKind = (a) => (a && a.type && a.type.indexOf('Autorisation de représentation') === 0 ? 'Représentation' : (a && a.type) || 'Autorisation');
const fpAuthParties = (a) => {
  const p = a && a.pid ? (window.FP_PEERS || {})[a.pid] : null;
  const up = window.fpUpperLast || ((s) => s);
  return {
    issuer: a && a.who ? up(a.who.name) : p ? up(p.name) : (a && a.org) || '',
    benef: up((a && a.benef && a.benef.name) || (window.FP_ME && window.FP_ME.name) || 'Alexandre Da Costa'),
  };
};
function AuthProofCard({ side, time, status, auth, onOpen }) {
  const tx = window.TX || ((s) => s);
  const a = auth || {};
  const p = a.who || (a.pid ? (window.FP_PEERS || {})[a.pid] : null);
  const { issuer } = fpAuthParties(a);
  return (
    <CardMsg side={side} time={time} status={status}>
      <div className="fpcard authproof">
        <div className="ap-who">
          {p ? <FPAvatar size={42} initials={p.initials} src={p.photo} /> : null}
          <div className="ap-whotxt">
            <b>{issuer}</b>
            {p ? <em>{tx(p.role)}{p.org ? ' · ' + p.org : ''}</em> : null}
          </div>
        </div>
        <div className="ap-proof"><FPIcon.Shield c="currentColor" s={12} /><span>{tx('Autorisation vérifiée')}</span><i>{tx(fpAuthKind(a))}</i></div>
        <button className="fpcard-action" onClick={() => onOpen && onOpen()}>{tx('Voir l’autorisation')}</button>
      </div>
    </CardMsg>
  );
}

// ── AGENDA · event with RSVP ──
function AgendaCard({ side, time, status, lang, rsvp = 'confirmed', ev, onRsvp, peerName }) {
  const t = (k) => fpT(lang, k);
  const confirmedLabel = t('agendaConfirmed').replace('{name}', (peerName || 'Lucas').split(' ')[0]);
  const e = ev || {
    day: '24', month: lang === 'en' ? 'JUN' : 'JUIN',
    title: lang === 'en' ? 'Medical' : 'Visite médicale',
    org: 'Real Madrid',
    when: lang === 'en' ? 'Tuesday · 10:00' : 'Mardi · 10:00',
    where: 'Valdebebas, Madrid',
  };
  return (
    <CardMsg side={side} time={time} status={status}>
      <div className="fpcard agenda">
        <div className="fpcard-row">
          <div className="agenda-date">
            <span className="agenda-day">{e.day}</span>
            <span className="agenda-month">{e.month}</span>
          </div>
          <div className="fpcard-main">
            <div className="fpcard-title">{e.title}</div>
            <div className="fpcard-meta">{e.org ? `${e.org} · ` : ''}{e.when}</div>
            <div className="fpcard-meta loc"><FPIcon.Pin c="currentColor" s={11} /> {e.where}</div>
          </div>
        </div>
        {side === 'sent' || rsvp === 'confirmed' || rsvp === 'declined' ? (
          <div className={`contract-status ${rsvp === 'confirmed' ? 'ok' : 'pending'}`}>
            {rsvp === 'confirmed'
              ? (<><svg className="sig-check" width="13" height="13" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="6.3" strokeWidth="1.3"></circle><path className="sig-check-mark" d="M4.2 7.2L6.2 9.2L9.9 5.1" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"></path></svg><span>{confirmedLabel}</span></>)
              : rsvp === 'declined'
                ? (<><span className="pending-dot"></span><span>{lang === 'en' ? 'Declined' : 'Présence déclinée'}</span></>)
                : (<><span className="pending-dot"></span><span>{t('agendaPending')}</span></>)}
          </div>
        ) : (
          <div className="agenda-actions">
            <button className="fpcard-action primary" onClick={() => onRsvp && onRsvp('confirmed')}>{t('agendaConfirm')}</button>
            <button className="fpcard-action" onClick={() => onRsvp && onRsvp('declined')}>{t('agendaDecline')}</button>
          </div>
        )}
      </div>
    </CardMsg>
  );
}

// ── PLAYER CARD · shareable profile ──
function PlayerCard({ side, time, status, lang }) {
  const t = (k) => fpT(lang, k);
  return (
    <CardMsg side={side} time={time} status={status}>
      <div className="fpcard player">
        <div className="player-head">
          <FPAvatar size={44} initials="LF" src={LUCAS_PHOTO} />
          <div className="fpcard-main">
            <div className="player-name">LUCAS FERREIRA</div>
            <div className="fpcard-meta">ATT · AS Monaco · 22</div>
          </div>
          <div className="player-num">9</div>
        </div>
        <div className="player-stats">
          <div className="pstat"><span className="pstat-v">26</span><span className="pstat-l">{t('matches')}</span></div>
          <div className="pstat"><span className="pstat-v">19</span><span className="pstat-l">{t('goals')}</span></div>
          <div className="pstat"><span className="pstat-v">7</span><span className="pstat-l">{t('assists')}</span></div>
        </div>
        <div className="player-season">{t('seasonLabel')}</div>
      </div>
    </CardMsg>
  );
}

// ── PASS ID · fiche partagée dans le fil ──
function PassIdCard({ side, time, status, lang, who }) {
  const t = (k) => fpT(lang, k);
  const tx = window.TX || ((s) => s);
  const p = who || { name: 'Lucas FERREIRA', id: 'FP-2847-9921-LF', initials: 'LF' };
  const peer = (p.pid && window.FP_PEERS && window.FP_PEERS[p.pid]) || null;
  const phone = (peer && peer.phone) || p.phone;
  const st = (peer && peer.agencyId && window.FP_STRUCTS && window.FP_STRUCTS[peer.agencyId]) || (p.agency ? { name: p.agency, type: 'Agence' } : null);
  const asPeer = () => ({ id: 'st_' + p.name.toLowerCase().replace(/[^a-z0-9]+/g, ''), name: p.name, initials: p.initials, role: p.role || 'Membre', org: p.org || '', fam: p.fam || 'joueur', passNo: p.id, phone });
  const detail = (extra) => Object.assign(p.pid ? { pid: p.pid } : { peer: asPeer() }, extra || {});
  const openMsg = () => window.dispatchEvent(new CustomEvent('fp:openchat', { detail: detail() }));
  const openCall = () => window.dispatchEvent(new CustomEvent('fp:call', { detail: detail({ kind: 'voice-out' }) }));
  const openFiche = () => {
    const member = st && [].concat(st.roster || [], st.team || []).find((m) => (p.pid && m.pid === p.pid) || m.name === p.name);
    window.dispatchEvent(new CustomEvent('fp:fiche', { detail: { p: member || { pid: p.pid, name: p.name, initials: p.initials, id2: p.role ? p.role + (p.org ? ' · ' + p.org : '') : '', fam: (peer && peer.fam) || p.fam || 'joueur', passNo: p.id, phone, cp: p.cp }, st } }));
  };
  return (
    <CardMsg side={side} time={time} status={status}>
      <div className="fpcard passid2">
        <div className="passid2-top">
          <FPAvatar size={46} initials={p.initials} src={p.photo} ring />
          <div className="passid2-idc">
            <div className="passid2-name">{window.fpUpperLast ? window.fpUpperLast(p.name) : p.name}</div>
            <div className="passid2-role">{p.role ? <React.Fragment><span>{p.role}</span>{p.org ? ' · ' + p.org : ''}</React.Fragment> : t('memberSince')}</div>
          </div>
        </div>
        <div className="passid2-acts">
          <button onClick={openMsg}><svg width="13" height="13" viewBox="0 0 16 16" fill="none"><path d="M8 2.3c3.6 0 6.4 2.4 6.4 5.3S11.6 13 8 13c-.8 0-1.5-.1-2.2-.3L2.9 13.8l.9-2.3C2.5 10.5 1.6 9.1 1.6 7.6 1.6 4.7 4.4 2.3 8 2.3z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"></path></svg> {tx('Message')}</button>
          {phone ? <button onClick={openCall}><FPIcon.Phone s={13} /> {tx('Appel')}</button> : null}
          <button onClick={openFiche}><svg width="13" height="13" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="5.4" r="2.6" stroke="currentColor" strokeWidth="1.4"></circle><path d="M2.8 13.4c.7-2.3 2.8-3.6 5.2-3.6s4.5 1.3 5.2 3.6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"></path></svg> {tx('Fiche')}</button>
        </div>
        <div className="passid2-foot">
          <span className="passid2-chip"><FPIcon.Shield s={11} /> PASS ID</span>
          <span className="passid2-num">{p.id}</span>
        </div>
      </div>
    </CardMsg>
  );
}

// ── LOCATION · monochrome map placeholder + pin ──
function LocationCard({ side, time, status, lang }) {
  const t = (k) => fpT(lang, k);
  return (
    <CardMsg side={side} time={time} status={status}>
      <div className="fpcard location">
        <div className="loc-map">
          <div className="loc-grid"></div>
          <div className="loc-road r1"></div>
          <div className="loc-road r2"></div>
          <div className="loc-pin"><FPIcon.Pin c="#fff" s={14} /></div>
        </div>
        <div className="fpcard-row loc-row">
          <div className="fpcard-main">
            <div className="fpcard-title">{t('locationShared')}</div>
            <div className="fpcard-meta">La Turbie · Centre d'entraînement</div>
          </div>
        </div>
      </div>
    </CardMsg>
  );
}

// ── PHOTO · placeholder block ──
function PhotoMsg({ side, time, status }) {
  return (
    <CardMsg side={side} time={time} status={status}>
      <div className="fpcard photomsg">
        <div className="photo-ph">
          <svg width="26" height="22" viewBox="0 0 26 22" fill="none">
            <rect x="1" y="1" width="24" height="20" rx="3" stroke="currentColor" strokeWidth="1.4"></rect>
            <circle cx="8" cy="8" r="2.2" stroke="currentColor" strokeWidth="1.4"></circle>
            <path d="M1 16l6-5 5 4 5-6 8 8" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"></path>
          </svg>
        </div>
      </div>
    </CardMsg>
  );
}

// ── CALL LOG · centered system line ──
function CallLogMsg({ kind, dur, lang }) {
  const t = (k) => fpT(lang, k);
  const missed = kind === 'missed';
  const label = missed ? t('callMissed') : kind === 'video' ? t('callVideo') : t('callVoice');
  return (
    <div className={`call-log ${missed ? 'missed' : ''}`}>
      {kind === 'video' ? <FPIcon.Video c="currentColor" s={15} /> : <FPIcon.Phone c="currentColor" s={13} />}
      <span>{label}{dur ? ` · ${dur}` : ''}</span>
    </div>
  );
}

// ── TYPING indicator ──
function TypingMsg() {
  return (
    <div className="msg received">
      <div className="bubble received typing-bubble">
        <span className="tdot"></span><span className="tdot"></span><span className="tdot"></span>
      </div>
    </div>
  );
}

Object.assign(window, {
  CardMsg, Ticks, ContractCard, AuthProofCard, fpAuthKind, fpAuthParties, AgendaCard, PlayerCard, PassIdCard,
  LocationCard, PhotoMsg, CallLogMsg, TypingMsg,
});
