// Clients_Matching.jsx — Vue "matches client ↔ listings" + modal de partage.
// Extrait de BrokerTab_Clients.jsx.
//
// Conventions : NO import/export, React global, unique hook aliases (suffix M).
//
// L'algo de matching (filtre budget/cities/propertyType + tri par profile score)
// reste dans l'orchestrateur BrokerTab_Clients.jsx (il a besoin de allListings
// et matchingClient ensemble pour le useMemo). Ce composant reçoit la liste
// déjà calculée via la prop `matchesForClient`.

function NewBadgeC() {
  return (
    <span style={{
      position: 'absolute', top: 8, left: 8, zIndex: 2,
      background: '#10b981', color: '#fff',
      fontSize: 10, fontWeight: 700, letterSpacing: '0.5px',
      padding: '3px 7px', borderRadius: 4,
      pointerEvents: 'none', boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
    }}>NOUVEAU</span>
  );
}

function ClientsMatching({
  matchingClient,
  matchesForClient,
  matchesNewCount,
  newOnly,
  setNewOnly,
  selectedShareIds,
  toggleShareSelected,
  copiedLink,
  onBack,
  onCopyShareLink,
  onOpenShareModal,
  // Modal de partage
  shareModalOpen,
  shareTitle,
  setShareTitle,
  shareTtlDays,
  setShareTtlDays,
  shareSubmitting,
  sharePublicUrl,
  shareCopied,
  shareError,
  onSubmitShareModal,
  onCloseShareModal,
  onCopyShareUrlAgain,
  // Utils
  t,
  lang,
}) {
  const u = window.vestoraBrokerClients || {};
  const CLIENT_NEW_MAX_DAYS = u.CLIENT_NEW_MAX_DAYS || 14;
  const isNewListing = u.isNewListing || (() => false);
  const clientSummary = u.clientSummary || (() => '');
  const styles = u.styles || {};
  const btnSmall = styles.btnSmall || {};
  const btnSecondary = styles.btnSecondary || {};

  const TT = window.TermTooltip || (({ children }) => <span>{children}</span>);

  if (!matchingClient) return null;

  return (
    <>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
          <button
            style={{ ...btnSecondary, padding: '6px 14px' }}
            onClick={onBack}
          >
            ← Retour
          </button>
          <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: '#111827' }}>
            Top 12 matches pour <em>{matchingClient.name}</em>
          </h3>
        </div>

        <div style={{ fontSize: 13, color: '#6b7280', marginBottom: 14 }}>
          {clientSummary(matchingClient)}
          {' '}&mdash;{' '}triés par{' '}
          <TT term="cap_rate" badge={false}>cap rate</TT>
          {' '}+{' '}
          <TT term="cash_flow" badge={false}>flux net</TT>
        </div>

        <div style={{ display: 'flex', gap: 10, marginBottom: 18, flexWrap: 'wrap', alignItems: 'center' }}>
          <button
            style={{
              ...btnSmall,
              background: copiedLink ? '#d1fae5' : 'transparent',
              color: copiedLink ? '#065f46' : '#374151',
              borderColor: copiedLink ? '#6ee7b7' : '#d1d5db',
            }}
            onClick={onCopyShareLink}
          >
            {copiedLink ? '✓ Copié !' : 'Copier lien partageable'}
          </button>

          {/* PR 2.3 — Partager une selection (portail client) */}
          <button
            style={{
              ...btnSmall,
              background: selectedShareIds.size > 0 ? '#1d4ed8' : '#eff6ff',
              color: selectedShareIds.size > 0 ? '#fff' : '#1d4ed8',
              borderColor: '#1d4ed8',
              fontWeight: 600,
            }}
            disabled={selectedShareIds.size === 0}
            onClick={onOpenShareModal}
            title="Cree un lien public a envoyer a votre client"
          >
            Partager une selection ({selectedShareIds.size})
          </button>

          <label
            title={`Affiche uniquement les biens listés depuis ≤ ${CLIENT_NEW_MAX_DAYS} jours`}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '5px 12px', borderRadius: 20,
              border: '1.5px solid', borderColor: newOnly ? '#10b981' : '#d1d5db',
              background: newOnly ? '#ecfdf5' : '#fff',
              color: newOnly ? '#065f46' : '#374151',
              fontSize: 13, fontWeight: newOnly ? 600 : 400,
              cursor: 'pointer', userSelect: 'none', whiteSpace: 'nowrap',
            }}
          >
            <input
              type="checkbox"
              checked={newOnly}
              onChange={(e) => setNewOnly(e.target.checked)}
              style={{ margin: 0, accentColor: '#10b981', cursor: 'pointer' }}
            />
            Nouveaux seulement
            <span style={{ fontSize: 11, color: newOnly ? '#047857' : '#9ca3af' }}>
              ({matchesNewCount})
            </span>
          </label>
        </div>

        {matchesForClient.length === 0 ? (
          <div style={{
            textAlign: 'center', padding: '40px 20px', color: '#9ca3af',
            fontSize: 14, background: '#f9fafb', borderRadius: 10,
            border: '1px dashed #d1d5db',
          }}>
            Aucun bien correspondant aux critères de ce client.
          </div>
        ) : (
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
            gap: 16,
          }}>
            {matchesForClient.map((l) => (
              <div key={l.id} style={{ position: 'relative' }}>
                {isNewListing(l) && <NewBadgeC />}
                {/* PR 2.3 — case a cocher selection partage */}
                <label
                  onClick={(e) => e.stopPropagation()}
                  style={{
                    position: 'absolute', top: 8, right: 8, zIndex: 3,
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                    padding: '4px 8px', borderRadius: 6,
                    background: 'rgba(255,255,255,0.92)',
                    border: '1px solid #cbd5e1',
                    fontSize: 11, color: '#0f172a', cursor: 'pointer',
                    userSelect: 'none', boxShadow: '0 1px 3px rgba(0,0,0,0.10)',
                  }}
                  title="Inclure dans la selection partageable"
                >
                  <input
                    type="checkbox"
                    checked={selectedShareIds.has(l.id)}
                    onChange={() => toggleShareSelected(l.id)}
                    style={{ accentColor: '#1d4ed8', cursor: 'pointer' }}
                  />
                  Partager
                </label>
                <ListingCard
                  listing={l}
                  t={t}
                  lang={lang}
                  activeProfile={matchingClient.profile}
                  active={false}
                  selected={false}
                  onHover={() => {}}
                  onLeave={() => {}}
                  onClick={() => {
                    const exists = (window.LISTINGS || []).some(x => String(x.id) === String(l.id));
                    if (!exists) {
                      alert(lang === 'en' ? 'Listing not found.' : 'Annonce introuvable.');
                      return;
                    }
                    window.navigateTo(`#/analyze/${encodeURIComponent(l.id)}`);
                  }}
                  isFav={false}
                  toggleFav={() => {}}
                />
              </div>
            ))}
          </div>
        )}
      </div>

      {/* ── Modal de creation de partage (PR 2.3) ── */}
      {shareModalOpen && (
        <div
          role="dialog"
          aria-modal="true"
          onClick={onCloseShareModal}
          style={{
            position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            zIndex: 1000, padding: 16,
          }}
        >
          <div
            onClick={(e) => e.stopPropagation()}
            style={{
              background: '#fff', borderRadius: 12, padding: 24,
              maxWidth: 520, width: '100%',
              boxShadow: '0 20px 60px rgba(0,0,0,0.25)',
            }}
          >
            <h3 style={{ margin: '0 0 12px', fontSize: 17, fontWeight: 700, color: '#0f172a' }}>
              Partager une selection
            </h3>

            {!sharePublicUrl && (
              <>
                <div style={{ fontSize: 13, color: '#475569', marginBottom: 12 }}>
                  {selectedShareIds.size} bien{selectedShareIds.size > 1 ? 's' : ''} selectionne{selectedShareIds.size > 1 ? 's' : ''}
                  {matchingClient ? ' pour ' + matchingClient.name : ''}.
                </div>
                <label style={{ display: 'block', fontSize: 13, color: '#374151', marginBottom: 4 }}>
                  Titre du partage
                </label>
                <input
                  type="text"
                  value={shareTitle}
                  onChange={(e) => setShareTitle(e.target.value)}
                  placeholder="ex. Selection pour Sophie"
                  style={{
                    width: '100%', padding: '8px 10px', borderRadius: 8,
                    border: '1px solid #cbd5e1', fontSize: 14,
                    boxSizing: 'border-box', marginBottom: 12,
                  }}
                  maxLength={256}
                />
                <label style={{ display: 'block', fontSize: 13, color: '#374151', marginBottom: 4 }}>
                  Validite (jours)
                </label>
                <input
                  type="number"
                  value={shareTtlDays}
                  onChange={(e) => setShareTtlDays(e.target.value)}
                  min={1}
                  max={180}
                  style={{
                    width: 120, padding: '8px 10px', borderRadius: 8,
                    border: '1px solid #cbd5e1', fontSize: 14, marginBottom: 12,
                  }}
                />
                <div style={{
                  fontSize: 11, color: '#64748b',
                  background: '#f8fafc', padding: 10, borderRadius: 8,
                  marginBottom: 12,
                }}>
                  Le lien public sera valable {Number(shareTtlDays) || 30} jours.
                  Vous pourrez revoquer le partage a tout moment depuis votre dashboard.
                </div>
                {shareError && (
                  <div style={{ color: '#dc2626', fontSize: 13, marginBottom: 8 }}>{shareError}</div>
                )}
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                  <button
                    type="button"
                    onClick={onCloseShareModal}
                    style={{
                      padding: '8px 16px', borderRadius: 8,
                      background: 'transparent', border: '1px solid #cbd5e1',
                      color: '#475569', cursor: 'pointer', fontSize: 14,
                    }}
                  >
                    Annuler
                  </button>
                  <button
                    type="button"
                    onClick={onSubmitShareModal}
                    disabled={shareSubmitting}
                    style={{
                      padding: '8px 16px', borderRadius: 8,
                      background: '#1d4ed8', color: '#fff',
                      border: 'none', cursor: shareSubmitting ? 'wait' : 'pointer',
                      fontSize: 14, fontWeight: 600,
                      opacity: shareSubmitting ? 0.7 : 1,
                    }}
                  >
                    {shareSubmitting ? 'Creation…' : 'Creer le lien'}
                  </button>
                </div>
              </>
            )}

            {sharePublicUrl && (
              <>
                <div style={{
                  background: '#ecfdf5', border: '1px solid #6ee7b7',
                  color: '#065f46', padding: 10, borderRadius: 8,
                  fontSize: 13, marginBottom: 12,
                }}>
                  Lien cree et copie dans le presse-papier !
                </div>
                <div style={{
                  display: 'flex', gap: 6, alignItems: 'center',
                  background: '#f1f5f9', padding: 8, borderRadius: 8,
                  fontFamily: 'monospace', fontSize: 12, color: '#0f172a',
                  wordBreak: 'break-all', marginBottom: 12,
                }}>
                  {sharePublicUrl}
                </div>
                <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                  <button
                    type="button"
                    onClick={onCopyShareUrlAgain}
                    style={{
                      padding: '8px 14px', borderRadius: 8,
                      background: shareCopied ? '#d1fae5' : 'transparent',
                      color: shareCopied ? '#065f46' : '#475569',
                      border: '1px solid ' + (shareCopied ? '#6ee7b7' : '#cbd5e1'),
                      cursor: 'pointer', fontSize: 13,
                    }}
                  >
                    {shareCopied ? '✓ Copie' : 'Copier a nouveau'}
                  </button>
                  <button
                    type="button"
                    onClick={onCloseShareModal}
                    style={{
                      padding: '8px 16px', borderRadius: 8,
                      background: '#1d4ed8', color: '#fff',
                      border: 'none', cursor: 'pointer', fontSize: 14, fontWeight: 600,
                    }}
                  >
                    Fermer
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      )}
    </>
  );
}

if (typeof window !== 'undefined') {
  window.ClientsMatching = ClientsMatching;
}
