/**
 * AI Chat view: IT/hotel assistant with KB search, tickets, CapEx, and (when permitted) property/portfolio data.
 * Sends messages to /api/chat; permissions are enforced server-side. Never trusts client for access control.
 */
const AIChatView = ({ onCreateTicket, onClearChat, messages, setMessages, attachments, setAttachments, allAttachments, setAllAttachments, selectedProperty, currentUser, onOpenKbDraft }) => {
    const { useState, useEffect, useRef } = React;
    const greetingMessage =
        (typeof window !== 'undefined' &&
            window.getAIAssistantGreeting &&
            window.getAIAssistantGreeting(currentUser)) ||
        "Hi! I'm your OTO Assistant. I can help with property information, directory lookups, knowledge base articles, and general questions about OTO-HUB.\n\nHow can I help you today?";
    const greetingTitle =
        (typeof window !== 'undefined' &&
            window.getAIAssistantTitle &&
            window.getAIAssistantTitle(currentUser)) || "AI Assistant";
    const greetingSubtitle =
        (typeof window !== 'undefined' &&
            window.getAIAssistantSubtitle &&
            window.getAIAssistantSubtitle(currentUser)) ||
        "Get instant help with property info, directory lookups, and knowledge base content across OTO-HUB.";
    const [input, setInput] = useState('');
    const [isTyping, setIsTyping] = useState(false);
    const [hasUserMessage, setHasUserMessage] = useState(false);
    const [isChatEnding, setIsChatEnding] = useState(false); // Track if countdown is active
    const currentUsername = (currentUser?.Username || currentUser?.username || localStorage.getItem('oto_username') || '').trim();
    const messagesEndRef = useRef(null);
    const inputRef = useRef(null);  // Add ref for textarea input
    const [isDragging, setIsDragging] = useState(false);
    const fileInputRef = useRef(null);
    const [ticketState, setTicketState] = useState(null);
    const [lastTicketId, setLastTicketId] = useState(null);
    const [viewingAttachment, setViewingAttachment] = useState(null); // For modal popup
    const [showTicketListModal, setShowTicketListModal] = useState(false); // For ticket list modal
    const [ticketListData, setTicketListData] = useState(null); // Ticket list data
    const [ticketListFilter, setTicketListFilter] = useState(''); // Search text for ticket list
    const [ticketListFilterStatus, setTicketListFilterStatus] = useState(''); // Status filter: '' | 'New' | 'In Progress' | 'Waiting' | 'Closed'
    const [ticketListFilterPriority, setTicketListFilterPriority] = useState(''); // Priority filter: '' | 'Low' | 'Normal' | 'High' | 'Critical'
    const [viewingTicketDetail, setViewingTicketDetail] = useState(null); // Selected ticket for detail view (object or null)
    const [ticketDetailFull, setTicketDetailFull] = useState(null); // Full ticket from API when viewing detail
    const [ticketDetailLoading, setTicketDetailLoading] = useState(false);
    const [ticketDetailError, setTicketDetailError] = useState(null);
    const [ticketDetailNewComment, setTicketDetailNewComment] = useState('');
    const [ticketDetailActionLoading, setTicketDetailActionLoading] = useState(null); // 'comment' | 'close' | 'update' | null
    const [ticketDetailCloseConfirm, setTicketDetailCloseConfirm] = useState(false);
    const [ticketDetailEditMode, setTicketDetailEditMode] = useState(false);
    const [ticketDetailEditSubject, setTicketDetailEditSubject] = useState('');
    const [ticketDetailEditBody, setTicketDetailEditBody] = useState('');
    const [ticketDetailEditPriority, setTicketDetailEditPriority] = useState('normal');
    const [showClearChatModal, setShowClearChatModal] = useState(false); // For clear chat confirmation modal
    const [pendingClearChatReason, setPendingClearChatReason] = useState(null); // Reason for clearing chat
    const [countdownPaused, setCountdownPaused] = useState(false); // Track if countdown is paused
    const [pausedCountdownValue, setPausedCountdownValue] = useState(null); // Store countdown value when paused
    const [showTicketSubmitConfirmModal, setShowTicketSubmitConfirmModal] = useState(false); // For ticket submission confirmation
    const [pendingTicketSubmission, setPendingTicketSubmission] = useState(null); // Pending ticket submission data
    const [ticketSubmitConfirmLoading, setTicketSubmitConfirmLoading] = useState(false); // Prevent double-submit
    const [showTicketUpdateConfirmModal, setShowTicketUpdateConfirmModal] = useState(false); // For ticket update confirmation
    const [pendingTicketUpdate, setPendingTicketUpdate] = useState(null); // Pending ticket update (subject/body/priority)
    const [ticketUpdateConfirmLoading, setTicketUpdateConfirmLoading] = useState(false);
    const [expandedRequestContextIndex, setExpandedRequestContextIndex] = useState(null); // Which assistant message shows "what was sent to the AI"
    const countdownIntervalRef = useRef(null);
    const countdownTimeoutRef = useRef(null);
    // Track which KB sources have already been shown in this chat so we don't repeat them.
    // Reset this when the user starts a New Chat / Clear Now.
    const seenSourceIdsRef = useRef(new Set());

    // Format JitBit comment body: strip <!--html--> and HTML tags to plain text for display
    const formatTicketCommentBody = (raw) => {
        if (raw == null || raw === '') return '—';
        let s = String(raw)
            .replace(/<!--\s*html\s*-->/gi, '')
            .replace(/<br\s*\/?>/gi, '\n')
            .replace(/<[^>]+>/g, '')
            .replace(/&nbsp;/g, ' ')
            .replace(/&amp;/g, '&')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&quot;/g, '"');
        return s.trim() || '—';
    };

    // Debug: Log when viewing attachment changes
    useEffect(() => {
        console.log('viewingAttachment changed:', viewingAttachment);
    }, [viewingAttachment]);

    // Helper to convert file to base64
    const fileToBase64 = (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result.split(',')[1]); // Remove data:image/png;base64, prefix
            reader.onerror = reject;
            reader.readAsDataURL(file);
        });
    };

    // Attachment functions
    const handleFileSelect = (e) => {
        const files = Array.from(e.target.files);
        const newAttachments = files.map(file => ({
            id: Date.now() + Math.random(),
            name: file.name,
            size: file.size,
            type: file.type,
            file: file  // Store actual file object for base64 conversion
        }));
        setAttachments(prev => [...prev, ...newAttachments]);
        setAllAttachments(prev => [...prev, ...newAttachments]);
    };

    const removeAttachment = (id) => {
        setAttachments(prev => prev.filter(att => att.id !== id));
    };

    const handleDragOver = (e) => {
        e.preventDefault();
        setIsDragging(true);
    };

    const handleDragLeave = (e) => {
        e.preventDefault();
        setIsDragging(false);
    };

    const handleDrop = (e) => {
        e.preventDefault();
        setIsDragging(false);
        const files = Array.from(e.dataTransfer.files);
        const newAttachments = files.map(file => ({
            id: Date.now() + Math.random(),
            name: file.name,
            size: file.size
        }));
        setAttachments(prev => [...prev, ...newAttachments]);
    };

    const formatFileSize = (bytes) => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    };

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    };

    useEffect(scrollToBottom, [messages]);

    // Fetch full ticket details when user opens the ticket detail view
    useEffect(() => {
        if (!viewingTicketDetail || !viewingTicketDetail.id) {
            setTicketDetailFull(null);
            setTicketDetailError(null);
            setTicketDetailLoading(false);
            return;
        }
        let cancelled = false;
        setTicketDetailLoading(true);
        setTicketDetailError(null);
        setTicketDetailFull(null);
        const tid = viewingTicketDetail.id;
        fetch(`/api/tickets/${tid}`, {
            headers: window.getApiHeaders ? window.getApiHeaders(currentUsername) : { 'X-OTO-User': currentUsername },
        })
            .then((res) => {
                if (cancelled) return;
                if (!res.ok) return res.json().then((d) => { throw new Error(d.detail || res.statusText); });
                return res.json();
            })
            .then((data) => {
                if (!cancelled) { setTicketDetailFull(data); setTicketDetailError(null); }
            })
            .catch((err) => {
                if (!cancelled) { setTicketDetailError(err.message || 'Failed to load ticket'); setTicketDetailFull(null); }
            })
            .finally(() => {
                if (!cancelled) setTicketDetailLoading(false);
            });
        return () => { cancelled = true; };
    }, [viewingTicketDetail?.id, currentUsername]);

    const refreshTicketDetail = () => {
        if (!viewingTicketDetail?.id) return;
        const tid = viewingTicketDetail.id;
        fetch(`/api/tickets/${tid}`, {
            headers: window.getApiHeaders ? window.getApiHeaders(currentUsername) : { 'X-OTO-User': currentUsername },
        })
            .then((res) => res.ok ? res.json() : res.json().then((d) => { throw new Error(d.detail || res.statusText); }))
            .then((data) => { setTicketDetailFull(data); setTicketDetailError(null); })
            .catch((err) => { setTicketDetailError(err.message || 'Failed to refresh'); });
    };

    const handleSend = async () => {
        if (!input.trim() && attachments.length === 0) return;

        const userMessage = {
            role: 'user',
            content: input || '(File attachments only)',
            timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
            attachments: attachments.length > 0 ? attachments.map(file => ({
                name: file.name,
                size: file.size,
                type: file.type,
                file: file.file  // Store the actual File object for viewing later
            })) : []
        };

        const updatedAllAttachments = [...allAttachments, ...attachments];
        setAllAttachments(updatedAllAttachments);

        // Clear any existing ticket previews from previous messages (user is continuing conversation)
        const messagesWithoutPreviews = messages.map(msg => {
            if (msg.ticketPreview) {
                console.log('🧹 Clearing ticket preview from previous message (user continuing conversation)');
                return {
                    ...msg,
                    ticketPreview: null
                };
            }
            return msg;
        });

        const newMessages = [...messagesWithoutPreviews, userMessage];
        setMessages(newMessages);
        setInput('');
        const currentAttachments = [...attachments]; // Save before clearing
        setAttachments([]);
        setIsTyping(true);

        try {
            // Collect ALL attachments from the entire conversation history
            const allConversationAttachments = [];
            for (const msg of newMessages) {
                if (msg.attachments && msg.attachments.length > 0) {
                    allConversationAttachments.push(...msg.attachments);
                }
            }

            // Convert all attachments to base64 for AI
            const attachmentsBase64 = await Promise.all(
                allConversationAttachments.map(async (att) => {
                    if (att.file) {
                        const base64 = await fileToBase64(att.file);
                        return {
                            name: att.name,
                            type: att.type,
                            data: base64
                        };
                    }
                    return null;
                })
            );

            const res = await fetch('/api/chat', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', ...(window.getApiHeaders ? window.getApiHeaders(currentUsername) : {}) },
                body: JSON.stringify({
                    // Filter out system/display-only messages (like the default greeting) before sending to backend
                    messages: newMessages.filter(m => !m.isSystemMessage).map(m => ({ role: m.role, content: m.content })),
                    draft: ticketState ? ticketState.draft : null,
                    property_code: selectedProperty?.property_code || null,
                    property_name: selectedProperty?.name || null,
                    attachments: attachmentsBase64.filter(a => a !== null),
                    last_ticket_id: lastTicketId,
                    current_user: {
                        full_name: `${currentUser.FirstName} ${currentUser.LastName}`.trim(),
                        first_name: currentUser.FirstName,
                        last_name: currentUser.LastName,
                        username: currentUser.Username,
                        email: currentUser.Email,
                        phone: currentUser.Phone,
                        role: currentUser.Role
                    }
                })
            });
            let data;
            try { data = await res.json(); } catch { throw new Error(`AI request failed (${res.status})`); }
            if (!res.ok) throw new Error(data.detail || 'AI request failed');

            console.log('[AI Response] Full data:', data);
            console.log('[AI Response] ticket_state:', data.ticket_state);
            if (data.ticket_state) {
                console.log('  ├─ show_ticket_preview:', data.ticket_state.show_ticket_preview);
                console.log('  ├─ ready_to_submit:', data.ticket_state.ready_to_submit);
                console.log('  ├─ draft:', data.ticket_state.draft);
                console.log('  └─ missing_fields:', data.ticket_state.missing_fields);
            }

            // Store the updated ticket state
            if (data.ticket_state) {
                setTicketState(data.ticket_state);
                console.log('[Ticket State] Updated:', data.ticket_state);
            }

            // Create the AI message
            // Deduplicate sources within the same chat so we only show *new* sources.
            const incomingSources = Array.isArray(data.sources) ? data.sources : [];
            const filteredSources = incomingSources.filter((src) => {
                // Prefer stable keys (DB id). Fall back to title+category+property_code.
                const key = String(
                    src?.id ?? `${src?.title || ''}::${src?.category || ''}::${src?.property_code || ''}`
                );
                if (seenSourceIdsRef.current.has(key)) return false;
                seenSourceIdsRef.current.add(key);
                return true;
            });

            console.log('🐛 RAW RESPONSE FROM SERVER:');
            console.log('Full data object:', data);
            console.log('data.reply:', data.reply);
            console.log('data.reply TYPE:', typeof data.reply);
            console.log('data.reply LENGTH:', data.reply?.length);
            console.log('data.reply IS EMPTY:', !data.reply);
            console.log('data.reply FIRST 100 chars:', data.reply?.substring(0, 100));

            const aiMessage = {
                role: 'assistant',
                content: (data.reply && data.reply.trim()) ? data.reply.trim() : ((data.ticket_state?.show_ticket_preview || data.ticket_state?.chat_clear_requested || data.ticket_state?.issue_resolved || data.ticket_state?.chat_ended || data.closeConfirmation || data.ticket_submission) ? '' : "I couldn't complete that. You may need different permissions for this action, or something went wrong—please try again or rephrase."),
                timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                ticketPreview: data.ticket_state?.show_ticket_preview ? data.ticket_state.draft : null,
                readyToSubmit: data.ticket_state?.ready_to_submit || false,
                closeConfirmation: data.closeConfirmation || null,
                ticketSubmission: data.ticket_submission || null,  // Direct ticket submission result
                sources: filteredSources,
                kbDraft: data.kb_draft || null,
                requestContext: data.request_context || null  // What was sent to the AI (prompt, messages, tools)
            };

            console.log('🐛 AI MESSAGE OBJECT:');
            console.log('aiMessage.content:', aiMessage.content);
            console.log('aiMessage.content LENGTH:', aiMessage.content?.length);
            console.log('aiMessage.content FIRST 100:', aiMessage.content?.substring(0, 100));

            setMessages(prev => [...prev, aiMessage]);

            // Handle ticket list modal display
            if (data.show_ticket_list && data.ticket_list) {
                console.log('📋 Showing ticket list modal:', data.ticket_list);
                setTicketListData(data.ticket_list);
                setShowTicketListModal(true);
            }

            // Handle single-ticket detail view (e.g. "view that ticket", after add comment/close/update)
            if (data.show_ticket_detail && data.ticket_detail) {
                const detail = data.ticket_detail;
                console.log('🎫 Opening ticket detail view:', detail);
                setTicketListData({
                    mode_used: 'single',
                    count: 1,
                    tickets: [{
                        id: detail.id,
                        subject: detail.subject || 'Untitled',
                        status: detail.status || '',
                        priority: detail.priority || 'Normal',
                        updated: detail.updated || '',
                        category: detail.category || '',
                        jitbit_url: detail.jitbit_url || '',
                    }],
                });
                setViewingTicketDetail({ ...detail, id: detail.id });
                setShowTicketListModal(true);
            }

            // Handle ticket update confirmation - show proposed changes before applying
            if (data.ticket_update && data.ticket_update.pending_confirmation) {
                console.log('🎫 Showing ticket update confirmation modal:', data.ticket_update);
                setPendingTicketUpdate(data.ticket_update);
                setShowTicketUpdateConfirmModal(true);
                setIsTyping(false);
                return;
            }

            // Handle direct ticket submission - show confirmation modal first if pending
            if (data.ticket_submission) {
                if (data.ticket_submission.pending_confirmation) {
                    // Show confirmation modal before submission
                    console.log('🎫 Showing ticket submission confirmation modal:', data.ticket_submission);
                    setPendingTicketSubmission(data.ticket_submission);
                    setShowTicketSubmitConfirmModal(true);
                    setIsTyping(false);
                    // Don't add ticketSubmission to message yet - wait for confirmation
                    const lastMsg = aiMessage;
                    lastMsg.ticketSubmission = null;
                    setMessages(prev => {
                        const updated = [...prev];
                        updated[updated.length - 1] = lastMsg;
                        return updated;
                    });
                    return; // Don't process further until user confirms
                } else {
                    // Already submitted - show success/error modal
                    console.log('🎫 Ticket submission result:', data.ticket_submission);
                    // Success/error modal will be shown via ticketSubmission in the message
                }
            }

            // NOTE: ready_to_submit just enables the Submit button - actual submission
            // and countdown only happen when user clicks "Submit Ticket" button
            // (handled in handleTicketSubmit function)

            // When AI inferred conversation ended (end_conversation tool): show countdown in chat, then fresh chat (no modal).
            if (data.ticket_state?.chat_ended && !data.ticket_state?.show_ticket_preview) {
                setIsChatEnding(true);
                setMessages(prev => {
                    const filtered = prev.filter(m => !(m.role === 'system' && m.countdown !== undefined));
                    return [...filtered, {
                        role: 'system',
                        content: 'Conversation ended. Starting fresh in...',
                        timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                        countdown: 15
                    }];
                });
                let remaining = 15;
                countdownIntervalRef.current = setInterval(() => {
                    remaining--;
                    if (remaining > 0) {
                        setMessages(prev => {
                            const newMessages = [...prev];
                            const lastMsg = newMessages[newMessages.length - 1];
                            if (lastMsg && lastMsg.role === 'system' && lastMsg.countdown !== undefined) {
                                lastMsg.countdown = remaining;
                            }
                            return newMessages;
                        });
                    } else {
                        if (countdownIntervalRef.current) {
                            clearInterval(countdownIntervalRef.current);
                            countdownIntervalRef.current = null;
                        }
                    }
                }, 1000);
                countdownTimeoutRef.current = setTimeout(() => {
                    if (countdownIntervalRef.current) {
                        clearInterval(countdownIntervalRef.current);
                        countdownIntervalRef.current = null;
                    }
                    setMessages([
                        { role: 'assistant', content: greetingMessage, isSystemMessage: true }
                    ]);
                    setInput('');
                    setAllAttachments([]);
                    setTicketState(null);
                    setLastTicketId(null);
                    setIsChatEnding(false);
                    if (onClearChat) onClearChat();
                }, 15000);
                setIsTyping(false);
                return;
            }

            // If issue resolved or user requested clear (no ticket preview): modal flow (confirm then clear).
            const shouldTriggerModal = (data.ticket_state?.issue_resolved || data.ticket_state?.chat_clear_requested) && !data.ticket_state?.show_ticket_preview;
            console.log('🔍 COUNTDOWN CHECK:', {
                issue_resolved: data.ticket_state?.issue_resolved,
                chat_clear_requested: data.ticket_state?.chat_clear_requested,
                chat_ended: data.ticket_state?.chat_ended,
                show_ticket_preview: data.ticket_state?.show_ticket_preview,
                shouldTriggerModal
            });

            if (shouldTriggerModal) {
                console.log('[Countdown] Triggered modal:', {
                    issue_resolved: data.ticket_state?.issue_resolved,
                    chat_clear_requested: data.ticket_state?.chat_clear_requested,
                    existing_interval: !!countdownIntervalRef.current,
                    existing_timeout: !!countdownTimeoutRef.current
                });

                // If a countdown is already running and user says "clear" again, clear immediately
                if (data.ticket_state?.chat_clear_requested && (countdownIntervalRef.current || countdownTimeoutRef.current)) {
                    console.log('[Countdown] User requested clear again - clearing immediately');

                    // Clear existing countdowns
                    if (countdownIntervalRef.current) {
                        clearInterval(countdownIntervalRef.current);
                        countdownIntervalRef.current = null;
                    }
                    if (countdownTimeoutRef.current) {
                        clearTimeout(countdownTimeoutRef.current);
                        countdownTimeoutRef.current = null;
                    }

                    // Clear immediately
                    setMessages([
                        { role: 'assistant', content: greetingMessage, isSystemMessage: true }
                    ]);
                    setInput('');
                    setAllAttachments([]);
                    setTicketState(null);
                    setLastTicketId(null);
                    setIsChatEnding(false);
                    if (onClearChat) onClearChat();

                    setIsTyping(false);
                    return; // Exit early, don't start a new countdown
                }

                // Show confirmation modal for chat clearing (no countdown in chat - just modal then clear)
                const reason = data.ticket_state?.chat_clear_requested
                    ? 'clear'
                    : data.ticket_state?.issue_resolved
                    ? 'resolved'
                    : 'unknown';
                setPendingClearChatReason(reason);
                setShowClearChatModal(true);
                setIsTyping(false);
                return; // Wait for user confirmation - no countdown in chat box
            }
        } catch (err) {
            setMessages(prev => [...prev, {
                role: 'assistant',
                content: `Sorry — I couldn't reach the AI backend. ${err?.message || ''}`.trim(),
                timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
            }]);
        } finally {
            setIsTyping(false);
            // Auto-focus input after AI response
            setTimeout(() => {
                if (inputRef.current) {
                    inputRef.current.focus();
                }
            }, 100);
        }
    };

    const handleKeyPress = (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSend();
        }
    };

    // Handle ticket submission to JitBit
    const handleTicketSubmit = async (ticketPreview) => {
        console.group('🎫 TICKET SUBMISSION STARTED');
        console.log('📋 Ticket Preview Data:', ticketPreview);
        console.log('👤 Current Username:', currentUsername);
        console.log('⏰ Timestamp:', new Date().toISOString());

        if (!ticketPreview || !ticketPreview.subject || !ticketPreview.description) {
            console.error('❌ VALIDATION FAILED: Missing required fields');
            console.log('  - Has ticketPreview:', !!ticketPreview);
            console.log('  - Has subject:', !!ticketPreview?.subject);
            console.log('  - Has description:', !!ticketPreview?.description);
            console.groupEnd();

            setMessages(prev => [...prev, {
                role: 'assistant',
                content: '❌ Unable to submit ticket - missing required information.',
                timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
            }]);
            return;
        }

        console.log('✓ Validation passed');
        console.log('📤 Preparing to send request...');

        // Collect image attachments from the chat
        const imageAttachments = [];
        for (const att of allAttachments) {
            if (att.type && att.type.startsWith('image/') && att.file) {
                try {
                    // Convert file to base64
                    const base64 = await new Promise((resolve, reject) => {
                        const reader = new FileReader();
                        reader.onload = () => resolve(reader.result.split(',')[1]);
                        reader.onerror = reject;
                        reader.readAsDataURL(att.file);
                    });

                    imageAttachments.push({
                        name: att.name,
                        type: att.type,
                        data: base64
                    });
                } catch (err) {
                    console.warn('Failed to process attachment:', att.name, err);
                }
            }
        }

        console.log(`📎 Including ${imageAttachments.length} image attachments`);

        // Add attachments to ticket preview
        const ticketWithAttachments = {
            ...ticketPreview,
            attachments: imageAttachments
        };

        // Show submitting message
        setMessages(prev => [...prev, {
            role: 'system',
            content: '⏳ Submitting your ticket to JitBit...',
            timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
        }]);

        try {
            console.log('🌐 Making fetch request to /api/tickets/submit');
            console.log('📦 Request payload:', JSON.stringify(ticketWithAttachments, null, 2));
            console.log('🔑 Headers:', {
                'Content-Type': 'application/json',
                'X-OTO-User': currentUsername || 'NOT SET'
            });

            const response = await fetch('/api/tickets/submit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-OTO-User': currentUsername || ''
                },
                body: JSON.stringify(ticketWithAttachments)
            });

            console.log('📥 Response received:');
            console.log('  - Status:', response.status, response.statusText);
            console.log('  - OK:', response.ok);
            console.log('  - Headers:', Object.fromEntries(response.headers.entries()));

            if (!response.ok) {
                let errorData;
                try {
                    errorData = await response.json();
                    console.error('❌ API Error Response:', errorData);
                } catch (parseError) {
                    console.error('❌ Failed to parse error response:', parseError);
                    errorData = { detail: `Server returned ${response.status}: ${response.statusText}` };
                }

                console.groupEnd();
                throw new Error(errorData.detail || `HTTP ${response.status}: ${response.statusText}`);
            }

            const result = await response.json();
            console.log('✅ Success! Ticket created:', result);
            console.groupEnd();

            // Remove the "submitting" message and clear all ticket previews
            setMessages(prev => prev.slice(0, -1).map(msg => {
                if (msg.ticketPreview) {
                    console.log('🧹 Clearing ticket preview after successful submission');
                    return {
                        ...msg,
                        ticketPreview: null
                    };
                }
                return msg;
            }));

            // Show success card
            setMessages(prev => [...prev, {
                role: 'assistant',
                content: '', // Empty content
                timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                ticketSuccess: {
                    ticketId: result.jitbit_ticket_id,
                    propertyCode: result.property_code,
                    jitbitUrl: result.jitbit_url
                }
            }]);

            setLastTicketId(result.jitbit_ticket_id);

            // Clear ticket state
            setTicketState(null);

            // Start countdown to clear chat after successful submission
            setTimeout(() => {
                setIsChatEnding(true); // Hide input controls

                setMessages(prev => {
                    const filtered = prev.filter(m => !(m.role === 'system' && m.countdown !== undefined));
                    return [...filtered, {
                        role: 'system',
                        content: 'Ticket submitted successfully! Starting fresh conversation in...',
                        timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                        countdown: 15
                    }];
                });

                // Start countdown
                let remaining = 15;
                countdownIntervalRef.current = setInterval(() => {
                    remaining--;
                    if (remaining > 0) {
                        setMessages(prev => {
                            const newMessages = [...prev];
                            const lastMsg = newMessages[newMessages.length - 1];
                            if (lastMsg && lastMsg.role === 'system' && lastMsg.countdown !== undefined) {
                                lastMsg.countdown = remaining;
                            }
                            return newMessages;
                        });
                    } else {
                        if (countdownIntervalRef.current) {
                            clearInterval(countdownIntervalRef.current);
                            countdownIntervalRef.current = null;
                        }
                    }
                }, 1000);

                // Clear chat after 15 seconds
                countdownTimeoutRef.current = setTimeout(() => {
                    if (countdownIntervalRef.current) {
                        clearInterval(countdownIntervalRef.current);
                        countdownIntervalRef.current = null;
                    }
                    setMessages([
                        { role: 'assistant', content: greetingMessage }
                    ]);
                    setInput('');
                    setAllAttachments([]);
                    setTicketState(null);
                    setLastTicketId(null);
                    setIsChatEnding(false);
                    if (onClearChat) onClearChat();
                }, 15000);
            }, 500);

        } catch (error) {
            console.error('💥 EXCEPTION CAUGHT:', error);
            console.error('  - Error name:', error.name);
            console.error('  - Error message:', error.message);
            console.error('  - Error stack:', error.stack);
            console.groupEnd();

            // Remove the "submitting" message
            setMessages(prev => prev.slice(0, -1));

            // Build detailed error message
            let errorDetails = error.message;

            // Check if it's a network error
            if (error.message.includes('fetch') || error.name === 'TypeError') {
                errorDetails = 'Network error - could not reach the server. Please check your connection and try again.';
            }

            // Show error message with troubleshooting tips
            let errorMessage = `❌ **Failed to Submit Ticket**\n\n**Error:** ${errorDetails}\n\n`;
            errorMessage += `**Troubleshooting:**\n`;
            errorMessage += `- Check the browser console (F12) for detailed error information\n`;
            errorMessage += `- Verify you have an email address in your profile\n`;
            errorMessage += `- Confirm your user exists in JitBit\n`;
            errorMessage += `- Contact IT support directly if the problem persists\n\n`;
            errorMessage += `**Note:** The server logs may contain additional details about what went wrong.`;

            setMessages(prev => [...prev, {
                role: 'assistant',
                content: errorMessage,
                timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
            }]);
        }
    };

    // Clear chat immediately (called from confirmation modal - no countdown in chat box)
    const clearChatImmediately = () => {
        // Clear any existing countdowns first
        if (countdownIntervalRef.current) {
            clearInterval(countdownIntervalRef.current);
            countdownIntervalRef.current = null;
        }
        if (countdownTimeoutRef.current) {
            clearTimeout(countdownTimeoutRef.current);
            countdownTimeoutRef.current = null;
        }
        
        // Reset source dedupe for a fresh conversation
        seenSourceIdsRef.current = new Set();
        
        // Clear chat immediately
        setMessages([
            { role: 'assistant', content: greetingMessage, isSystemMessage: true }
        ]);
        setInput('');
        setAllAttachments([]);
        setTicketState(null);
        setLastTicketId(null);
        setIsChatEnding(false);
        setCountdownPaused(false);
        if (onClearChat) onClearChat();
    };

    // Handle ticket cancellation
    const handleTicketCancel = () => {
        console.log('🚫 Ticket cancelled - removing all ticket previews from messages');

        // Remove ticketPreview from all messages
        setMessages(prev => prev.map(msg => {
            if (msg.ticketPreview) {
                return {
                    ...msg,
                    ticketPreview: null
                };
            }
            return msg;
        }).concat({
            role: 'assistant',
            content: 'Ticket creation cancelled. Is there anything else I can help you with?',
            timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
        }));

        setTicketState(null);
    };

    const handleCreateTicketFromChat = () => {
        const conversationSummary = messages
            .filter(m => m.role === 'user')
            .map(m => m.content)
            .join('\n\n');
        onCreateTicket(conversationSummary, attachments);
    };

    return (
        <div className="flex flex-col h-full">
            <div className="bg-white border-b border-slate-200 p-4 flex items-center justify-between shadow-sm">
                <div>
                    <h2 className="text-2xl font-bold text-gray-900">{greetingTitle}</h2>
                    <p className="text-sm text-gray-700 mt-1">{greetingSubtitle}</p>
                </div>
                {messages.length > 1 && !isChatEnding && (
                    <button
                        onClick={() => {
                            setPendingClearChatReason('clear');
                            setShowClearChatModal(true);
                        }}
                        className="px-5 py-2.5 bg-primary hover:bg-primary-hover text-white rounded-lg text-sm font-semibold transition-colors shadow-sm whitespace-nowrap"
                    >
                        New Chat
                    </button>
                )}
            </div>

            <div className="flex-1 overflow-y-auto p-6 space-y-4 scrollbar-thin">
                {messages.map((msg, idx) => (
                    <div key={idx} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'} chat-message`}>
                        <div className={`max-w-2xl rounded-2xl px-6 py-4 ${msg.role === 'user'
                                ? 'bg-primary text-white'
                                : msg.role === 'system'
                                    ? 'bg-white border-2 border-primary/30 text-gray-800 shadow-lg'
                                    : 'bg-white border border-gray-200 text-gray-800'
                            }`}>
                            {msg.role === 'assistant' && msg.ticketPreview && (() => {
                                console.log('🎫 RENDERING TICKET PREVIEW:', msg.ticketPreview);
                                return true;
                            })() && (
                                    <div className="mb-4 bg-white border-2 border-primary rounded-xl shadow-lg overflow-hidden">
                                        {/* Header */}
                                        <div className="bg-gradient-to-r from-primary to-primary-dark px-6 py-4">
                                            <div className="flex items-center gap-3 text-white">
                                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                                </svg>
                                                <h3 className="text-lg font-bold">Ticket Preview</h3>
                                            </div>
                                        </div>

                                        {/* Content */}
                                        <div className="px-6 py-5 space-y-3">
                                            {msg.ticketPreview.property_code && (
                                                <div className="flex gap-3">
                                                    <span className="font-semibold text-gray-600 min-w-[100px]">Property:</span>
                                                    <span className="text-gray-900">{msg.ticketPreview.property_code} - {msg.ticketPreview.property_name}</span>
                                                </div>
                                            )}
                                            <div className="flex gap-3">
                                                <span className="font-semibold text-gray-600 min-w-[100px]">Subject:</span>
                                                <span className="text-gray-900 font-medium">{msg.ticketPreview.subject}</span>
                                            </div>
                                            <div className="flex gap-3">
                                                <span className="font-semibold text-gray-600 min-w-[100px]">Description:</span>
                                                <span className="text-gray-900">{(() => {
                                                    const desc = msg.ticketPreview.description || '';
                                                    const issueSummaryIndex = desc.indexOf('Issue Summary:');
                                                    if (issueSummaryIndex !== -1) {
                                                        let summary = desc.substring(issueSummaryIndex + 'Issue Summary:'.length).trim();
                                                        const troubleshootingIndex = summary.indexOf('Troubleshooting Performed:');
                                                        if (troubleshootingIndex !== -1) {
                                                            summary = summary.substring(0, troubleshootingIndex).trim();
                                                        }
                                                        return summary;
                                                    }
                                                    return desc;
                                                })()}</span>
                                            </div>
                                            <div className="flex gap-3">
                                                <span className="font-semibold text-gray-600 min-w-[100px]">Category:</span>
                                                <span className="text-gray-900">{msg.ticketPreview.category || 'Not specified'}</span>
                                            </div>
                                            <div className="flex gap-3">
                                                <span className="font-semibold text-gray-600 min-w-[100px]">Priority:</span>
                                                <span className="text-gray-900">{msg.ticketPreview.priority}</span>
                                            </div>
                                            {msg.ticketPreview.reportee && (
                                                <div className="flex gap-3">
                                                    <span className="font-semibold text-gray-600 min-w-[100px]">On behalf of:</span>
                                                    <span className="text-gray-900">{msg.ticketPreview.reportee}</span>
                                                </div>
                                            )}
                                        </div>

                                        {/* Action Buttons */}
                                        <div className="px-6 py-4 bg-gray-50 border-t border-gray-200 flex gap-3">
                                            <button
                                                onClick={() => {
                                                    console.log('🖱️ SUBMIT BUTTON CLICKED!');
                                                    handleTicketSubmit(msg.ticketPreview);
                                                }}
                                                className="flex-1 px-5 py-3 bg-primary text-white rounded-lg hover:bg-primary-hover transition-all font-semibold shadow-md hover:shadow-lg flex items-center justify-center gap-2"
                                            >
                                                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                                                </svg>
                                                Submit Ticket
                                            </button>
                                            <button
                                                onClick={handleTicketCancel}
                                                className="px-5 py-3 bg-white text-gray-700 border-2 border-gray-300 rounded-lg hover:bg-gray-50 hover:border-gray-400 transition-all font-semibold"
                                            >
                                                Cancel
                                            </button>
                                        </div>
                                    </div>
                                )}

                            {/* Knowledge Base draft card */}
                            {msg.role === 'assistant' && msg.kbDraft && onOpenKbDraft && (
                                <div className="mb-4 bg-white border-2 border-primary rounded-xl shadow-lg overflow-hidden">
                                    <div className="bg-gradient-to-r from-primary to-primary-dark px-6 py-4">
                                        <div className="flex items-center gap-3 text-white">
                                            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                                            </svg>
                                            <h3 className="text-lg font-bold">Knowledge Base Draft</h3>
                                        </div>
                                    </div>
                                    <div className="px-6 py-5 space-y-3">
                                        <div className="flex gap-3">
                                            <span className="font-semibold text-gray-600 min-w-[80px]">Title:</span>
                                            <span className="text-gray-900 font-medium">{msg.kbDraft.title || 'Untitled'}</span>
                                        </div>
                                        {msg.kbDraft.category && (
                                            <div className="flex gap-3">
                                                <span className="font-semibold text-gray-600 min-w-[80px]">Category:</span>
                                                <span className="text-gray-900">{msg.kbDraft.category}</span>
                                            </div>
                                        )}
                                        <div className="flex gap-3">
                                            <span className="font-semibold text-gray-600 min-w-[80px]">Content:</span>
                                            <span className="text-gray-900 line-clamp-3">{msg.kbDraft.content ? (msg.kbDraft.content.length > 200 ? msg.kbDraft.content.slice(0, 200) + '…' : msg.kbDraft.content) : ''}</span>
                                        </div>
                                    </div>
                                    <div className="px-6 py-4 bg-gray-50 border-t border-gray-200">
                                        <button
                                            onClick={() => onOpenKbDraft(msg.kbDraft)}
                                            className="w-full px-5 py-3 bg-primary text-white rounded-lg hover:bg-primary-hover transition-all font-semibold shadow-md hover:shadow-lg flex items-center justify-center gap-2"
                                        >
                                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                                            </svg>
                                            Submit to Knowledge Base
                                        </button>
                                    </div>
                                </div>
                            )}

                            {/* Close Confirmation Dialog */}
                            {msg.role === 'assistant' && msg.closeConfirmation && (
                                <div className="bg-white border-2 border-primary rounded-xl shadow-xl overflow-hidden">
                                    {/* Header */}
                                    <div className="bg-gradient-to-r from-primary to-primary-dark px-6 py-4">
                                        <div className="flex items-center gap-3 text-white">
                                            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                            </svg>
                                            <h3 className="text-lg font-bold">Close Ticket #{msg.closeConfirmation?.ticket_id}</h3>
                                        </div>
                                    </div>

                                    {/* Content */}
                                    <div className="px-6 py-5">
                                        {msg.closeConfirmation.error ? (
                                            <div className="text-red-600 text-base leading-relaxed">
                                                ❌ {msg.closeConfirmation.error}
                                            </div>
                                        ) : (
                                            <p className="text-gray-800 text-base leading-relaxed">
                                                {msg.closeConfirmation?.message || `Are you sure you want to close ticket #${msg.closeConfirmation?.ticket_id || "this ticket"}? This will mark the ticket as resolved.`}
                                            </p>
                                        )}
                                    </div>

                                    {/* Action Buttons */}
                                    <div className="px-6 py-4 bg-gray-50 border-t border-gray-200 flex gap-3">{msg.closeConfirmation.loading ? (
                                        <div className="flex-1 px-5 py-3 bg-gray-300 text-gray-600 rounded-lg font-semibold flex items-center justify-center gap-2 cursor-not-allowed">
                                            <svg className="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                            </svg>
                                            Closing ticket...
                                        </div>
                                    ) : (
                                        <React.Fragment>
                                            <button
                                                onClick={async () => {
                                                    console.log('✅ USER CONFIRMED CLOSE');

                                                    // Update THIS message to show loading state
                                                    setMessages(prev => prev.map((m, i) =>
                                                        i === messages.length - 1 && m.closeConfirmation ?
                                                            { ...m, closeConfirmation: { ...m.closeConfirmation, loading: true } }
                                                            : m
                                                    ));

                                                    // Send "yes" message to confirm close
                                                    const confirmMessage = {
                                                        role: 'user',
                                                        content: 'yes',
                                                        timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
                                                    };

                                                    setIsTyping(true);

                                                    try {
                                                        const res = await fetch('/api/chat', {
                                                            method: 'POST',
                                                            headers: {
                                                                'Content-Type': 'application/json',
                                                                ...(window.getApiHeaders ? window.getApiHeaders(currentUsername) : {})
                                                            },
                                                            body: JSON.stringify({
                                                                messages: [...messages, confirmMessage].filter(m => !m.isSystemMessage).map(m => ({ role: m.role, content: m.content })),
                                                                draft: ticketState ? ticketState.draft : null,
                                                                property_code: selectedProperty?.property_code || null,
                                                                property_name: selectedProperty?.name || null,
                                                                attachments: [],
                                                                last_ticket_id: msg.closeConfirmation.ticket_id,
                                                                current_user: {
                                                                    full_name: `${currentUser.FirstName} ${currentUser.LastName}`.trim(),
                                                                    first_name: currentUser.FirstName,
                                                                    last_name: currentUser.LastName,
                                                                    username: currentUser.Username,
                                                                    email: currentUser.Email,
                                                                    phone: currentUser.Phone,
                                                                    role: currentUser.Role
                                                                }
                                                            })
                                                        });

                                                        const data = await res.json();
                                                        if (!res.ok) throw new Error(data.detail || 'Request failed');

                                                        // Transform THIS message into success state instead of adding new message
                                                        setMessages(prev => prev.map((m, i) =>
                                                            i === messages.length - 1 && m.closeConfirmation ?
                                                                {
                                                                    ...m,
                                                                    closeConfirmation: null,
                                                                    closeSuccess: {
                                                                        ticketId: m.closeConfirmation.ticket_id,
                                                                        message: data.reply
                                                                    }
                                                                }
                                                                : m
                                                        ));

                                                        // If chat_clear_requested, clear the chat after showing success
                                                        if (data.ticket_state?.chat_clear_requested) {
                                                            setTimeout(() => {
                                                                setMessages([
                                                                    { role: 'assistant', content: greetingMessage }
                                                                ]);
                                                                setInput('');
                                                                setAllAttachments([]);
                                                                setTicketState(null);
                                                                setLastTicketId(null);
                                                                if (onClearChat) onClearChat();
                                                            }, 3000); // 3 second delay to show success message
                                                        }
                                                    } catch (err) {
                                                        // On error, show error in the same card
                                                        setMessages(prev => prev.map((m, i) =>
                                                            i === messages.length - 1 && m.closeConfirmation ?
                                                                {
                                                                    ...m,
                                                                    closeConfirmation: {
                                                                        ...m.closeConfirmation,
                                                                        loading: false,
                                                                        error: `Failed to close ticket. ${err?.message || ''}`.trim()
                                                                    }
                                                                }
                                                                : m
                                                        ));
                                                    } finally {
                                                        setIsTyping(false);
                                                    }
                                                }}
                                                className="flex-1 px-5 py-3 bg-primary text-white rounded-lg hover:bg-primary-hover active:opacity-90 transition-all font-semibold shadow-md hover:shadow-lg flex items-center justify-center gap-2"
                                            >
                                                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                                                </svg>
                                                Yes, Close Ticket
                                            </button>
                                            <button
                                                onClick={async () => {
                                                    console.log('❌ USER CANCELLED CLOSE');
                                                    // Send "cancel" message
                                                    const cancelMessage = {
                                                        role: 'user',
                                                        content: 'cancel',
                                                        timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
                                                    };

                                                    setMessages(prev => [...prev, cancelMessage]);
                                                    setIsTyping(true);

                                                    try {
                                                        const res = await fetch('/api/chat', {
                                                            method: 'POST',
                                                            headers: {
                                                                'Content-Type': 'application/json',
                                                                ...(window.getApiHeaders ? window.getApiHeaders(currentUsername) : {})
                                                            },
                                                            body: JSON.stringify({
                                                                messages: [...messages, cancelMessage].filter(m => !m.isSystemMessage).map(m => ({ role: m.role, content: m.content })),
                                                                draft: ticketState ? ticketState.draft : null,
                                                                property_code: selectedProperty?.property_code || null,
                                                                property_name: selectedProperty?.name || null,
                                                                attachments: [],
                                                                last_ticket_id: msg.closeConfirmation.ticket_id,
                                                                current_user: {
                                                                    full_name: `${currentUser.FirstName} ${currentUser.LastName}`.trim(),
                                                                    first_name: currentUser.FirstName,
                                                                    last_name: currentUser.LastName,
                                                                    username: currentUser.Username,
                                                                    email: currentUser.Email,
                                                                    phone: currentUser.Phone,
                                                                    role: currentUser.Role
                                                                }
                                                            })
                                                        });

                                                        const data = await res.json();
                                                        if (!res.ok) throw new Error(data.detail || 'Request failed');

                                                        // Add response message
                                                        setMessages(prev => [...prev, {
                                                            role: 'assistant',
                                                            content: data.reply || '(No response)',
                                                            timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
                                                        }]);
                                                    } catch (err) {
                                                        setMessages(prev => [...prev, {
                                                            role: 'assistant',
                                                            content: `Sorry — I couldn't process that request. ${err?.message || ''}`.trim(),
                                                            timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
                                                        }]);
                                                    } finally {
                                                        setIsTyping(false);
                                                    }
                                                }}
                                                className="px-5 py-3 bg-white text-gray-700 border-2 border-gray-300 rounded-lg hover:bg-gray-50 hover:border-gray-400 transition-all font-semibold"
                                            >
                                                Cancel
                                            </button>
                                        </React.Fragment>
                                    )}
                                    </div>
                                </div>
                            )}

                            {/* Close Success Card */}
                            {msg.role === 'assistant' && msg.closeSuccess && (
                                <div className="bg-white border-2 border-primary rounded-xl shadow-xl overflow-hidden">
                                    {/* Header */}
                                    <div className="bg-gradient-to-r from-primary to-primary-hover px-6 py-4">
                                        <div className="flex items-center gap-3 text-white">
                                            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                                            </svg>
                                            <h3 className="text-lg font-bold">Ticket Closed Successfully</h3>
                                        </div>
                                    </div>

                                    {/* Content */}
                                    <div className="px-6 py-5 space-y-3">
                                        <div className="flex items-center gap-3">
                                            <span className="font-semibold text-gray-600 min-w-[80px]">Ticket #:</span>
                                            <span className="text-gray-900 font-semibold">{msg.closeSuccess.ticketId}</span>
                                        </div>
                                        <div className="flex items-center gap-3">
                                            <span className="font-semibold text-gray-600 min-w-[80px]">Status:</span>
                                            <span className="text-white font-semibold">Closed</span>
                                        </div>
                                        <p className="text-gray-700 leading-relaxed pt-2">
                                            {msg.closeSuccess.message || 'The ticket has been marked as resolved.'}
                                        </p>
                                    </div>
                                </div>
                            )}

                            {/* Ticket Success Card */}
                            {msg.role === 'assistant' && msg.ticketSuccess && (
                                <div className="bg-white border-2 border-primary rounded-xl shadow-xl overflow-hidden">
                                    {/* Header */}
                                    <div className="bg-gradient-to-r from-primary to-primary-hover px-6 py-4">
                                        <div className="flex items-center gap-3 text-white">
                                            <div className="flex-shrink-0 w-10 h-10 bg-white/20 rounded-full flex items-center justify-center">
                                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                                                </svg>
                                            </div>
                                            <h3 className="text-lg font-bold">Ticket Submitted Successfully</h3>
                                        </div>
                                    </div>

                                    {/* Content */}
                                    <div className="px-6 py-5 space-y-4">
                                        <div className="flex items-center gap-3">
                                            <span className="font-semibold text-gray-600 min-w-[80px]">Ticket #:</span>
                                            <span className="text-gray-900 font-semibold text-lg">{msg.ticketSuccess.ticketId}</span>
                                        </div>
                                        {msg.ticketSuccess.propertyCode && (
                                            <div className="flex items-center gap-3">
                                                <span className="font-semibold text-gray-600 min-w-[80px]">Property:</span>
                                                <span className="text-gray-900">{msg.ticketSuccess.propertyCode}</span>
                                            </div>
                                        )}
                                        <p className="text-gray-700 leading-relaxed">
                                            Our IT support team has been notified and will review your ticket shortly. You'll receive email updates as we work on resolving your issue.
                                        </p>
                                        <div className="pt-2 text-sm text-gray-600 border-t border-gray-200">
                                            <strong>Need to add more details?</strong> Reply to the ticket notification email or contact IT support directly.
                                        </div>
                                    </div>

                                    {/* Action Button */}
                                    {msg.ticketSuccess.jitbitUrl && (
                                        <div className="px-6 py-4 bg-gray-50 border-t border-gray-200">
                                            <a
                                                href={msg.ticketSuccess.jitbitUrl}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="block w-full px-5 py-3 bg-primary text-white rounded-lg hover:bg-primary-hover transition-all font-semibold text-center shadow-md hover:shadow-lg"
                                            >
                                                View Ticket in JitBit →
                                            </a>
                                        </div>
                                    )}
                                </div>
                            )}

                            {/* Direct Ticket Submission card – matches app (primary), shows full submitted details */}
                            {msg.role === 'assistant' && msg.ticketSubmission && (
                                <div className={`bg-white border-2 rounded-xl shadow-lg overflow-hidden ${msg.ticketSubmission.error ? 'border-red-300' : 'border-primary/30'}`}>
                                    {/* Header – primary blue to match app */}
                                    <div className={`px-6 py-4 flex items-center justify-between gap-3 flex-shrink-0 ${msg.ticketSubmission.error ? 'bg-red-600' : 'bg-gradient-to-r from-primary to-primary-hover'}`}>
                                        <div className="flex items-center gap-3 text-white min-w-0">
                                            <div className="flex-shrink-0 w-10 h-10 bg-white/20 rounded-full flex items-center justify-center">
                                                {msg.ticketSubmission.error ? (
                                                    <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M6 18L18 6M6 6l12 12" />
                                                    </svg>
                                                ) : (
                                                    <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                                                    </svg>
                                                )}
                                            </div>
                                            <h3 className="text-lg font-bold truncate text-white">
                                                {msg.ticketSubmission.error 
                                                    ? `Failed to Submit ${msg.ticketSubmission.type === 'capex' ? 'CapEx Request' : 'Support Ticket'}`
                                                    : `${msg.ticketSubmission.type === 'capex' ? 'CapEx Request' : 'Support Ticket'} Submitted`}
                                            </h3>
                                        </div>
                                        <button
                                            type="button"
                                            onClick={() => setMessages(prev => prev.map((m, i) => i === idx ? { ...m, ticketSubmission: null } : m))}
                                            className="flex-shrink-0 text-white/80 hover:text-white transition-colors p-1 rounded hover:bg-white/10"
                                            aria-label="Close"
                                        >
                                            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                            </svg>
                                        </button>
                                    </div>

                                    {/* Content – structured list of everything submitted */}
                                    <div className="px-6 py-5 space-y-3">
                                        {msg.ticketSubmission.error ? (
                                            <div className="text-red-700">
                                                <p className="font-semibold mb-2">Error:</p>
                                                <p className="leading-relaxed">{msg.ticketSubmission.error}</p>
                                            </div>
                                        ) : (
                                            <>
                                                <p className="text-sm text-gray-600 mb-3">Submitted details:</p>
                                                <dl className="space-y-2.5 text-sm">
                                                    <div className="flex gap-3">
                                                        <dt className="font-semibold text-gray-600 min-w-[110px] shrink-0">Ticket #</dt>
                                                        <dd className="text-gray-900 font-semibold">{msg.ticketSubmission.ticket_id ?? '—'}</dd>
                                                    </div>
                                                    {(msg.ticketSubmission.subject != null && msg.ticketSubmission.subject !== '') && (
                                                        <div className="flex gap-3">
                                                            <dt className="font-semibold text-gray-600 min-w-[110px] shrink-0">Subject</dt>
                                                            <dd className="text-gray-900">{msg.ticketSubmission.subject}</dd>
                                                        </div>
                                                    )}
                                                    {(msg.ticketSubmission.description != null && msg.ticketSubmission.description !== '') && (
                                                        <div className="flex gap-3">
                                                            <dt className="font-semibold text-gray-600 min-w-[110px] shrink-0">Description</dt>
                                                            <dd className="text-gray-700 whitespace-pre-wrap break-words max-h-24 overflow-y-auto">{msg.ticketSubmission.description}</dd>
                                                        </div>
                                                    )}
                                                    <div className="flex gap-3">
                                                        <dt className="font-semibold text-gray-600 min-w-[110px] shrink-0">Priority</dt>
                                                        <dd className="text-gray-900 capitalize">{msg.ticketSubmission.priority || 'Normal'}</dd>
                                                    </div>
                                                    <div className="flex gap-3">
                                                        <dt className="font-semibold text-gray-600 min-w-[110px] shrink-0">Property / Site</dt>
                                                        <dd className="text-gray-900">{msg.ticketSubmission.property_code || '—'}</dd>
                                                    </div>
                                                    {msg.ticketSubmission.type === 'capex' && (
                                                        <div className="flex gap-3">
                                                            <dt className="font-semibold text-gray-600 min-w-[110px] shrink-0">Estimated cost</dt>
                                                            <dd className="text-gray-900">{msg.ticketSubmission.estimated_cost ?? '—'}</dd>
                                                        </div>
                                                    )}
                                                    {msg.ticketSubmission.type === 'it_support' && (msg.ticketSubmission.category != null && msg.ticketSubmission.category !== '') && (
                                                        <div className="flex gap-3">
                                                            <dt className="font-semibold text-gray-600 min-w-[110px] shrink-0">Category</dt>
                                                            <dd className="text-gray-900">{msg.ticketSubmission.category}</dd>
                                                        </div>
                                                    )}
                                                </dl>
                                                <p className="text-gray-600 text-sm mt-4 leading-relaxed">
                                                    {msg.ticketSubmission.type === 'capex' 
                                                        ? 'Your CapEx request has been submitted and will be reviewed by the appropriate team.'
                                                        : 'Our IT support team has been notified and will review your ticket shortly.'}
                                                </p>
                                            </>
                                        )}
                                    </div>

                                    {/* Action Buttons */}
                                    <div className="px-6 py-4 bg-gray-50 border-t border-gray-200 flex flex-wrap gap-3">
                                        {!msg.ticketSubmission.error && msg.ticketSubmission.ticket_url && (
                                            <a
                                                href={msg.ticketSubmission.ticket_url}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="flex-1 min-w-[200px] px-5 py-3 bg-primary hover:bg-primary-hover text-white rounded-lg transition-all font-semibold text-center shadow-sm hover:shadow"
                                            >
                                                View {msg.ticketSubmission.type === 'capex' ? 'Request' : 'Ticket'} in JitBit →
                                            </a>
                                        )}
                                        <button
                                            type="button"
                                            onClick={() => setMessages(prev => prev.map((m, i) => i === idx ? { ...m, ticketSubmission: null } : m))}
                                            className="px-5 py-3 bg-white border-2 border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 font-semibold transition-all"
                                        >
                                            Close
                                        </button>
                                    </div>
                                </div>
                            )}

                            {msg.role === 'system' && msg.countdown !== undefined ? (
                                <div className="flex items-center gap-2 text-primary">
                                    <svg className="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                    </svg>
                                    <span className="font-semibold">{msg.content}</span>
                                </div>
                            ) : msg.role === 'assistant' && (msg.ticketPreview || msg.closeConfirmation || msg.closeSuccess || msg.ticketSuccess || msg.ticketSubmission) ? (
                                // Don't show content when confirmation/success dialogs or ticket preview are displayed
                                // The dialogs/previews are rendered above
                                null
                            ) : msg.role === 'user' ? (
                                // User messages: render as plain text (no markdown formatting)
                                <div className="whitespace-pre-wrap">{msg.content}</div>
                            ) : (
                                // Assistant messages: render with markdown formatting
                                <MarkdownText text={msg.content} isUserMessage={false} />
                            )}

                            {msg.role === 'assistant' && Array.isArray(msg.sources) && msg.sources.length > 0 && (
                                <div className="mt-4 pt-4 border-t border-gray-200">
                                    <div className="text-sm font-semibold text-gray-700 mb-2">Sources</div>
                                    <div className="space-y-2">
                                        {msg.sources.map((src, i) => (
                                            <div
                                                key={src?.id ?? `${src?.title || 'source'}-${i}`}
                                                className="flex items-center justify-between gap-3 bg-gray-50 rounded-lg px-3 py-2"
                                            >
                                                <div className="min-w-0">
                                                    <div className="text-sm font-semibold text-gray-900 truncate">
                                                        {src?.title || 'Untitled'}
                                                    </div>
                                                    <div className="text-xs text-gray-600">
                                                        {src?.category || 'kb'}
                                                        {src?.property_code ? ` • ${src.property_code}` : ' • Global'}
                                                    </div>
                                                </div>
                                                {src?.download_url && (
                                                    <button
                                                        onClick={async () => {
                                                            try {
                                                                const response = await fetch(src.download_url, {
                                                                    headers: {
                                                                        'X-OTO-User': currentUsername
                                                                    }
                                                                });

                                                                if (!response.ok) {
                                                                    const errorText = await response.text();
                                                                    console.error('Download failed:', errorText);
                                                                    window.otoNotify?.toast('Failed to download file: ' + (response.statusText || 'Unknown error'), 'error');
                                                                    return;
                                                                }

                                                                const blob = await response.blob();
                                                                const url = window.URL.createObjectURL(blob);
                                                                const a = document.createElement('a');
                                                                a.href = url;
                                                                a.download = src.title || 'download';
                                                                document.body.appendChild(a);
                                                                a.click();
                                                                window.URL.revokeObjectURL(url);
                                                                document.body.removeChild(a);
                                                            } catch (error) {
                                                                console.error('Download error:', error);
                                                                window.otoNotify?.toast('Failed to download file: ' + error.message, 'error');
                                                            }
                                                        }}
                                                        className="ml-auto px-3 py-1 text-xs bg-primary hover:bg-primary-hover text-white rounded-lg font-semibold transition-colors whitespace-nowrap cursor-pointer"
                                                    >
                                                        Download
                                                    </button>
                                                )}
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}
                            {msg.role === 'assistant' && msg.requestContext && (
                                <div className="mt-4 pt-4 border-t border-gray-200">
                                    {expandedRequestContextIndex === idx ? (
                                        <div className="space-y-4">
                                            <div className="flex justify-between items-center">
                                                <span className="text-sm font-semibold text-gray-700">What was sent to the AI</span>
                                                <button
                                                    type="button"
                                                    onClick={() => setExpandedRequestContextIndex(null)}
                                                    className="text-xs text-gray-500 hover:text-gray-700 underline"
                                                >
                                                    Hide
                                                </button>
                                            </div>
                                            <div className="rounded-lg bg-gray-50 border border-gray-200 overflow-hidden">
                                                <div className="px-3 py-2 bg-gray-100 border-b border-gray-200 text-xs font-semibold text-gray-600">System prompt</div>
                                                <pre className="p-3 text-xs text-gray-800 whitespace-pre-wrap break-words max-h-64 overflow-y-auto font-sans">
                                                    {msg.requestContext.system_prompt || '—'}
                                                </pre>
                                            </div>
                                            <div className="rounded-lg bg-gray-50 border border-gray-200 overflow-hidden">
                                                <div className="px-3 py-2 bg-gray-100 border-b border-gray-200 text-xs font-semibold text-gray-600">
                                                    Messages ({Array.isArray(msg.requestContext.messages) ? msg.requestContext.messages.length : 0})
                                                </div>
                                                <div className="p-3 space-y-3 max-h-48 overflow-y-auto">
                                                    {Array.isArray(msg.requestContext.messages) && msg.requestContext.messages.map((m, i) => (
                                                        <div key={i} className="text-xs">
                                                            <span className="font-semibold text-gray-600">{m.role}:</span>
                                                            <pre className="mt-1 whitespace-pre-wrap break-words text-gray-800 font-sans">{m.content || '—'}</pre>
                                                        </div>
                                                    ))}
                                                </div>
                                            </div>
                                            {Array.isArray(msg.requestContext.tool_names) && msg.requestContext.tool_names.length > 0 && (
                                                <div className="text-xs">
                                                    <span className="font-semibold text-gray-600">Tools available: </span>
                                                    <span className="text-gray-800">{msg.requestContext.tool_names.join(', ')}</span>
                                                </div>
                                            )}
                                            {msg.requestContext.mode && (
                                                <div className="text-xs text-gray-600">Mode: <span className="font-medium">{msg.requestContext.mode}</span></div>
                                            )}
                                        </div>
                                    ) : (
                                        <button
                                            type="button"
                                            onClick={() => setExpandedRequestContextIndex(idx)}
                                            className="text-sm text-gray-500 hover:text-gray-700 underline"
                                        >
                                            Show what was sent to the AI (prompt, messages, tools)
                                        </button>
                                    )}
                                </div>
                            )}
                            {msg.countdown !== undefined && msg.role === 'system' && (
                                <div className="mt-4 pt-4 border-t border-primary/20">
                                    <div className="flex items-center justify-center mb-5">
                                        <div className="relative">
                                            <div className="absolute inset-0 bg-primary/5 rounded-full blur-xl"></div>
                                            <div className="relative text-7xl font-bold text-primary tabular-nums">
                                                {countdownPaused ? '⏸' : msg.countdown}
                                            </div>
                                        </div>
                                    </div>
                                    {countdownPaused && (
                                        <div className="text-center mb-4">
                                            <p className="text-gray-600 mb-3">Countdown paused</p>
                                        </div>
                                    )}
                                    <div className="flex gap-3">
                                        {!countdownPaused ? (
                                            <button
                                                onClick={() => {
                                                    // Pause the countdown
                                                    if (countdownIntervalRef.current) {
                                                        clearInterval(countdownIntervalRef.current);
                                                        countdownIntervalRef.current = null;
                                                    }
                                                    if (countdownTimeoutRef.current) {
                                                        clearTimeout(countdownTimeoutRef.current);
                                                        countdownTimeoutRef.current = null;
                                                        setPausedCountdownValue(msg.countdown);
                                                    }
                                                    setCountdownPaused(true);
                                                }}
                                                className="flex-1 px-4 py-3 bg-gray-500 hover:bg-gray-600 text-white rounded-lg font-semibold transition-colors shadow-sm"
                                            >
                                                Pause
                                            </button>
                                        ) : (
                                            <button
                                                onClick={() => {
                                                    // Resume the countdown
                                                    const remaining = pausedCountdownValue !== null ? pausedCountdownValue : msg.countdown;
                                                    setCountdownPaused(false);
                                                    
                                                    // Update the message with current countdown value
                                                    setMessages(prev => {
                                                        const newMessages = [...prev];
                                                        const lastMsg = newMessages[newMessages.length - 1];
                                                        if (lastMsg && lastMsg.role === 'system' && lastMsg.countdown !== undefined) {
                                                            lastMsg.countdown = remaining;
                                                        }
                                                        return newMessages;
                                                    });
                                                    
                                                    // Resume countdown interval
                                                    let currentRemaining = remaining;
                                                    countdownIntervalRef.current = setInterval(() => {
                                                        currentRemaining--;
                                                        if (currentRemaining > 0) {
                                                            setMessages(prev => {
                                                                const newMessages = [...prev];
                                                                const lastMsg = newMessages[newMessages.length - 1];
                                                                if (lastMsg && lastMsg.role === 'system' && lastMsg.countdown !== undefined) {
                                                                    lastMsg.countdown = currentRemaining;
                                                                }
                                                                return newMessages;
                                                            });
                                                        } else {
                                                            if (countdownIntervalRef.current) {
                                                                clearInterval(countdownIntervalRef.current);
                                                                countdownIntervalRef.current = null;
                                                            }
                                                        }
                                                    }, 1000);
                                                    
                                                    // Resume timeout
                                                    countdownTimeoutRef.current = setTimeout(() => {
                                                        if (countdownIntervalRef.current) {
                                                            clearInterval(countdownIntervalRef.current);
                                                            countdownIntervalRef.current = null;
                                                        }
                                                        setMessages([
                                                            { role: 'assistant', content: greetingMessage, isSystemMessage: true }
                                                        ]);
                                                        setInput('');
                                                        setAllAttachments([]);
                                                        setTicketState(null);
                                                        setIsChatEnding(false);
                                                        setCountdownPaused(false);
                                                        setPausedCountdownValue(null);
                                                        if (onClearChat) onClearChat();
                                                    }, currentRemaining * 1000);
                                                    
                                                    setPausedCountdownValue(null);
                                                }}
                                                className="flex-1 px-4 py-3 bg-primary hover:bg-primary-hover text-white rounded-lg font-semibold transition-colors shadow-sm"
                                            >
                                                Continue
                                            </button>
                                        )}
                                        <button
                                            onClick={() => {
                                                // Clear the countdown interval and timeout
                                                if (countdownIntervalRef.current) {
                                                    clearInterval(countdownIntervalRef.current);
                                                    countdownIntervalRef.current = null;
                                                }
                                                if (countdownTimeoutRef.current) {
                                                    clearTimeout(countdownTimeoutRef.current);
                                                    countdownTimeoutRef.current = null;
                                                }
                                                // Reset source dedupe for a fresh conversation
                                                seenSourceIdsRef.current = new Set();
                                                // Clear chat immediately
                                                setMessages([
                                                    { role: 'assistant', content: greetingMessage, isSystemMessage: true }
                                                ]);
                                                setInput('');
                                                setAllAttachments([]);
                                                setTicketState(null);
                                                setIsChatEnding(false);
                                                setCountdownPaused(false);
                                                if (onClearChat) onClearChat();
                                            }}
                                            className="flex-1 px-4 py-3 bg-primary hover:bg-primary-hover text-white rounded-lg font-semibold transition-colors shadow-sm"
                                        >
                                            Clear Now
                                        </button>
                                        <button
                                            onClick={() => {
                                                // Cancel the countdown
                                                if (countdownIntervalRef.current) {
                                                    clearInterval(countdownIntervalRef.current);
                                                    countdownIntervalRef.current = null;
                                                }
                                                if (countdownTimeoutRef.current) {
                                                    clearTimeout(countdownTimeoutRef.current);
                                                    countdownTimeoutRef.current = null;
                                                }
                                                // Remove ALL system messages with countdown
                                                setMessages(prev => prev.filter(m => !(m.role === 'system' && m.countdown !== undefined)));
                                                // Show input controls again
                                                setIsChatEnding(false);
                                                setCountdownPaused(false);
                                            }}
                                            className="flex-1 px-4 py-3 bg-white hover:bg-gray-50 text-gray-700 border-2 border-gray-300 rounded-lg font-medium transition-colors"
                                        >
                                            Cancel
                                        </button>
                                    </div>
                                </div>
                            )}
                            {msg.attachments && msg.attachments.length > 0 && (
                                <div className="mt-3 space-y-2">
                                    {msg.attachments.map((att, attIdx) => (
                                        <div
                                            key={attIdx}
                                            onClick={() => {
                                                console.log('Attachment clicked:', att);
                                                // The attachment already has the file stored
                                                if (att.file) {
                                                    console.log('Opening attachment:', att.name);
                                                    setViewingAttachment(att);
                                                } else {
                                                    console.log('No file object found for:', att.name);
                                                }
                                            }}
                                            className={`flex items-center gap-2 p-2 rounded-lg cursor-pointer transition-all ${msg.role === 'user'
                                                    ? 'bg-primary-dark hover:bg-primary-hover'
                                                    : 'bg-gray-100 hover:bg-gray-200'
                                                }`}
                                        >
                                            <svg className={`w-4 h-4 flex-shrink-0 ${msg.role === 'user' ? 'text-white' : 'text-primary'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
                                            </svg>
                                            <div className="flex-1 min-w-0">
                                                <p className={`text-xs font-medium truncate ${msg.role === 'user' ? 'text-white' : 'text-gray-900'}`}>{att.name}</p>
                                                <p className={`text-xs ${msg.role === 'user' ? 'text-blue-200' : 'text-gray-600'}`}>{formatFileSize(att.size)}</p>
                                            </div>
                                            <svg className={`w-4 h-4 flex-shrink-0 ${msg.role === 'user' ? 'text-white' : 'text-primary'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                            </svg>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                ))}

                {isTyping && (
                    <div className="flex justify-start chat-message">
                        <div className="max-w-2xl rounded-2xl px-6 py-4 bg-white border border-gray-200">
                            <div className="flex space-x-2">
                                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
                                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.4s' }}></div>
                            </div>
                        </div>
                    </div>
                )}

                <div ref={messagesEndRef} />
            </div>

            <div className="border-t border-gray-200 p-6 bg-white">
                <div className="max-w-4xl mx-auto">
                    {attachments.length > 0 && (
                        <div className="mb-3 space-y-2">
                            {attachments.map(att => (
                                <div key={att.id} className="flex items-center justify-between p-3 bg-primary/5 rounded-lg border border-primary/30">
                                    <div className="flex items-center gap-3 flex-1 min-w-0">
                                        <svg className="w-5 h-5 text-primary flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
                                        </svg>
                                        <div className="flex-1 min-w-0">
                                            <p className="text-sm font-semibold text-gray-900 truncate">{att.name}</p>
                                            <p className="text-xs text-gray-600">{formatFileSize(att.size)}</p>
                                        </div>
                                    </div>
                                    <button onClick={() => removeAttachment(att.id)} className="text-gray-400 hover:text-red-600 transition-colors ml-3 flex-shrink-0">
                                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                        </svg>
                                    </button>
                                </div>
                            ))}
                        </div>
                    )}
                    {!isChatEnding && (
                        <>
                            <div
                                className={`flex gap-3 items-center border-2 rounded-xl px-4 py-3 transition-all ${isDragging ? 'border-primary bg-primary/5 border-dashed' : 'border-gray-200 bg-white'
                                    }`}
                                onDragOver={handleDragOver}
                                onDragLeave={handleDragLeave}
                                onDrop={handleDrop}
                            >
                                <input
                                    ref={fileInputRef}
                                    type="file"
                                    multiple
                                    onChange={handleFileSelect}
                                    className="hidden"
                                />
                                <button
                                    type="button"
                                    onClick={() => fileInputRef.current?.click()}
                                    disabled={isTyping}
                                    className="text-gray-400 hover:text-primary transition-colors flex-shrink-0 disabled:opacity-50 disabled:cursor-not-allowed"
                                    title="Attach files"
                                >
                                    <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
                                    </svg>
                                </button>
                                <textarea
                                    ref={inputRef}
                                    value={input}
                                    onChange={(e) => setInput(e.target.value)}
                                    onKeyPress={handleKeyPress}
                                    placeholder="Describe your IT issue or ask a question..."
                                    disabled={isTyping}
                                    className="flex-1 outline-none resize-none bg-transparent disabled:opacity-50 disabled:cursor-not-allowed"
                                    rows="1"
                                    style={{ minHeight: '24px', maxHeight: '120px' }}
                                    onInput={(e) => {
                                        e.target.style.height = 'auto';
                                        e.target.style.height = Math.min(e.target.scrollHeight, 120) + 'px';
                                    }}
                                />
                                <button
                                    onClick={handleSend}
                                    disabled={!input.trim() || isTyping}
                                    className="bg-primary hover:bg-primary-hover text-white px-6 py-2 rounded-lg font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap flex-shrink-0"
                                >
                                    {isTyping ? 'Waiting...' : 'Send'}
                                </button>
                            </div>
                            <div className="mt-3 flex gap-2 flex-wrap justify-center">
                                <button
                                    onClick={() => setInput("My printer is not working")}
                                    className="text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-2 rounded-lg transition-colors">
                                    Printer not working
                                </button>
                                <button
                                    onClick={() => setInput("I need to reset my password")}
                                    className="text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-2 rounded-lg transition-colors">
                                    Password reset
                                </button>
                                <button
                                    onClick={() => setInput("My computer is running slow")}
                                    className="text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-2 rounded-lg transition-colors">
                                    Computer running slow
                                </button>
                                <button
                                    onClick={() => setInput("I'm having email issues")}
                                    className="text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 px-3 py-2 rounded-lg transition-colors">
                                    Email issues
                                </button>
                            </div>
                        </>
                    )}
                </div>
            </div>

            {/* Attachment Viewer Modal */}
            {viewingAttachment && (
                <div
                    className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
                    onClick={() => setViewingAttachment(null)}
                >
                    <div
                        className="bg-white rounded-lg max-w-6xl max-h-[90vh] overflow-auto"
                        onClick={(e) => {
                            console.log('Modal content clicked, preventing close');
                            e.stopPropagation();
                        }}
                    >
                        <div className="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between">
                            <div className="flex items-center gap-3">
                                <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
                                </svg>
                                <div>
                                    <h3 className="font-semibold text-gray-900">{viewingAttachment.name}</h3>
                                    <p className="text-xs text-gray-500">{formatFileSize(viewingAttachment.size)}</p>
                                </div>
                            </div>
                            <button
                                onClick={() => setViewingAttachment(null)}
                                className="text-gray-500 hover:text-gray-700 transition-colors"
                            >
                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                        <div className="p-6">
                            {!viewingAttachment.file ? (
                                <div className="text-center py-12">
                                    <p className="text-gray-600">Preview not available for this attachment.</p>
                                </div>
                            ) : viewingAttachment.type.startsWith('image/') ? (
                                <img
                                    src={URL.createObjectURL(viewingAttachment.file)}
                                    alt={viewingAttachment.name}
                                    className="max-w-full h-auto rounded-lg"
                                />
                            ) : viewingAttachment.type === 'application/pdf' ? (
                                <iframe
                                    src={URL.createObjectURL(viewingAttachment.file)}
                                    className="w-full h-[70vh] rounded-lg"
                                    title={viewingAttachment.name}
                                />
                            ) : viewingAttachment.type.startsWith('text/') ? (
                                <pre className="bg-gray-50 p-4 rounded-lg overflow-auto max-h-[70vh] text-sm">
                                    {/* Text file content would be loaded here */}
                                    <div className="text-gray-500">Text preview not yet implemented</div>
                                </pre>
                            ) : (
                                <div className="text-center py-12">
                                    <svg className="w-16 h-16 mx-auto text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
                                    </svg>
                                    <p className="text-gray-600 mb-2">Preview not available for this file type</p>
                                    <p className="text-sm text-gray-500">{viewingAttachment.type}</p>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            )}

            {/* Ticket List Modal – professional layout, search, custom ticket detail view */}
            {showTicketListModal && ticketListData && (
                <div
                    className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
                    onClick={() => { setShowTicketListModal(false); setViewingTicketDetail(null); setTicketListFilter(''); setTicketListFilterStatus(''); setTicketListFilterPriority(''); }}
                >
                    <div
                        className="bg-white rounded-xl max-w-4xl w-full h-[85vh] max-h-[800px] overflow-hidden shadow-2xl flex flex-col"
                        onClick={(e) => e.stopPropagation()}
                    >
                        {/* Header */}
                        <div className="flex-shrink-0 bg-gradient-to-r from-primary to-primary-hover px-6 py-4 flex items-center justify-between">
                            <div className="flex items-center gap-3">
                                <svg className="w-6 h-6 text-white shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
                                </svg>
                                <div>
                                    <h3 className="text-xl font-bold text-white">
                                        {viewingTicketDetail
                                            ? (ticketListData.mode_used === 'mycapex' ? 'CapEx Request' : 'Ticket') + ' #' + viewingTicketDetail.id
                                            : ticketListData.mode_used === 'handledbyme'
                                            ? 'Tickets Assigned to Me'
                                            : ticketListData.mode_used === 'opened_by_user'
                                            ? (ticketListData.opened_by ? `Tickets opened by ${ticketListData.opened_by}` : 'Tickets opened by member')
                                            : ticketListData.mode_used === 'mycapex'
                                            ? 'My CapEx Requests'
                                            : 'My Support Tickets'}
                                    </h3>
                                    <p className="text-sm text-white/85">
                                        {viewingTicketDetail
                                            ? 'Details'
                                            : `${ticketListData.tickets?.length || 0} ${ticketListData.mode_used === 'mycapex' ? 'requests' : 'tickets'}`}
                                    </p>
                                </div>
                            </div>
                            <button
                                onClick={() => { setShowTicketListModal(false); setViewingTicketDetail(null); setTicketListFilter(''); setTicketListFilterStatus(''); setTicketListFilterPriority(''); }}
                                className="text-white/90 hover:text-white p-1 rounded transition-colors"
                                aria-label="Close"
                            >
                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                            </button>
                        </div>

                        {viewingTicketDetail ? (
                            /* Custom ticket detail view – all info populated from API */
                            <div className="flex-1 flex flex-col min-h-0 overflow-hidden">
                                <div className="flex-shrink-0 px-6 py-3 border-b border-gray-200 bg-gray-50">
                                    <button
                                        type="button"
                                        onClick={() => { setViewingTicketDetail(null); setTicketDetailFull(null); setTicketDetailError(null); }}
                                        className="flex items-center gap-2 text-gray-600 hover:text-primary font-medium text-sm"
                                    >
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" /></svg>
                                        Back to list
                                    </button>
                                </div>
                                <div className="flex-1 overflow-y-auto p-6">
                                    <div className="max-w-2xl space-y-5">
                                        {ticketDetailLoading && (
                                            <div className="flex items-center justify-center py-12">
                                                <svg className="w-8 h-8 animate-spin text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg>
                                                <span className="ml-3 text-gray-600">Loading ticket details...</span>
                                            </div>
                                        )}
                                        {ticketDetailError && !ticketDetailLoading && (
                                            <div className="rounded-lg bg-amber-50 border border-amber-200 px-4 py-3 text-sm text-amber-800">
                                                Could not load full details: {ticketDetailError}. Showing summary from list.
                                            </div>
                                        )}
                                        {!ticketDetailLoading && (ticketDetailFull || viewingTicketDetail) && (
                                            <>
                                                <section className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
                                                    <h2 className="text-lg font-semibold text-gray-900 mb-3">{(ticketDetailFull && ticketDetailFull.subject) || viewingTicketDetail.subject || 'Untitled'}</h2>
                                                    <div className="flex flex-wrap gap-2 mb-3">
                                                        <span className="oto-tag inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium bg-primary/10 text-primary border border-primary/20">#{(ticketDetailFull && ticketDetailFull.id) || viewingTicketDetail.id}</span>
                                                        {(() => { const s = (ticketDetailFull && ticketDetailFull.status) || viewingTicketDetail.status; return s ? <span className={`inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium ${s === 'New' ? 'bg-primary/10 text-primary border border-primary/20' : s === 'In Progress' ? 'bg-primary/10 text-primary border border-primary/20' : s === 'Waiting' ? 'bg-primary/10 text-primary border border-primary/20' : s === 'Closed' ? 'bg-primary/10 text-primary border border-primary/20' : 'bg-primary/10 text-primary border border-primary/20'}`}>{s}</span> : null; })()}
                                                        {(() => { const p = (ticketDetailFull && ticketDetailFull.priority) || viewingTicketDetail.priority; return p && p !== 'Normal' ? <span className={`inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium border ${p === 'Critical' ? 'bg-red-100 text-red-800 border-red-200' : 'bg-primary/10 text-primary border-primary/20'}`}>{p}</span> : null; })()}
                                                        {(() => { const c = (ticketDetailFull && ticketDetailFull.category) || viewingTicketDetail.category; return c ? <span className="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium bg-primary/10 text-primary border border-primary/20">{c}</span> : null; })()}
                                                    </div>
                                                    <dl className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm text-gray-600">
                                                        {(ticketDetailFull && ticketDetailFull.created) && (
                                                            <div>
                                                                <dt className="font-medium text-gray-500">Created</dt>
                                                                <dd className="text-gray-900 mt-0.5">{new Date(ticketDetailFull.created).toLocaleString()}</dd>
                                                            </div>
                                                        )}
                                                        {((ticketDetailFull && ticketDetailFull.updated) || viewingTicketDetail.updated) && (
                                                            <div>
                                                                <dt className="font-medium text-gray-500">Last updated</dt>
                                                                <dd className="text-gray-900 mt-0.5">{new Date((ticketDetailFull && ticketDetailFull.updated) || viewingTicketDetail.updated).toLocaleString()}</dd>
                                                            </div>
                                                        )}
                                                    </dl>
                                                </section>
                                                {(ticketDetailFull && (ticketDetailFull.summary || ticketDetailFull.body)) && (
                                                    <section className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
                                                        {ticketDetailFull.summary ? (
                                                            <>
                                                                <h3 className="text-sm font-semibold text-gray-700 mb-1">Summary</h3>
                                                                <p className="text-xs text-gray-500 mb-2">AI-generated summary of the ticket (description and comments).</p>
                                                                <div className="text-sm text-gray-800 leading-relaxed">{ticketDetailFull.summary}</div>
                                                            </>
                                                        ) : (
                                                            <>
                                                                <h3 className="text-sm font-semibold text-gray-700 mb-2">Description</h3>
                                                                <div className="text-sm text-gray-800 whitespace-pre-wrap leading-relaxed">{ticketDetailFull.body}</div>
                                                            </>
                                                        )}
                                                    </section>
                                                )}
                                                {/* Comments */}
                                                {ticketDetailFull && (
                                                    <section className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm space-y-3">
                                                        <h3 className="text-sm font-semibold text-gray-700">Comments</h3>
                                                        {Array.isArray(ticketDetailFull.comments) && ticketDetailFull.comments.length > 0 && (
                                                        <div className="space-y-2 max-h-56 overflow-y-auto">
                                                            {ticketDetailFull.comments.map((c, i) => {
                                                                const isSystem = c.IsSystem === true || c.is_system === true;
                                                                const author = isSystem ? 'System' : (c.UserName || c.Email || 'Unknown');
                                                                const body = formatTicketCommentBody(c.Body || c.body);
                                                                return (
                                                                <div key={c.CommentID || i} className={`rounded-lg p-3 text-sm ${isSystem ? 'bg-gray-100 border border-gray-200 text-gray-600' : 'bg-gray-50/80 border border-gray-200'}`}>
                                                                    <div className="flex flex-wrap items-center gap-2 text-xs text-gray-500 mb-1">
                                                                        <span className={isSystem ? 'font-medium text-gray-500' : 'font-medium text-gray-700'}>{author}</span>
                                                                        {c.CommentDate && <span>{new Date(c.CommentDate).toLocaleString()}</span>}
                                                                        {c.ForTechsOnly && <span className="px-1.5 py-0.5 rounded bg-primary/10 text-primary border border-primary/20 text-xs font-medium">Techs only</span>}
                                                                    </div>
                                                                    <div className={isSystem ? 'text-gray-600 whitespace-pre-wrap' : 'text-gray-800 whitespace-pre-wrap'}>{body}</div>
                                                                </div>
                                                                );
                                                            })}
                                                        </div>
                                                        )}
                                                        <div className="flex flex-col gap-2">
                                                            <textarea
                                                                value={ticketDetailNewComment}
                                                                onChange={(e) => setTicketDetailNewComment(e.target.value)}
                                                                placeholder="Add a comment..."
                                                                rows={3}
                                                                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary resize-none"
                                                                disabled={!!ticketDetailActionLoading}
                                                            />
                                                            <button
                                                                type="button"
                                                                disabled={!ticketDetailNewComment.trim() || ticketDetailActionLoading === 'comment'}
                                                                onClick={async () => {
                                                                    const body = ticketDetailNewComment.trim();
                                                                    if (!body || !viewingTicketDetail?.id) return;
                                                                    setTicketDetailActionLoading('comment');
                                                                    try {
                                                                        const res = await fetch(`/api/tickets/${viewingTicketDetail.id}/comments`, {
                                                                            method: 'POST',
                                                                            headers: { 'Content-Type': 'application/json', ...(window.getApiHeaders ? window.getApiHeaders(currentUsername) : { 'X-OTO-User': currentUsername }) },
                                                                            body: JSON.stringify({ body, for_techs_only: false }),
                                                                        });
                                                                        const data = await res.json();
                                                                        if (!res.ok) throw new Error(data.detail || 'Failed to add comment');
                                                                        setTicketDetailNewComment('');
                                                                        refreshTicketDetail();
                                                                        window.otoNotify?.toast('Comment added', 'success');
                                                                    } catch (err) {
                                                                        window.otoNotify?.toast(err.message || 'Failed to add comment', 'error');
                                                                    } finally {
                                                                        setTicketDetailActionLoading(null);
                                                                    }
                                                                }}
                                                                className="self-start px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover font-medium text-sm disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                                                            >
                                                                {ticketDetailActionLoading === 'comment' ? 'Adding...' : 'Add comment'}
                                                            </button>
                                                        </div>
                                                    </section>
                                                )}
                                                {/* Close ticket */}
                                                {ticketDetailFull && (ticketDetailFull.status || viewingTicketDetail.status) !== 'Closed' && (
                                                    <div className="flex flex-wrap gap-2">
                                                        {!ticketDetailCloseConfirm ? (
                                                            <button
                                                                type="button"
                                                                disabled={!!ticketDetailActionLoading}
                                                                onClick={() => setTicketDetailCloseConfirm(true)}
                                                                className="inline-flex items-center gap-2 px-4 py-2.5 border border-amber-500 text-amber-700 rounded-lg hover:bg-amber-50 font-medium text-sm transition-colors disabled:opacity-50"
                                                            >
                                                                Close ticket
                                                            </button>
                                                        ) : (
                                                            <span className="inline-flex items-center gap-2 flex-wrap">
                                                                <span className="text-sm text-gray-600">Mark this ticket as resolved?</span>
                                                                <button
                                                                    type="button"
                                                                    disabled={ticketDetailActionLoading === 'close'}
                                                                    onClick={async () => {
                                                                        if (!viewingTicketDetail?.id) return;
                                                                        setTicketDetailActionLoading('close');
                                                                        try {
                                                                            const res = await fetch(`/api/tickets/${viewingTicketDetail.id}/close`, {
                                                                                method: 'POST',
                                                                                headers: { 'Content-Type': 'application/json', ...(window.getApiHeaders ? window.getApiHeaders(currentUsername) : { 'X-OTO-User': currentUsername }) },
                                                                                body: JSON.stringify({ suppress_notification: false }),
                                                                            });
                                                                            const data = await res.json();
                                                                            if (!res.ok) throw new Error(data.detail || 'Failed to close ticket');
                                                                            setTicketDetailCloseConfirm(false);
                                                                            refreshTicketDetail();
                                                                            setTicketListData(prev => prev && prev.tickets ? { ...prev, tickets: prev.tickets.map(t => t.id === viewingTicketDetail.id ? { ...t, status: 'Closed' } : t) } : prev);
                                                                            window.otoNotify?.toast('Ticket closed', 'success');
                                                                        } catch (err) {
                                                                            window.otoNotify?.toast(err.message || 'Failed to close ticket', 'error');
                                                                        } finally {
                                                                            setTicketDetailActionLoading(null);
                                                                        }
                                                                    }}
                                                                    className="px-3 py-1.5 bg-amber-600 text-white rounded-lg hover:bg-amber-700 text-sm font-medium disabled:opacity-50"
                                                                >
                                                                    Yes, close
                                                                </button>
                                                                <button type="button" onClick={() => setTicketDetailCloseConfirm(false)} className="px-3 py-1.5 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50">Cancel</button>
                                                            </span>
                                                        )}
                                                    </div>
                                                )}
                                                {/* Edit ticket (subject / body / priority) */}
                                                {ticketDetailFull && (
                                                    <div className="border-t border-gray-200 pt-4">
                                                        {!ticketDetailEditMode ? (
                                                            <button
                                                                type="button"
                                                                onClick={() => {
                                                                    setTicketDetailEditMode(true);
                                                                    setTicketDetailEditSubject((ticketDetailFull && ticketDetailFull.subject) || viewingTicketDetail.subject || '');
                                                                    setTicketDetailEditBody(formatTicketCommentBody((ticketDetailFull && ticketDetailFull.body) || ''));
                                                                    setTicketDetailEditPriority(String((ticketDetailFull && ticketDetailFull.priority) || viewingTicketDetail.priority || 'normal').toLowerCase());
                                                                }}
                                                                className="text-sm font-medium text-primary hover:underline"
                                                            >
                                                                Edit ticket
                                                            </button>
                                                        ) : (
                                                            <div className="space-y-3 rounded-lg border border-gray-200 bg-gray-50/50 p-4">
                                                                <h4 className="text-sm font-semibold text-gray-700">Edit ticket</h4>
                                                                <label className="block text-xs font-medium text-gray-600">Subject</label>
                                                                <input
                                                                    type="text"
                                                                    value={ticketDetailEditSubject}
                                                                    onChange={(e) => setTicketDetailEditSubject(e.target.value)}
                                                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary"
                                                                />
                                                                <label className="block text-xs font-medium text-gray-600">Description</label>
                                                                <textarea
                                                                    value={ticketDetailEditBody}
                                                                    onChange={(e) => setTicketDetailEditBody(e.target.value)}
                                                                    rows={4}
                                                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary resize-none"
                                                                />
                                                                <label className="block text-xs font-medium text-gray-600">Priority</label>
                                                                <select
                                                                    value={ticketDetailEditPriority}
                                                                    onChange={(e) => setTicketDetailEditPriority(e.target.value)}
                                                                    className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white"
                                                                >
                                                                    <option value="low">Low</option>
                                                                    <option value="normal">Normal</option>
                                                                    <option value="high">High</option>
                                                                    <option value="critical">Critical</option>
                                                                </select>
                                                                <div className="flex gap-2">
                                                                    <button
                                                                        type="button"
                                                                        disabled={ticketDetailActionLoading === 'update'}
                                                                        onClick={async () => {
                                                                            if (!viewingTicketDetail?.id) return;
                                                                            setTicketDetailActionLoading('update');
                                                                            try {
                                                                                const res = await fetch(`/api/tickets/${viewingTicketDetail.id}`, {
                                                                                    method: 'PATCH',
                                                                                    headers: { 'Content-Type': 'application/json', ...(window.getApiHeaders ? window.getApiHeaders(currentUsername) : { 'X-OTO-User': currentUsername }) },
                                                                                    body: JSON.stringify({
                                                                                        subject: ticketDetailEditSubject.trim() || undefined,
                                                                                        body: ticketDetailEditBody || undefined,
                                                                                        priority: ticketDetailEditPriority || undefined,
                                                                                    }),
                                                                                });
                                                                                const data = await res.json();
                                                                                if (!res.ok) throw new Error(data.detail || 'Failed to update ticket');
                                                                                setTicketDetailEditMode(false);
                                                                                refreshTicketDetail();
                                                                                window.otoNotify?.toast('Ticket updated', 'success');
                                                                            } catch (err) {
                                                                                window.otoNotify?.toast(err.message || 'Failed to update ticket', 'error');
                                                                            } finally {
                                                                                setTicketDetailActionLoading(null);
                                                                            }
                                                                        }}
                                                                        className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover text-sm font-medium disabled:opacity-50"
                                                                    >
                                                                        {ticketDetailActionLoading === 'update' ? 'Saving...' : 'Save'}
                                                                    </button>
                                                                    <button type="button" onClick={() => setTicketDetailEditMode(false)} className="px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50">Cancel</button>
                                                                </div>
                                                            </div>
                                                        )}
                                                    </div>
                                                )}
                                                <div className="pt-2 flex flex-wrap gap-3">
                                                    {(ticketDetailFull && ticketDetailFull.jitbit_url) || viewingTicketDetail.jitbit_url ? (
                                                        <a
                                                            href={(ticketDetailFull && ticketDetailFull.jitbit_url) || viewingTicketDetail.jitbit_url}
                                                            target="_blank"
                                                            rel="noopener noreferrer"
                                                            className="inline-flex items-center gap-2 px-4 py-2.5 bg-primary text-white rounded-lg hover:bg-primary-hover font-medium text-sm transition-colors"
                                                        >
                                                            View in JitBit
                                                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" /></svg>
                                                        </a>
                                                    ) : null}
                                                    <button
                                                        type="button"
                                                        onClick={() => { setInput(`Tell me about ticket #${viewingTicketDetail.id}`); setShowTicketListModal(false); setViewingTicketDetail(null); setTicketListFilter(''); setTicketListFilterStatus(''); setTicketListFilterPriority(''); setTicketDetailFull(null); setTicketDetailError(null); }}
                                                        className="inline-flex items-center gap-2 px-4 py-2.5 bg-gray-100 text-gray-800 rounded-lg hover:bg-gray-200 font-medium text-sm transition-colors"
                                                    >
                                                        Ask AI about this {ticketListData.mode_used === 'mycapex' ? 'request' : 'ticket'}
                                                    </button>
                                                </div>
                                            </>
                                        )}
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <>
                                {/* Search + filter: search bar with Status/Priority to the right */}
                                <div className="flex-shrink-0 px-6 py-3 border-b border-gray-200 bg-gray-50">
                                    <div className="flex flex-wrap items-center gap-3">
                                        <input
                                            type="text"
                                            placeholder="Search by #id, subject, status, priority..."
                                            value={ticketListFilter}
                                            onChange={(e) => setTicketListFilter(e.target.value)}
                                            className="flex-1 min-w-[180px] px-4 py-2.5 border border-gray-300 rounded-lg text-sm placeholder-gray-500 focus:ring-2 focus:ring-primary/20 focus:border-primary"
                                        />
                                        <label className="flex items-center gap-2 text-sm text-gray-600 shrink-0">
                                            <span>Status</span>
                                            <select
                                                value={ticketListFilterStatus}
                                                onChange={(e) => setTicketListFilterStatus(e.target.value)}
                                                className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white"
                                            >
                                                <option value="">All</option>
                                                <option value="New">New</option>
                                                <option value="In Progress">In Progress</option>
                                                <option value="Waiting">Waiting</option>
                                                <option value="Closed">Closed</option>
                                            </select>
                                        </label>
                                        <label className="flex items-center gap-2 text-sm text-gray-600 shrink-0">
                                            <span>Priority</span>
                                            <select
                                                value={ticketListFilterPriority}
                                                onChange={(e) => setTicketListFilterPriority(e.target.value)}
                                                className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white"
                                            >
                                                <option value="">All</option>
                                                <option value="Low">Low</option>
                                                <option value="Normal">Normal</option>
                                                <option value="High">High</option>
                                                <option value="Critical">Critical</option>
                                            </select>
                                        </label>
                                        {(ticketListFilterStatus || ticketListFilterPriority) && (
                                            <button
                                                type="button"
                                                onClick={() => { setTicketListFilterStatus(''); setTicketListFilterPriority(''); }}
                                                className="text-sm text-primary hover:underline font-medium shrink-0"
                                            >
                                                Clear filters
                                            </button>
                                        )}
                                    </div>
                                </div>
                                {/* Scrollable list */}
                                <div className="flex-1 min-h-0 overflow-y-auto p-6">
                                    {(() => {
                                        const tickets = ticketListData.tickets || [];
                                        const q = String(ticketListFilter || '').trim().toLowerCase();
                                        const statusFilter = ticketListFilterStatus ? String(ticketListFilterStatus).trim() : '';
                                        const priorityFilter = ticketListFilterPriority ? String(ticketListFilterPriority).trim() : '';
                                        const norm = (s) => String(s ?? '').trim().toLowerCase().replace(/\s+/g, '');
                                        const filtered = tickets.filter(t => {
                                            if (statusFilter && norm(t.status) !== norm(statusFilter)) return false;
                                            if (priorityFilter && norm(t.priority) !== norm(priorityFilter)) return false;
                                            if (!q) return true;
                                            return (
                                                String(t.id ?? '').toLowerCase().includes(q) ||
                                                String(t.subject ?? '').toLowerCase().includes(q) ||
                                                String(t.status ?? '').toLowerCase().includes(q) ||
                                                String(t.priority ?? '').toLowerCase().includes(q) ||
                                                String(t.category ?? '').toLowerCase().includes(q)
                                            );
                                        });
                                        const hasActiveFilters = q || statusFilter || priorityFilter;
                                        if (filtered.length === 0) {
                                            return (
                                                <div className="text-center py-12">
                                                    <svg className="w-14 h-14 mx-auto text-gray-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /></svg>
                                                    <p className="text-gray-600 font-medium">{hasActiveFilters ? 'No tickets match your search or filters' : (ticketListData.mode_used === 'mycapex' ? 'No CapEx requests found' : ticketListData.mode_used === 'opened_by_user' ? 'No tickets found for this person' : 'No tickets found')}</p>
                                                    <p className="text-sm text-gray-500 mt-1">{hasActiveFilters ? 'Try changing your search or filter options.' : (ticketListData.mode_used === 'handledbyme' ? "You don't have any tickets assigned to you." : ticketListData.mode_used === 'opened_by_user' ? "This person hasn't opened any tickets." : ticketListData.mode_used === 'mycapex' ? "You don't have any CapEx requests." : "You don't have any support tickets.")}</p>
                                                </div>
                                            );
                                        }
                                        return (
                                            <div className="space-y-2">
                                                {filtered.map((ticket, idx) => (
                                                    <div
                                                        key={ticket.id || idx}
                                                        role="button"
                                                        tabIndex={0}
                                                        onClick={() => setViewingTicketDetail(ticket)}
                                                        onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setViewingTicketDetail(ticket); } }}
                                                        className="bg-white border border-gray-200 rounded-lg p-4 hover:border-primary/40 hover:shadow-sm transition-all cursor-pointer group text-left"
                                                    >
                                                        <div className="flex items-start justify-between gap-4">
                                                            <div className="flex-1 min-w-0">
                                                                <div className="flex flex-wrap items-center gap-2 mb-1.5">
                                                                    <span className="oto-tag inline-flex items-center px-2 py-0.5 rounded text-xs font-semibold bg-primary/10 text-primary border border-primary/20">#{ticket.id}</span>
                                                                    <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${ticket.status === 'New' ? 'bg-primary/10 text-primary border border-primary/20' : ticket.status === 'In Progress' ? 'bg-primary/10 text-primary border border-primary/20' : ticket.status === 'Waiting' ? 'bg-primary/10 text-primary border border-primary/20' : ticket.status === 'Closed' ? 'bg-primary/10 text-primary border border-primary/20' : 'bg-primary/10 text-primary border border-primary/20'}`}>{ticket.status}</span>
                                                                    {ticket.priority && ticket.priority !== 'Normal' && <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium border ${ticket.priority === 'Critical' ? 'bg-red-100 text-red-800 border-red-200' : ticket.priority === 'High' ? 'bg-primary/10 text-primary border-primary/20' : 'bg-primary/10 text-primary border-primary/20'}`}>{ticket.priority}</span>}
                                                                </div>
                                                                <h4 className="text-sm font-semibold text-gray-900 line-clamp-2 group-hover:text-primary transition-colors">{ticket.subject || 'Untitled'}</h4>
                                                                {ticket.updated && <p className="text-xs text-gray-500 mt-1">Last updated: {new Date(ticket.updated).toLocaleString()}</p>}
                                                            </div>
                                                            <svg className="w-5 h-5 text-gray-400 group-hover:text-primary shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" /></svg>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                        );
                                    })()}
                                </div>
                                {/* Footer */}
                                <div className="flex-shrink-0 border-t border-gray-200 px-6 py-3 bg-gray-50 flex items-center justify-between text-sm text-gray-600">
                                    <span>Click a {ticketListData.mode_used === 'mycapex' ? 'request' : 'ticket'} to view details</span>
                                    <button onClick={() => { setShowTicketListModal(false); setViewingTicketDetail(null); setTicketListFilter(''); setTicketListFilterStatus(''); setTicketListFilterPriority(''); }} className="px-4 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 font-medium text-gray-700">Close</button>
                                </div>
                            </>
                        )}
                    </div>
                </div>
            )}

            {/* Clear Chat Confirmation Modal */}
            {showClearChatModal && (
                <div
                    className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
                    onClick={() => {
                        setShowClearChatModal(false);
                        setPendingClearChatReason(null);
                    }}
                >
                    <div
                        className="bg-white rounded-xl max-w-md w-full shadow-2xl"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="bg-gradient-to-r from-primary to-primary-hover px-6 py-5 flex items-center justify-between">
                            <div className="flex items-center gap-3 text-white">
                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                </svg>
                                <h3 className="text-xl font-bold">Clear Chat?</h3>
                            </div>
                            <button
                                onClick={() => {
                                    setShowClearChatModal(false);
                                    setPendingClearChatReason(null);
                                }}
                                className="text-white/80 hover:text-white transition-colors"
                            >
                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                        <div className="px-6 py-5">
                            <p className="text-gray-700 leading-relaxed mb-4">
                                {pendingClearChatReason === 'clear'
                                    ? 'Are you sure you want to clear this chat? All conversation history will be removed and you\'ll start with a fresh conversation.'
                                    : 'Great! Starting a new conversation will clear the current chat history.'}
                            </p>
                        </div>
                        <div className="px-6 py-4 bg-gray-50 border-t border-gray-200 flex gap-3">
                            <button
                                onClick={() => {
                                    setShowClearChatModal(false);
                                    setPendingClearChatReason(null);
                                }}
                                className="flex-1 px-5 py-3 bg-white border-2 border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-all font-semibold"
                            >
                                Cancel
                            </button>
                            <button
                                onClick={() => {
                                    setShowClearChatModal(false);
                                    setPendingClearChatReason(null);
                                    clearChatImmediately(); // Clear immediately, no countdown
                                }}
                                className="flex-1 px-5 py-3 bg-primary hover:bg-primary-hover text-white rounded-lg transition-all font-semibold shadow-md hover:shadow-lg"
                            >
                                {pendingClearChatReason === 'clear' ? 'Clear Chat' : 'Start New Conversation'}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Ticket Submission Confirmation Modal */}
            {showTicketSubmitConfirmModal && pendingTicketSubmission && (
                <div
                    className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
                    onClick={() => {
                        if (ticketSubmitConfirmLoading) return;
                        setShowTicketSubmitConfirmModal(false);
                        setPendingTicketSubmission(null);
                        setTicketSubmitConfirmLoading(false);
                    }}
                >
                    <div
                        className="bg-white rounded-xl max-w-lg w-full shadow-2xl max-h-[90vh] flex flex-col"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="bg-gradient-to-r from-primary to-primary-hover px-6 py-5 flex items-center justify-between flex-shrink-0">
                            <div className="flex items-center gap-3 text-white">
                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                </svg>
                                <h3 className="text-xl font-bold">
                                    Submit {pendingTicketSubmission.type === 'capex' ? 'CapEx Request' : 'Support Ticket'}?
                                </h3>
                            </div>
                            <button
                                onClick={() => {
                                    if (ticketSubmitConfirmLoading) return;
                                    setShowTicketSubmitConfirmModal(false);
                                    setPendingTicketSubmission(null);
                                    setTicketSubmitConfirmLoading(false);
                                }}
                                className="text-white/80 hover:text-white transition-colors"
                            >
                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                        <div className="px-6 py-5 overflow-y-auto flex-1">
                            <p className="text-sm text-gray-600 mb-4">Please review the details below. If anything is wrong, click Cancel and tell the assistant what to change.</p>
                            <dl className="space-y-4">
                                <div>
                                    <dt className="text-sm font-semibold text-gray-600 mb-1">Subject</dt>
                                    <dd className="text-gray-900">{pendingTicketSubmission.subject || '—'}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-semibold text-gray-600 mb-1">Description</dt>
                                    <dd className="text-gray-700 text-sm whitespace-pre-wrap max-h-32 overflow-y-auto border border-gray-200 rounded-lg p-3 bg-gray-50">{pendingTicketSubmission.description || '—'}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-semibold text-gray-600 mb-1">Priority</dt>
                                    <dd className="text-gray-900 capitalize">{pendingTicketSubmission.priority || pendingTicketSubmission.tool_args?.priority || 'Normal'}</dd>
                                </div>
                                <div>
                                    <dt className="text-sm font-semibold text-gray-600 mb-1">Property / Site</dt>
                                    <dd className="text-gray-900">{pendingTicketSubmission.property_code || pendingTicketSubmission.tool_args?.property_code || '—'}</dd>
                                </div>
                                {pendingTicketSubmission.type === 'capex' && (
                                    <div>
                                        <dt className="text-sm font-semibold text-gray-600 mb-1">Estimated cost</dt>
                                        <dd className="text-gray-900">{pendingTicketSubmission.estimated_cost ?? pendingTicketSubmission.tool_args?.estimated_cost ?? '—'}</dd>
                                    </div>
                                )}
                                {pendingTicketSubmission.type === 'it_support' && (
                                    <div>
                                        <dt className="text-sm font-semibold text-gray-600 mb-1">Category</dt>
                                        <dd className="text-gray-900">{pendingTicketSubmission.tool_args?.category || '—'}</dd>
                                    </div>
                                )}
                            </dl>
                            <p className="mt-4 text-gray-600 text-sm leading-relaxed">
                                {pendingTicketSubmission.type === 'capex'
                                    ? 'This request will be sent to the appropriate team for review.'
                                    : 'Our IT team will be notified and will review your request.'}
                            </p>
                        </div>
                        <div className="px-6 py-4 bg-gray-50 border-t border-gray-200 flex gap-3">
                            <button
                                onClick={() => {
                                    if (ticketSubmitConfirmLoading) return;
                                    setShowTicketSubmitConfirmModal(false);
                                    setPendingTicketSubmission(null);
                                    setTicketSubmitConfirmLoading(false);
                                }}
                                disabled={ticketSubmitConfirmLoading}
                                className="flex-1 px-5 py-3 bg-white border-2 border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-all font-semibold disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                Cancel
                            </button>
                            <button
                                onClick={async () => {
                                    if (ticketSubmitConfirmLoading) return;
                                    // User confirmed - actually submit the ticket
                                    try {
                                        setTicketSubmitConfirmLoading(true);
                                        setIsTyping(true);
                                        const response = await fetch('/api/chat/confirm-ticket', {
                                            method: 'POST',
                                            headers: {
                                                'Content-Type': 'application/json',
                                                ...(window.getApiHeaders ? window.getApiHeaders(currentUsername) : { 'X-OTO-User': currentUsername }),
                                            },
                                            body: JSON.stringify({
                                                tool_name: pendingTicketSubmission.tool_name,
                                                tool_args: pendingTicketSubmission.tool_args,
                                                // Prefer property_code from tool_args (AI-extracted) over selected property
                                                property_code: pendingTicketSubmission.tool_args?.property_code || pendingTicketSubmission.property_code || selectedProperty?.property_code || '',
                                                mode: currentUser?.mode || 'it_staff',
                                                current_user: currentUser,
                                                // Forward conversation attachments so they get uploaded to the ticket
                                                attachments: await Promise.all(
                                                    allAttachments.filter(a => a.file).map(async (att) => {
                                                        const base64 = await fileToBase64(att.file);
                                                        return { name: att.name, type: att.type, data: base64 };
                                                    })
                                                ),
                                            }),
                                        });
                                        
                                        if (!response.ok) {
                                            const errorData = await response.json();
                                            throw new Error(errorData.detail || 'Failed to submit ticket');
                                        }
                                        
                                        const result = await response.json();
                                        // Merge in full submission details so the success card shows everything (priority, estimated_cost, category, description)
                                        const fullSubmission = {
                                            ...result,
                                            priority: pendingTicketSubmission.priority || pendingTicketSubmission.tool_args?.priority,
                                            estimated_cost: pendingTicketSubmission.estimated_cost ?? pendingTicketSubmission.tool_args?.estimated_cost,
                                            category: pendingTicketSubmission.tool_args?.category,
                                            description: pendingTicketSubmission.description || pendingTicketSubmission.tool_args?.description,
                                        };
                                        // Update the last message to show success/error modal with all submitted fields
                                        setMessages(prev => {
                                            const updated = [...prev];
                                            const lastMsg = updated[updated.length - 1];
                                            if (lastMsg && lastMsg.role === 'assistant') {
                                                lastMsg.ticketSubmission = fullSubmission;
                                            }
                                            return updated;
                                        });
                                        
                                        setShowTicketSubmitConfirmModal(false);
                                        setPendingTicketSubmission(null);
                                        setTicketSubmitConfirmLoading(false);
                                        setIsTyping(false);
                                    } catch (error) {
                                        console.error('Failed to submit ticket:', error);
                                        // Update message with error and merge attempted details so card shows what was submitted
                                        const errPayload = {
                                            error: error.message,
                                            type: pendingTicketSubmission.type,
                                            subject: pendingTicketSubmission.subject,
                                            description: pendingTicketSubmission.description || pendingTicketSubmission.tool_args?.description,
                                            priority: pendingTicketSubmission.priority || pendingTicketSubmission.tool_args?.priority,
                                            property_code: pendingTicketSubmission.property_code || pendingTicketSubmission.tool_args?.property_code,
                                            estimated_cost: pendingTicketSubmission.estimated_cost ?? pendingTicketSubmission.tool_args?.estimated_cost,
                                            category: pendingTicketSubmission.tool_args?.category,
                                        };
                                        setMessages(prev => {
                                            const updated = [...prev];
                                            const lastMsg = updated[updated.length - 1];
                                            if (lastMsg && lastMsg.role === 'assistant') {
                                                lastMsg.ticketSubmission = errPayload;
                                            }
                                            return updated;
                                        });
                                        setShowTicketSubmitConfirmModal(false);
                                        setPendingTicketSubmission(null);
                                        setTicketSubmitConfirmLoading(false);
                                        setIsTyping(false);
                                    }
                                }}
                                disabled={ticketSubmitConfirmLoading}
                                className="flex-1 px-5 py-3 bg-primary hover:bg-primary-hover text-white rounded-lg transition-all font-semibold shadow-md hover:shadow-lg disabled:opacity-70 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                            >
                                {ticketSubmitConfirmLoading ? (
                                    <>
                                        <svg className="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg>
                                        Submitting...
                                    </>
                                ) : (
                                    <>Submit {pendingTicketSubmission.type === 'capex' ? 'Request' : 'Ticket'}</>
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Ticket Update Confirmation Modal */}
            {showTicketUpdateConfirmModal && pendingTicketUpdate && (
                <div
                    className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
                    onClick={() => {
                        if (ticketUpdateConfirmLoading) return;
                        setShowTicketUpdateConfirmModal(false);
                        setPendingTicketUpdate(null);
                        setTicketUpdateConfirmLoading(false);
                    }}
                >
                    <div
                        className="bg-white rounded-xl max-w-lg w-full shadow-2xl max-h-[90vh] flex flex-col"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <div className="bg-gradient-to-r from-primary to-primary-hover px-6 py-5 flex items-center justify-between flex-shrink-0">
                            <div className="flex items-center gap-3 text-white">
                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828L14.172 9.172z" />
                                </svg>
                                <h3 className="text-xl font-bold">Update ticket #{pendingTicketUpdate.ticket_id}?</h3>
                            </div>
                            <button
                                onClick={() => {
                                    if (ticketUpdateConfirmLoading) return;
                                    setShowTicketUpdateConfirmModal(false);
                                    setPendingTicketUpdate(null);
                                    setTicketUpdateConfirmLoading(false);
                                }}
                                className="text-white/80 hover:text-white transition-colors"
                            >
                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                        <div className="px-6 py-5 overflow-y-auto flex-1">
                            <p className="text-sm text-gray-600 mb-4">The following changes will be applied. Only the fields listed below will be updated.</p>
                            <dl className="space-y-4">
                                {pendingTicketUpdate.subject !== undefined && pendingTicketUpdate.subject !== null && pendingTicketUpdate.subject !== '' && (
                                    <div>
                                        <dt className="text-sm font-semibold text-gray-600 mb-1">Subject</dt>
                                        <dd className="text-gray-900 whitespace-pre-wrap border border-gray-200 rounded-lg p-3 bg-gray-50">{pendingTicketUpdate.subject}</dd>
                                    </div>
                                )}
                                {pendingTicketUpdate.body !== undefined && pendingTicketUpdate.body !== null && pendingTicketUpdate.body !== '' && (
                                    <div>
                                        <dt className="text-sm font-semibold text-gray-600 mb-1">Description</dt>
                                        <dd className="text-gray-700 text-sm whitespace-pre-wrap max-h-32 overflow-y-auto border border-gray-200 rounded-lg p-3 bg-gray-50">{pendingTicketUpdate.body}</dd>
                                    </div>
                                )}
                                {pendingTicketUpdate.priority !== undefined && pendingTicketUpdate.priority !== null && pendingTicketUpdate.priority !== '' && (
                                    <div>
                                        <dt className="text-sm font-semibold text-gray-600 mb-1">Priority</dt>
                                        <dd className="text-gray-900 capitalize">{pendingTicketUpdate.priority}</dd>
                                    </div>
                                )}
                                {(!pendingTicketUpdate.subject || pendingTicketUpdate.subject === '') &&
                                 (!pendingTicketUpdate.body || pendingTicketUpdate.body === '') &&
                                 (!pendingTicketUpdate.priority || pendingTicketUpdate.priority === '') && (
                                    <p className="text-gray-500 text-sm">No changes specified.</p>
                                )}
                            </dl>
                        </div>
                        <div className="px-6 py-4 bg-gray-50 border-t border-gray-200 flex gap-3">
                            <button
                                onClick={() => {
                                    if (ticketUpdateConfirmLoading) return;
                                    setShowTicketUpdateConfirmModal(false);
                                    setPendingTicketUpdate(null);
                                    setTicketUpdateConfirmLoading(false);
                                }}
                                disabled={ticketUpdateConfirmLoading}
                                className="flex-1 px-5 py-3 bg-white border-2 border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-all font-semibold disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                Cancel
                            </button>
                            <button
                                onClick={async () => {
                                    if (ticketUpdateConfirmLoading) return;
                                    try {
                                        setTicketUpdateConfirmLoading(true);
                                        const response = await fetch('/api/chat/confirm-ticket', {
                                            method: 'POST',
                                            headers: {
                                                'Content-Type': 'application/json',
                                                ...(window.getApiHeaders ? window.getApiHeaders(currentUsername) : { 'X-OTO-User': currentUsername }),
                                            },
                                            body: JSON.stringify({
                                                tool_name: 'update_ticket',
                                                tool_args: pendingTicketUpdate.tool_args || {
                                                    ticket_id: pendingTicketUpdate.ticket_id,
                                                    subject: pendingTicketUpdate.subject,
                                                    body: pendingTicketUpdate.body,
                                                    priority: pendingTicketUpdate.priority,
                                                },
                                                mode: currentUser?.mode || 'it_staff',
                                                current_user: currentUser,
                                            }),
                                        });
                                        if (!response.ok) {
                                            const err = await response.json();
                                            throw new Error(err.detail || err.error || 'Update failed');
                                        }
                                        const result = await response.json();
                                        setShowTicketUpdateConfirmModal(false);
                                        setPendingTicketUpdate(null);
                                        setTicketUpdateConfirmLoading(false);
                                        if (result.success && result.ticket_id) {
                                            setShowTicketListModal(true);
                                            setTicketListData({ mode_used: 'single', count: 1, tickets: [{ id: result.ticket_id }] });
                                            setViewingTicketDetail({ id: result.ticket_id });
                                        }
                                    } catch (err) {
                                        console.error('Ticket update failed:', err);
                                        setMessages(prev => [...prev, {
                                            role: 'assistant',
                                            content: `Update failed: ${err.message}`,
                                        }]);
                                        setShowTicketUpdateConfirmModal(false);
                                        setPendingTicketUpdate(null);
                                        setTicketUpdateConfirmLoading(false);
                                    }
                                }}
                                disabled={ticketUpdateConfirmLoading || (
                                    (!pendingTicketUpdate.subject || pendingTicketUpdate.subject === '') &&
                                    (!pendingTicketUpdate.body || pendingTicketUpdate.body === '') &&
                                    (!pendingTicketUpdate.priority || pendingTicketUpdate.priority === '')
                                )}
                                className="flex-1 px-5 py-3 bg-primary hover:bg-primary-hover text-white rounded-lg transition-all font-semibold shadow-md hover:shadow-lg disabled:opacity-70 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                            >
                                {ticketUpdateConfirmLoading ? (
                                    <>
                                        <svg className="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg>
                                        Updating...
                                    </>
                                ) : (
                                    'Confirm update'
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            )}

        </div>
    );
};

// Create Ticket Form Component
const CreateTicketForm = ({ onBack, initialDescription = '', initialDraft = null, initialAttachments = [], fromAIChat = false, onBackToChat, onSubmit }) => {
    // Data from staff table
    const [activeEmployees, setActiveEmployees] = useState([]);
    const [employeesLoading, setEmployeesLoading] = useState(true);

    // Detect if reportee is specified in draft
    const reporteeName = initialDraft?.reportee || '';
    let initialBehalfOfType = reporteeName ? 'Someone Else' : 'Myself';
    let initialSelectedEmployee = null;
    let initialFirstName = '';
    let initialLastName = '';

    if (reporteeName) {
        const nameParts = reporteeName.trim().split(/\s+/);
        initialFirstName = nameParts[0] || '';
        initialLastName = nameParts.slice(1).join(' ') || '';
    }

    const [behalfOfType, setBehalfOfType] = useState(initialBehalfOfType);
    const [attachments, setAttachments] = useState(initialAttachments);
    const [isDragging, setIsDragging] = useState(false);
    const fileInputRef = useRef(null);

    // Initialize form fields from AI draft if available
    const [selectedEmployee, setSelectedEmployee] = useState(initialSelectedEmployee);
    const [subject, setSubject] = useState(initialDraft?.subject || '');
    const [description, setDescription] = useState(initialDraft?.description || initialDescription);
    const [priority, setPriority] = useState(initialDraft?.priority || 'Normal');
    const [otherFirstName, setOtherFirstName] = useState(initialFirstName);
    const [otherLastName, setOtherLastName] = useState(initialLastName);
    const [otherEmail, setOtherEmail] = useState('');
    const [otherPhone, setOtherPhone] = useState('');

    const formatPhoneForDisplay = (digits) => {
        if (!digits) return '';
        const cleaned = String(digits).replace(/\D/g, '');
        if (cleaned.length !== 10) return String(digits);
        return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(6, 10)}`;
    };

    const mapStaffToEmployee = (staffRow, idx) => ({
        UserID: staffRow.id ?? staffRow.user_id ?? (idx + 1),
        FirstName: staffRow.first_name ?? '',
        LastName: staffRow.last_name ?? '',
        Username: staffRow.username ?? '',
        Email: staffRow.email ?? '',
        Phone: formatPhoneForDisplay(staffRow.phone ?? ''),
        Role: staffRow.role ?? staffRow.department ?? 'Employee',
        Status: staffRow.normalized_status ?? staffRow.status ?? (staffRow.is_active === false ? 'Disabled' : 'Active'),
    });

    useEffect(() => {
        (async () => {
            try {
                setEmployeesLoading(true);
                const res = await fetch('/api/staff?status=Active');
                const data = await res.json();
                const rows = (data.users || []).map(mapStaffToEmployee);
                setActiveEmployees(rows);
            } catch (e) {
                console.error('Failed to load staff users', e);
                setActiveEmployees([]);
            } finally {
                setEmployeesLoading(false);
            }
        })();
    }, []);

    // After employees load, if AI draft had a reportee name, try to map it to a staff user.
    useEffect(() => {
        if (!reporteeName || selectedEmployee) return;
        if (!activeEmployees.length) return;

        const nameParts = reporteeName.trim().split(/\s+/);
        const firstName = nameParts[0] || '';
        const lastName = nameParts.slice(1).join(' ') || '';

        const matched = activeEmployees.find(emp =>
            emp.FirstName?.toLowerCase() === firstName.toLowerCase() &&
            emp.LastName?.toLowerCase() === lastName.toLowerCase()
        );

        if (matched) {
            setBehalfOfType('Another Employee');
            setSelectedEmployee(matched);
        }
    }, [employeesLoading, activeEmployees, reporteeName]);
    const handleFileSelect = (e) => {
        const files = Array.from(e.target.files);
        const newAttachments = files.map(file => ({
            id: Date.now() + Math.random(),
            name: file.name,
            size: file.size
        }));
        setAttachments(prev => [...prev, ...newAttachments]);
    };

    const removeAttachment = (id) => {
        setAttachments(prev => prev.filter(att => att.id !== id));
    };

    const handleDragOver = (e) => {
        e.preventDefault();
        setIsDragging(true);
    };

    const handleDragLeave = (e) => {
        e.preventDefault();
        setIsDragging(false);
    };

    const handleDrop = (e) => {
        e.preventDefault();
        setIsDragging(false);
        const files = Array.from(e.dataTransfer.files);
        const newAttachments = files.map(file => ({
            id: Date.now() + Math.random(),
            name: file.name,
            size: file.size
        }));
        setAttachments(prev => [...prev, ...newAttachments]);
    };

    const formatFileSize = (bytes) => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    };

    const formatPhoneNumber = (value) => {
        const digits = value.replace(/\D/g, '');
        if (digits.length === 0) return '';
        if (digits.length <= 3) return `(${digits}`;
        if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
        return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6, 10)}`;
    };

    const handlePhoneChange = (e) => {
        const formatted = formatPhoneNumber(e.target.value);
        setOtherPhone(formatted);
    };

    const handleSubmit = () => {
        if (behalfOfType === 'Another Employee' && !selectedEmployee) {
            window.otoNotify?.toast('Please select an employee', 'error');
            return;
        }
        if (behalfOfType === 'Someone Else') {
            if (!otherFirstName || !otherLastName || !otherEmail) {
                window.otoNotify?.toast('Please fill in all required fields for the external contact', 'error');
                return;
            }
        }
        if (!subject || !description) {
            window.otoNotify?.toast('Please fill in Subject and Description', 'error');
            return;
        }

        const priorityMap = { 'Low': -1, 'Normal': 0, 'High': 1, 'Critical': 2 };

        let finalDescription = description;

        if (behalfOfType === 'Another Employee' && selectedEmployee) {
            const contactInfo = `[Submitted by Hotel Rep on behalf of ${selectedEmployee.FirstName} ${selectedEmployee.LastName}]\n\nContact Information:\nName: ${selectedEmployee.FirstName} ${selectedEmployee.LastName}\nUsername: ${selectedEmployee.Username}\nEmail: ${selectedEmployee.Email}\nPhone: ${selectedEmployee.Phone}\nRole: ${selectedEmployee.Role}\n\n---\n\n`;
            finalDescription = contactInfo + description;
        } else if (behalfOfType === 'Someone Else') {
            const contactInfo = `[Submitted by Hotel Rep on behalf of ${otherFirstName} ${otherLastName} - External]\n\nContact Information:\nName: ${otherFirstName} ${otherLastName}\nEmail: ${otherEmail}${otherPhone ? '\nPhone: ' + otherPhone : ''}\n\n---\n\n`;
            finalDescription = contactInfo + description;
        }

        const newTicket = {
            IssueID: Math.floor(Math.random() * 9000) + 1000,
            Subject: subject,
            Status: 'Waiting',
            Priority: priority,
            PriorityID: priorityMap[priority],
            IssueDate: new Date().toISOString(),
            LastUpdated: new Date().toISOString(),
            Category: 'General Support',
            AssignedTo: 'Unassigned',
            Description: finalDescription
        };

        console.log('Ticket submit payload (test):', newTicket);

        onSubmit(newTicket);
        onBack();
    };

    const handleCancel = () => {
        if (fromAIChat) {
            onBackToChat();
        } else {
            onBack();
        }
    };

    return (
        <div className="p-8 overflow-y-auto h-full scrollbar-thin">
            <div className="max-w-3xl mx-auto bg-white rounded-xl border border-gray-200 p-8">
                <div className="mb-6">
                    <h2 className="text-2xl font-bold text-gray-800">Create Ticket</h2>
                    <p className="text-sm text-gray-600 mt-1">Review and submit your support ticket</p>
                </div>

                <div className="space-y-6">
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            Submit Ticket on Behalf Of: <span className="text-red-500">*</span>
                        </label>
                        <select
                            value={behalfOfType}
                            onChange={(e) => setBehalfOfType(e.target.value)}
                            className="w-full border border-gray-300 rounded-lg px-4 py-2"
                        >
                            <option>Myself</option>
                            <option>Another Employee</option>
                            <option>Someone Else</option>
                        </select>
                    </div>

                    {behalfOfType === 'Another Employee' && (
                        <div className="bg-primary/10 border border-primary/20 rounded-lg p-4">
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                Select Employee
                            </label>
                            <select
                                value={selectedEmployee?.UserID || ''}
                                onChange={(e) => {
                                    const emp = activeEmployees.find(u => u.UserID === parseInt(e.target.value));
                                    setSelectedEmployee(emp);
                                }}
                                className="w-full border border-gray-300 rounded-lg px-4 py-2"
                            >
                                <option value="">-- Select an employee --</option>
                                {activeEmployees.map(emp => (
                                    <option key={emp.UserID} value={emp.UserID}>
                                        {emp.FirstName} {emp.LastName} ({emp.Username}) - {emp.Role}
                                    </option>
                                ))}
                            </select>
                            {selectedEmployee && (
                                <div className="mt-3 p-3 bg-white rounded border border-primary/20">
                                    <div className="text-xs font-semibold text-gray-700 mb-1">Selected Employee:</div>
                                    <div className="text-sm">
                                        <div>{selectedEmployee.FirstName} {selectedEmployee.LastName}</div>
                                        <div className="text-gray-600">{selectedEmployee.Role}</div>
                                        <div className="text-gray-600">Email: {selectedEmployee.Email}</div>
                                        <div className="text-gray-600">Phone: {selectedEmployee.Phone}</div>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    {behalfOfType === 'Someone Else' && (
                        <div className="bg-amber-50 border border-amber-200 rounded-lg p-4 space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        First Name <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                        type="text"
                                        value={otherFirstName}
                                        onChange={(e) => setOtherFirstName(e.target.value)}
                                        className="w-full border border-gray-300 rounded-lg px-4 py-2"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        Last Name <span className="text-red-500">*</span>
                                    </label>
                                    <input
                                        type="text"
                                        value={otherLastName}
                                        onChange={(e) => setOtherLastName(e.target.value)}
                                        className="w-full border border-gray-300 rounded-lg px-4 py-2"
                                    />
                                </div>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Email Address <span className="text-red-500">*</span>
                                </label>
                                <input
                                    type="email"
                                    value={otherEmail}
                                    onChange={(e) => setOtherEmail(e.target.value)}
                                    className="w-full border border-gray-300 rounded-lg px-4 py-2"
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Phone Number
                                </label>
                                <input
                                    type="tel"
                                    value={otherPhone}
                                    onChange={handlePhoneChange}
                                    className="w-full border border-gray-300 rounded-lg px-4 py-2"
                                />
                            </div>
                        </div>
                    )}

                    <div className="border-t border-gray-300 pt-6"></div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            Priority
                        </label>
                        <select
                            value={priority}
                            onChange={(e) => setPriority(e.target.value)}
                            className="w-full border border-gray-300 rounded-lg px-4 py-2"
                        >
                            <option>Low</option>
                            <option>Normal</option>
                            <option>High</option>
                            <option>Critical</option>
                        </select>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            Subject <span className="text-red-500">*</span>
                        </label>
                        <input
                            type="text"
                            value={subject}
                            onChange={(e) => setSubject(e.target.value)}
                            className="w-full border border-gray-300 rounded-lg px-4 py-2"
                            placeholder="Brief description of the issue"
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            Description <span className="text-red-500">*</span>
                        </label>
                        <textarea
                            rows="6"
                            value={description}
                            onChange={(e) => setDescription(e.target.value)}
                            className="w-full border border-gray-300 rounded-lg px-4 py-2"
                            placeholder="Detailed description of the issue..."
                        />
                    </div>



                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            Attachments
                        </label>

                        {attachments.length > 0 && (
                            <div className="mb-4">
                                <div className="space-y-2">
                                    {attachments.map(att => (
                                        <div key={att.id} className="flex items-center justify-between p-3 bg-primary/5 rounded-lg border border-primary/30">
                                            <div className="flex items-center gap-3 flex-1 min-w-0">
                                                <svg className="w-5 h-5 text-primary flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
                                                </svg>
                                                <div className="flex-1 min-w-0">
                                                    <p className="text-sm font-semibold text-gray-900 truncate">{att.name}</p>
                                                    <p className="text-xs text-gray-600">{formatFileSize(att.size)}</p>
                                                </div>
                                            </div>
                                            <button
                                                type="button"
                                                onClick={() => removeAttachment(att.id)}
                                                className="text-gray-400 hover:text-red-600 transition-colors ml-3 flex-shrink-0"
                                            >
                                                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                                </svg>
                                            </button>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        <div
                            onDragOver={handleDragOver}
                            onDragLeave={handleDragLeave}
                            onDrop={handleDrop}
                            className={`border-2 border-dashed rounded-lg p-6 text-center transition-all ${isDragging ? 'drag-active' : 'border-gray-300 hover:border-primary'
                                }`}
                        >
                            <input
                                ref={fileInputRef}
                                type="file"
                                multiple
                                onChange={handleFileSelect}
                                className="hidden"
                            />
                            <svg className="w-12 h-12 mx-auto text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                            </svg>
                            <p className="text-gray-600 mb-2">
                                {attachments.length > 0 ? 'Add more files: drag and drop here, or ' : 'Drag and drop files here, or '}
                                <button
                                    type="button"
                                    onClick={() => fileInputRef.current?.click()}
                                    className="text-primary hover:text-primary-hover font-semibold"
                                >
                                    browse
                                </button>
                            </p>
                            <p className="text-xs text-gray-500">Supports images, documents, and other files</p>
                        </div>
                    </div>

                    <div className="flex gap-3 justify-end pt-4">
                        <button
                            onClick={handleCancel}
                            className="px-6 py-2 border border-gray-300 rounded-lg font-semibold text-gray-700 hover:bg-gray-50 transition-colors"
                        >
                            Cancel
                        </button>
                        <button
                            onClick={handleSubmit}
                            className="px-6 py-2 bg-primary hover:bg-primary-hover text-white rounded-lg font-semibold transition-colors"
                        >
                            Submit Ticket
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};

if (typeof window !== 'undefined') window.AIChatView = AIChatView;
// IT Support View
// IT Support View