<?php
require_once __DIR__ . '/../config/bootstrap.php';
$user = Auth::requireLogin();
$pageTitle = 'My Campaigns';
$activeNav = 'campaigns';
require __DIR__ . '/../includes/partials/dashboard-head.php';
?>

<div class="page-header">
    <div class="page-header-left">
        <h4>My Campaigns</h4>
        <p>All your beta testing campaigns in one place</p>
    </div>
    <div class="page-header-actions">
        <a href="/dashboard/campaigns/add" class="btn-primary-custom">
            <i class="bi bi-plus"></i> Add Campaign
        </a>
    </div>
</div>

<div class="content-wrapper">
    <!-- Filter chips -->
    <div class="d-flex gap-2 mb-3 flex-wrap" id="filterChips">
        <?php foreach ([
            'all'       => 'All',
            'active'    => 'Active',
            'review'    => 'In Review',
            'completed' => 'Completed',
            'rejected'  => 'Rejected',
        ] as $key => $label): ?>
            <button class="filter-chip <?= $key === 'all' ? 'active' : '' ?>" data-filter="<?= $key ?>">
                <?= e($label) ?>
            </button>
        <?php endforeach; ?>
    </div>

    <div class="campaign-list-card">
        <!-- Header row -->
        <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
            <div style="display:grid;grid-template-columns:2fr 1fr 1fr 1fr 48px;gap:12px;flex:1;min-width:300px;padding:0 14px">
                <span style="font-size:12px;color:var(--text-secondary);font-weight:500">App Details</span>
                <span style="font-size:12px;color:var(--text-secondary);font-weight:500">Active Tester</span>
                <span style="font-size:12px;color:var(--text-secondary);font-weight:500">Status</span>
                <span style="font-size:12px;color:var(--text-secondary);font-weight:500">Publishing Date</span>
                <span></span>
            </div>
            <div class="pagination-custom">
                <span id="pageDisplay">01/01</span>
                <button class="page-btn" id="prevPage" disabled><i class="bi bi-chevron-left"></i></button>
                <button class="page-btn" id="nextPage" disabled><i class="bi bi-chevron-right"></i></button>
            </div>
        </div>

        <div id="campaignsList">
            <div class="text-center py-5 text-muted">
                <div class="spinner-border spinner-border-sm me-2"></div> Loading…
            </div>
        </div>
    </div>
</div>

<style>
.filter-chip {
    background: white;
    border: 1.5px solid var(--card-border);
    color: var(--text-secondary);
    border-radius: 30px;
    padding: 8px 18px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.15s ease;
}
.filter-chip:hover { border-color: var(--primary); color: var(--primary); }
.filter-chip.active {
    background: var(--primary);
    border-color: var(--primary);
    color: white;
}
.badge-rejected {
    background: #FEE; color: var(--danger);
    padding: 4px 12px; border-radius: 20px;
    font-size: 11px; font-weight: 600;
}
</style>

<script>
(function () {
    let currentFilter = 'all';
    let currentPage = 1;
    let currentQuery = '';
    let typingTimer = null;

    function escapeHtml(s) {
        return String(s ?? '').replace(/[&<>"']/g, c =>
            ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));
    }

    function row(c) {
        const initial = c.app_title ? c.app_title.charAt(0).toUpperCase() : '?';
        const iconHtml = c.app_logo
            ? `<img src="${escapeHtml(c.app_logo)}" class="campaign-app-icon-placeholder" style="object-fit:cover" alt="">`
            : `<div class="campaign-app-icon-placeholder" style="background:linear-gradient(135deg,#1B7A43,#2D9B5A);color:white;font-weight:700">${initial}</div>`;
        return `
            <div class="campaign-row">
                ${iconHtml}
                <div class="flex-grow-1">
                    <div class="campaign-app-name">${escapeHtml(c.app_title)}</div>
                    <div class="campaign-app-dev">${escapeHtml(c.app_developer || '—')}</div>
                </div>
                <div style="min-width:100px;font-size:13px;color:var(--text-secondary)">
                    ${c.completed_users || 0}/${c.total_users || 0} Testers
                </div>
                <div style="min-width:90px"><span class="${escapeHtml(c.status_badge)}">${escapeHtml(c.status_label)}</span></div>
                <div style="min-width:90px;font-size:13px;color:var(--text-secondary)">${escapeHtml(c.created_at_human)}</div>
                <a href="${escapeHtml(c.detail_url)}" class="go-btn"><i class="bi bi-arrow-right"></i></a>
            </div>`;
    }

    async function load() {
        const list = document.getElementById('campaignsList');
        list.innerHTML = '<div class="text-center py-5 text-muted"><div class="spinner-border spinner-border-sm me-2"></div> Loading…</div>';
        try {
            const params = new URLSearchParams({ filter: currentFilter, page: currentPage, q: currentQuery });
            const resp = await window.api('/api/campaign/list?' + params.toString());
            if (resp.status !== 'success') throw new Error(resp.message);
            const d = resp.data;

            if (!d.campaigns.length) {
                list.innerHTML = `
                    <div class="text-center py-5">
                        <div style="font-size:48px">📭</div>
                        <p class="text-muted mt-2">${currentQuery ? 'No campaigns match your search.' : 'No campaigns in this category yet.'}</p>
                    </div>`;
            } else {
                list.innerHTML = d.campaigns.map(row).join('');
            }

            const pag = d.pagination;
            document.getElementById('pageDisplay').textContent =
                String(pag.page).padStart(2, '0') + '/' + String(pag.total_pages).padStart(2, '0');
            document.getElementById('prevPage').disabled = !pag.has_prev;
            document.getElementById('nextPage').disabled = !pag.has_next;
        } catch (err) {
            list.innerHTML = '<div class="text-center py-5 text-muted">Failed to load. Please refresh.</div>';
            console.error(err);
        }
    }

    // Filter chips
    document.querySelectorAll('.filter-chip').forEach(chip => {
        chip.addEventListener('click', function () {
            document.querySelectorAll('.filter-chip').forEach(c => c.classList.remove('active'));
            this.classList.add('active');
            currentFilter = this.dataset.filter;
            currentPage = 1;
            load();
        });
    });

    // Pagination
    document.getElementById('prevPage').addEventListener('click', () => { currentPage--; load(); });
    document.getElementById('nextPage').addEventListener('click', () => { currentPage++; load(); });

    // Search (debounced)
    const searchInput = document.getElementById('globalSearch');
    if (searchInput) {
        searchInput.addEventListener('input', function () {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(() => {
                currentQuery = this.value.trim();
                currentPage = 1;
                load();
            }, 300);
        });
    }

    load();
})();
</script>

<?php require __DIR__ . '/../includes/partials/dashboard-foot.php'; ?>
