// screens-home.jsx — home (listings list), map, listing detail

function CategoryChips({ active, onChange, t }) {
  return (
    <div style={{
      display: 'flex', gap: 8, padding: '0 20px 14px', overflowX: 'auto',
      scrollbarWidth: 'none', WebkitOverflowScrolling: 'touch',
    }}>
      {CATEGORIES.map(c => {
        const isActive = active === c.id;
        return (
          <button key={c.id} onClick={() => onChange(c.id)} style={{
            flexShrink: 0, height: 36, padding: '0 16px', borderRadius: 12,
            background: isActive ? COLORS.gold : COLORS.card,
            color: isActive ? '#0A0A0A' : COLORS.text2,
            border: `1px solid ${isActive ? COLORS.gold : COLORS.borderSoft}`,
            fontFamily: 'Inter, system-ui', fontSize: 13, fontWeight: isActive ? 700 : 500,
            cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6,
            whiteSpace: 'nowrap',
          }}>
            <span style={{ fontSize: 14 }}>{c.icon}</span>
            {t('cat_' + c.id)}
          </button>
        );
      })}
    </div>
  );
}

// Helper : extrait le titre/location selon le format (mock bilingue OU API string)
function listingTitle(l, lang) {
  if (typeof l.title === 'object' && l.title !== null) return l.title[lang] || l.title.fr || '';
  return l.title || '';
}
function listingCity(l, lang) {
  // Priorité : array cities (V2), puis city (string), puis location (mock)
  if (Array.isArray(l.cities) && l.cities.length) {
    if (l.cities.length === 1) return l.cities[0];
    return l.cities[0] + ' +' + (l.cities.length - 1);
  }
  if (l.city) return l.city;
  if (typeof l.location === 'object' && l.location !== null) return l.location[lang] || l.location.fr || '';
  return '';
}
function listingPrice(l) {
  if (l.price && typeof l.price === 'object') return l.price.amount;
  return l.rate;
}
function listingPriceUnit(l, t) {
  const unit = (l.price && l.price.unit) || 'hour';
  if (unit === 'hour') return t('hour_short');
  if (unit === 'day')  return 'j';
  return 'fc'; // forfait
}
function listingPhoto(l) {
  if (Array.isArray(l.photos) && l.photos.length) return l.photos[0];
  return l.img || null;
}

