{% extends "layouts/base.html" %}

{% block title %}Support Ticket - {{ ticket[1] }}{% endblock %}

{% block extra_css %}
<style>
    .ticket-detail-container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 32px 24px 80px;
    }

    .ticket-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 24px;
        gap: 16px;
    }

    .ticket-header h2 {
        margin: 0 0 6px;
        font-size: 28px;
        font-weight: 700;
        color: #0f172a;
    }

    .ticket-header p {
        margin: 0;
        color: #475569;
        font-size: 15px;
    }

    .back-link {
        padding: 11px 18px;
        border-radius: 12px;
        text-decoration: none;
        border: 1px solid rgba(148, 163, 184, 0.32);
        color: #0f172a;
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        transition: all 0.2s ease;
        background: #fff;
    }

    .back-link:hover {
        color: #2563eb;
        border-color: rgba(37, 99, 235, 0.45);
        box-shadow: 0 10px 20px rgba(37, 99, 235, 0.18);
    }

    .ticket-info-card {
        background: #ffffff;
        border-radius: 16px;
        padding: 24px;
        margin-bottom: 24px;
        box-shadow: 0 12px 24px rgba(15, 23, 42, 0.08);
        border: 1px solid rgba(148, 163, 184, 0.12);
    }

    .ticket-info-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-bottom: 20px;
    }

    .ticket-info-item {
        display: flex;
        flex-direction: column;
        gap: 6px;
    }

    .ticket-info-label {
        font-size: 12px;
        text-transform: uppercase;
        color: #94a3b8;
        letter-spacing: 0.08em;
        font-weight: 600;
    }

    .ticket-info-value {
        font-size: 16px;
        font-weight: 600;
        color: #0f172a;
    }

    .ticket-reason {
        margin-top: 20px;
        padding-top: 20px;
        border-top: 1px solid rgba(148, 163, 184, 0.12);
    }

    .ticket-reason-label {
        font-size: 12px;
        text-transform: uppercase;
        color: #94a3b8;
        letter-spacing: 0.08em;
        font-weight: 600;
        margin-bottom: 8px;
    }

    .ticket-reason-text {
        font-size: 15px;
        color: #475569;
        line-height: 1.6;
        white-space: pre-wrap;
    }

    .priority-badge, .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 999px;
        font-size: 12px;
        font-weight: 600;
        text-transform: capitalize;
    }

    .priority-low { background: rgba(148, 163, 184, 0.16); color: #64748b; }
    .priority-medium { background: rgba(59, 130, 246, 0.16); color: #2563eb; }
    .priority-high { background: rgba(245, 158, 11, 0.16); color: #d97706; }
    .priority-urgent { background: rgba(239, 68, 68, 0.16); color: #dc2626; }

    .status-open { background: rgba(34, 197, 94, 0.16); color: #15803d; }
    .status-in-progress { background: rgba(14, 165, 233, 0.16); color: #0369a1; }
    .status-resolved { background: rgba(168, 85, 247, 0.16); color: #7c3aed; }
    .status-closed { background: rgba(148, 163, 184, 0.16); color: #64748b; }

    .chat-container {
        background: #ffffff;
        border-radius: 16px;
        box-shadow: 0 12px 24px rgba(15, 23, 42, 0.08);
        border: 1px solid rgba(148, 163, 184, 0.12);
        display: flex;
        flex-direction: column;
        height: 600px;
    }

    .chat-header {
        padding: 20px 24px;
        border-bottom: 1px solid rgba(148, 163, 184, 0.12);
        background: #f8fafc;
        border-radius: 16px 16px 0 0;
    }

    .chat-header h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #0f172a;
    }

    .chat-messages {
        flex: 1;
        overflow-y: auto;
        padding: 24px;
        display: flex;
        flex-direction: column;
        gap: 16px;
    }

    .message {
        display: flex;
        gap: 12px;
        max-width: 75%;
        animation: fadeIn 0.3s ease;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .message.company {
        align-self: flex-end;
        flex-direction: row-reverse;
    }

    .message.admin {
        align-self: flex-start;
    }

    .message-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        font-size: 14px;
        flex-shrink: 0;
    }

    .message.company .message-avatar {
        background: #2563eb;
        color: #ffffff;
    }

    .message.admin .message-avatar {
        background: #10b981;
        color: #ffffff;
    }

    .message-content {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }

    .message.company .message-content {
        align-items: flex-end;
    }

    .message.admin .message-content {
        align-items: flex-start;
    }

    .message-bubble {
        padding: 12px 16px;
        border-radius: 16px;
        font-size: 14px;
        line-height: 1.5;
        word-wrap: break-word;
        white-space: pre-wrap;
    }

    .message.company .message-bubble {
        background: #2563eb;
        color: #ffffff;
        border-bottom-right-radius: 4px;
    }

    .message.admin .message-bubble {
        background: #f1f5f9;
        color: #0f172a;
        border-bottom-left-radius: 4px;
    }

    .message-time {
        font-size: 11px;
        color: #94a3b8;
        padding: 0 4px;
    }

    .message-sender {
        font-size: 12px;
        font-weight: 600;
        color: #64748b;
        margin-bottom: 4px;
    }

    .chat-input-container {
        padding: 20px 24px;
        border-top: 1px solid rgba(148, 163, 184, 0.12);
        background: #f8fafc;
        border-radius: 0 0 16px 16px;
    }

    .chat-input-form {
        display: flex;
        gap: 12px;
        align-items: flex-end;
    }

    .chat-input {
        flex: 1;
        padding: 12px 16px;
        border: 1px solid #dbe3ee;
        border-radius: 12px;
        font-size: 14px;
        color: #0f172a;
        font-family: inherit;
        resize: none;
        min-height: 44px;
        max-height: 120px;
        transition: border 0.2s ease, box-shadow 0.2s ease;
    }

    .chat-input:focus {
        outline: none;
        border-color: #2563eb;
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
    }

    .send-button {
        padding: 12px 24px;
        border-radius: 12px;
        border: none;
        background: #2563eb;
        color: #ffffff;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
        gap: 8px;
        box-shadow: 0 10px 24px rgba(37, 99, 235, 0.25);
    }

    .send-button:hover:not(:disabled) {
        background: #1d4ed8;
        box-shadow: 0 12px 28px rgba(37, 99, 235, 0.35);
        transform: translateY(-1px);
    }

    .send-button:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }

    .empty-chat {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #94a3b8;
        font-size: 14px;
    }

    @media (max-width: 768px) {
        .ticket-detail-container {
            padding: 24px 18px 60px;
        }

        .ticket-header {
            flex-direction: column;
        }

        .ticket-info-row {
            grid-template-columns: 1fr;
        }

        .message {
            max-width: 85%;
        }

        .chat-container {
            height: 500px;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="ticket-detail-container mt-5">
    <div class="ticket-header">
        <div>
            <h2>{{ ticket[1] }}</h2>
            <p>Ticket #{{ ticket[0][:8] }}</p>
        </div>
        <a href="{{ url_for('company.support_tickets') }}" class="back-link">
            <i class="fa-light fa-arrow-left"></i> Back to Tickets
        </a>
    </div>

    <div class="ticket-info-card">
        <div class="ticket-info-row">
            <div class="ticket-info-item">
                <span class="ticket-info-label">Priority</span>
                <span class="priority-badge priority-{{ ticket[3] }}">{{ ticket[3]|title }}</span>
            </div>
            <div class="ticket-info-item">
                <span class="ticket-info-label">Status</span>
                <span class="status-badge status-{{ ticket[4]|replace('_', '-') }}">{{ ticket[4]|replace('_', ' ')|title }}</span>
            </div>
            <div class="ticket-info-item">
                <span class="ticket-info-label">Created</span>
                <span class="ticket-info-value">{{ ticket[5].strftime('%B %d, %Y %I:%M %p') if ticket[5] else '—' }}</span>
            </div>
            <div class="ticket-info-item">
                <span class="ticket-info-label">Last Updated</span>
                <span class="ticket-info-value">{{ ticket[6].strftime('%B %d, %Y %I:%M %p') if ticket[6] else '—' }}</span>
            </div>
        </div>
        <div class="ticket-reason">
            <div class="ticket-reason-label">Description</div>
            <div class="ticket-reason-text">{{ ticket[2] }}</div>
        </div>
    </div>

    <div class="chat-container">
        <div class="chat-header">
            <h3>Conversation</h3>
        </div>
        <div class="chat-messages" id="chatMessages">
            {% if messages %}
                {% for message in messages %}
                <div class="message {{ message[1] }}">
                    <div class="message-avatar">
                        {% if message[1] == 'company' %}
                            {{ company_name[0]|upper }}
                        {% else %}
                            A
                        {% endif %}
                    </div>
                    <div class="message-content">
                        <div class="message-sender">
                            {% if message[1] == 'company' %}
                                {{ company_name }}
                            {% else %}
                                Admin
                            {% endif %}
                        </div>
                        <div class="message-bubble">{{ message[3] }}</div>
                        <div class="message-time">{{ message[4].strftime('%I:%M %p') if message[4] else '' }}</div>
                    </div>
                </div>
                {% endfor %}
            {% else %}
                <div class="empty-chat">
                    <p>No messages yet. Start the conversation below.</p>
                </div>
            {% endif %}
        </div>
        <div class="chat-input-container">
            {% if ticket[4] == 'closed' %}
            <div class="closed-notice" style="padding: 12px 16px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 12px; color: #991b1b; font-size: 14px; text-align: center;">
                <i class="fa-light fa-lock"></i> This ticket is closed. No further messages can be sent.
            </div>
            {% else %}
            <form id="messageForm" class="chat-input-form">
                <textarea 
                    id="messageInput" 
                    class="chat-input" 
                    placeholder="Type your message..."
                    rows="1"
                    required></textarea>
                <button type="submit" class="send-button" id="sendButton">
                    <i class="fa-light fa-paper-plane"></i>
                    Send
                </button>
            </form>
            {% endif %}
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    const chatMessages = document.getElementById('chatMessages');
    const messageForm = document.getElementById('messageForm');
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');
    const ticketId = '{{ ticket[0] }}';
    const companyName = '{{ company_name }}';
    const ticketStatus = '{{ ticket[4] }}';

    // Scroll to bottom on load
    chatMessages.scrollTop = chatMessages.scrollHeight;

    // Auto-resize textarea (only if form exists)
    if (messageInput) {
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 120) + 'px';
        });
    }

    // Only set up form if ticket is not closed
    if (messageForm && ticketStatus !== 'closed') {
        messageForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const message = messageInput.value.trim();
        if (!message) return;

        // Disable form
        sendButton.disabled = true;
        const originalButtonText = sendButton.innerHTML;
        sendButton.innerHTML = '<i class="fa-light fa-spinner fa-spin"></i> Sending...';

        try {
            const response = await fetch(`/company/support-tickets/${ticketId}/message`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ message: message })
            });

            const data = await response.json();

            if (data.success) {
                // Add message to chat
                addMessageToChat(message, 'company', companyName);
                messageInput.value = '';
                messageInput.style.height = 'auto';
                
                // Scroll to bottom
                setTimeout(() => {
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }, 100);
            } else {
                alert(data.error || 'Failed to send message');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('An error occurred while sending the message');
        } finally {
            sendButton.disabled = false;
            sendButton.innerHTML = originalButtonText;
        }
        });
    }

    function addMessageToChat(messageText, senderType, senderName) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${senderType}`;
        
        const now = new Date();
        const timeString = now.toLocaleTimeString('en-US', { 
            hour: '2-digit', 
            minute: '2-digit',
            hour12: true 
        });

        messageDiv.innerHTML = `
            <div class="message-avatar">
                ${senderType === 'company' ? companyName[0].toUpperCase() : 'A'}
            </div>
            <div class="message-content">
                <div class="message-sender">${senderName}</div>
                <div class="message-bubble">${escapeHtml(messageText)}</div>
                <div class="message-time">${timeString}</div>
            </div>
        `;

        // Remove empty chat message if exists
        const emptyChat = chatMessages.querySelector('.empty-chat');
        if (emptyChat) {
            emptyChat.remove();
        }

        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
</script>
{% endblock %}

