// ==========================================
// ChatPane Kit — MessageList Component
// ==========================================
// Scrollable message list with auto-scroll-to-bottom
// and "load older" pagination.
// Independently importable.
//
// v0.37.10: Added pagination (load more), regenerate/delete wiring.
//
// Usage:
//   html`<${MessageList} messages=${msgs} streamContent=${text}
//         streaming=${true} hasMore=${true} loadingMore=${false}
//         onLoadMore=${fn} onRegenerate=${fn} onDelete=${fn} />`

import { MessageBubble } from './message-bubble.js';

const { useRef, useEffect, useCallback } = window.hooks;
const html = window.html;

const SCROLL_THRESHOLD = 60;

/**
 * @param {{
 *   messages: Array<{role: string, content: string, id?: string, created_at?: string}>,
 *   streamContent?: string,
 *   streamThinking?: string,
 *   streaming?: boolean,
 *   hasMore?: boolean,
 *   loadingMore?: boolean,
 *   onLoadMore?: () => void,
 *   onRegenerate?: (msgId: string) => void,
 *   onDelete?: (msgId: string) => void,
 *   className?: string,
 * }} props
 */
export function MessageList({
    messages, streamContent, streamThinking, streaming, hasMore, loadingMore,
    onLoadMore, onRegenerate, onDelete, className,
}) {
    const scrollRef = useRef(null);
    const wasAtBottom = useRef(true);
    const prevScrollHeightRef = useRef(0);

    // Track scroll position
    function _onScroll() {
        const el = scrollRef.current;
        if (!el) return;
        wasAtBottom.current = (el.scrollHeight - el.scrollTop - el.clientHeight) < SCROLL_THRESHOLD;
    }

    // Auto-scroll when new content arrives (only if was at bottom)
    useEffect(() => {
        const el = scrollRef.current;
        if (el && wasAtBottom.current) {
            el.scrollTop = el.scrollHeight;
        }
    }, [messages, streamContent]);

    // Preserve scroll position when prepending older messages
    useEffect(() => {
        const el = scrollRef.current;
        if (!el) return;
        const prevH = prevScrollHeightRef.current;
        if (prevH && el.scrollHeight > prevH && !wasAtBottom.current) {
            // Older messages were prepended — maintain relative position
            el.scrollTop += (el.scrollHeight - prevH);
        }
        prevScrollHeightRef.current = el.scrollHeight;
    }, [messages.length]);

    const hasContent = messages.length > 0 || streaming;
    const myUserId = window.sw?.auth?.user?.id;

    return html`
        <div class=${'sw-chat-pane__messages' + (className ? ' ' + className : '')}
             ref=${scrollRef}
             onScroll=${_onScroll}
             role="log"
             aria-label="Chat messages"
             aria-live="polite">
            ${hasMore && html`
                <div class="sw-chat-pane__load-more">
                    <button class="sw-chat-pane__load-more-btn"
                            onClick=${onLoadMore}
                            disabled=${loadingMore}
                            aria-label="Load older messages">
                        ${loadingMore ? 'Loading\u2026' : 'Load older messages'}
                    </button>
                </div>`}
            ${!hasContent && html`
                <div class="sw-chat-welcome">
                    <p class="sw-chat-welcome__title">Start a conversation</p>
                    <p class="sw-chat-welcome__hint">Type a message below to get started.</p>
                </div>`}
            ${messages.map((m, i) => {
                // Determine if this message was sent by the current user
                const senderId = m.user_id || m.participant_id;
                const isMine = m.role === 'user' && (!senderId || senderId === myUserId);
                return html`
                <${MessageBubble}
                    key=${m.id || i}
                    role=${m.role}
                    content=${m.content}
                    thinking=${m.thinking}
                    id=${m.id}
                    created_at=${m.created_at}
                    isMine=${isMine}
                    senderName=${m.role === 'user' && !isMine ? (m.display_name || m.sender_name || m.username || '') : ''}
                    onRegenerate=${m.role === 'assistant' && m.id && onRegenerate ? () => onRegenerate(m.id) : undefined}
                    onDelete=${m.id && onDelete ? () => onDelete(m.id) : undefined} />`;
            })}
            ${streaming && html`
                <${MessageBubble} role="assistant" content=${streamContent}
                    thinking=${streamThinking} streaming=${true} />`}
        </div>`;
}