function ListingCard({ listing, lang, t, onOpen }) {
  const photo = listingPhoto(listing);
  const price = listingPrice(listing);
  const title = listingTitle(listing, lang);
  const city = listingCity(listing, lang);
  return (
    <div style={{ position: 'relative' }}>
    <button onClick={() => onOpen(listing)} style={{
      width: '100%', textAlign: 'left', padding: 0, border: 'none', cursor: 'pointer',
      background: COLORS.card, borderRadius: 16, overflow: 'hidden',
      display: 'flex', gap: 12, alignItems: 'stretch',
      borderTop: `1px solid ${COLORS.borderSoft}`,
    }}>
      <div style={{
        width: 96, minHeight: 96, flexShrink: 0, position: 'relative',
        background: photo
          ? `url(${photo}) center/cover`
          : `linear-gradient(135deg, ${COLORS.card} 0%, rgba(212,175,55,0.08) 100%)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {!photo && (
          <svg width="28" height="28" viewBox="0 0 24 24" opacity="0.35">
            <path d="M3 5h18v14H3z M3 17l5-5 4 4 4-3 5 4" fill="none" stroke={COLORS.gold} strokeWidth="1.4" strokeLinejoin="round" />
          </svg>
        )}
      </div>
      <div style={{ flex: 1, padding: '12px 14px 12px 0', display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0 }}>
        <div style={{
          fontFamily: 'Inter, system-ui', fontSize: 14, fontWeight: 600, color: '#fff',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{title}</div>
        <div style={{
          fontFamily: 'Inter, system-ui', fontSize: 11, color: COLORS.text3,
          display: 'flex', alignItems: 'center', gap: 5,
        }}>
          <svg width="10" height="10" viewBox="0 0 10 10"><path d="M5 1 C7 1 8.5 2.5 8.5 4.5 C8.5 6.5 5 9 5 9 C5 9 1.5 6.5 1.5 4.5 C1.5 2.5 3 1 5 1 Z" fill="none" stroke={COLORS.text3} strokeWidth="1" /><circle cx="5" cy="4.5" r="1.2" fill={COLORS.text3} /></svg>
          {city}
        </div>
        <div style={{ flex: 1 }} />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{
            fontFamily: '"Playfair Display", serif', fontSize: 17, color: COLORS.gold, fontWeight: 600,
          }}>
            {price !== null && price !== undefined
              ? <>€{price}<span style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text3, fontWeight: 400 }}> /{listingPriceUnit(listing, t)}</span></>
              : <span style={{ fontFamily: 'Inter', fontSize: 12, color: COLORS.text3, fontWeight: 400 }}>{t('to_negotiate') || 'À discuter'}</span>
            }
          </div>
          {listing.user && listing.user.verified && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontFamily: 'Inter', fontSize: 11, color: COLORS.gold }}>
              <svg width="11" height="11" viewBox="0 0 12 12"><path d="M6 1 L7.5 4 L11 4.5 L8.5 7 L9 10.5 L6 9 L3 10.5 L3.5 7 L1 4.5 L4.5 4 Z" fill={COLORS.gold} /></svg>
              {(listing.user.name || '').split(' ')[0]}
            </div>
          )}
        </div>
      </div>
    </button>
      <div style={{ position: 'absolute', top: 8, right: 8, zIndex: 2 }}>
        <HeartButton kind="listing" id={listing.id} size={18} />
      </div>
    </div>
  );
}

function HomeScreen({ lang, t, onOpenListing, onOpenMap, query, setQuery, onCreateListing, refreshKey }) {
  const [cat, setCat] = React.useState('all');
  const [listings, setListings] = React.useState(null); // null = loading, [] = empty, [...] = data
  const [error, setError] = React.useState(null);
  const me = (window.TrustaAuth && window.TrustaAuth.getUser()) || null;
  const displayName = (me && me.name) ? me.name.split(' ')[0] : (lang === 'ka' ? 'მეგობარო' : 'ami');
  const displayCity = (me && me.city) ? me.city : (lang === 'ka' ? 'საფრანგეთი' : 'France');

  // Fetch annonces depuis l'API au montage + au changement de filtre catégorie
  React.useEffect(() => {
    if (!window.API_AVAILABLE) {
      setListings(LISTINGS); // fallback dev/preview
      return;
    }
    setListings(null); setError(null);
    const filters = {};
    if (cat !== 'all') filters.category = cat;
    window.TrustaAPI.listListings(filters)
      .then(rows => setListings(rows || []))
      .catch(err => {
        console.error('[HomeScreen] fetch failed', err);
        setError(err);
        setListings([]);
      });
  }, [cat, refreshKey]);

  // Filtre client-side pour la recherche texte
  const filtered = (listings || []).filter(l => {
    if (!query) return true;
    const q = query.toLowerCase();
    const title = listingTitle(l, lang).toLowerCase();
    const city = listingCity(l, lang).toLowerCase();
    return title.includes(q) || city.includes(q);
  });

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <Header
        sub={t('hello') + ', ' + displayName}
        title={displayCity}
        right={
          <button onClick={onOpenMap} style={{
            width: 38, height: 38, borderRadius: 12,
            background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.08)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}>
            <svg width="16" height="16" viewBox="0 0 16 16"><path d="M5 2 L1 4 V14 L5 12 L11 14 L15 12 V2 L11 4 Z M5 2 V12 M11 4 V14" stroke={COLORS.gold} strokeWidth="1.3" fill="none" strokeLinejoin="round" /></svg>
          </button>
        }
      />
      <div style={{ padding: '4px 20px 14px', display: 'flex', gap: 10 }}>
        <div style={{
          flex: 1, height: 44, borderRadius: 12,
          background: COLORS.card, border: `1px solid ${COLORS.borderSoft}`,
          display: 'flex', alignItems: 'center', padding: '0 14px', gap: 8,
        }}>
          <svg width="16" height="16" viewBox="0 0 16 16"><circle cx="7" cy="7" r="5" fill="none" stroke={COLORS.text3} strokeWidth="1.5" /><path d="M11 11 L14 14" stroke={COLORS.text3} strokeWidth="1.5" strokeLinecap="round" /></svg>
          <input
            value={query} onChange={e => setQuery(e.target.value)}
            placeholder={t('search_placeholder')}
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              color: '#fff', fontFamily: 'Inter, system-ui', fontSize: 14,
            }}
          />
        </div>
        <button style={{
          width: 44, height: 44, borderRadius: 12,
          background: COLORS.goldSoft, border: `1px solid ${COLORS.gold}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}>
          <svg width="16" height="16" viewBox="0 0 16 16"><path d="M2 4 H14 M4 8 H12 M6 12 H10" stroke={COLORS.gold} strokeWidth="1.5" strokeLinecap="round" /></svg>
        </button>
      </div>

      <CategoryChips active={cat} onChange={setCat} t={t} />

      <div style={{ flex: 1, overflow: 'auto', padding: '4px 20px 110px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          marginBottom: 12,
        }}>
          <div style={{ fontFamily: 'Inter, system-ui', fontSize: 13, fontWeight: 600, color: '#fff', textTransform: 'uppercase', letterSpacing: 0.6 }}>
            {t('new_listings')}
          </div>
          <div style={{ fontFamily: 'Inter', fontSize: 12, color: COLORS.gold }}>{t('see_all')}</div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {listings === null && (
            <div style={{ padding: 40, textAlign: 'center', color: COLORS.text3, fontFamily: 'Inter', fontSize: 13 }}>
              {lang === 'ka' ? 'იტვირთება…' : 'Chargement…'}
            </div>
          )}
          {listings !== null && filtered.map(l => <ListingCard key={l.id} listing={l} lang={lang} t={t} onOpen={onOpenListing} />)}
          {listings !== null && filtered.length === 0 && !error && (
            <div style={{ padding: '40px 20px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
              <svg width="56" height="56" viewBox="0 0 56 56" opacity="0.4">
                <circle cx="28" cy="28" r="25" fill="none" stroke={COLORS.gold} strokeWidth="1.5" />
                <path d="M18 28 L26 36 L40 22" fill="none" stroke={COLORS.gold} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 18, color: '#fff' }}>
                {query
                  ? (lang === 'ka' ? 'შედეგი ვერ მოიძებნა' : 'Aucun résultat')
                  : (lang === 'ka' ? 'ჯერ არცერთი განცხადება არ არის' : 'Pas encore d\'annonces')}
              </div>
              <div style={{ fontFamily: 'Inter', fontSize: 13, color: COLORS.text3, maxWidth: 280 }}>
                {query
                  ? (lang === 'ka' ? 'სცადეთ სხვა ძიება' : 'Essayez une autre recherche')
                  : (lang === 'ka' ? 'იყავი პირველი, ვინც განცხადებას დადებს ჩვენს თემში' : 'Sois le premier à publier dans la communauté')}
              </div>
              {!query && onCreateListing && (
                <button onClick={onCreateListing} style={{
                  marginTop: 8, padding: '12px 24px', borderRadius: 12,
                  background: COLORS.gold, border: 'none', color: '#0A0A0A',
                  fontFamily: 'Inter', fontSize: 14, fontWeight: 700, cursor: 'pointer',
                }}>
                  {lang === 'ka' ? '+ ახალი განცხადება' : '+ Créer une annonce'}
                </button>
              )}
            </div>
          )}
          {error && filtered.length === 0 && (
            <div style={{ padding: 40, textAlign: 'center', color: COLORS.red, fontFamily: 'Inter', fontSize: 13 }}>
              {lang === 'ka' ? 'შეცდომა. სცადეთ თავიდან.' : 'Erreur de chargement. Réessayez.'}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function MapScreen({ lang, t, onBack, onOpenListing }) {
  const [selected, setSelected] = React.useState(LISTINGS[0]);
  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, position: 'relative' }}>
      {/* faux map */}
      <div style={{
        position: 'absolute', inset: 0, background: '#0F0F0F',
        backgroundImage: `
          linear-gradient(rgba(212,175,55,0.04) 1px, transparent 1px),
          linear-gradient(90deg, rgba(212,175,55,0.04) 1px, transparent 1px),
          radial-gradient(circle at 30% 40%, rgba(212,175,55,0.08), transparent 40%),
          radial-gradient(circle at 70% 60%, rgba(212,175,55,0.06), transparent 35%)
        `,
        backgroundSize: '40px 40px, 40px 40px, 100% 100%, 100% 100%',
      }}>
        {/* roads */}
        <svg style={{ position: 'absolute', inset: 0 }} width="100%" height="100%" viewBox="0 0 400 800" preserveAspectRatio="none">
          <path d="M0 200 Q 200 220 400 180" stroke="rgba(212,175,55,0.15)" strokeWidth="2" fill="none" />
          <path d="M50 0 Q 80 300 60 600 T 100 800" stroke="rgba(212,175,55,0.12)" strokeWidth="2" fill="none" />
          <path d="M250 0 Q 280 200 300 400 T 320 800" stroke="rgba(212,175,55,0.12)" strokeWidth="2" fill="none" />
          <path d="M0 500 Q 200 480 400 540" stroke="rgba(212,175,55,0.1)" strokeWidth="1.5" fill="none" />
          <path d="M0 350 L400 360" stroke="rgba(212,175,55,0.08)" strokeWidth="1" fill="none" />
        </svg>
        {/* river */}
        <svg style={{ position: 'absolute', inset: 0 }} width="100%" height="100%" viewBox="0 0 400 800" preserveAspectRatio="none">
          <path d="M120 0 Q 160 300 140 600 L 180 800" stroke="rgba(80,140,200,0.25)" strokeWidth="14" fill="none" strokeLinecap="round" />
        </svg>
      </div>

      <Header onBack={onBack} title={t('map_view')} right={
        <button style={{
          width: 38, height: 38, borderRadius: 12,
          background: 'rgba(20,20,20,0.85)', border: '1px solid rgba(255,255,255,0.08)',
          backdropFilter: 'blur(8px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 3 H12 M3 7 H11 M5 11 H9" stroke={COLORS.gold} strokeWidth="1.4" strokeLinecap="round" /></svg>
        </button>
      } />

      {/* Pins */}
      {[
        { l: LISTINGS[0], x: '32%', y: '38%' },
        { l: LISTINGS[1], x: '64%', y: '30%' },
        { l: LISTINGS[2], x: '52%', y: '52%' },
        { l: LISTINGS[3], x: '24%', y: '60%' },
        { l: LISTINGS[4], x: '72%', y: '64%' },
        { l: LISTINGS[5], x: '44%', y: '44%' },
      ].map((p, i) => (
        <button key={i} onClick={() => setSelected(p.l)} style={{
          position: 'absolute', left: p.x, top: p.y,
          transform: 'translate(-50%, -100%)',
          background: 'transparent', border: 'none', cursor: 'pointer',
          padding: 0,
        }}>
          <div style={{
            background: selected?.id === p.l.id ? COLORS.gold : '#1A1A1A',
            color: selected?.id === p.l.id ? '#0A0A0A' : COLORS.gold,
            padding: '6px 12px', borderRadius: 14,
            fontFamily: 'Inter', fontSize: 12, fontWeight: 700,
            border: `1.5px solid ${COLORS.gold}`,
            boxShadow: '0 6px 16px rgba(0,0,0,0.5)',
            whiteSpace: 'nowrap',
          }}>€{p.l.rate}</div>
          <div style={{
            width: 0, height: 0,
            borderLeft: '5px solid transparent', borderRight: '5px solid transparent',
            borderTop: `7px solid ${selected?.id === p.l.id ? COLORS.gold : COLORS.gold}`,
            margin: '0 auto',
          }} />
        </button>
      ))}

      {/* Bottom card */}
      {selected && (
        <div style={{
          position: 'absolute', left: 16, right: 16, bottom: 100,
        }}>
          <ListingCard listing={selected} lang={lang} t={t} onOpen={onOpenListing} />
        </div>
      )}
    </div>
  );
}

function ListingDetailScreen({ listing, lang, t, onBack, onOpenChat, onOpenProfile, onDeleted }) {
  const [photoIdx, setPhotoIdx] = React.useState(0);
  const [deleting, setDeleting] = React.useState(false);
  const [lightboxOpen, setLightboxOpen] = React.useState(false);
  const [showReport, setShowReport] = React.useState(false);
  const touchStartX = React.useRef(null);
  const me = window.TrustaAuth ? window.TrustaAuth.getUser() : null;
  const isMine = me && listing.user && me.id === listing.user.id;

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

  // Adapte le listing à un format unifié (compatible mock + API)
  const title = listingTitle(listing, lang);
  const city  = listingCity(listing, lang);
  const price = listingPrice(listing);
  const unit  = listingPriceUnit(listing, t);
  const photos = (Array.isArray(listing.photos) && listing.photos.length)
    ? listing.photos
    : (listing.img ? [listing.img] : []);
  const description = (typeof listing.description === 'object' && listing.description !== null)
    ? (listing.description[lang] || listing.description.fr || '')
    : (listing.description || '');

  // Poster : depuis l'API on a listing.user, depuis le mock on a MEMBERS[posterId]
  const poster = listing.user ? {
    id: listing.user.id,
    name: listing.user.name || (lang === 'ka' ? 'მომხმარებელი' : 'Utilisateur'),
    avatar: listing.user.photo || null,
    verified: !!listing.user.verified,
    rating: null,
    missions: null,
  } : (listing.posterId && window.MEMBERS && window.MEMBERS[listing.posterId]) ? {
    ...window.MEMBERS[listing.posterId],
    name: typeof window.MEMBERS[listing.posterId].name === 'object'
      ? window.MEMBERS[listing.posterId].name[lang]
      : window.MEMBERS[listing.posterId].name,
  } : { name: lang === 'ka' ? 'მომხმარებელი' : 'Utilisateur', avatar: null, verified: false, rating: null, missions: null };

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      {/* Photo carousel */}
      <div style={{ position: 'relative', width: '100%', height: 320, flexShrink: 0 }}>
        <div
          onClick={() => { if (photos.length) setLightboxOpen(true); }}
          onTouchStart={(e) => { touchStartX.current = e.touches[0].clientX; }}
          onTouchEnd={(e) => {
            if (touchStartX.current === null || photos.length < 2) return;
            const dx = e.changedTouches[0].clientX - touchStartX.current;
            if (Math.abs(dx) > 50) {
              if (dx < 0) setPhotoIdx((i) => Math.min(i + 1, photos.length - 1));
              else setPhotoIdx((i) => Math.max(i - 1, 0));
            }
            touchStartX.current = null;
          }}
          style={{
          position: 'absolute', inset: 0,
          background: photos.length
            ? `url(${photos[photoIdx]}) center/cover`
            : `linear-gradient(135deg, ${COLORS.card} 0%, rgba(212,175,55,0.06) 100%)`,
          cursor: photos.length ? 'zoom-in' : 'default',
        }} />
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, rgba(0,0,0,0.5) 0%, rgba(0,0,0,0) 30%, rgba(0,0,0,0) 70%, rgba(11,11,11,1) 100%)',
          pointerEvents: 'none',
        }} />
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0 }}>
          <Header onBack={onBack} title="" right={
            <div style={{ display: 'flex', gap: 8 }}>
              {!isMine && <HeartButton kind="listing" id={listing.id} size={18} style={{ width: 38, height: 38, borderRadius: 12 }} />}
              <button onClick={() => {
                const url = window.location.origin + window.location.pathname + '#/listing/' + listing.id;
                const text = `${title} — ${city || ''} ${price ? '· €' + price : ''}`;
                if (navigator.share) {
                  navigator.share({ title: 'Trusta', text, url }).catch(() => {});
                } else if (navigator.clipboard) {
                  navigator.clipboard.writeText(url);
                  alert(lang === 'ka' ? 'ლინკი დაკოპირდა' : 'Lien copié');
                }
              }} style={{ width: 38, height: 38, borderRadius: 12, background: 'rgba(0,0,0,0.5)', border: '1px solid rgba(255,255,255,0.1)', backdropFilter: 'blur(8px)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 7 L11 7 M8 4 L11 7 L8 10" stroke="#fff" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" /><path d="M3 4 L3 10" stroke="#fff" strokeWidth="1.5" fill="none" strokeLinecap="round" /></svg>
              </button>
            </div>
          } />
        </div>
        {photos.length > 1 && (
          <div style={{
            position: 'absolute', bottom: 32, right: 16,
            padding: '4px 10px', borderRadius: 12,
            background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(8px)',
            fontFamily: 'Inter', fontSize: 11, color: '#fff', fontWeight: 600,
          }}>{photoIdx + 1}/{photos.length}</div>
        )}
        {photos.length > 1 && (
          <div style={{ position: 'absolute', bottom: 14, left: 0, right: 0, display: 'flex', justifyContent: 'center', gap: 4 }}>
            {photos.map((_, i) => (
              <button key={i} onClick={() => setPhotoIdx(i)} style={{
                width: i === photoIdx ? 18 : 6, height: 6, borderRadius: 3,
                background: i === photoIdx ? COLORS.gold : 'rgba(255,255,255,0.4)',
                border: 'none', cursor: 'pointer', transition: 'width .2s',
              }} />
            ))}
          </div>
        )}
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '0 24px 220px' }}>
        <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 24, color: '#fff', fontWeight: 600, marginTop: 4 }}>
          {title}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6, color: COLORS.text2, fontFamily: 'Inter', fontSize: 13 }}>
          <svg width="12" height="12" viewBox="0 0 12 12"><path d="M6 1 C8.5 1 10 2.8 10 5 C10 8 6 11 6 11 C6 11 2 8 2 5 C2 2.8 3.5 1 6 1 Z" stroke={COLORS.gold} strokeWidth="1.2" fill="none" /><circle cx="6" cy="5" r="1.5" fill={COLORS.gold} /></svg>
          {city}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 14, padding: '14px 0', borderTop: `1px solid ${COLORS.borderSoft}`, borderBottom: `1px solid ${COLORS.borderSoft}` }}>
          <div>
            {price !== null && price !== undefined
              ? <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 26, color: COLORS.gold, fontWeight: 600 }}>€{price}<span style={{ fontFamily: 'Inter', fontSize: 13, color: COLORS.text3, fontWeight: 400 }}>/{unit}</span></div>
              : <div style={{ fontFamily: 'Inter', fontSize: 14, color: COLORS.text2 }}>{t('to_negotiate') || 'À discuter'}</div>
            }
          </div>
        </div>

        {/* Catégories (chips) */}
        {((Array.isArray(listing.categories) && listing.categories.length) || listing.category) && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 14 }}>
            {(Array.isArray(listing.categories) && listing.categories.length ? listing.categories : [listing.category]).map(c => (
              <div key={c} style={{ padding: '6px 12px', borderRadius: 999, background: COLORS.goldSoft, border: `1px solid ${COLORS.gold}`, fontFamily: 'Inter', fontSize: 11, color: COLORS.gold, fontWeight: 600 }}>
                {t('cat_' + c)}
              </div>
            ))}
          </div>
        )}

        {/* Villes desservies (si plusieurs) */}
        {Array.isArray(listing.cities) && listing.cities.length > 1 && (
          <div style={{ marginTop: 14, padding: 12, background: COLORS.card, borderRadius: 12, border: `1px solid ${COLORS.borderSoft}` }}>
            <div style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text3, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 6 }}>
              {lang === 'ka' ? 'მომსახურების ქალაქები' : 'Villes desservies'}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {listing.cities.map((c, i) => (
                <div key={c + i} style={{ padding: '4px 10px', borderRadius: 8, background: COLORS.bg, fontFamily: 'Inter', fontSize: 12, color: COLORS.text2 }}>
                  {c}
                </div>
              ))}
            </div>
          </div>
        )}

        {description && (
          <div style={{ marginTop: 20, fontFamily: 'Inter', fontSize: 14, lineHeight: 1.55, color: COLORS.text2, whiteSpace: 'pre-wrap' }}>
            {description}
          </div>
        )}

        {/* Poster */}
        <div style={{ marginTop: 22 }}>
          <div style={{ fontFamily: 'Inter', fontSize: 12, color: COLORS.text3, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 10 }}>{t('posted_by')}</div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: 12, background: COLORS.card, borderRadius: 14,
            border: `1px solid ${COLORS.borderSoft}`,
          }}>
            <button onClick={() => onOpenProfile && onOpenProfile(poster)} style={{
              flex: 1, display: 'flex', alignItems: 'center', gap: 12,
              background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, textAlign: 'left',
            }}>
              <Avatar src={poster.avatar} size={44} verified={poster.verified} />
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'Inter', fontSize: 14, color: '#fff', fontWeight: 600 }}>{poster.name}</div>
                {poster.rating != null && poster.missions != null && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 2 }}>
                    <Stars value={poster.rating} size={10} />
                    <span style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text3 }}>{poster.rating} · {poster.missions} {t('missions_done').toLowerCase()}</span>
                  </div>
                )}
                {poster.verified && poster.rating == null && (
                  <div style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.gold, marginTop: 2 }}>✓ {t('verified')}</div>
                )}
              </div>
              <svg width="10" height="14" viewBox="0 0 10 14"><path d="M2 1 L8 7 L2 13" stroke={COLORS.text3} strokeWidth="1.5" fill="none" strokeLinecap="round" /></svg>
            </button>
            {!isMine && poster.id && (
              <HeartButton kind="profile" id={poster.id} size={16} />
            )}
          </div>
        </div>
      </div>

      {/* Footer */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '16px 20px 32px', background: 'linear-gradient(180deg, rgba(11,11,11,0) 0%, #0B0B0B 30%)',
      }}>
        {isMine ? (
          <>
            <div style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text3, textAlign: 'center', marginBottom: 10 }}>
              {lang === 'ka' ? 'ეს არის შენი განცხადება' : 'Ceci est votre annonce'}
            </div>
            <button
              onClick={handleDelete}
              disabled={deleting}
              style={{
                width: '100%', padding: '14px', borderRadius: 12,
                background: 'transparent',
                border: '1px solid rgba(255,107,107,0.5)',
                color: '#ff6b6b',
                fontFamily: 'Inter', fontSize: 14, fontWeight: 600,
                cursor: deleting ? 'not-allowed' : 'pointer',
                opacity: deleting ? 0.5 : 1,
              }}>
              {deleting
                ? (lang === 'ka' ? 'იშლება…' : 'Suppression…')
                : (lang === 'ka' ? '🗑 განცხადების წაშლა' : '🗑 Supprimer mon annonce')}
            </button>
          </>
        ) : (
          <>
            <div style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text3, textAlign: 'center', marginBottom: 10 }}>
              🛡 {t('protected_chat')}
            </div>
            <GoldButton onClick={() => onOpenChat(poster)}>{t('contact_chat')}</GoldButton>
            <button
              onClick={() => setShowReport(true)}
              style={{
                width: '100%', marginTop: 8, padding: '10px',
                background: 'transparent', border: 'none',
                color: COLORS.text3, fontFamily: 'Inter', fontSize: 12, fontWeight: 500,
                cursor: 'pointer', textDecoration: 'underline',
              }}>
              🚩 {lang === 'ka' ? 'ამ განცხადებაზე სიგნალის გაგზავნა' : 'Signaler cette annonce'}
            </button>
          </>
        )}
      </div>

      {/* Modal Signaler */}
      {showReport && window.ReportModal && (
        <ReportModal
          target={{ type: 'listing', id: listing.id }}
          lang={lang}
          onClose={() => setShowReport(false)}
        />
      )}

      {/* Photo lightbox */}
      {lightboxOpen && photos.length > 0 && (
        <div
          onClick={() => setLightboxOpen(false)}
          onTouchStart={(e) => { touchStartX.current = e.touches[0].clientX; }}
          onTouchEnd={(e) => {
            if (touchStartX.current === null) return;
            const dx = e.changedTouches[0].clientX - touchStartX.current;
            if (Math.abs(dx) > 50 && photos.length > 1) {
              e.stopPropagation();
              if (dx < 0) setPhotoIdx((i) => Math.min(i + 1, photos.length - 1));
              else setPhotoIdx((i) => Math.max(i - 1, 0));
            }
            touchStartX.current = null;
          }}
          style={{
            position: 'fixed', inset: 0, zIndex: 500,
            background: 'rgba(0,0,0,0.96)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'zoom-out',
          }}
        >
          <img
            src={photos[photoIdx]}
            alt=""
            onClick={(e) => e.stopPropagation()}
            style={{
              maxWidth: '100%', maxHeight: '100%',
              objectFit: 'contain',
              userSelect: 'none', pointerEvents: 'none',
            }}
          />

          {/* Close button */}
          <button
            onClick={(e) => { e.stopPropagation(); setLightboxOpen(false); }}
            style={{
              position: 'absolute',
              top: 'calc(env(safe-area-inset-top, 0px) + 12px)',
              right: 12,
              width: 40, height: 40, borderRadius: 999,
              background: 'rgba(255,255,255,0.1)',
              border: '1px solid rgba(255,255,255,0.2)',
              color: '#fff', fontSize: 20, fontWeight: 300,
              cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
              backdropFilter: 'blur(8px)',
            }}
          >×</button>

          {/* Counter */}
          {photos.length > 1 && (
            <div style={{
              position: 'absolute',
              top: 'calc(env(safe-area-inset-top, 0px) + 18px)',
              left: '50%', transform: 'translateX(-50%)',
              padding: '6px 14px', borderRadius: 999,
              background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(8px)',
              fontFamily: 'Inter', fontSize: 12, color: '#fff', fontWeight: 600,
            }}>
              {photoIdx + 1} / {photos.length}
            </div>
          )}

          {/* Prev / Next arrows (desktop) */}
          {photos.length > 1 && photoIdx > 0 && (
            <button
              onClick={(e) => { e.stopPropagation(); setPhotoIdx((i) => Math.max(i - 1, 0)); }}
              style={{
                position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)',
                width: 44, height: 44, borderRadius: 999,
                background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)',
                color: '#fff', fontSize: 22, cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                backdropFilter: 'blur(8px)',
              }}
            >‹</button>
          )}
          {photos.length > 1 && photoIdx < photos.length - 1 && (
            <button
              onClick={(e) => { e.stopPropagation(); setPhotoIdx((i) => Math.min(i + 1, photos.length - 1)); }}
              style={{
                position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
                width: 44, height: 44, borderRadius: 999,
                background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.2)',
                color: '#fff', fontSize: 22, cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                backdropFilter: 'blur(8px)',
              }}
            >›</button>
          )}
        </div>
      )}
    </div>
  );
}

window.HomeScreen = HomeScreen;
window.MapScreen = MapScreen;
window.ListingDetailScreen = ListingDetailScreen;
