<% currentPage = 'campaigns' %>

<%
const sentCount = logs.filter(l => l.status === 'sent').length;
const failedCount = logs.filter(l => l.status === 'failed').length;
const pendingCount = campaign.contacts.length - sentCount - failedCount;
const successWidth = campaign.contacts.length > 0 ? Math.round((sentCount / campaign.contacts.length) * 100) : 0;
const failedWidth = campaign.contacts.length > 0 ? Math.round((failedCount / campaign.contacts.length) * 100) : 0;
const successRate = logs.length > 0 ? Math.round((sentCount / logs.length) * 100) : 0;
%>

<div class="d-flex align-items-center gap-3 mb-3">
    <a href="/campaigns" class="btn btn-light btn-sm" style="min-width: 44px; min-height: 44px; display: flex; align-items: center; justify-content: center;">
        <i class="fas fa-arrow-left"></i>
    </a>
    <div class="flex-grow-1 min-w-0">
        <h4 class="mb-0 fw-bold text-truncate" style="font-size: clamp(1rem, 4vw, 1.25rem);"><%= campaign.name %></h4>
        <small class="text-muted d-none d-sm-inline">Created <%= new Date(campaign.created_at).toLocaleDateString() %></small>
    </div>
    <% if (campaign.status === 'completed') { %>
        <span class="badge bg-success rounded-pill px-3 py-2 d-none d-md-inline-flex"><i class="fas fa-check me-1"></i>Completed</span>
    <% } else if (campaign.status === 'running') { %>
        <span class="badge bg-warning rounded-pill px-3 py-2 d-none d-md-inline-flex"><i class="fas fa-spinner fa-pulse me-1"></i>Running</span>
    <% } else if (campaign.status === 'paused') { %>
        <span class="badge bg-info rounded-pill px-3 py-2 d-none d-md-inline-flex"><i class="fas fa-pause me-1"></i>Paused</span>
    <% } else if (campaign.status === 'pending') { %>
        <span class="badge bg-secondary rounded-pill px-3 py-2 d-none d-md-inline-flex"><i class="fas fa-clock me-1"></i>Pending</span>
    <% } else if (campaign.status === 'failed') { %>
        <span class="badge bg-danger rounded-pill px-3 py-2 d-none d-md-inline-flex"><i class="fas fa-times me-1"></i>Stopped</span>
    <% } %>
</div>

<!-- Mobile Action Buttons - Top -->
<% if (campaign.status === 'pending' || campaign.status === 'running' || campaign.status === 'paused') { %>
<div class="d-lg-none mb-3">
    <div class="d-flex gap-2">
        <% if (campaign.status === 'pending') { %>
            <button class="btn btn-success flex-grow-1 fw-semibold shadow" id="btnStartCampaignMobile" data-campaign-id="<%= campaign.id %>" style="min-height: 54px; border-radius: 12px; font-size: 15px; background: linear-gradient(135deg, #28a745 0%, #20c997 100%); border: none;">
                <i class="fas fa-play me-2"></i>Start Campaign
            </button>
        <% } else if (campaign.status === 'running') { %>
            <button class="btn btn-warning text-white flex-grow-1 fw-semibold shadow" id="btnPauseCampaignMobile" data-campaign-id="<%= campaign.id %>" style="min-height: 54px; border-radius: 12px; font-size: 15px; background: linear-gradient(135deg, #ffc107 0%, #ff9800 100%); border: none;">
                <i class="fas fa-pause me-2"></i>Pause
            </button>
            <button class="btn btn-danger fw-semibold shadow" id="btnStopCampaignMobile" data-campaign-id="<%= campaign.id %>" style="min-height: 54px; min-width: 100px; border-radius: 12px; font-size: 15px; background: linear-gradient(135deg, #dc3545 0%, #c82333 100%); border: none;">
                <i class="fas fa-stop me-2"></i>Stop
            </button>
        <% } else if (campaign.status === 'paused') { %>
            <button class="btn btn-success flex-grow-1 fw-semibold shadow" id="btnResumeCampaignMobile" data-campaign-id="<%= campaign.id %>" style="min-height: 54px; border-radius: 12px; font-size: 15px; background: linear-gradient(135deg, #28a745 0%, #20c997 100%); border: none;">
                <i class="fas fa-play me-2"></i>Resume
            </button>
            <button class="btn btn-danger fw-semibold shadow" id="btnStopCampaignMobile" data-campaign-id="<%= campaign.id %>" style="min-height: 54px; min-width: 100px; border-radius: 12px; font-size: 15px; background: linear-gradient(135deg, #dc3545 0%, #c82333 100%); border: none;">
                <i class="fas fa-stop me-2"></i>Stop
            </button>
        <% } %>
    </div>
</div>
<% } %>

