// screens-chat.jsx — chat list + thread (branchés sur l'API)

// === Helpers ===
function formatRelativeTime(iso, lang) {
  if (!iso) return '';
  const d = new Date(iso.replace(' ', 'T') + 'Z');
  const now = new Date();
  const diff = Math.floor((now - d) / 1000);
  if (diff < 60)        return lang === 'ka' ? 'ახლა' : 'maint.';
  if (diff < 3600)      return Math.floor(diff / 60) + (lang === 'ka' ? ' წ' : ' min');
  if (diff < 86400)     return Math.floor(diff / 3600) + 'h';
  if (diff < 86400 * 7) return Math.floor(diff / 86400) + 'j';
  return d.toLocaleDateString(lang === 'ka' ? 'ka-GE' : 'fr-FR');
}

function formatTimeShort(iso) {
  if (!iso) return '';
  const d = new Date(iso.replace(' ', 'T') + 'Z');
  return d.getHours() + ':' + String(d.getMinutes()).padStart(2, '0');
}

// === ChatListScreen ===
function ChatListScreen({ lang, t, onOpenThread }) {
  const [conversations, setConversations] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [search, setSearch] = React.useState('');

  const load = React.useCallback(async () => {
    if (!window.API_AVAILABLE) { setConversations([]); return; }
    try {
      const list = await window.TrustaAPI.listConversations();
      setConversations(list);
    } catch (e) {
      console.error(e);
      setError(window.errorMessage(e, lang));
    }
  }, [lang]);

  React.useEffect(() => { load(); }, [load]);
  // Refresh quand on revient sur l'écran (toutes les 15s)
  React.useEffect(() => {
    const id = setInterval(load, 15000);
    return () => clearInterval(id);
  }, [load]);

  const filtered = (conversations || []).filter(c =>
    !search.trim() || (c.peer_name || '').toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <Header big title={t('chats')} />
      <div style={{ padding: '4px 20px 14px' }}>
        <div style={{
          height: 44, borderRadius: 12,
          background: COLORS.card, border: `1px solid ${COLORS.borderSoft}`,
          display: 'flex', alignItems: 'center', padding: '0 14px', gap: 8,
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14"><circle cx="6" cy="6" r="4.5" fill="none" stroke={COLORS.text3} strokeWidth="1.4" /><path d="M9.5 9.5 L13 13" stroke={COLORS.text3} strokeWidth="1.4" strokeLinecap="round" /></svg>
          <input
            value={search} onChange={e => setSearch(e.target.value)}
            placeholder={t('search_placeholder')}
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              color: '#fff', fontFamily: 'Inter', fontSize: 13,
            }}
          />
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '0 8px 110px' }}>
        {conversations === null ? (
          <div style={{ textAlign: 'center', padding: 60, color: COLORS.text3, fontFamily: 'Inter', fontSize: 13 }}>
            {lang === 'ka' ? 'იტვირთება...' : 'Chargement...'}
          </div>
        ) : error ? (
          <div style={{ textAlign: 'center', padding: 60, color: '#ff6b6b', fontFamily: 'Inter', fontSize: 13 }}>{error}</div>
        ) : filtered.length === 0 ? (
          <EmptyChats lang={lang} />
        ) : filtered.map(c => (
          <ConvItem key={c.id} conv={c} lang={lang} onOpen={() => onOpenThread(c)} />
        ))}
      </div>
    </div>
  );
}

function EmptyChats({ lang }) {
  return (
    <div style={{
      textAlign: 'center', padding: '80px 30px', color: COLORS.text3,
      fontFamily: 'Inter', fontSize: 14, lineHeight: 1.6,
    }}>
      <div style={{ fontSize: 40, marginBottom: 16 }}>💬</div>
      <div style={{ color: '#fff', fontWeight: 600, marginBottom: 6, fontSize: 16 }}>
        {lang === 'ka' ? 'ჯერ ჩატები არ გაქვს' : 'Pas encore de conversation'}
      </div>
      <div>
        {lang === 'ka'
          ? 'დაიწყე საუბარი განცხადებიდან "შეტყობინება" ღილაკით'
          : 'Démarre une conversation depuis une annonce avec "Contacter"'}
      </div>
    </div>
  );
}

