// screens-profile.jsx — profile + reviews + my profile

// Helpers : adapte un user qui peut venir du mock (objects bilingues) OU de l'API (strings)
function userName(u, lang) {
  if (!u) return '';
  if (typeof u.name === 'object' && u.name !== null) return u.name[lang] || u.name.fr || '';
  return u.name || '';
}
function userLocation(u, lang) {
  if (!u) return '';
  if (u.city) return u.city;
  if (typeof u.location === 'object' && u.location !== null) return u.location[lang] || u.location.fr || '';
  return u.location || '';
}
function userBio(u, lang) {
  if (!u) return '';
  if (typeof u.bio === 'object' && u.bio !== null) return u.bio[lang] || u.bio.fr || '';
  return u.bio || '';
}
function userPhoto(u) {
  return (u && (u.profile_photo || u.avatar)) || null;
}
function memberSinceLabel(u, lang) {
  if (!u || !u.created_at) return null;
  const d = new Date(u.created_at);
  if (isNaN(d.getTime())) return null;
  const year = d.getFullYear();
  return lang === 'ka' ? `წევრი ${year}-დან` : `Membre depuis ${year}`;
}

function ProfileScreen({ user, lang, t, onBack, onOpenChat, onLeaveReview, isMe = false, onOpenReferral, onLogout, onOpenMyListings, onOpenFavorites, onOpenAbout, onOpenContact, onOpenPrivacy, onOpenTerms, onOpenDeleteAccount, onOpenBlocked }) {
  const [showReport, setShowReport] = React.useState(false);
  const [showBlock, setShowBlock] = React.useState(false);
  // En mode "isMe", on utilise toujours le user réel du localStorage (ignore le prop user mock)
  const realUser = isMe
    ? (window.TrustaAuth && window.TrustaAuth.getUser()) || null
    : user;

  if (!realUser) {
    return (
      <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ color: COLORS.text3, fontFamily: 'Inter', fontSize: 13 }}>
          {lang === 'ka' ? 'იტვირთება…' : 'Chargement…'}
        </div>
      </div>
    );
  }

  const name = userName(realUser, lang);
  const location = userLocation(realUser, lang);
  const photo = userPhoto(realUser);
  const bio = userBio(realUser, lang);
  const memberSince = memberSinceLabel(realUser, lang);
  const verified = !!realUser.verified;

  // Stats : seulement si le user a des données réelles (pour l'instant aucune)
  const hasStats = (realUser.missions != null && realUser.missions > 0)
    || (realUser.recommend != null);
  const hasReviews = realUser.reviewCount && realUser.reviewCount > 0;
  const hasRating = realUser.rating != null && realUser.rating > 0;

  const handleLogout = async () => {
    if (!window.TrustaAPI) return;
    try { await window.TrustaAPI.logout(); } catch (e) {}
    if (onLogout) onLogout();
    else window.location.reload();
  };

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <Header onBack={isMe ? null : onBack} title="" right={
        <div style={{ display: 'flex', gap: 8 }}>
          {!isMe && realUser && realUser.id && (
            <HeartButton kind="profile" id={realUser.id} size={18} style={{ width: 38, height: 38, borderRadius: 12 }} />
          )}
        </div>
      } />

      <div style={{ flex: 1, overflow: 'auto', padding: '0 24px 110px' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
          <Avatar src={photo} size={92} ring verified={verified} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 8 }}>
            <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 24, color: '#fff', fontWeight: 600 }}>
              {name || (lang === 'ka' ? 'უსახელო' : 'Sans nom')}
            </div>
            {verified && (
              <div style={{ width: 18, height: 18, borderRadius: 9, background: COLORS.gold, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <svg width="10" height="10" viewBox="0 0 10 10"><path d="M2 5 L4 7 L8 3" stroke="#0A0A0A" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
              </div>
            )}
          </div>
          {(location || memberSince) && (
            <div style={{ fontFamily: 'Inter', fontSize: 12, color: COLORS.text3, display: 'flex', alignItems: 'center', gap: 4 }}>
              {location && (
                <>
                  <svg width="10" height="10" viewBox="0 0 10 10"><path d="M5 1 C7 1 8 2 8 4 C8 6 5 9 5 9 C5 9 2 6 2 4 C2 2 3 1 5 1 Z" stroke={COLORS.text3} strokeWidth="1" fill="none" /></svg>
                  {location}
                </>
              )}
              {location && memberSince && ' · '}
              {memberSince}
            </div>
          )}
          {hasRating && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6 }}>
              <Stars value={realUser.rating} size={14} />
              <span style={{ fontFamily: 'Inter', fontSize: 14, color: COLORS.gold, fontWeight: 600 }}>{realUser.rating}</span>
              <span style={{ fontFamily: 'Inter', fontSize: 12, color: COLORS.text3 }}>({realUser.reviewCount} {t('reviews')})</span>
            </div>
          )}
        </div>

        {/* Stats — seulement si le user a des données réelles */}
        {hasStats && (
          <div style={{
            marginTop: 22, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10,
            padding: '18px 0', borderTop: `1px solid ${COLORS.borderSoft}`, borderBottom: `1px solid ${COLORS.borderSoft}`,
          }}>
            {[
              { val: realUser.missions || 0, label: t('missions_done') },
              { val: realUser.years || 0, label: t('years_active') },
              { val: (realUser.recommend || 0) + '%', label: t('recommendation') },
            ].map((s, i) => (
              <div key={i} style={{ textAlign: 'center', borderLeft: i > 0 ? `1px solid ${COLORS.borderSoft}` : 'none' }}>
                <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 26, color: COLORS.gold, fontWeight: 600 }}>{s.val}</div>
                <div style={{ fontFamily: 'Inter', fontSize: 10, color: COLORS.text3, textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 2 }}>{s.label}</div>
              </div>
            ))}
          </div>
        )}

        {/* Bio */}
        {bio && (
          <div style={{ marginTop: 18, fontFamily: 'Inter', fontSize: 13, color: COLORS.text2, lineHeight: 1.55, whiteSpace: 'pre-wrap' }}>
            {bio}
          </div>
        )}

        {/* Empty state pour profil neuf */}
        {isMe && !bio && !hasReviews && !hasStats && (
          <div style={{
            marginTop: 24, padding: '20px 16px', textAlign: 'center',
            background: COLORS.card, borderRadius: 14, border: `1px dashed ${COLORS.borderSoft}`,
          }}>
            <div style={{ fontFamily: 'Inter', fontSize: 13, color: COLORS.text2, lineHeight: 1.5 }}>
              {lang === 'ka'
                ? 'შენი პროფილი ჯერ ცარიელია. შექმენი განცხადება, რომ თემამ გაგიცნოს.'
                : 'Ton profil est encore vide. Crée une annonce pour que la communauté te découvre.'}
            </div>
          </div>
        )}

        {/* Reviews — seulement si vraies reviews */}
        {hasReviews && window.REVIEWS && window.REVIEWS[realUser.id] && (
          <div style={{ marginTop: 22 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
              <div style={{ fontFamily: 'Inter', fontSize: 12, color: '#fff', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6 }}>{t('reviews_section')}</div>
              <div style={{ fontFamily: 'Inter', fontSize: 12, color: COLORS.gold }}>{t('view_all')}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {window.REVIEWS[realUser.id].slice(0, 2).map((r, i) => {
                const author = window.MEMBERS && window.MEMBERS[r.author];
                if (!author) return null;
                return (
                  <div key={i} style={{ padding: 14, background: COLORS.card, borderRadius: 14, border: `1px solid ${COLORS.borderSoft}` }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <Avatar src={author.avatar} size={32} />
                      <div style={{ flex: 1 }}>
                        <div style={{ fontFamily: 'Inter', fontSize: 13, color: '#fff', fontWeight: 600 }}>{userName(author, lang)}</div>
                        <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginTop: 1 }}>
                          <Stars value={r.stars} size={10} />
                          <span style={{ fontFamily: 'Inter', fontSize: 10, color: COLORS.text3 }}>{r.date}</span>
                        </div>
                      </div>
                    </div>
                    <div style={{ marginTop: 8, fontFamily: 'Inter', fontSize: 13, color: COLORS.text2, lineHeight: 1.5 }}>
                      {r.text[lang]}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {!isMe && (
          <div style={{
            marginTop: 22, paddingTop: 18,
            borderTop: `1px solid ${COLORS.borderSoft}`,
            display: 'flex', justifyContent: 'center', gap: 20,
          }}>
            <button onClick={() => setShowReport(true)} style={{
              display: 'flex', alignItems: 'center', gap: 6,
              background: 'transparent', border: 'none', cursor: 'pointer',
              color: COLORS.text2, fontFamily: 'Inter', fontSize: 13, fontWeight: 500,
              padding: '6px 10px',
            }}>
              <span style={{ fontSize: 14 }}>🚩</span>
              {lang === 'ka' ? 'სიგნალი' : 'Signaler'}
            </button>
            <div style={{ width: 1, background: COLORS.borderSoft }} />
            <button onClick={() => setShowBlock(true)} style={{
              display: 'flex', alignItems: 'center', gap: 6,
              background: 'transparent', border: 'none', cursor: 'pointer',
              color: COLORS.red, fontFamily: 'Inter', fontSize: 13, fontWeight: 500,
              padding: '6px 10px',
            }}>
              <span style={{ fontSize: 14 }}>🚫</span>
              {lang === 'ka' ? 'დაბლოკვა' : 'Bloquer'}
            </button>
          </div>
        )}

        {isMe && (
          <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <button onClick={onOpenMyListings} style={menuRowStyle()}>
              <div style={menuIconStyle()}>
                <svg width="14" height="14" viewBox="0 0 14 14"><rect x="2" y="2" width="10" height="3" fill="none" stroke={COLORS.gold} strokeWidth="1.4" /><rect x="2" y="6.5" width="10" height="3" fill="none" stroke={COLORS.gold} strokeWidth="1.4" /><rect x="2" y="11" width="10" height="1.5" fill="none" stroke={COLORS.gold} strokeWidth="1.4" /></svg>
              </div>
              <div style={{ flex: 1, textAlign: 'left' }}>{lang === 'ka' ? 'ჩემი განცხადებები' : 'Mes annonces'}</div>
              <svg width="8" height="12" viewBox="0 0 8 12"><path d="M2 1 L6 6 L2 11" stroke={COLORS.text3} strokeWidth="1.4" fill="none" strokeLinecap="round" /></svg>
            </button>
            <button onClick={onOpenFavorites} style={menuRowStyle()}>
              <div style={menuIconStyle()}>
                <svg width="14" height="14" viewBox="0 0 24 24"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" stroke={COLORS.gold} strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
              </div>
              <div style={{ flex: 1, textAlign: 'left' }}>{lang === 'ka' ? 'ფავორიტები' : 'Favoris'}</div>
              <svg width="8" height="12" viewBox="0 0 8 12"><path d="M2 1 L6 6 L2 11" stroke={COLORS.text3} strokeWidth="1.4" fill="none" strokeLinecap="round" /></svg>
            </button>
            <button onClick={onOpenReferral} style={menuRowStyle()}>
              <div style={menuIconStyle()}>
                <svg width="14" height="14" viewBox="0 0 14 14"><path d="M7 8 C5 8 3 6.5 3 4.5 C3 2.5 4.5 1 7 1 C9.5 1 11 2.5 11 4.5 C11 6.5 9 8 7 8 Z M2 13 C2 11 4 10 7 10 C10 10 12 11 12 13" fill="none" stroke={COLORS.gold} strokeWidth="1.4" /></svg>
              </div>
              <div style={{ flex: 1, textAlign: 'left' }}>{t('invite_friends')}</div>
              <svg width="8" height="12" viewBox="0 0 8 12"><path d="M2 1 L6 6 L2 11" stroke={COLORS.text3} strokeWidth="1.4" fill="none" strokeLinecap="round" /></svg>
            </button>
            <button onClick={handleLogout} style={menuRowStyle()}>
              <div style={menuIconStyle()}>
                <svg width="14" height="14" viewBox="0 0 14 14"><path d="M9 3 V1 H2 V13 H9 V11 M5 7 H13 M11 5 L13 7 L11 9" stroke={COLORS.gold} strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
              </div>
              <div style={{ flex: 1, textAlign: 'left' }}>{lang === 'ka' ? 'გასვლა' : 'Déconnexion'}</div>
              <svg width="8" height="12" viewBox="0 0 8 12"><path d="M2 1 L6 6 L2 11" stroke={COLORS.text3} strokeWidth="1.4" fill="none" strokeLinecap="round" /></svg>
            </button>

            {/* Section légale & support (pages requises App Store / Google Play) */}
            <div style={{
              marginTop: 14, paddingTop: 14, borderTop: `1px solid ${COLORS.borderSoft}`,
              display: 'flex', flexDirection: 'column', gap: 8,
            }}>
              <div style={{
                fontFamily: 'Inter', fontSize: 11, fontWeight: 600,
                color: COLORS.text3, letterSpacing: '0.18em', textTransform: 'uppercase',
                marginBottom: 4, paddingLeft: 4,
              }}>
                {lang === 'ka' ? 'ინფორმაცია' : 'Informations'}
              </div>

              {onOpenAbout && (
                <button onClick={onOpenAbout} style={menuRowStyle()}>
                  <div style={menuIconStyle()}>
                    <svg width="14" height="14" viewBox="0 0 14 14"><circle cx="7" cy="7" r="5.5" fill="none" stroke={COLORS.gold} strokeWidth="1.4"/><circle cx="7" cy="4.5" r="0.6" fill={COLORS.gold}/><path d="M7 6.5 V10" stroke={COLORS.gold} strokeWidth="1.4" strokeLinecap="round"/></svg>
                  </div>
                  <div style={{ flex: 1, textAlign: 'left' }}>{lang === 'ka' ? 'ჩვენს შესახებ' : 'À propos'}</div>
                  <svg width="8" height="12" viewBox="0 0 8 12"><path d="M2 1 L6 6 L2 11" stroke={COLORS.text3} strokeWidth="1.4" fill="none" strokeLinecap="round" /></svg>
                </button>
              )}

              {onOpenContact && (
                <button onClick={onOpenContact} style={menuRowStyle()}>
                  <div style={menuIconStyle()}>
                    <svg width="14" height="14" viewBox="0 0 14 14"><rect x="1.5" y="3" width="11" height="8" rx="1" fill="none" stroke={COLORS.gold} strokeWidth="1.4"/><path d="M1.5 4 L7 8 L12.5 4" fill="none" stroke={COLORS.gold} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </div>
                  <div style={{ flex: 1, textAlign: 'left' }}>{lang === 'ka' ? 'კონტაქტი' : 'Contact / Aide'}</div>
                  <svg width="8" height="12" viewBox="0 0 8 12"><path d="M2 1 L6 6 L2 11" stroke={COLORS.text3} strokeWidth="1.4" fill="none" strokeLinecap="round" /></svg>
                </button>
              )}

              {onOpenPrivacy && (
                <button onClick={onOpenPrivacy} style={menuRowStyle()}>
                  <div style={menuIconStyle()}>
                    <svg width="14" height="14" viewBox="0 0 14 14"><path d="M7 1 L12 3 V7 C12 10 9.5 12.5 7 13 C4.5 12.5 2 10 2 7 V3 L7 1 Z" fill="none" stroke={COLORS.gold} strokeWidth="1.4" strokeLinejoin="round"/></svg>
                  </div>
                  <div style={{ flex: 1, textAlign: 'left' }}>{lang === 'ka' ? 'კონფიდენციალურობა' : 'Confidentialité'}</div>
                  <svg width="8" height="12" viewBox="0 0 8 12"><path d="M2 1 L6 6 L2 11" stroke={COLORS.text3} strokeWidth="1.4" fill="none" strokeLinecap="round" /></svg>
                </button>
              )}

              {onOpenTerms && (
                <button onClick={onOpenTerms} style={menuRowStyle()}>
                  <div style={menuIconStyle()}>
                    <svg width="14" height="14" viewBox="0 0 14 14"><rect x="2.5" y="1.5" width="9" height="11" rx="0.5" fill="none" stroke={COLORS.gold} strokeWidth="1.4"/><path d="M4.5 4.5 H9.5 M4.5 7 H9.5 M4.5 9.5 H7.5" stroke={COLORS.gold} strokeWidth="1.2" strokeLinecap="round"/></svg>
                  </div>
                  <div style={{ flex: 1, textAlign: 'left' }}>{lang === 'ka' ? 'პირობები' : 'Conditions d\'utilisation'}</div>
                  <svg width="8" height="12" viewBox="0 0 8 12"><path d="M2 1 L6 6 L2 11" stroke={COLORS.text3} strokeWidth="1.4" fill="none" strokeLinecap="round" /></svg>
                </button>
              )}

              {onOpenBlocked && (
                <button onClick={onOpenBlocked} style={menuRowStyle()}>
                  <div style={menuIconStyle()}>
                    <svg width="14" height="14" viewBox="0 0 14 14"><circle cx="7" cy="7" r="5.5" fill="none" stroke={COLORS.gold} strokeWidth="1.4"/><path d="M3 3 L11 11" stroke={COLORS.gold} strokeWidth="1.4" strokeLinecap="round"/></svg>
                  </div>
                  <div style={{ flex: 1, textAlign: 'left' }}>{lang === 'ka' ? 'დაბლოკილი მომხმარებლები' : 'Utilisateurs bloqués'}</div>
                  <svg width="8" height="12" viewBox="0 0 8 12"><path d="M2 1 L6 6 L2 11" stroke={COLORS.text3} strokeWidth="1.4" fill="none" strokeLinecap="round" /></svg>
                </button>
              )}

              {/* Suppression de compte — obligatoire Apple/Google. Rouge pour signaler la criticité */}
              {onOpenDeleteAccount && (
                <button onClick={onOpenDeleteAccount} style={{
                  ...menuRowStyle(),
                  marginTop: 8,
                  border: '1px solid rgba(239, 68, 68, 0.25)',
                  background: 'rgba(239, 68, 68, 0.04)',
                }}>
                  <div style={{
                    ...menuIconStyle(),
                    background: 'rgba(239, 68, 68, 0.10)',
                    border: '1px solid rgba(239, 68, 68, 0.25)',
                  }}>
                    <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 4 H11 M5 4 V2 H9 V4 M4 4 L4.5 12 H9.5 L10 4" stroke={COLORS.red} strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </div>
                  <div style={{ flex: 1, textAlign: 'left', color: COLORS.red }}>
                    {lang === 'ka' ? 'ანგარიშის წაშლა' : 'Supprimer mon compte'}
                  </div>
                  <svg width="8" height="12" viewBox="0 0 8 12"><path d="M2 1 L6 6 L2 11" stroke={COLORS.text3} strokeWidth="1.4" fill="none" strokeLinecap="round" /></svg>
                </button>
              )}

              <div style={{
                fontFamily: 'Inter', fontSize: 10, color: COLORS.text3,
                textAlign: 'center', marginTop: 18, opacity: 0.5,
              }}>
                TRUSTA · v1.0 · trusta.click
              </div>
            </div>
          </div>
        )}
      </div>

      {!isMe && onOpenChat && (
        <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '12px 20px 28px', background: 'linear-gradient(180deg, rgba(11,11,11,0) 0%, #0B0B0B 30%)', display: 'flex', gap: 10 }}>
          {onLeaveReview && <GhostButton onClick={onLeaveReview}>{t('leave_review')}</GhostButton>}
          <GoldButton onClick={() => onOpenChat(realUser)}>{t('message_btn')}</GoldButton>
        </div>
      )}

      {/* Modals signaler / bloquer */}
      {showReport && window.ReportModal && (
        <ReportModal
          target={{ type: 'user', id: realUser.id }}
          lang={lang}
          onClose={() => setShowReport(false)}
        />
      )}
      {showBlock && window.BlockUserModal && (
        <BlockUserModal
          targetUser={realUser}
          lang={lang}
          onClose={() => setShowBlock(false)}
          onBlocked={() => {
            // Une fois bloqué, retour à l'accueil (on ne devrait plus voir ce profil)
            if (onBack) onBack();
          }}
        />
      )}
    </div>
  );
}

function menuRowStyle() {
  return {
    display: 'flex', alignItems: 'center', gap: 12, padding: '14px 14px',
    background: COLORS.card, borderRadius: 12, border: `1px solid ${COLORS.borderSoft}`,
    color: '#fff', fontFamily: 'Inter', fontSize: 14, fontWeight: 500,
    cursor: 'pointer', textAlign: 'left',
  };
}
function menuIconStyle() {
  return {
    width: 28, height: 28, borderRadius: 8, background: COLORS.goldSoft,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  };
}

function ReviewModal({ user, lang, t, onClose }) {
  const [stars, setStars] = React.useState(5);
  const [text, setText] = React.useState('');
  const [sent, setSent] = React.useState(false);
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'flex-end',
    }}>
      <div style={{
        width: '100%', background: COLORS.bg2, borderRadius: '24px 24px 0 0',
        padding: '20px 24px 36px', animation: 'slideUp .3s ease-out',
      }}>
        <div style={{ width: 36, height: 4, borderRadius: 2, background: 'rgba(255,255,255,0.2)', margin: '0 auto 18px' }} />
        {sent ? (
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <div style={{ width: 56, height: 56, borderRadius: 28, background: COLORS.goldSoft, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
              <svg width="24" height="24" viewBox="0 0 24 24"><path d="M5 12 L10 17 L19 7" stroke={COLORS.gold} strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
            </div>
            <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 20, color: '#fff' }}>
              {lang === 'ka' ? 'გმადლობთ!' : 'Merci !'}
            </div>
            <div style={{ fontFamily: 'Inter', fontSize: 13, color: COLORS.text2, marginTop: 8 }}>
              {lang === 'ka' ? 'შეფასება გაგზავნილია' : 'Votre avis a été envoyé'}
            </div>
          </div>
        ) : (
          <React.Fragment>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
              <Avatar src={userPhoto(user)} size={64} verified={!!user.verified} />
              <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 22, color: '#fff' }}>{userName(user, lang)}</div>
              <div style={{ fontFamily: 'Inter', fontSize: 13, color: COLORS.text2 }}>{t('how_was')}</div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'center', gap: 6, marginTop: 18 }}>
              {[1, 2, 3, 4, 5].map(i => (
                <button key={i} onClick={() => setStars(i)} style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 4 }}>
                  <svg width="32" height="32" viewBox="0 0 32 32">
                    <path d="M16 3 L20 12 L30 13 L22.5 20 L24.5 30 L16 25 L7.5 30 L9.5 20 L2 13 L12 12 Z"
                      fill={i <= stars ? COLORS.gold : 'transparent'}
                      stroke={i <= stars ? COLORS.gold : COLORS.text3} strokeWidth="1.2" />
                  </svg>
                </button>
              ))}
            </div>
            <div style={{ marginTop: 18 }}>
              <div style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text3, marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.4 }}>{t('comment')}</div>
              <textarea
                value={text} onChange={e => setText(e.target.value)}
                placeholder={t('comment_ph')}
                style={{
                  width: '100%', minHeight: 80, padding: 14, borderRadius: 12,
                  background: COLORS.card, border: `1px solid ${COLORS.borderSoft}`,
                  color: '#fff', fontFamily: 'Inter', fontSize: 13, outline: 'none', resize: 'none',
                  boxSizing: 'border-box',
                }}
              />
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
              <button onClick={onClose} style={{
                flex: 1, height: 48, borderRadius: 12,
                background: 'transparent', border: `1px solid ${COLORS.borderSoft}`,
                color: COLORS.text2, fontFamily: 'Inter', fontSize: 14, fontWeight: 600, cursor: 'pointer',
              }}>{lang === 'ka' ? 'გაუქმება' : 'Annuler'}</button>
              <GoldButton onClick={() => { setSent(true); setTimeout(onClose, 1400); }}>{t('send')}</GoldButton>
            </div>
          </React.Fragment>
        )}
      </div>
      <style>{`@keyframes slideUp { from { transform: translateY(40%); opacity: 0; } to { transform: translateY(0); opacity: 1; } }`}</style>
    </div>
  );
}

