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

{% block extra_css %}
<link href="{{ url_for('static', filename='css/campaign.css') }}" rel="stylesheet">
<style>
    .tab-container {
        margin-top: 30px;
    }

    .tab-header {
        display: flex;
        border-bottom: 2px solid #eee;
        justify-content: space-around;
    }

    .tab-header button {
        background: none;
        border: none;
        padding: 12px 32px;
        font-size: 1.1em;
        cursor: pointer;
        border-bottom: 3px solid transparent;
        transition: border 0.2s;
    }

    .tab-header button.active {
        border-bottom: 3px solid #2563eb;
        color: #2563eb;
    }

    .tab-content {
        padding: 20px 0;
    }

    .reply-list {
        margin-top: 10px;
    }

    .reply-item {
        border-bottom: 1px solid #eee;
        padding: 10px 0;
    }

    .reply-header {
        font-weight: bold;
    }

    .reply-date {
        color: #888;
        font-size: 0.95em;
        margin-left: 10px;
    }

    .reply-content {
        margin-top: 4px;
    }

    .paginate-btn {
        background: #042954;
        border: none;
        color: white;
        border-radius: 4px;
    }
    .disabled{
        background-color: grey;
    }
    .campaign-show{
        display: flex;
        gap: 14px;
    }
</style>
{% endblock %}

