/* B28 HospeX — Concierge (conversas) */
function ViewConcierge({ hotelId }) {
  const [conversations, setConversations] = useState([]);
  const [activeId, setActiveId] = useState(null);
  const [messages, setMessages] = useState([]);
  const [text, setText] = useState('');
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);

  async function fetchConversations() {
    const url = hotelId ? `/api/concierge/conversations?hotel_id=${encodeURIComponent(hotelId)}` : '/api/concierge/conversations';
    const res = await fetch(url);
    const json = await res.json();
    const list = Array.isArray(json?.conversations) ? json.conversations : [];
    setConversations(list);
    if (!activeId && list.length) setActiveId(list[0].id);
  }

  async function fetchMessages(convoId) {
    if (!convoId) {
      setMessages([]);
      return;
    }
    const res = await fetch(`/api/concierge/conversations/${convoId}/messages`);
    const json = await res.json();
    setMessages(Array.isArray(json?.messages) ? json.messages : []);
  }

  useEffect(() => {
    let canceled = false;
    async function load() {
      try {
        await fetchConversations();
      } catch (e) {
        if (!canceled) setConversations([]);
      } finally {
        if (!canceled) setLoading(false);
      }
    }
    load();
    return () => {
      canceled = true;
    };
  }, [hotelId]);

  useEffect(() => {
    fetchMessages(activeId);
  }, [activeId]);

  async function send() {
    if (!hotelId) return alert('Selecione um hotel no topo para usar o concierge.');
    if (!text.trim()) return;

    setSending(true);
    try {
      const res = await fetch('/api/concierge/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ hotel_id: hotelId, conversation_id: activeId, message: text.trim() })
      });
      const json = await res.json();
      if (res.ok) {
        setText('');
        if (!activeId) setActiveId(json.conversation_id);
        await fetchConversations();
        await fetchMessages(json.conversation_id);
      }
    } finally {
      setSending(false);
    }
  }

  const conversations24h = conversations.filter(c => (Date.now() - new Date(c.created_at).getTime()) <= 24 * 60 * 60 * 1000).length;

  if (loading) return (
    <div style={{ display: 'grid', placeItems: 'center', height: '40vh' }}>
      <Icon name="progress_activity" size={40} className="hx-spin" style={{ color: 'var(--primary)' }} />
    </div>
  );

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18, marginBottom: 22 }}>
        <Stat label="Conversas" value={conversations.length} icon="forum" accent="var(--secondary)" />
        <Stat label="Conversas 24h" value={conversations24h} icon="schedule" accent="#caa53a" />
        <Stat label="Mensagens" value={messages.length} icon="chat" accent="var(--primary)" />
      </div>

      <Card pad={0} style={{ overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', height: 660 }}>
          <div style={{ borderRight: '1px solid var(--outline-variant)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
            <div style={{ padding: '18px 20px 14px', borderBottom: '1px solid var(--outline-variant)' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                <h3 className="font-headline" style={{ margin: 0, fontSize: 16, fontWeight: 800 }}>Conversas</h3>
                <button className="btn btn-outline" onClick={() => setActiveId(null)} style={{ fontSize: 12.5, padding: '8px 10px' }}><Icon name="add" size={16} /> Nova</button>
              </div>
              <button className="hx-link" onClick={fetchConversations}>Atualizar <Icon name="refresh" size={15} /></button>
            </div>
            <div style={{ flex: 1, overflow: 'auto' }}>
              {conversations.length ? conversations.map(c => (
                <div key={c.id} onClick={() => setActiveId(c.id)} className="hx-conv"
                  style={{ display: 'flex', gap: 12, padding: '14px 18px', cursor: 'pointer', borderLeft: '3px solid ' + (activeId === c.id ? 'var(--primary)' : 'transparent'), background: activeId === c.id ? 'var(--surface-container-low)' : 'transparent' }}>
                  <Avatar name={'Conversa'} size={42} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6 }}>
                      <span style={{ fontSize: 13.5, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.id.slice(0, 8)}</span>
                      <span style={{ fontSize: 10.5, color: 'var(--on-surface-variant)', whiteSpace: 'nowrap' }}>{new Date(c.created_at).toLocaleString('pt-BR')}</span>
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--on-surface-variant)' }}>Hotel: {c.hotel_id?.slice(0, 8)}</div>
                  </div>
                </div>
              )) : (
                <div style={{ padding: 16, color: 'var(--on-surface-variant)', fontSize: 13 }}>Nenhuma conversa ainda.</div>
              )}
            </div>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', minHeight: 0, background: 'var(--surface-container-low)' }}>
            <div style={{ padding: '16px 22px', borderBottom: '1px solid var(--outline-variant)', display: 'flex', alignItems: 'center', gap: 12, background: 'var(--surface-container-lowest)' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14.5, fontWeight: 700 }}>{activeId ? `Conversa ${activeId.slice(0, 8)}` : 'Nova conversa'}</div>
                <div style={{ fontSize: 11.5, color: 'var(--on-surface-variant)' }}>Mensagens persistidas no banco (dados reais)</div>
              </div>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, fontWeight: 700, color: 'var(--primary)', background: 'var(--secondary-container)', padding: '6px 12px', borderRadius: 999 }}><Icon name="smart_toy" size={14} fill={1} />Assistente</span>
            </div>

            <div style={{ flex: 1, overflow: 'auto', padding: '22px 26px', display: 'flex', flexDirection: 'column', gap: 12 }}>
              {messages.length ? messages.map(m => {
                const bot = m.role === 'assistant';
                return (
                  <div key={m.id} style={{ display: 'flex', justifyContent: bot ? 'flex-end' : 'flex-start' }}>
                    <div style={{ maxWidth: '76%', padding: '11px 15px', borderRadius: bot ? '16px 16px 4px 16px' : '16px 16px 16px 4px', background: bot ? 'var(--primary)' : 'var(--surface-container-lowest)', color: bot ? '#fff' : 'var(--on-surface)' }}>
                      <div style={{ fontSize: 13.5, lineHeight: 1.5 }}>{m.content}</div>
                      <div style={{ fontSize: 10, marginTop: 5, textAlign: 'right', color: bot ? 'rgba(255,255,255,0.7)' : 'var(--on-surface-variant)' }}>{new Date(m.created_at).toLocaleString('pt-BR')}</div>
                    </div>
                  </div>
                );
              }) : (
                <div style={{ padding: 16, borderRadius: 12, background: 'var(--surface-container-lowest)', color: 'var(--on-surface-variant)', fontSize: 13 }}>
                  Envie a primeira mensagem para iniciar.
                </div>
              )}
            </div>

            <div style={{ padding: '14px 22px', borderTop: '1px solid var(--outline-variant)', background: 'var(--surface-container-lowest)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 10, background: 'var(--surface-container-low)', borderRadius: 999, padding: '10px 16px' }}>
                  <Icon name="chat" size={19} style={{ color: 'var(--on-surface-variant)' }} />
                  <input value={text} onChange={e => setText(e.target.value)} placeholder="Digite a mensagem…" style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 13, color: 'var(--on-surface)' }} />
                </div>
                <button disabled={sending} onClick={send} style={{ width: 44, height: 44, borderRadius: 999, border: 'none', background: 'var(--primary)', color: '#fff', cursor: 'pointer', display: 'grid', placeItems: 'center', opacity: sending ? 0.7 : 1 }}><Icon name="send" size={19} /></button>
              </div>
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
}

window.ViewConcierge = ViewConcierge;