// === Mes annonces ===
function MyListingsScreen({ lang, t, onBack, onOpenListing, onCreateListing }) {
  const [listings, setListings] = React.useState(null);
  const [error, setError] = React.useState(null);
  const me = (window.TrustaAuth && window.TrustaAuth.getUser()) || null;

  const load = React.useCallback(() => {
    if (!window.API_AVAILABLE || !me) { setListings([]); return; }
    setListings(null); setError(null);
    window.TrustaAPI.listListings({ user_id: me.id })
      .then(rows => setListings(rows || []))
      .catch(err => { setError(err); setListings([]); });
  }, [me ? me.id : 0]);

  React.useEffect(() => { load(); }, [load]);

  const handleDelete = async (l) => {
    const msg = lang === 'ka' ? 'წავშალო ეს განცხადება?' : 'Supprimer cette annonce ?';
    if (!window.confirm(msg)) return;
    try {
      await window.TrustaAPI.deleteListing(l.id);
      setListings(prev => prev.filter(x => x.id !== l.id));
    } catch (e) {
      alert(window.errorMessage ? window.errorMessage(e, lang) : 'Erreur');
    }
  };

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <Header onBack={onBack} title={lang === 'ka' ? 'ჩემი განცხადებები' : 'Mes annonces'} />

      <div style={{ flex: 1, overflow: 'auto', padding: '4px 16px 110px' }}>
        {listings === null ? (
          <div style={{ textAlign: 'center', padding: 60, color: COLORS.text3, fontFamily: 'Inter', fontSize: 13 }}>
            {lang === 'ka' ? 'იტვირთება...' : 'Chargement...'}
          </div>
        ) : listings.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '60px 20px', color: COLORS.text3, fontFamily: 'Inter' }}>
            <div style={{ fontSize: 40, marginBottom: 16 }}>📋</div>
            <div style={{ color: '#fff', fontWeight: 600, fontSize: 16, marginBottom: 6 }}>
              {lang === 'ka' ? 'ჯერ განცხადება არ გაქვთ' : 'Pas encore d\'annonce'}
            </div>
            <div style={{ fontSize: 13, marginBottom: 20 }}>
              {lang === 'ka' ? 'შექმენი შენი პირველი განცხადება' : 'Créez votre première annonce'}
            </div>
            {onCreateListing && (
              <GoldButton onClick={onCreateListing}>
                {lang === 'ka' ? '+ განცხადების დამატება' : '+ Créer une annonce'}
              </GoldButton>
            )}
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {listings.map(l => {
              const title = (typeof l.title === 'object' ? (l.title[lang] || l.title.fr) : l.title) || '';
              const city = l.city || (Array.isArray(l.cities) ? l.cities[0] : '');
              const photo = (Array.isArray(l.photos) && l.photos[0]) || null;
              const price = l.price && l.price.amount ? `${l.price.amount}€` : (lang === 'ka' ? 'შესათანხმებელი' : 'À discuter');
              return (
                <div key={l.id} style={{
                  background: COLORS.card, border: `1px solid ${COLORS.borderSoft}`,
                  borderRadius: 12, overflow: 'hidden', display: 'flex', gap: 12, padding: 10,
                }}>
                  <button onClick={() => onOpenListing(l)} style={{
                    width: 84, height: 84, borderRadius: 10, border: 'none', cursor: 'pointer',
                    flexShrink: 0,
                    background: photo ? `url(${photo}) center/cover` : `linear-gradient(135deg, ${COLORS.bg2} 0%, rgba(212,175,55,0.06) 100%)`,
                  }} />
                  <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                    <button onClick={() => onOpenListing(l)} style={{
                      background: 'transparent', border: 'none', cursor: 'pointer', textAlign: 'left', padding: 0,
                    }}>
                      <div style={{ fontFamily: 'Inter', fontSize: 14, fontWeight: 600, color: '#fff',
                        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {title}
                      </div>
                      <div style={{ fontFamily: 'Inter', fontSize: 12, color: COLORS.text3, marginTop: 4 }}>
                        📍 {city || '—'} · <span style={{ color: COLORS.gold, fontWeight: 600 }}>{price}</span>
                      </div>
                    </button>
                    <div style={{ display: 'flex', gap: 6 }}>
                      <button onClick={() => onOpenListing(l)} style={smallBtnStyle(false)}>
                        {lang === 'ka' ? 'ნახვა' : 'Voir'}
                      </button>
                      <button onClick={() => handleDelete(l)} style={smallBtnStyle(true)}>
                        🗑 {lang === 'ka' ? 'წაშლა' : 'Supprimer'}
                      </button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

function smallBtnStyle(danger) {
  return {
    flex: 1, padding: '8px 10px', borderRadius: 8,
    background: 'transparent',
    border: danger ? '1px solid rgba(255,107,107,0.5)' : `1px solid ${COLORS.borderSoft}`,
    color: danger ? '#ff6b6b' : '#fff',
    fontFamily: 'Inter', fontSize: 12, fontWeight: 500, cursor: 'pointer',
  };
}

// === Favoris (2 onglets : annonces + profils) ===
function FavoritesScreen({ lang, t, onBack, onOpenListing, onOpenProfile }) {
  const [activeTab, setActiveTab] = React.useState('listing');
  const [listings, setListings] = React.useState(null);
  const [profiles, setProfiles] = React.useState(null);
  const [error, setError] = React.useState(null);

  const load = React.useCallback(async (tab) => {
    if (!window.API_AVAILABLE) { setListings([]); setProfiles([]); return; }
    setError(null);
    try {
      if (tab === 'listing') {
        setListings(null);
        const rows = await window.TrustaAPI.listFavorites('listing');
        setListings(rows || []);
      } else {
        setProfiles(null);
        const rows = await window.TrustaAPI.listFavorites('profile');
        setProfiles(rows || []);
      }
    } catch (e) {
      setError(e);
      if (tab === 'listing') setListings([]); else setProfiles([]);
    }
  }, []);

  React.useEffect(() => { load(activeTab); }, [activeTab, load]);

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <Header onBack={onBack} title={lang === 'ka' ? 'ფავორიტები' : 'Favoris'} />

      {/* Tabs switcher */}
      <div style={{
        margin: '0 16px 12px', display: 'flex', gap: 6,
        background: COLORS.card, borderRadius: 12, padding: 4, border: `1px solid ${COLORS.borderSoft}`,
      }}>
        {[
          { key: 'listing', fr: 'Annonces', ka: 'განცხადებები' },
          { key: 'profile', fr: 'Profils',  ka: 'პროფილები' },
        ].map(tab => (
          <button key={tab.key} onClick={() => setActiveTab(tab.key)} style={{
            flex: 1, padding: '10px 12px', borderRadius: 8,
            background: activeTab === tab.key ? COLORS.gold : 'transparent',
            color: activeTab === tab.key ? '#0A0A0A' : COLORS.text2,
            border: 'none', cursor: 'pointer',
            fontFamily: 'Inter', fontSize: 13, fontWeight: 600,
          }}>
            {tab[lang]}
          </button>
        ))}
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '0 16px 110px' }}>
        {activeTab === 'listing' ? (
          listings === null ? (
            <Loading lang={lang} />
          ) : listings.length === 0 ? (
            <EmptyFav lang={lang} kind="listing" />
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {listings.map(l => <FavListingRow key={l.id} listing={l} lang={lang} t={t} onOpen={onOpenListing} />)}
            </div>
          )
        ) : (
          profiles === null ? (
            <Loading lang={lang} />
          ) : profiles.length === 0 ? (
            <EmptyFav lang={lang} kind="profile" />
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {profiles.map(p => <FavProfileRow key={p.id} user={p} lang={lang} onOpen={onOpenProfile} />)}
            </div>
          )
        )}
      </div>
    </div>
  );
}

function Loading({ lang }) {
  return (
    <div style={{ textAlign: 'center', padding: 60, color: COLORS.text3, fontFamily: 'Inter', fontSize: 13 }}>
      {lang === 'ka' ? 'იტვირთება...' : 'Chargement...'}
    </div>
  );
}

function EmptyFav({ lang, kind }) {
  const txt = kind === 'listing'
    ? { fr: 'Aucune annonce en favori', ka: 'რჩეულ განცხადებებში ცარიელია' }
    : { fr: 'Aucun profil en favori',   ka: 'რჩეულ პროფილებში ცარიელია' };
  const hint = kind === 'listing'
    ? { fr: 'Touche le ♡ sur une annonce pour l\'ajouter ici', ka: 'დააჭირე ♡-ს განცხადებაზე' }
    : { fr: 'Touche le ♡ sur un profil pour l\'ajouter ici', ka: 'დააჭირე ♡-ს პროფილზე' };
  return (
    <div style={{ textAlign: 'center', padding: '60px 20px', color: COLORS.text3, fontFamily: 'Inter' }}>
      <div style={{ fontSize: 40, marginBottom: 16 }}>♡</div>
      <div style={{ color: '#fff', fontWeight: 600, fontSize: 16, marginBottom: 6 }}>{txt[lang]}</div>
      <div style={{ fontSize: 13 }}>{hint[lang]}</div>
    </div>
  );
}

function FavListingRow({ listing, lang, t, onOpen }) {
  const title = (typeof listing.title === 'object' ? (listing.title[lang] || listing.title.fr) : listing.title) || '';
  const city = listing.city || (Array.isArray(listing.cities) ? listing.cities[0] : '');
  const photo = (Array.isArray(listing.photos) && listing.photos[0]) || null;
  const price = listing.price && listing.price.amount ? `${listing.price.amount}€` : (lang === 'ka' ? 'შესათანხმებელი' : 'À discuter');
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => onOpen(listing)} style={{
        width: '100%', textAlign: 'left', padding: 0, border: 'none', cursor: 'pointer',
        background: COLORS.card, borderRadius: 14, overflow: 'hidden',
        display: 'flex', gap: 12, alignItems: 'stretch',
      }}>
        <div style={{
          width: 84, minHeight: 84, flexShrink: 0,
          background: photo
            ? `url(${photo}) center/cover`
            : `linear-gradient(135deg, ${COLORS.bg2} 0%, rgba(212,175,55,0.06) 100%)`,
        }} />
        <div style={{ flex: 1, padding: '12px 14px 12px 0', minWidth: 0 }}>
          <div style={{ fontFamily: 'Inter', fontSize: 14, fontWeight: 600, color: '#fff',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title}</div>
          <div style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text3, marginTop: 4 }}>📍 {city || '—'}</div>
          <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 16, color: COLORS.gold, fontWeight: 600, marginTop: 6 }}>{price}</div>
        </div>
      </button>
      <div style={{ position: 'absolute', top: 8, right: 8 }}>
        <HeartButton kind="listing" id={listing.id} size={16} />
      </div>
    </div>
  );
}

