/**
 * Message List Component
 * Displays all chat messages with auto-scroll
 */

import { useEffect, useRef } from 'react';
import { AnimatePresence } from 'framer-motion';
import { Message } from './Message';
import { TypingIndicator } from './TypingIndicator';
import { useChatStore } from '@/store/chatStore';
import { resolveValue, GlobalValues } from '@/utils/resolveAppearance';
import { t } from '@/lib/i18n';

export function MessageList() {
  const { messages, isTyping, isThinking, thinkingMessage, config } = useChatStore();
  const containerRef = useRef<HTMLDivElement>(null);
  
  // Debug: Track renders
  useEffect(() => {
    try {
      const logs = JSON.parse(sessionStorage.getItem('boostbot_render_debug') || '[]');
      const lastBotMsg = messages.filter(m => m.role === 'bot').pop();
      logs.push({ 
        t: Date.now(), 
        msgCount: messages.length,
        lastBotContent: lastBotMsg?.content?.length || 0,
        isStreaming: lastBotMsg?.isStreaming
      });
      if (logs.length > 50) logs.shift();
      sessionStorage.setItem('boostbot_render_debug', JSON.stringify(logs));
    } catch { /* ignore */ }
  });
  
  const globalValues = (config.appearance_preset?.global_values || {}) as GlobalValues;
  const windowSettings = config.element_settings?.chatWindow || config.appearance_preset?.element_settings?.chatWindow;
  const messagesPadding = resolveValue(windowSettings?.messagesPadding, globalValues, '12px');
  const messagesGap = resolveValue(windowSettings?.messagesGap, globalValues, '12px');
  
  // Auto-scroll to bottom on new messages or thinking state.
  // Use container.scrollTop instead of scrollIntoView to avoid scrolling
  // ancestor elements (e.g. the page itself when the widget is embedded inline).
  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      container.scrollTo({ top: container.scrollHeight, behavior: 'smooth' });
    }
  }, [messages, isTyping, isThinking]);
  
  return (
    <div 
      ref={containerRef}
      className="bb-message-list bb-chat-window-messages h-full overflow-y-auto custom-scrollbar"
      style={{
        padding: messagesPadding,
        display: 'flex',
        flexDirection: 'column',
        gap: messagesGap,
      }}
    >
      {messages.length === 0 && (
        <div className="text-center text-gray-400 text-sm py-8">
          <p>👋 {t('Hello! How can I help you?')}</p>
        </div>
      )}
      
      <AnimatePresence initial={false}>
        {messages.map((message, index) => (
          <Message 
            key={message.id} 
            message={message}
            isLast={index === messages.length - 1}
          />
        ))}
      </AnimatePresence>
      
      {/* Typing indicator */}
      <AnimatePresence>
        {isTyping && <TypingIndicator />}
      </AnimatePresence>

      {/* Thinking indicator (Gemini orchestrator is analyzing) */}
      <AnimatePresence>
        {isThinking && thinkingMessage && (
          <div className="bb-thinking-indicator flex items-center gap-2 text-sm text-gray-500 py-2 px-3">
            <span className="animate-pulse">🔍</span>
            <span>{thinkingMessage}</span>
          </div>
        )}
      </AnimatePresence>
      
      {/* Scroll anchor (spacer for auto-scroll target) */}
      <div />
    </div>
  );
}