<div class="row g-3">
    <div class="col-lg-8">
        <div class="row g-2 mb-3">
            <div class="col-6 col-md-3">
                <div class="card shadow-sm h-100">
                    <div class="card-body p-3 text-center">
                        <div class="text-primary mb-1"><i class="fas fa-users fa-lg"></i></div>
                        <div class="fs-4 fw-bold text-primary"><%= campaign.contacts.length %></div>
                        <small class="text-muted">Recipients</small>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="card shadow-sm h-100">
                    <div class="card-body p-3 text-center">
                        <div class="text-success mb-1"><i class="fas fa-check-circle fa-lg"></i></div>
                        <div class="fs-4 fw-bold text-success"><%= sentCount %></div>
                        <small class="text-muted">Sent</small>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="card shadow-sm h-100">
                    <div class="card-body p-3 text-center">
                        <div class="text-danger mb-1"><i class="fas fa-times-circle fa-lg"></i></div>
                        <div class="fs-4 fw-bold text-danger"><%= failedCount %></div>
                        <small class="text-muted">Failed</small>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="card shadow-sm h-100">
                    <div class="card-body p-3 text-center">
                        <div class="text-info mb-1"><i class="fas fa-percentage fa-lg"></i></div>
                        <div class="fs-4 fw-bold text-info"><%= successRate %>%</div>
                        <small class="text-muted">Success</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="card shadow-sm mb-3">
            <div class="card-body p-3">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <small class="fw-semibold">Progress</small>
                    <small class="text-muted"><%= sentCount + failedCount %>/<%= campaign.contacts.length %></small>
                </div>
                <div class="progress" style="height: 8px;">
                    <div class="progress-bar bg-success" id="progressSuccess"></div>
                    <div class="progress-bar bg-danger" id="progressFailed"></div>
                </div>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="card-header bg-white py-2 d-flex justify-content-between align-items-center">
                <span class="fw-semibold"><i class="fas fa-list-alt me-2"></i>Delivery Logs</span>
                <span class="badge bg-secondary rounded-pill"><%= logs.length %></span>
            </div>
            <div class="card-body p-0" style="max-height: 500px; overflow-y: auto;">
                <% if (logs.length === 0) { %>
                    <div class="text-center py-5 text-muted">
                        <i class="fas fa-inbox fa-3x mb-3 opacity-50"></i>
                        <p class="mb-0">No delivery logs yet</p>
                    </div>
                <% } else { %>
                    <div class="list-group list-group-flush">
                        <% logs.forEach(function(log) { %>
                            <div class="list-group-item px-3 py-2">
                                <div class="d-flex align-items-center gap-2">
                                    <div class="rounded-circle bg-success text-white d-flex align-items-center justify-content-center" style="width: 36px; height: 36px; font-size: 0.75rem; font-weight: 600;">
                                        <%= (log.contact_name || 'U').charAt(0).toUpperCase() %>
                                    </div>
                                    <div class="flex-grow-1 min-w-0">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <span class="fw-semibold text-truncate" style="font-size: 0.875rem;"><%= log.contact_name || log.phone_number %></span>
                                            <% if (log.status === 'sent') { %>
                                                <span class="badge bg-success-subtle text-success"><i class="fas fa-check"></i></span>
                                            <% } else if (log.status === 'failed') { %>
                                                <span class="badge bg-danger-subtle text-danger"><i class="fas fa-times"></i></span>
                                            <% } else { %>
                                                <span class="badge bg-secondary-subtle text-secondary"><i class="fas fa-clock"></i></span>
                                            <% } %>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <small class="text-muted font-monospace"><%= log.phone_number %></small>
                                            <small class="text-muted"><%= log.sent_at ? new Date(log.sent_at).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }) : '-' %></small>
                                        </div>
                                        <% if (log.error) { %>
                                            <small class="text-danger d-block mt-1">
                                                <i class="fas fa-exclamation-circle me-1"></i><%= log.error.substring(0, 50) %>
                                            </small>
                                        <% } %>
                                    </div>
                                </div>
                            </div>
                        <% }); %>
                    </div>
                <% } %>
            </div>
        </div>
    </div>

    <!-- Sidebar - Hidden on mobile, shown on desktop -->
    <div class="col-lg-4 d-none d-lg-block" id="sidebarColumn">
        <% if (campaign.status === 'pending' || campaign.status === 'running' || campaign.status === 'paused') { %>
        <div class="card border-0 shadow-sm mb-3" style="border-radius: 12px; overflow: hidden;">
            <div class="card-body p-4">
                <div class="d-flex align-items-center mb-3">
                    <div class="rounded-circle bg-primary bg-opacity-10 p-2 me-2">
                        <i class="fas fa-sliders-h text-primary"></i>
                    </div>
                    <h6 class="mb-0 fw-bold">Campaign Controls</h6>
                </div>
                <div class="d-grid gap-2">
                    <% if (campaign.status === 'pending') { %>
                        <button class="btn btn-success py-3 fw-semibold position-relative overflow-hidden" id="btnStartCampaign" data-campaign-id="<%= campaign.id %>" style="border-radius: 10px; font-size: 15px;">
                            <i class="fas fa-play me-2"></i>Start Campaign
                        </button>
                    <% } else if (campaign.status === 'running') { %>
                        <button class="btn btn-warning text-white py-3 fw-semibold position-relative overflow-hidden" id="btnPauseCampaign" data-campaign-id="<%= campaign.id %>" style="border-radius: 10px; font-size: 15px; background: linear-gradient(135deg, #ffc107 0%, #ff9800 100%); border: none;">
                            <i class="fas fa-pause me-2"></i>Pause Campaign
                        </button>
                        <button class="btn btn-danger py-3 fw-semibold position-relative overflow-hidden" id="btnStopCampaign" data-campaign-id="<%= campaign.id %>" style="border-radius: 10px; font-size: 15px; background: linear-gradient(135deg, #dc3545 0%, #c82333 100%); border: none;">
                            <i class="fas fa-stop me-2"></i>Stop Campaign
                        </button>
                    <% } else if (campaign.status === 'paused') { %>
                        <button class="btn btn-success py-3 fw-semibold position-relative overflow-hidden" id="btnResumeCampaign" data-campaign-id="<%= campaign.id %>" style="border-radius: 10px; font-size: 15px; background: linear-gradient(135deg, #28a745 0%, #20c997 100%); border: none;">
                            <i class="fas fa-play me-2"></i>Resume Campaign
                        </button>
                        <button class="btn btn-danger py-3 fw-semibold position-relative overflow-hidden" id="btnStopCampaign" data-campaign-id="<%= campaign.id %>" style="border-radius: 10px; font-size: 15px; background: linear-gradient(135deg, #dc3545 0%, #c82333 100%); border: none;">
                            <i class="fas fa-stop me-2"></i>Stop Campaign
                        </button>
                    <% } %>
                </div>
            </div>
        </div>
        <% } %>



        <div class="card shadow-sm mb-3">
            <div class="card-header bg-white py-2">
                <span class="fw-semibold"><i class="fas fa-info-circle me-2"></i>Campaign Info</span>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush">
                    <li class="list-group-item d-flex justify-content-between py-2 px-3">
                        <span class="text-muted"><i class="fab fa-whatsapp me-2"></i>Sessions</span>
                        <span class="fw-semibold"><%= campaign.session_ids.length %></span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between py-2 px-3">
                        <span class="text-muted"><i class="fas fa-random me-2"></i>Method</span>
                        <span class="badge bg-info"><%= campaign.method %></span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between py-2 px-3">
                        <span class="text-muted"><i class="fas fa-clock me-2"></i>Delay</span>
                        <span class="fw-semibold"><%= campaign.delay || 3 %>s</span>
                    </li>
                    <% if (campaign.message_type && campaign.message_type !== 'text') { %>
                    <li class="list-group-item d-flex justify-content-between py-2 px-3">
                        <span class="text-muted"><i class="fas fa-envelope me-2"></i>Type</span>
                        <span class="badge bg-primary"><%= campaign.message_type %></span>
                    </li>
                    <% } %>
                    <% if (campaign.media_url) { %>
                    <li class="list-group-item d-flex justify-content-between py-2 px-3">
                        <span class="text-muted"><i class="fas fa-paperclip me-2"></i>Media</span>
                        <span class="text-success"><i class="fas fa-check"></i> Attached</span>
                    </li>
                    <% } %>
                </ul>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="card-header bg-success text-white py-2">
                <small class="fw-semibold"><i class="fab fa-whatsapp me-2"></i>Message Preview</small>
            </div>
            <div class="whatsapp-preview-compact">
                <div class="wa-message-bubble">
                    <div class="wa-message-text"><%= campaign.message || 'No message content' %></div>
                    <div class="wa-message-time">
                        <span>12:00</span>
                        <i class="fas fa-check-double"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Mobile Preview Panel -->