function FavProfileRow({ user, lang, onOpen }) {
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => onOpen(user)} style={{
        width: '100%', textAlign: 'left', padding: 12, border: 'none', cursor: 'pointer',
        background: COLORS.card, borderRadius: 14,
        display: 'flex', gap: 12, alignItems: 'center',
      }}>
        <Avatar src={user.profile_photo} size={48} verified={!!user.verified} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'Inter', fontSize: 15, fontWeight: 600, color: '#fff',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {user.name || (lang === 'ka' ? 'უსახელო' : 'Sans nom')}
          </div>
          <div style={{ fontFamily: 'Inter', fontSize: 12, color: COLORS.text3, marginTop: 2 }}>
            {user.city ? `📍 ${user.city}` : ''}
            {user.role ? `${user.city ? ' · ' : ''}${user.role === 'worker' ? (lang === 'ka' ? 'ვეძებ სამუშაოს' : 'Cherche du travail') : (lang === 'ka' ? 'ვთავაზობ სამუშაოს' : 'Propose du travail')}` : ''}
          </div>
        </div>
      </button>
      <div style={{ position: 'absolute', top: 12, right: 12 }}>
        <HeartButton kind="profile" id={user.id} size={16} />
      </div>
    </div>
  );
}

window.ProfileScreen = ProfileScreen;
window.MyListingsScreen = MyListingsScreen;
window.FavoritesScreen = FavoritesScreen;
window.ReviewModal = ReviewModal;
