<?php
require_once __DIR__ . '/../config/bootstrap.php';
$user = Auth::requireLogin();

$campaignId = (int)($_GET['id'] ?? 0);
if ($campaignId <= 0) redirect('/dashboard/campaigns');

$pageTitle = 'Campaign Details';
$activeNav = 'campaigns';
$extraCss  = ['campaigns'];
require __DIR__ . '/../includes/partials/dashboard-head.php';
?>

<div class="content-wrapper" style="padding-top:8px">
    <div id="campaignDetailRoot">
        <div class="text-center py-5 text-muted">
            <div class="spinner-border me-2"></div> Loading campaign…
        </div>
    </div>
</div>

<style>
.tester-list-item {
    display: flex; align-items: center; gap: 12px; padding: 12px 0;
    border-bottom: 1px solid var(--card-border);
}
.tester-list-item:last-child { border-bottom: none; }
.tester-avatar {
    width: 40px; height: 40px; border-radius: 50%;
    background: linear-gradient(135deg,#1B7A43,#2D9B5A); color: white;
    display: flex; align-items: center; justify-content: center;
    font-weight: 700; font-size: 14px;
}
.tester-name { font-weight: 600; font-size: 14px; }
.tester-email { font-size: 12px; color: var(--text-secondary); }
.tester-action-btn {
    margin-left: auto; padding: 6px 14px; border: none; border-radius: 20px;
    font-size: 12px; font-weight: 600; cursor: pointer;
}
.tester-chat-btn { background: var(--bg-light-green); color: var(--primary); }
.tester-approve-btn { background: var(--primary); color: white; }
</style>

<script>
(async function () {
    const id = <?= $campaignId ?>;
    const root = document.getElementById('campaignDetailRoot');

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

    function testerRow(t) {
        return `
            <div class="tester-list-item">
                <div class="tester-avatar">${escapeHtml(t.initials)}</div>
                <div>
                    <div class="tester-name">${escapeHtml(t.name)}</div>
                    <div class="tester-email">${escapeHtml(t.email)}</div>
                </div>
                <span style="margin-left:auto;font-size:11px;color:var(--text-secondary);padding:4px 10px;background:#f8f8f8;border-radius:12px">
                    ${escapeHtml(t.status_label)}
                </span>
            </div>`;
    }

    try {
        const resp = await window.api('/api/campaign/details?id=' + id);
        if (resp.status !== 'success') throw new Error(resp.message);
        const c = resp.data.campaign;
        const testers = resp.data.testers;

        const initial = c.app_title ? c.app_title.charAt(0).toUpperCase() : '?';
        const iconHtml = c.app_logo
            ? `<img src="${escapeHtml(c.app_logo)}" class="campaign-big-icon" style="object-fit:cover" alt="">`
            : `<div class="campaign-big-icon" style="background:linear-gradient(135deg,#1B7A43,#2D9B5A);color:white;font-weight:800;font-size:32px">${initial}</div>`;

        root.innerHTML = `
            <div class="campaign-detail-layout">
                <div>
                    <div class="campaign-app-header">
                        ${iconHtml}
                        <div>
                            <div class="campaign-app-title">${escapeHtml(c.app_title)}</div>
                            <div class="campaign-app-dev-name">${escapeHtml(c.app_developer || '—')}</div>
                            <div style="margin-top:6px">
                                <span class="${escapeHtml(c.status_badge)}">${escapeHtml(c.status_label)}</span>
                                <span style="font-size:12px;color:var(--text-secondary);margin-left:8px">
                                    ${escapeHtml(c.plan_name)} Plan
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="campaign-list-card mb-3">
                        <div class="card-header-title" style="margin-bottom:16px">Campaign Details</div>
                        <div class="info-boxes-grid">
                            <div class="info-box">
                                <div class="info-box-icon green"><i class="bi bi-calendar-fill"></i></div>
                                <div>
                                    <div class="info-box-label">Created Date</div>
                                    <div class="info-box-value">${escapeHtml(c.created_at_human)}</div>
                                </div>
                            </div>
                            <div class="info-box">
                                <div class="info-box-icon blue"><i class="bi bi-clock-fill"></i></div>
                                <div>
                                    <div class="info-box-label">Testing Duration</div>
                                    <div class="info-box-value">${c.plan_testing_days} Days</div>
                                </div>
                            </div>
                            <div class="info-box">
                                <div class="info-box-icon green"><i class="bi bi-coin"></i></div>
                                <div>
                                    <div class="info-box-label">Reward / Tester</div>
                                    <div class="info-box-value">${c.total_reward} Coins</div>
                                </div>
                            </div>
                            <div class="info-box">
                                <div class="info-box-icon orange"><i class="bi bi-people-fill"></i></div>
                                <div>
                                    <div class="info-box-label">Testers Slot</div>
                                    <div class="info-box-value">${c.completed_users}/${c.total_users}</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="campaign-list-card">
                        <div class="card-header-title" style="margin-bottom:12px">Application Description</div>
                        <p style="font-size:14px;color:var(--text-secondary);line-height:1.8;white-space:pre-wrap">${escapeHtml(c.app_des || 'No description provided.')}</p>
                        ${c.app_pkg ? `<div style="margin-top:12px;font-size:12px;color:var(--text-muted)">Package: <code>${escapeHtml(c.app_pkg)}</code></div>` : ''}
                    </div>
                </div>

                <div class="right-panel">
                    <div class="tester-joined-card">
                        <div class="tj-label">Testers Joined</div>
                        <div class="tj-count">${c.active_testers}/${c.total_users}</div>
                    </div>

                    <div class="campaign-list-card" style="padding:16px">
                        <div class="card-header-title" style="margin-bottom:12px">
                            ${testers.length ? 'Tester List' : 'No Testers Yet'}
                        </div>
                        ${testers.length
                            ? testers.map(testerRow).join('')
                            : '<p class="text-muted text-center" style="font-size:13px;padding:20px 0">Testers will appear here once they apply.</p>'}
                        ${resp.data.can_start ? `
                            <div class="mt-3">
                                <button class="start-campaign-btn active-btn" id="startCampaignBtn">Start Campaign</button>
                            </div>` : ''}
                    </div>
                </div>
            </div>
        `;

        // Wire start button (Phase 6 will activate the API)
        const startBtn = document.getElementById('startCampaignBtn');
        if (startBtn) {
            startBtn.addEventListener('click', () => {
                window.Toast && window.Toast.fire({ icon: 'info', title: 'Campaign start API arrives in Phase 6.' });
            });
        }
    } catch (err) {
        root.innerHTML = `
            <div class="text-center py-5">
                <div style="font-size:48px">⚠️</div>
                <p class="text-muted mt-2">Could not load campaign. ${escapeHtml(err.message || '')}</p>
                <a href="/dashboard/campaigns" class="btn-primary-custom" style="display:inline-flex;margin-top:12px">
                    <i class="bi bi-arrow-left"></i> Back to Campaigns
                </a>
            </div>`;
    }
})();
</script>

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