// BrokerTab_Partages — Liste des selections partagees (PR 2.3 Vague 2)
//
// Onglet "Partages" du Dashboard Courtier :
// - Liste les partages actifs (titre, vues, derniere consultation, expiration)
// - Bouton "Voir feedback" -> affiche les reactions du client
// - Bouton "Supprimer" -> revoque le partage
//
// Conventions React global, hooks alias suffixe BP.

(function () {
  'use strict';

  const {
    useState: useSBP,
    useEffect: useEBP,
    useMemo: useMBP,
  } = React;

  function _fmtDate(ts) {
    if (!ts) return '—';
    try {
      return new Intl.DateTimeFormat('fr-CA', {
        day: '2-digit', month: 'short', year: 'numeric',
      }).format(new Date(ts));
    } catch (_) {
      return new Date(ts).toLocaleDateString();
    }
  }

  function _fmtDateTime(ts) {
    if (!ts) return '—';
    try {
      return new Intl.DateTimeFormat('fr-CA', {
        day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit',
      }).format(new Date(ts));
    } catch (_) {
      return new Date(ts).toLocaleString();
    }
  }

  function _actionBadge(action) {
    const map = {
      like:     { label: 'J\'aime',      bg: '#dcfce7', fg: '#166534', icon: '👍' },
      dislike:  { label: 'Pas pour moi', bg: '#fee2e2', fg: '#991b1b', icon: '👎' },
      question: { label: 'Question',     bg: '#dbeafe', fg: '#1e40af', icon: '💬' },
    };
    const m = map[action] || { label: action, bg: '#e5e7eb', fg: '#374151', icon: '•' };
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 4,
        padding: '2px 8px', borderRadius: 12,
        background: m.bg, color: m.fg, fontSize: 11, fontWeight: 600,
      }}>
        <span aria-hidden="true">{m.icon}</span>{m.label}
      </span>
    );
  }

  function BrokerTabPartages({ lang }) {
    const [loading, setLoading] = useSBP(true);
    const [shares, setShares] = useSBP([]);
    const [error, setError] = useSBP('');
    const [openFeedbackId, setOpenFeedbackId] = useSBP(null);
    const [feedbackItems, setFeedbackItems] = useSBP([]);
    const [feedbackLoading, setFeedbackLoading] = useSBP(false);

    async function reload() {
      const api = window.vestora && window.vestora.brokerApi;
      if (!api || typeof api.listShares !== 'function') {
        setError('Module API indisponible.');
        setLoading(false);
        return;
      }
      setLoading(true);
      setError('');
      const r = await api.listShares();
      setLoading(false);
      if (!r.ok) {
        setError((r.error && r.error.message) || 'Echec du chargement.');
        return;
      }
      setShares(r.data || []);
    }

    useEBP(() => { reload(); }, []);

    async function loadFeedback(share) {
      const api = window.vestora && window.vestora.brokerApi;
      if (!api) return;
      setOpenFeedbackId(share.id);
      setFeedbackLoading(true);
      setFeedbackItems([]);
      const r = await api.getShareFeedback(share.id);
      setFeedbackLoading(false);
      if (r.ok) setFeedbackItems(r.data || []);
    }

    async function handleDelete(share) {
      if (!window.confirm('Supprimer ce partage ? Le lien public sera immediatement invalide.')) return;
      const api = window.vestora && window.vestora.brokerApi;
      if (!api) return;
      const r = await api.deleteShare(share.id);
      if (!r.ok) {
        alert('Suppression echouee : ' + ((r.error && r.error.message) || 'erreur inconnue'));
        return;
      }
      setShares((prev) => prev.filter((s) => s.id !== share.id));
      if (openFeedbackId === share.id) {
        setOpenFeedbackId(null);
        setFeedbackItems([]);
      }
    }

    async function copyLink(share) {
      // Reconstruit l'URL publique depuis l'origine actuelle.
      const url = location.origin + '/#/portail/' + share.shareToken;
      try { await navigator.clipboard.writeText(url); } catch (_) {}
    }

    const sortedShares = useMBP(() => {
      return [...shares].sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
    }, [shares]);

    const cardStyle = {
      background: 'var(--bg-elev, #fff)',
      border: '1px solid var(--line, #e5e7eb)',
      borderRadius: 12,
      padding: '14px 18px',
      marginBottom: 12,
    };

    if (loading) {
      return (
        <div style={{ padding: 40, textAlign: 'center', color: '#64748b' }}>
          Chargement des partages…
        </div>
      );
    }

    if (error) {
      return (
        <div style={{
          padding: 20, textAlign: 'center', color: '#991b1b',
          background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 10,
        }}>
          {error}
        </div>
      );
    }

    if (sortedShares.length === 0) {
      return (
        <div style={{
          padding: 40, textAlign: 'center', color: '#64748b',
          background: '#f8fafc', borderRadius: 12,
        }}>
          <div style={{ fontSize: 36, marginBottom: 12 }}>🔗</div>
          <div style={{ fontSize: 15, fontWeight: 600, color: '#0f172a', marginBottom: 6 }}>
            Aucun partage actif
          </div>
          <div style={{ fontSize: 13 }}>
            Allez dans l'onglet <em>Clients</em>, ouvrez les matches d'un client,
            cochez les biens a partager puis cliquez sur <em>Partager une selection</em>.
          </div>
        </div>
      );
    }

    return (
      <div style={{ padding: '8px 0' }}>
        <h2 style={{ fontSize: 16, fontWeight: 700, color: '#0f172a', margin: '0 0 12px' }}>
          Selections partagees ({sortedShares.length})
        </h2>
        {sortedShares.map((s) => {
          const expired = s.expiresAt && s.expiresAt <= Date.now();
          return (
            <div key={s.id} style={cardStyle}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 12,
                flexWrap: 'wrap', marginBottom: 6,
              }}>
                <div style={{ fontWeight: 700, fontSize: 14, color: '#0f172a', flex: 1, minWidth: 160 }}>
                  {s.title}
                </div>
                {expired && (
                  <span style={{
                    padding: '2px 8px', borderRadius: 10,
                    background: '#fee2e2', color: '#991b1b',
                    fontSize: 11, fontWeight: 600,
                  }}>EXPIRE</span>
                )}
              </div>
              <div style={{ fontSize: 12, color: '#64748b', marginBottom: 8 }}>
                {s.listingIds.length} bien{s.listingIds.length > 1 ? 's' : ''}
                {' · '}{s.viewCount} vue{s.viewCount > 1 ? 's' : ''}
                {' · '}Dernier acces : {_fmtDateTime(s.lastViewedAt)}
                {' · '}Expire le {_fmtDate(s.expiresAt)}
              </div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                <button
                  onClick={() => copyLink(s)}
                  style={{
                    padding: '5px 10px', borderRadius: 6,
                    background: 'transparent', border: '1px solid #cbd5e1',
                    color: '#475569', cursor: 'pointer', fontSize: 12,
                  }}
                >
                  Copier le lien
                </button>
                <button
                  onClick={() => loadFeedback(s)}
                  style={{
                    padding: '5px 10px', borderRadius: 6,
                    background: '#eff6ff', border: '1px solid #bfdbfe',
                    color: '#1d4ed8', cursor: 'pointer', fontSize: 12, fontWeight: 600,
                  }}
                >
                  Voir le feedback
                </button>
                <button
                  onClick={() => handleDelete(s)}
                  style={{
                    padding: '5px 10px', borderRadius: 6,
                    background: 'transparent', border: '1px solid #fecaca',
                    color: '#dc2626', cursor: 'pointer', fontSize: 12,
                  }}
                >
                  Supprimer
                </button>
              </div>

              {openFeedbackId === s.id && (
                <div style={{
                  marginTop: 12, padding: 12,
                  background: '#f8fafc', borderRadius: 8,
                  border: '1px solid #e2e8f0',
                }}>
                  {feedbackLoading ? (
                    <div style={{ fontSize: 13, color: '#64748b' }}>Chargement du feedback…</div>
                  ) : feedbackItems.length === 0 ? (
                    <div style={{ fontSize: 13, color: '#64748b' }}>
                      Aucun feedback recu pour le moment.
                    </div>
                  ) : (
                    feedbackItems.map((f) => (
                      <div key={f.id} style={{
                        padding: '6px 0', borderBottom: '1px solid #e2e8f0',
                      }}>
                        <div style={{
                          display: 'flex', alignItems: 'center', gap: 8,
                          fontSize: 12, color: '#0f172a', marginBottom: 2,
                        }}>
                          {_actionBadge(f.action)}
                          <span style={{ color: '#64748b' }}>
                            {f.listingId}
                          </span>
                          <span style={{ color: '#94a3b8', marginLeft: 'auto', fontSize: 11 }}>
                            {_fmtDateTime(f.createdAt)}
                          </span>
                        </div>
                        {f.comment && (
                          <div style={{ fontSize: 13, color: '#334155', marginTop: 4 }}>
                            « {f.comment} »
                          </div>
                        )}
                      </div>
                    ))
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>
    );
  }

  window.BrokerTabPartages = BrokerTabPartages;
})();