function ConvItem({ conv, lang, onOpen }) {
  const me = window.TrustaAuth.getUser();
  const myId = me ? me.id : 0;
  const lastFromMe = conv.last_sender_id === myId;
  const preview = conv.last_message_body || (lang === 'ka' ? 'საუბარი დაიწყო' : 'Conversation démarrée');
  const photoSrc = conv.peer_photo || null;

  return (
    <button onClick={onOpen} style={{
      width: '100%', textAlign: 'left', cursor: 'pointer', border: 'none',
      background: 'transparent', display: 'flex', gap: 12, padding: '12px 14px',
      alignItems: 'center', borderRadius: 14,
    }}>
      <Avatar src={photoSrc} size={48} verified={conv.peer_verified} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontFamily: 'Inter', fontSize: 15, color: '#fff', fontWeight: 600 }}>
            {conv.peer_name || (lang === 'ka' ? 'მომხმარებელი' : 'Utilisateur')}
          </div>
          <div style={{ fontFamily: 'Inter', fontSize: 11, color: conv.unread ? COLORS.gold : COLORS.text3 }}>
            {formatRelativeTime(conv.last_message_at, lang)}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
          <div style={{
            flex: 1, fontFamily: 'Inter', fontSize: 13,
            color: conv.unread ? '#fff' : COLORS.text2,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>
            {lastFromMe ? (lang === 'ka' ? 'შენ: ' : 'Vous : ') : ''}{preview}
          </div>
          {conv.unread > 0 && (
            <div style={{
              minWidth: 20, height: 20, borderRadius: 10,
              background: COLORS.gold, color: '#0A0A0A',
              fontFamily: 'Inter', fontSize: 11, fontWeight: 700,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              padding: '0 6px',
            }}>{conv.unread}</div>
          )}
        </div>
      </div>
    </button>
  );
}