<div class="d-lg-none" id="mobilePreviewPanel" style="display: none;">
    <div class="card shadow-sm mb-3">
        <div class="card-header bg-success text-white py-2 d-flex justify-content-between align-items-center">
            <small class="fw-semibold"><i class="fab fa-whatsapp me-2"></i>Message Preview</small>
            <button type="button" class="btn btn-sm btn-light" id="hidePreviewBtn" style="padding: 0.25rem 0.5rem;">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="whatsapp-preview-compact">
            <div class="wa-message-bubble">
                <div class="wa-message-text"><%= campaign.message || 'No message content' %></div>
                <div class="wa-message-time">
                    <span>12:00</span>
                    <i class="fas fa-check-double"></i>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Campaign Info in Mobile Preview -->
    <div class="card shadow-sm mb-3">
        <div class="card-header bg-white py-2">
            <span class="fw-semibold"><i class="fas fa-info-circle me-2"></i>Campaign Info</span>
        </div>
        <div class="card-body p-0">
            <ul class="list-group list-group-flush">
                <li class="list-group-item d-flex justify-content-between py-2 px-3">
                    <span class="text-muted"><i class="fab fa-whatsapp me-2"></i>Sessions</span>
                    <span class="fw-semibold"><%= campaign.session_ids.length %></span>
                </li>
                <li class="list-group-item d-flex justify-content-between py-2 px-3">
                    <span class="text-muted"><i class="fas fa-random me-2"></i>Method</span>
                    <span class="badge bg-info"><%= campaign.method %></span>
                </li>
                <li class="list-group-item d-flex justify-content-between py-2 px-3">
                    <span class="text-muted"><i class="fas fa-clock me-2"></i>Delay</span>
                    <span class="fw-semibold"><%= campaign.delay || 3 %>s</span>
                </li>
            </ul>
        </div>
    </div>
    
    <button type="button" class="btn btn-outline-secondary w-100" id="backToLogsBtn" style="min-height: 48px;">
        <i class="fas fa-arrow-left me-1"></i>Back to Logs
    </button>