{% block content %}
<div class="campaign-details-page">
    <h2>{{ campaign[1] }} <small style="font-size:0.6em;color:#888;">({{ campaign[4] }})</small></h2>
    <div style="line-height: 30px;font-size: 15px;">
        <div class="campaign-show">
            <strong>Subject:</strong>
            <span>{{ campaign[2] }}</span>
        </div>
        <div class="campaign-show">
            <strong>Scheduled At:</strong>
            <span>{{ campaign[5] or '-' }}</span>
        </div>
        <div class="campaign-show">
            <strong>Created At:</strong>
            <span>{{ campaign[6] or '-' }}</span>
        </div>
        <div>
            <strong>Content:</strong>
            <div class="campaign-content-box">{{ campaign[3] }}</div>
        </div>
    </div>

    <div class="tab-container">
        <div class="tab-header">
            <button id="tab-recipients" class="active" onclick="showTab('recipients')">Recipients</button>
            <button id="tab-replies" onclick="showTab('replies')">Replies</button>
        </div>
        <div id="recipients-tab" class="tab-content">
            <table class="recipients-table" style="width: 100%;text-align: center;">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="recipientsTableBody">
                    <!-- Recipients will be rendered here by JS -->
                </tbody>
            </table>
            <div id="recipientsPagination" style="margin-top: 10px; text-align: right;display: flex;
                justify-content: end;
                align-items: center;
                gap: 9px;
                font-size: 13px;"></div>
            <div id="recipient-thread-modal"
                style="display:none;position:fixed;top:4%;left:50%;transform:translateX(-50%);background:#fff;z-index:9999;padding:30px;width:700px;box-shadow:0 8px 32px rgba(0,0,0,0.15);border-radius:12px;">
                <h4>Conversation with <span id="thread-recipient-email"></span></h4>
                <div id="thread-chat-list" style="max-height:400px;overflow-y:auto;padding:10px 0;"></div>
                <button onclick="closeRecipientThreadModal()" class="action-button primary"
                    style="margin-top:10px;">Close</button>
            </div>
        </div>
        
        <div id="replies-tab" class="tab-content" style="display:none;">
            <div class="reply-list">
                {% for reply in replies %}
                {% if reply[5] %}
                <div class="reply-item" style="background-color: #f0f9ff;">
                    <div class="reply-header">
                        AI Response <span class="reply-date">{{ reply[4] }}</span>
                    </div>
                    <div class="reply-content">{{ reply[3] }}</div>
                </div>
                {% else %}
                <div class="reply-item">
                    <div class="reply-header">
                        {{ reply[2] }} <span class="reply-date">{{ reply[4] }}</span>
                    </div>
                    <div class="reply-content">{{ reply[3] }}</div>
                </div>
                {% endif %}
                {% endfor %}
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    function showTab(tab) {
        document.getElementById('recipients-tab').style.display = (tab === 'recipients') ? '' : 'none';
        document.getElementById('replies-tab').style.display = (tab === 'replies') ? '' : 'none';
        document.getElementById('tab-recipients').classList.toggle('active', tab === 'recipients');
        document.getElementById('tab-replies').classList.toggle('active', tab === 'replies');
    }

    // Show all replies for a specific recipient
    function showRepliesForRecipient(recipientId, recipientEmail) {
        fetch(`/company/campaigns/recipient/${recipientId}/thread?campaign_id={{ campaign[0] }}`)
            .then(response => response.json())
            .then(data => {
                document.getElementById('thread-recipient-email').innerText = recipientEmail;
                console.log(data);
                
                let html = '';
                if (data.success && data.sent) {
                    // Sent email (from you)
                    html += `
                    <div style="display:flex;justify-content:flex-end;margin-bottom:10px;">
                        <div style="background:#2563eb;color:#fff;padding:10px 16px;border-radius:16px 16px 0 16px;width: max-content">
                            <div style="font-size:0.95em;font-weight:600;">You</div>
                            <div style="font-size:12px;margin:4px 0;">${data.sent.content}</div>
                            <div style="font-size:11px;color:#c7d2fe;text-align:right;">${data.sent.date}</div>
                        </div>
                    </div>
                `;
                    // Replies (from recipient)
                    data.replies.forEach(reply => {
                        if (reply.is_ai_response) {
                            html += `
                            <div style="display:flex;justify-content:flex-end;margin-bottom:10px;">
                                <div style="background:#2563eb;color:#fff;padding:10px 16px;border-radius:16px 16px 0 16px;width: max-content">
                                    <div style="font-size:0.95em;font-weight:600;">You (AI Response)</div>
                                    <div style="font-size:12px;margin:4px 0;">${reply.content}</div>
                                    <div style="font-size:11px;color:#c7d2fe;text-align:right;">${reply.date}</div>
                                </div>
                            </div>
                            `;
                        } else {
                            html += `
                            <div style="display:flex;justify-content:flex-start;margin-bottom:10px;">
                                <div style="background:#f3f4f6;color:#222;padding:10px 16px;border-radius:16px 16px 16px 0;width: max-content">
                                    <div style="font-size:0.95em;font-weight:600;">${recipientEmail}</div>
                                    <div style="font-size:12px;margin:4px 0;">${reply.content}</div>
                                    <div style="font-size:11px;color:#888;text-align:left;">${reply.date}</div>
                                </div>
                            </div>
                            `;
                        }
                    });
                } else {
                    html = '<p class="text-muted">No conversation found.</p>';
                }
                document.getElementById('thread-chat-list').innerHTML = html;
                document.getElementById('recipient-thread-modal').style.display = 'block';
            });
    }
    function closeRecipientThreadModal() {
        document.getElementById('recipient-thread-modal').style.display = 'none';
    }

    // Pass recipients data to JS
    const recipientsData = [
        {% for r in recipients %}
    {
        id: "{{ r[0] }}",
            name: "{{ r[1] }}",
                email: "{{ r[2] }}",
                    status: "{{ r[3] }}",
    },
    {% endfor %}
];

    let recipientsPerPage = 5;
    let currentRecipientsPage = 1;

    function renderRecipientsTable() {
        const start = (currentRecipientsPage - 1) * recipientsPerPage;
        const end = start + recipientsPerPage;
        const pageRecipients = recipientsData.slice(start, end);

        document.getElementById('recipientsTableBody').innerHTML = pageRecipients.map(r => `
        <tr>
            <td>${r.name}</td>
            <td>${r.email}</td>
            <td>${r.status}</td>
            <td>
                <button onclick="showRepliesForRecipient('${r.id}', '${r.email}')" class="action-button secondary">View Replies</button>
            </td>
        </tr>
    `).join('');

        renderRecipientsPagination();
    }

    function renderRecipientsPagination() {
        const totalPages = Math.ceil(recipientsData.length / recipientsPerPage);
        let html = '';

        if (totalPages > 1) {
            html += `<button onclick="changeRecipientsPage(-1)"  class="paginate-btn ${currentRecipientsPage === 1 ? 'disabled' : ''}">
            <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-chevron-left"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M15 6l-6 6l6 6" /></svg>
            </button>`;
            html += ` Page ${currentRecipientsPage} of ${totalPages} `;
            html += `<button onclick="changeRecipientsPage(1)"  class="paginate-btn ${currentRecipientsPage === totalPages ? 'disabled' : ''}">
            <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon icon-tabler icons-tabler-outline icon-tabler-chevron-right"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 6l6 6l-6 6" /></svg>
            </button>`;
        }

        document.getElementById('recipientsPagination').innerHTML = html;
    }

    function changeRecipientsPage(delta) {
        const totalPages = Math.ceil(recipientsData.length / recipientsPerPage);
        currentRecipientsPage += delta;
        if (currentRecipientsPage < 1) currentRecipientsPage = 1;
        if (currentRecipientsPage > totalPages) currentRecipientsPage = totalPages;
        renderRecipientsTable();
    }

    // Initial render
    document.addEventListener('DOMContentLoaded', function () {
        renderRecipientsTable();
    });
</script>
{% endblock %}