// === ChatThreadScreen ===
function ChatThreadScreen({ peer, lang, t, onBack, onOpenProfile }) {
  // peer = conversation object (from list) OR { peer_id, peer_name, peer_photo, peer_verified, listing_id }
  const [conv, setConv] = React.useState(peer && peer.id ? peer : null);
  const [messages, setMessages] = React.useState([]);
  const [draft, setDraft] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);
  const scrollRef = React.useRef(null);
  const fileRef = React.useRef(null);

  // Ouverture / création de la conversation si nécessaire
  React.useEffect(() => {
    if (conv) return;
    if (!peer || !peer.peer_id || !window.API_AVAILABLE) return;
    (async () => {
      try {
        const c = await window.TrustaAPI.openConversation(peer.peer_id, peer.listing_id || null);
        setConv(c);
      } catch (e) {
        setError(window.errorMessage(e, lang));
      }
    })();
  }, [conv, peer, lang]);

  // Polling des messages toutes les 5s
  const lastIdRef = React.useRef(0);
  const fetchMessages = React.useCallback(async () => {
    if (!conv || !window.API_AVAILABLE) return;
    try {
      const list = await window.TrustaAPI.listMessages(conv.id, lastIdRef.current);
      if (list.length > 0) {
        setMessages(prev => {
          const existing = new Set(prev.map(m => m.id));
          const merged = [...prev, ...list.filter(m => !existing.has(m.id))];
          if (merged.length) lastIdRef.current = Math.max(...merged.map(m => m.id));
          return merged;
        });
      }
    } catch (e) {
      console.error(e);
    }
  }, [conv]);

  React.useEffect(() => {
    if (!conv) return;
    lastIdRef.current = 0;
    setMessages([]);
    fetchMessages();
    const id = setInterval(fetchMessages, 5000);
    return () => clearInterval(id);
  }, [conv, fetchMessages]);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async () => {
    const text = draft.trim();
    if (!text || sending || !conv) return;
    setSending(true); setError(null);
    try {
      const msg = await window.TrustaAPI.sendMessage(conv.id, text);
      setMessages(prev => [...prev, msg]);
      lastIdRef.current = Math.max(lastIdRef.current, msg.id);
      setDraft('');
    } catch (e) {
      setError(window.errorMessage(e, lang));
    } finally {
      setSending(false);
    }
  };

  const sendPhoto = async (file) => {
    if (!conv || !file || sending) return;
    setSending(true); setError(null);
    try {
      const up = await window.TrustaAPI.uploadListingPhoto(file);
      const msg = await window.TrustaAPI.sendMessage(conv.id, '', up.url);
      setMessages(prev => [...prev, msg]);
      lastIdRef.current = Math.max(lastIdRef.current, msg.id);
    } catch (e) {
      setError(window.errorMessage(e, lang));
    } finally {
      setSending(false);
      if (fileRef.current) fileRef.current.value = '';
    }
  };

  // Infos peer pour le header
  const me = window.TrustaAuth.getUser();
  const myId = me ? me.id : 0;
  const peerName = (conv && conv.peer_name) || peer?.peer_name || (lang === 'ka' ? 'მომხმარებელი' : 'Utilisateur');
  const peerPhoto = (conv && conv.peer_photo) || peer?.peer_photo || null;
  const peerVerified = (conv && conv.peer_verified) || peer?.peer_verified || false;

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <Header
        onBack={onBack}
        left={null}
        title={
          <button onClick={() => onOpenProfile && onOpenProfile({ id: conv?.peer_id || peer?.peer_id, name: { fr: peerName, ka: peerName }, avatar: peerPhoto, verified: peerVerified })}
                  style={{ display: 'flex', gap: 10, alignItems: 'center', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0 }}>
            <Avatar src={peerPhoto} size={36} verified={peerVerified} />
            <div style={{ textAlign: 'left' }}>
              <div style={{ fontFamily: 'Inter', fontSize: 15, fontWeight: 600, color: '#fff' }}>{peerName}</div>
            </div>
          </button>
        }
      />

      {/* Trust banner */}
      <div style={{
        margin: '0 16px 6px', padding: '8px 12px',
        background: 'rgba(212,175,55,0.06)', border: '1px solid rgba(212,175,55,0.2)',
        borderRadius: 10, display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <svg width="14" height="14" viewBox="0 0 14 14"><path d="M7 1 L12 3 V7 C12 10 7 13 7 13 C7 13 2 10 2 7 V3 Z" fill="none" stroke={COLORS.gold} strokeWidth="1.3" /></svg>
        <div style={{ fontFamily: 'Inter', fontSize: 11, color: COLORS.text2, lineHeight: 1.4 }}>{t('protected_chat')}</div>
      </div>

      <div ref={scrollRef} style={{ flex: 1, overflow: 'auto', padding: '8px 16px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {messages.map((m) => {
          const me = m.sender_id === myId;
          return (
            <div key={m.id} style={{ display: 'flex', justifyContent: me ? 'flex-end' : 'flex-start' }}>
              <div style={{
                maxWidth: '78%', padding: m.photo_url ? 4 : '10px 14px',
                borderRadius: me ? '18px 18px 4px 18px' : '18px 18px 18px 4px',
                background: me ? COLORS.gold : COLORS.card,
                color: me ? '#0A0A0A' : '#fff',
                fontFamily: 'Inter', fontSize: 14, lineHeight: 1.4,
                fontWeight: me ? 500 : 400,
                overflow: 'hidden',
              }}>
                {m.photo_url && (
                  <img src={m.photo_url} alt=""
                       style={{ display: 'block', maxWidth: '100%', maxHeight: 280, borderRadius: 14 }} />
                )}
                {m.body && (
                  <div style={{ padding: m.photo_url ? '8px 10px 4px' : 0 }}>{m.body}</div>
                )}
                <div style={{
                  fontSize: 10, marginTop: 4, opacity: 0.6,
                  textAlign: me ? 'right' : 'left', fontWeight: 400,
                  padding: m.photo_url ? '0 10px 6px' : 0,
                }}>{formatTimeShort(m.created_at)}</div>
              </div>
            </div>
          );
        })}
      </div>

      {error && (
        <div style={{ margin: '0 16px 8px', padding: 10, background: 'rgba(255,107,107,0.1)', border: '1px solid rgba(255,107,107,0.3)', borderRadius: 8, color: '#ff8e8e', fontSize: 12 }}>
          {error}
        </div>
      )}

      {/* Composer */}
      <div style={{
        padding: '8px 12px 28px', display: 'flex', gap: 8, alignItems: 'center',
        background: COLORS.bg, borderTop: `1px solid ${COLORS.borderSoft}`,
      }}>
        <input
          ref={fileRef}
          type="file"
          accept="image/*"
          style={{ display: 'none' }}
          onChange={e => e.target.files && e.target.files[0] && sendPhoto(e.target.files[0])}
        />
        <button onClick={() => fileRef.current && fileRef.current.click()} disabled={sending} style={{
          width: 44, height: 44, borderRadius: 22,
          background: COLORS.card, border: `1px solid ${COLORS.borderSoft}`,
          cursor: sending ? 'not-allowed' : 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={COLORS.gold} strokeWidth="1.7">
            <rect x="3" y="5" width="18" height="14" rx="2" />
            <circle cx="8.5" cy="10.5" r="1.5" />
            <path d="M21 15l-5-5L5 19" />
          </svg>
        </button>

        <div style={{
          flex: 1, minHeight: 44, borderRadius: 22,
          background: COLORS.card, border: `1px solid ${COLORS.borderSoft}`,
          padding: '0 16px', display: 'flex', alignItems: 'center',
        }}>
          <input
            value={draft} onChange={e => setDraft(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && send()}
            placeholder={t('type_message')}
            disabled={!conv || sending}
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              color: '#fff', fontFamily: 'Inter', fontSize: 14,
            }}
          />
        </div>
        <button onClick={send} disabled={!conv || sending || !draft.trim()} style={{
          width: 44, height: 44, borderRadius: 22,
          background: 'linear-gradient(180deg, #E4C25C, #B6932B)',
          border: 'none',
          cursor: (!conv || sending || !draft.trim()) ? 'not-allowed' : 'pointer',
          opacity: (!conv || sending || !draft.trim()) ? 0.5 : 1,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 4px 14px -2px rgba(212,175,55,0.5)',
        }}>
          <svg width="18" height="18" viewBox="0 0 18 18"><path d="M2 9 L16 2 L11 16 L8 10 Z" fill="#0A0A0A" /></svg>
        </button>
      </div>
    </div>
  );
}

window.ChatListScreen = ChatListScreen;
window.ChatThreadScreen = ChatThreadScreen;