</div>

<!-- Mobile Preview Toggle Button (FAB) -->
<button type="button" class="btn btn-success btn-fab d-lg-none" id="togglePreviewBtn">
    <i class="fab fa-whatsapp"></i>
</button>

<div id="campaignData" 
     data-success-width="<%= successWidth %>" 
     data-failed-width="<%= failedWidth %>" 
     data-status="<%= campaign.status %>" 
     style="display:none;"></div>

<script>
(function() {
    var dataEl = document.getElementById('campaignData');
    var successWidth = dataEl.dataset.successWidth;
    var failedWidth = dataEl.dataset.failedWidth;
    var campaignStatus = dataEl.dataset.status;
    var csrfToken = document.querySelector('meta[name="csrf-token"]') ? document.querySelector('meta[name="csrf-token"]').content : '';

    document.getElementById('progressSuccess').style.width = successWidth + '%';
    document.getElementById('progressFailed').style.width = failedWidth + '%';

    function handleCampaignAction(action, campaignId) {
        fetch('/webapi/campaigns/' + campaignId + '/' + action, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'x-csrf-token': csrfToken
            }
        })
        .then(function(response) { return response.json(); })
        .then(function(data) {
            if (data.success) {
                if (window.showToast) window.showToast(data.message, 'success');
                setTimeout(function() { location.reload(); }, 1500);
            } else {
                if (window.showToast) window.showToast(data.message || 'Failed', 'danger');
            }
        })
        .catch(function(error) {
            console.error('Error:', error);
            if (window.showToast) window.showToast('Failed to ' + action + ' campaign', 'danger');
        });
    }

    var btnStart = document.getElementById('btnStartCampaign');
    var btnPause = document.getElementById('btnPauseCampaign');
    var btnResume = document.getElementById('btnResumeCampaign');
    var btnStop = document.getElementById('btnStopCampaign');
    
    // Mobile buttons
    var btnStartMobile = document.getElementById('btnStartCampaignMobile');
    var btnPauseMobile = document.getElementById('btnPauseCampaignMobile');
    var btnResumeMobile = document.getElementById('btnResumeCampaignMobile');
    var btnStopMobile = document.getElementById('btnStopCampaignMobile');

    function bindStartHandler(btn) {
        if (btn) {
            btn.addEventListener('click', function() {
                var id = this.dataset.campaignId;
                ConfirmModal.show({
                    title: 'Start Campaign',
                    message: 'Are you sure you want to start this campaign?',
                    confirmText: 'Start',
                    type: 'success',
                    onConfirm: function() { handleCampaignAction('start', id); }
                });
            });
        }
    }
    
    function bindPauseHandler(btn) {
        if (btn) {
            btn.addEventListener('click', function() {
                var id = this.dataset.campaignId;
                ConfirmModal.show({
                    title: 'Pause Campaign',
                    message: 'Are you sure you want to pause this campaign?',
                    confirmText: 'Pause',
                    type: 'warning',
                    onConfirm: function() { handleCampaignAction('pause', id); }
                });
            });
        }
    }
    
    function bindResumeHandler(btn) {
        if (btn) {
            btn.addEventListener('click', function() {
                var id = this.dataset.campaignId;
                ConfirmModal.show({
                    title: 'Resume Campaign',
                    message: 'Are you sure you want to resume this campaign?',
                    confirmText: 'Resume',
                    type: 'success',
                    onConfirm: function() { handleCampaignAction('resume', id); }
                });
            });
        }
    }
    
    function bindStopHandler(btn) {
        if (btn) {
            btn.addEventListener('click', function() {
                var id = this.dataset.campaignId;
                ConfirmModal.show({
                    title: 'Stop Campaign',
                    message: 'Are you sure you want to stop this campaign?<br><small class="text-muted">This action cannot be undone.</small>',
                    confirmText: 'Stop',
                    type: 'danger',
                    onConfirm: function() { handleCampaignAction('stop', id); }
                });
            });
        }
    }
    
    // Desktop buttons
    bindStartHandler(btnStart);
    bindPauseHandler(btnPause);
    bindResumeHandler(btnResume);
    bindStopHandler(btnStop);
    
    // Mobile buttons
    bindStartHandler(btnStartMobile);
    bindPauseHandler(btnPauseMobile);
    bindResumeHandler(btnResumeMobile);
    bindStopHandler(btnStopMobile);
    


    // FAB Preview Toggle
    var togglePreviewBtn = document.getElementById('togglePreviewBtn');
    var hidePreviewBtn = document.getElementById('hidePreviewBtn');
    var backToLogsBtn = document.getElementById('backToLogsBtn');
    var mobilePreviewPanel = document.getElementById('mobilePreviewPanel');
    var mainContent = document.querySelector('.col-lg-8');
    
    function showMobilePreview() {
        if (mobilePreviewPanel && mainContent && togglePreviewBtn) {
            mobilePreviewPanel.style.display = 'block';
            mainContent.style.display = 'none';
            togglePreviewBtn.style.display = 'none';
            setTimeout(function() {
                mobilePreviewPanel.scrollIntoView({ behavior: 'smooth' });
            }, 100);
        }
    }
    
    function hideMobilePreview() {
        if (mobilePreviewPanel && mainContent && togglePreviewBtn) {
            mobilePreviewPanel.style.display = 'none';
            mainContent.style.display = 'block';
            togglePreviewBtn.style.display = 'flex';
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }
    
    if (togglePreviewBtn) {
        togglePreviewBtn.addEventListener('click', showMobilePreview);
    }
    if (hidePreviewBtn) {
        hidePreviewBtn.addEventListener('click', hideMobilePreview);
    }
    if (backToLogsBtn) {
        backToLogsBtn.addEventListener('click', hideMobilePreview);
    }

    if (campaignStatus === 'running') {
        setInterval(function() { location.reload(); }, 5000);
    }
})();
</script>
