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

{% block title %}Call Campaign{% endblock %}

{% block extra_css %}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/css/select2.min.css" rel="stylesheet" />
<link href="{{ url_for('static', filename='css/campaign.css') }}" rel="stylesheet">

<style>
    .campaigns-container {
        /* padding: 32px 24px 80px; */
        max-width: 1200px;
        margin: 0 auto;
    }

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

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

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

    .header-legend {
        display: flex;
        align-items: center;
        gap: 12px;
        background: #fff;
        border-radius: 999px;
        padding: 10px 16px;
        box-shadow: 0 6px 20px rgba(15, 23, 42, 0.08);
    }

    .legend-item {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 13px;
        color: #334155;
        font-weight: 500;
    }

    .legend-dot {
        width: 10px;
        height: 10px;
        border-radius: 50%;
    }

    .legend-dot.success {
        background: #16a34a;
    }

    .legend-dot.warning {
        background: #f59e0b;
    }

    .legend-dot.info {
        background: #0ea5e9;
    }

    .legend-dot.danger {
        background: #f97316;
    }

    .legend-dot.neutral {
        background: #a855f7;
    }

    .table-card {
        background: #ffffff;
        border-radius: 18px;
        box-shadow: 0 35px 65px rgba(15, 23, 42, 0.06);
        overflow: hidden;
        border: 1px solid rgba(148, 163, 184, 0.12);
    }

    .table-title-bar {
        padding: 18px 24px;
        border-bottom: 1px solid rgba(148, 163, 184, 0.18);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .table-title-bar h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #0f172a;
    }

    .campaign-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
    }

    .campaign-table thead th {
        background: #f8fafc;
        padding: 16px 20px;
        text-align: left;
        font-size: 13px;
        letter-spacing: 0.04em;
        text-transform: uppercase;
        color: #64748b;
        border-bottom: 1px solid rgba(148, 163, 184, 0.18);
    }

    .campaign-table tbody tr {
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .campaign-table tbody tr:hover {
        transform: translateY(-2px);
        box-shadow: 0 12px 24px rgba(15, 23, 42, 0.08);
    }

    .campaign-table tbody tr+tr td {
        border-top: 1px solid rgba(148, 163, 184, 0.12);
    }

    .campaign-table tbody td {
        padding: 18px 20px;
        font-size: 15px;
        color: #1f2937;
        background: #ffffff;
    }

    .campaign-name {
        font-weight: 600;
        color: #0f172a;
    }

    .campaign-meta {
        display: flex;
        /* flex-direction: column; */
        gap: 4px;
    }

    .campaign-meta span {
        font-size: 13px;
        color: #64748b;
    }

    .campaign-status-pill {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 6px 14px;
        border-radius: 999px;
        font-size: 13px;
        font-weight: 600;
        background: rgba(14, 116, 144, 0.08);
        color: #0f172a;
    }

    .status-pending {
        background: rgba(245, 158, 11, 0.16);
        color: #b45309;
    }

    .status-in-progress {
        background: rgba(14, 165, 233, 0.16);
        color: #0369a1;
    }

    .status-completed {
        background: rgba(34, 197, 94, 0.16);
        color: #15803d;
    }

    .status-failed {
        background: rgba(249, 115, 22, 0.16);
        color: #c2410c;
    }

    .status-limit-reached {
        background: rgba(168, 85, 247, 0.16);
        color: #6b21a8;
    }

    .metric-value {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        font-weight: 600;
        color: #0f172a;
    }

    .metric-value span {
        display: inline-flex;
        align-items: center;
        gap: 6px;
    }

    .metric-value .label-muted {
        color: #94a3b8;
        font-weight: 500;
        text-transform: uppercase;
        font-size: 11px;
        letter-spacing: 0.08em;
    }

    .campaign-actions {
        display: flex;
        gap: 10px;
    }

    .action-icon {
        width: 38px;
        height: 38px;
        border-radius: 12px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        color: #0f172a;
        text-decoration: none;
        border: 1px solid rgba(148, 163, 184, 0.32);
        transition: all 0.2s ease;
        background: #fff;
    }

    .action-icon:hover {
        color: #1d4ed8;
        border-color: rgba(37, 99, 235, 0.45);
        box-shadow: 0 8px 16px rgba(29, 78, 216, 0.15);
    }

    .action-button {
        padding: 12px 18px;
        border: none;
        border-radius: 12px;
        cursor: pointer;
        font-size: 15px;
        font-weight: 600;
        transition: all 0.2s ease;
    }

    .action-button.primary {
        background: linear-gradient(135deg, #1d4ed8, #2563eb);
        color: #fff;
        box-shadow: 0 12px 24px rgba(37, 99, 235, 0.25);
    }

    .action-button.primary:hover {
        transform: translateY(-1px);
        box-shadow: 0 16px 30px rgba(37, 99, 235, 0.3);
    }

    .limit-info {
        margin-bottom: 24px;
        padding: 18px 22px;
        background: #ffffff;
        border-radius: 16px;
        display: flex;
        align-items: center;
        gap: 16px;
        color: #0f172a;
        box-shadow: 0 25px 50px rgba(15, 23, 42, 0.05);
        border: 1px solid rgba(148, 163, 184, 0.12);
    }

    .limit-info i {
        font-size: 20px;
        color: #2563eb;
    }

    .import-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 1050;
        overflow-y: auto;
    }

    .modal-content {
        background: white;
        width: 640px;
        height: 560px;
        margin: auto;
        padding: 28px;
        border-radius: 18px;
        position: relative;
        box-shadow: 0 40px 80px rgba(15, 23, 42, .25);
        transform: translate(-50%, 12%);
    }

    .modal-content .form-group {
        margin-bottom: 20px;
    }

    .modal-content .form-group label {
        font-weight: 600;
        margin-bottom: 8px;
        display: block;
        color: #0f172a;
    }

    .modal-content textarea.form-control {
        min-height: 150px;
        resize: vertical;
    }

    .modal-content .form-control {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #cbd5f5;
        border-radius: 10px;
        background: #f8fafc;
        transition: border 0.2s ease, box-shadow 0.2s ease;
    }

    .modal-content .form-control:focus {
        border-color: #2563eb;
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
        outline: none;
        background: #fff;
    }

    .modal-content .select2-container .select2-selection--multiple {
        min-height: 45px;
        border: 1px solid #cbd5f5;
        padding: 8px 12px;
        line-height: 1.5;
        border-radius: 10px;
        background: #f8fafc;
    }

    .modal-content .select2-container--default .select2-selection--multiple .select2-selection__choice {
        background-color: #2563eb;
        color: white;
        border: none;
        border-radius: 8px;
        padding: 2px 10px;
        margin-top: 6px;
        font-size: 13px;
    }

    .modal-content .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
        color: rgba(255, 255, 255, 0.8);
        margin-left: 6px;
        font-weight: bold;
        cursor: pointer;
    }

    .modal-content .select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover {
        color: #fff;
    }

    .modal-content .select2-container--default.select2-container--focus .select2-selection--multiple {
        border-color: #2563eb;
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
    }

    .action-button.secondary {
        background-color: #e2e8f0;
        color: #0f172a;
    }

    .action-button.secondary:hover {
        background-color: #cbd5f5;
        transform: translateY(-1px);
    }

    .pagination-controls {
        margin-top: 24px;
        display: flex;
        justify-content: flex-end;
        gap: 8px;
    }

    .pagination-button {
        padding: 10px 18px;
        border-radius: 10px;
        border: 1px solid rgba(148, 163, 184, 0.28);
        background: #ffffff;
        color: #0f172a;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .pagination-button:hover {
        border-color: rgba(37, 99, 235, 0.35);
        color: #2563eb;
    }

    .pagination-button:disabled {
        opacity: 0.45;
        cursor: not-allowed;
        box-shadow: none;
    }

    .filters-toolbar {
        display: flex;
        flex-wrap: wrap;
        align-items: flex-end;
        gap: 16px;
        padding: 16px 20px;
        background: #f8fafc;
        border-radius: 16px;
        border: 1px solid rgba(148, 163, 184, 0.18);
        min-width: 280px;
    }

    .filters-toolbar .filter-input {
        display: flex;
        flex-direction: column;
        gap: 6px;
        flex: 1 1 200px;
        min-width: 180px;
    }

    .filters-toolbar .filter-input label {
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #64748b;
        font-weight: 600;
    }

    .filters-toolbar .input-wrapper {
        position: relative;
        display: flex;
        align-items: center;
        background: #ffffff;
        border-radius: 12px;
        border: 1px solid #dbe3ee;
        padding: 10px 12px;
        box-shadow: 0 10px 24px rgba(15, 23, 42, 0.05);
        transition: border 0.2s ease, box-shadow 0.2s ease;
    }

    .filters-toolbar .input-wrapper:focus-within {
        border-color: #2563eb;
        box-shadow: 0 12px 26px rgba(37, 99, 235, 0.18);
    }

    .filters-toolbar .input-wrapper i {
        margin-right: 10px;
        color: #94a3b8;
        font-size: 16px;
    }

    .filters-toolbar .input-wrapper input,
    .filters-toolbar .input-wrapper select {
        flex: 1;
        border: none;
        background: transparent;
        outline: none;
        font-size: 14px;
        color: #0f172a;
    }

    .filters-toolbar .input-wrapper select {
        appearance: none;
        padding-right: 18px;
    }

    .filters-toolbar .input-wrapper.input-select {
        position: relative;
    }

    .filters-toolbar .input-wrapper.input-select::after {
        content: '\f107';
        font-family: "Font Awesome 6 Pro";
        position: absolute;
        right: 12px;
        color: #94a3b8;
        pointer-events: none;
    }

    .filters-toolbar .filter-action {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        margin-left: auto;
        flex: 0 0 auto;
    }

    .filters-toolbar .filter-action .action-button {
        height: 44px;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 0 18px;
    }

    @media (max-width: 1024px) {
        .campaigns-container {
            padding: 24px 18px 60px;
        }

        .header-actions {
            flex-direction: column;
            align-items: stretch;
        }

        .header-legend {
            align-self: flex-start;
        }

        .filters-toolbar {
            width: 100%;
        }
    }

    @media (max-width: 768px) {
        .campaign-table thead {
            display: none;
        }

        .campaign-table,
        .campaign-table tbody,
        .campaign-table tr,
        .campaign-table td {
            display: block;
            width: 100%;
        }

        .campaign-table tbody tr {
            margin-bottom: 16px;
            border-radius: 16px;
            box-shadow: 0 12px 24px rgba(15, 23, 42, 0.08);
        }

        .campaign-table tbody td {
            padding: 14px 18px;
            position: relative;
        }

        .campaign-table tbody td::before {
            content: attr(data-label);
            display: block;
            margin-bottom: 6px;
            font-size: 12px;
            font-weight: 600;
            color: #94a3b8;
            text-transform: uppercase;
            letter-spacing: 0.06em;
        }

        .campaign-actions {
            justify-content: flex-start;
        }

        .filters-toolbar {
            flex-direction: column;
            align-items: stretch;
            padding: 12px;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="campaigns-container mt-5">
    <div class="header-actions">
        <div class="header-content" style="display: block;">
            <h2>Call Campaigns</h2>
            <p>Monitor campaign progress and launch new automations with ease.</p>
        </div>
        <div class="campaign-filters">

            <div class="filter-action">
                <button style="width: max-content;" type="button" class="action-button primary" onclick="showNewCampaignModal()">
                    <i class="fa-light fa-plus"></i> Create Campaign
                </button>
            </div>
        </div>
    </div>
    <!-- <div class="header-legend" style="margin-bottom: 20px;">
        <span class="legend-item"><span class="legend-dot success"></span>Completed</span>
        <span class="legend-item"><span class="legend-dot warning"></span>Pending</span>
        <span class="legend-item"><span class="legend-dot info"></span>In Progress</span>
        <span class="legend-item"><span class="legend-dot danger"></span>Failed</span>
        <span class="legend-item"><span class="legend-dot neutral"></span>Limit Reached</span>
    </div> -->
    <div class="filters-toolbar " style="margin-bottom: 10px;">
        <div class="filter-input">
            <label for="campaignSearch">Campaign</label>
            <div class="input-wrapper">
                <i class="fa-light fa-magnifying-glass"></i>
                <input type="text" id="campaignSearch" placeholder="Search campaign name">
            </div>
        </div>
        <div class="filter-input">
            <label for="statusFilter">Status</label>
            <div class="input-wrapper input-select">
                <i class="fa-light fa-signal-bars"></i>
                <select id="statusFilter">
                    <option value="all">All statuses</option>
                    <option value="pending">Pending</option>
                    <option value="in_progress">In Progress</option>
                    <option value="completed">Completed</option>
                    <option value="failed">Failed</option>
                    <option value="limit_reached">Limit Reached</option>
                </select>
            </div>
        </div>
        <div class="filter-input">
            <label for="dateFrom">From</label>
            <div class="input-wrapper">
                <i class="fa-light fa-calendar-day"></i>
                <input type="date" id="dateFrom">
            </div>
        </div>
        <div class="filter-input">
            <label for="dateTo">To</label>
            <div class="input-wrapper">
                <i class="fa-light fa-calendar-day"></i>
                <input type="date" id="dateTo">
            </div>
        </div>
        <div class="filter-action">
            <button id="refreshCompanies" class="btn btn-secondary">
                <i class="fa-light fa-rotate"></i>
                <span>Refresh</span>
            </button>
        </div>
    </div>

    <div class="limit-info">
        <i class="fa-light fa-phone-volume"></i>
        <span>
            {% if call_minute_limit is not none %}
            {% if call_minute_limit > 0 %}
            Plan allows <strong>{{ call_minute_limit }}</strong> minutes per 30-day cycle.
            Used so far: <strong>{{ used_minutes_readable }}</strong>.
            Remaining: <strong>{{ remaining_minutes_readable }}</strong>
            {% if remaining_days is not none %} ({{ remaining_days }} day{{ 's' if remaining_days != 1 else '' }}
            left).{% else %}.{% endif %}
            {% else %}
            Your current plan does not include outbound call minutes. Please upgrade to launch new campaigns.
            {% endif %}
            {% else %}
            Unlimited call minutes available. Used so far: <strong>{{ used_minutes_readable }}</strong>.
            {% endif %}
        </span>
    </div>
    <!-- Call Campaigns Table -->
    <div class="table-card">
        <div class="table-title-bar">
            <h3>Campaign Activity</h3>
            <div id="campaignsCount" class="table-count"></div>
        </div>
        <table class="campaign-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Campaign</th>
                    <th>Status</th>
                    <th>Total Calls</th>
                    <th>Completed</th>
                    <th>Failed</th>
                    <th>Created</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="campaignsList">
                <!-- Campaign rows will be rendered here by JS -->
            </tbody>
        </table>
    </div>
    <div class="table-footer">
        <div class="pagination-controls" id="campaignsPagination"></div>
    </div>
</div>

<!-- New Campaign Modal -->
<div id="newCampaignModal" class="import-modal">
    <div class="modal-content">
        <h3>Create New Call Campaign</h3>
        <form id="new-campaign-form">
            <!-- Contact Selection -->
            <div class="form-group">
                <label for="contact-select-modal">Select Contacts:</label>
                <select multiple="multiple" class="form-control" id="contact-select-modal">
                    {% for contact in contacts %}
                    <option value="{{ contact[0] }}">{{ contact[1] }} - {{ contact[2] }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="form-group">
                <label for="group-select-modal">Select Contact Groups (optional):</label>
                {% if contact_groups %}
                <select multiple="multiple" class="form-control" id="group-select-modal">
                    {% for group in contact_groups %}
                    <option value="{{ group[0] }}">{{ group[1] }}{% if group[2] %} ({{ group[2] }} contacts){% endif %}</option>
                    {% endfor %}
                </select>
                {% else %}
                <div class="text-muted" style="font-size: 13px;">
                    No contact groups yet. Create groups from the Contacts Groups page to reuse them here.
                </div>
                {% endif %}
            </div>

            <!-- Campaign Settings -->
            <div class="form-group">
                <label for="campaign-name-modal">Campaign Name:</label>
                <input type="text" class="form-control" id="campaign-name-modal" required>
            </div>
            <div class="form-group">
                <label for="call-script-modal">Call Script:</label>
                <textarea class="form-control" id="call-script-modal" rows="4" required></textarea>
            </div>
            <div class="form-group">
                <label for="retry-attempts-modal">Retry Attempts:</label>
                <input type="number" class="form-control" id="retry-attempts-modal" min="0" max="3" value="1">
            </div>
            <div class="form-group">
                <label for="retry-delay-modal">Retry Delay (minutes):</label>
                <input type="number" class="form-control" id="retry-delay-modal" min="5" max="60" value="30">
            </div>

            <div class="mt-3">
                <button type="button" onclick="hideNewCampaignModal()" style="border: none;"
                    class="action-button secondary">Cancel</button>
                <button type="button" class="action-button primary" id="submit-new-campaign">Create Campaign</button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-beta.1/js/select2.min.js"></script>
<script>
    const refreshButton = document.getElementById('refreshCompanies');
    function showNewCampaignModal() {
        document.getElementById('newCampaignModal').style.display = 'block';
        $('#contact-select-modal').select2({
            dropdownParent: $('#newCampaignModal .modal-content'),
            placeholder: "Select contacts...",
            allowClear: true
        });
        if ($('#group-select-modal').length) {
            $('#group-select-modal').select2({
                dropdownParent: $('#newCampaignModal .modal-content'),
                placeholder: "Select contact groups...",
                allowClear: true
            });
        }
    }

    function hideNewCampaignModal() {
        document.getElementById('newCampaignModal').style.display = 'none';
        document.getElementById('new-campaign-form').reset();
        $('#contact-select-modal').val(null).trigger('change');
        if ($('#contact-select-modal').data('select2')) {
            $('#contact-select-modal').select2('destroy');
        }
        if ($('#group-select-modal').length) {
            $('#group-select-modal').val(null).trigger('change');
            if ($('#group-select-modal').data('select2')) {
                $('#group-select-modal').select2('destroy');
            }
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('submit-new-campaign').addEventListener('click', async function () {
            const selectedContacts = $('#contact-select-modal').val() || [];
            const selectedGroups = $('#group-select-modal').length ? ($('#group-select-modal').val() || []) : [];

            if (selectedContacts.length === 0 && selectedGroups.length === 0) {
                alert('Please select at least one contact or group.');
                return;
            }

            const campaignData = {
                name: document.getElementById('campaign-name-modal').value,
                script: document.getElementById('call-script-modal').value,
                contacts: selectedContacts,
                contact_groups: selectedGroups,
                retry_attempts: document.getElementById('retry-attempts-modal').value,
                retry_delay: document.getElementById('retry-delay-modal').value
            };

            if (!campaignData.name || !campaignData.script) {
                alert('Please provide a campaign name and script.');
                return;
            }

            try {
                this.disabled = true;
                this.textContent = 'Creating...';

                const response = await fetch('/company/call-campaign/start', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(campaignData)
                });

                const data = await response.json();

                if (data.success) {
                    hideNewCampaignModal();
                    location.reload();
                } else {
                    alert(data.error || 'Failed to create campaign');
                }
            } catch (error) {
                alert('Error creating campaign');
            } finally {
                this.disabled = false;
                this.textContent = 'Create Campaign';
            }
        });
    });

    // Pass campaigns data to JS
    const campaignsDataRaw = JSON.parse('{{ campaigns_data|tojson|safe }}');

    const campaignsData = campaignsDataRaw.map(item => {
        const createdAt = item[3] ? new Date(item[3]) : null;
        return {
            id: item[0],
            name: item[1] || '',
            status: item[2] || '',
            createdAt,
            createdAtText: createdAt ? createdAt.toLocaleString('en-US', {
                year: 'numeric',
                month: 'short',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                hour12: true
            }) : '—',
            totalCalls: item[4] || 0,
            completed: item[5] || 0,
            failed: item[6] || 0,
        };
    });

    let campaignsPerPage = 10;
    let currentCampaignsPage = 1;
    const campaignsList = document.getElementById('campaignsList');
    const campaignsPagination = document.getElementById('campaignsPagination');
    const campaignsCount = document.getElementById('campaignsCount');

    const searchInput = document.getElementById('campaignSearch');
    const statusFilter = document.getElementById('statusFilter');
    const dateFromInput = document.getElementById('dateFrom');
    const dateToInput = document.getElementById('dateTo');

    function formatStatusClass(status) {
        if (!status) return 'status-pending';
        return `status-${status.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`;
    }

    function getFilteredCampaigns() {
        const query = (searchInput.value || '').trim().toLowerCase();
        const statusValue = (statusFilter.value || 'all').toLowerCase();
        let dateFrom = dateFromInput.value ? new Date(dateFromInput.value) : null;
        let dateTo = dateToInput.value ? new Date(dateToInput.value) : null;
        if (dateFrom && dateTo && dateFrom > dateTo) {
            const temp = dateFrom;
            dateFrom = dateTo;
            dateTo = temp;
        }
        if (dateTo) {
            dateTo.setHours(23, 59, 59, 999);
        }

        return campaignsData.filter(campaign => {
            const text = campaign.name.toLowerCase();
            const matchesText = !query || text.includes(query);

            const matchesStatus = statusValue === 'all' || campaign.status.toLowerCase() === statusValue;

            let matchesDate = true;
            if (dateFrom && campaign.createdAt) {
                matchesDate = matchesDate && campaign.createdAt >= dateFrom;
            }
            if (dateTo && campaign.createdAt) {
                matchesDate = matchesDate && campaign.createdAt <= dateTo;
            }

            return matchesText && matchesStatus && matchesDate;
        });
    }

    function renderCampaignsTable() {
        const filtered = getFilteredCampaigns();
        const totalPages = Math.max(1, Math.ceil(filtered.length / campaignsPerPage));
        if (currentCampaignsPage > totalPages) currentCampaignsPage = totalPages;
        const start = (currentCampaignsPage - 1) * campaignsPerPage;
        const end = start + campaignsPerPage;
        const pageCampaigns = filtered.slice(start, end);

        if (campaignsCount) {
            campaignsCount.textContent = `${filtered.length} campaign${filtered.length === 1 ? '' : 's'} found`;
        }

        if (pageCampaigns.length === 0) {
            campaignsList.innerHTML = `
                <tr>
                    <td colspan="8" class="text-center" style="padding: 48px 0; font-size: 16px; color: #94a3b8;">
                        No call campaigns found.
                    </td>
                </tr>
            `;
        } else {
            campaignsList.innerHTML = pageCampaigns.map((campaign, idx) => `
                <tr>
                    <td data-label="#">${start + idx + 1}</td>
                    <td data-label="Campaign">
                        <div class="campaign-meta">
                            <span class="campaign-name">${campaign.name}</span>
                        </div>
                    </td>
                    <td data-label="Status">
                        <span class="campaign-status-pill ${formatStatusClass(campaign.status)}">
                            <i class="fa-solid fa-circle"></i>
                            ${campaign.status}
                        </span>
                    </td>
                    <td data-label="Total Calls">
                        <div class="campaign-meta">
                            <span class="metric-value">${campaign.totalCalls}</span>
                            <span class="label-muted">TOTAL</span>
                        </div>
                    </td>
                    <td data-label="Completed">
                        <div class="campaign-meta">
                            <span class="metric-value"><i class="fa-regular fa-check-circle"></i> ${campaign.completed}</span>
                            <span class="label-muted">SUCCESS</span>
                        </div>
                    </td>
                    <td data-label="Failed">
                        <div class="campaign-meta">
                            <span class="metric-value"><i class="fa-regular fa-times-circle"></i> ${campaign.failed}</span>
                            <span class="label-muted">FAILED</span>
                        </div>
                    </td>
                    <td data-label="Created">${campaign.createdAtText}</td>
                    <td data-label="Actions">
                        <div class="campaign-actions">
                            <a href="/company/call-campaign/${campaign.id}/view" class="action-icon" title="View details">
                                <i class="fa-light fa-eye"></i>
                            </a>
                        </div>
                    </td>
                </tr>
            `).join('');
        }

        renderCampaignsPagination(filtered.length, totalPages);
    }

    function renderCampaignsPagination(totalItems, totalPages) {
        if (!campaignsPagination) return;
        if (totalPages <= 1) {
            campaignsPagination.innerHTML = '';
            return;
        }

        const prevDisabled = currentCampaignsPage === 1 ? 'disabled' : '';
        const nextDisabled = currentCampaignsPage === totalPages ? 'disabled' : '';
        campaignsPagination.innerHTML = `
            <button class="pagination-button" ${prevDisabled} onclick="changeCampaignsPage(-1)">Previous</button>
            <span style="align-self: center; color: #475569; font-weight: 600;">Page ${currentCampaignsPage} of ${totalPages}</span>
            <button class="pagination-button" ${nextDisabled} onclick="changeCampaignsPage(1)">Next</button>
        `;
    }

    function changeCampaignsPage(delta) {
        const filteredCount = getFilteredCampaigns().length;
        const totalPages = Math.max(1, Math.ceil(filteredCount / campaignsPerPage));
        currentCampaignsPage += delta;
        if (currentCampaignsPage < 1) currentCampaignsPage = 1;
        if (currentCampaignsPage > totalPages) currentCampaignsPage = totalPages;
        renderCampaignsTable();
    }
    window.changeCampaignsPage = changeCampaignsPage;

    [searchInput, statusFilter, dateFromInput, dateToInput].forEach(input => {
        if (input) {
            input.addEventListener('input', () => {
                currentCampaignsPage = 1;
                renderCampaignsTable();
            });
            if (input.type === 'date') {
                input.addEventListener('change', () => {
                    currentCampaignsPage = 1;
                    renderCampaignsTable();
                });
            }
        }
    });

    document.addEventListener('DOMContentLoaded', function () {
        renderCampaignsTable();
    });
    refreshButton.addEventListener('click', () => window.location.reload());
</script>
{% endblock %}