<?php
// =============================================
// SHARK CRM - Audience Page (Improved)
// =============================================

$audience_list = $conn->query("
    SELECT a.*, u.name as creator_name,
           (SELECT COUNT(*) FROM audience_customers WHERE audience_id = a.id) as customers_count
    FROM audience a
    LEFT JOIN users u ON a.added_by = u.id
    WHERE a.account_id = $account_id OR a.account_id IS NULL
    ORDER BY a.date_created DESC
");

// Get initial batch of customers for the Add/Edit modal (first 30, rest loaded via AJAX)
$initial_customers = $conn->query("
    SELECT c.id, c.customer_name, c.business_name, c.phone, c.email, c.priority
    FROM customers c
    WHERE c.account_id = $account_id
    ORDER BY c.customer_name
    LIMIT 30
");

$initial_customers_data = [];
while ($c = $initial_customers->fetch_assoc()) {
    $initial_customers_data[] = $c;
}
?>

<div class="fade-in">
<div class="toolbar">
    <div class="search-wrap">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
        <input type="text" id="audienceSearch" placeholder="Search audiences...">
    </div>
    <button class="btn btn-primary" onclick="openAudienceModal()">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right: 6px;"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
        New Audience
    </button>
</div>

<div class="card">
    <div class="table-wrapper">
        <table class="crm-table" id="audienceTable">
            <thead>
                <tr>
                    <th>Audience Name</th>
                    <th>Description</th>
                    <th>Members</th>
                    <th>Status</th>
                    <th>Created By</th>
                    <th>Created</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($audience_list->num_rows === 0): ?>
                <tr><td colspan="7" class="text-center text-muted" style="padding:60px">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom: 12px;"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>
                    <p>No audiences created yet</p>
                    <button class="btn btn-primary btn-sm" onclick="openAudienceModal()">Create your first audience</button>
                </td></tr>
                <?php else: ?>
                <?php while($aud = $audience_list->fetch_assoc()): ?>
                <tr id="aud_<?= $aud['id'] ?>">
                    <td class="font-bold">
                        <div class="d-flex align-center gap-8">
                            <div class="avatar avatar-sm" style="background: var(--accent)22; color: var(--accent);">👥</div>
                            <?= htmlspecialchars($aud['name']) ?>
                        </div>
                    </td>
                    <td style="max-width: 250px;"><?= htmlspecialchars($aud['description'] ?: '—') ?></td>
                    <td>
                        <button class="btn-ghost-sm" onclick="viewAudienceMembers(<?= $aud['id'] ?>, '<?= addslashes($aud['name']) ?>')" style="display: inline-flex; align-items: center; gap: 6px;">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
                            <span class="badge badge-blue"><?= $aud['customers_count'] ?></span>
                        </button>
                    </td>
                    <td>
                        <span class="badge badge-<?= $aud['statuss'] ? 'green' : 'gray' ?> statuss-badge"
                              data-id="<?= $aud['id'] ?>" data-status="<?= $aud['statuss'] ?>"
                              onclick="toggleAudienceStatus(<?= $aud['id'] ?>, <?= $aud['statuss'] ?>)"
                              style="cursor:pointer">
                            <?= $aud['statuss'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </td>
                    <td class="text-muted text-sm"><?= htmlspecialchars($aud['creator_name'] ?? 'System') ?></td>
                    <td class="text-muted text-xs"><?= formatDate($aud['date_created']) ?></td>
                    <td>
                        <div class="action-buttons">
                            <button class="btn-icon-sm" onclick="editAudience(<?= $aud['id'] ?>)" title="Edit">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 3l4 4-7 7H10v-4l7-7z"></path><path d="M4 20h16"></path></svg>
                            </button>
                            <button class="btn-icon-sm" onclick="manageAudienceMembers(<?= $aud['id'] ?>, '<?= addslashes($aud['name']) ?>')" title="Manage Members">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
                            </button>
                            <button class="btn-icon-sm danger" onclick="deleteAudience(<?= $aud['id'] ?>)" title="Delete">
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endwhile; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
</div>

<!-- ===================== NICE CONFIRM MODAL ===================== -->
<div class="modal-overlay" id="confirmModal" style="z-index: 10000;">
    <div class="modal" style="max-width: 420px;">
        <div class="modal-header" style="border-bottom: none; padding-bottom: 0;">
            <span></span>
            <button class="modal-close" onclick="closeModal('confirmModal')">✕</button>
        </div>
        <div class="modal-body" style="text-align: center; padding: 8px 32px 24px;">
            <div id="confirmIcon" style="width: 56px; height: 56px; border-radius: 50%; background: #fee2e2; display: flex; align-items: center; justify-content: center; margin: 0 auto 16px;">
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#dc2626" stroke-width="2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
            </div>
            <h3 id="confirmTitle" style="margin: 0 0 8px; font-size: 17px;">Are you sure?</h3>
            <p id="confirmMessage" style="margin: 0; color: var(--text-muted); font-size: 14px; line-height: 1.5;">This action cannot be undone.</p>
        </div>
        <div class="modal-footer" style="justify-content: center; gap: 12px; padding-top: 0;">
            <button class="btn btn-secondary" onclick="closeModal('confirmModal')" style="min-width: 110px;">Cancel</button>
            <button class="btn btn-danger" id="confirmAcceptBtn" style="min-width: 110px;">Confirm</button>
        </div>
    </div>
</div>

<!-- ===================== ADD/EDIT AUDIENCE MODAL ===================== -->
<div class="modal-overlay" id="audienceModal">
    <div class="modal modal-lg" style="max-width: 940px;">
        <div class="modal-header">
            <span class="modal-title" id="audienceModalTitle">Create New Audience</span>
            <button class="modal-close">✕</button>
        </div>
        <div class="modal-body" style="padding-bottom: 8px;">
            <form id="audienceForm">
                <input type="hidden" name="audience_id" id="audienceId">
                <div class="form-grid" style="grid-template-columns: 1fr 1fr; gap: 12px;">
                    <div class="form-group span-2" style="margin-bottom: 0;">
                        <label class="form-label">Audience Name *</label>
                        <input type="text" name="name" id="audienceName" class="form-control" required placeholder="e.g., VIP Customers, Newsletter Subscribers">
                    </div>
                    <div class="form-group span-2" style="margin-bottom: 0;">
                        <label class="form-label">Description</label>
                        <textarea name="description" id="audienceDescription" class="form-control" rows="2" placeholder="Describe who belongs to this audience..."></textarea>
                    </div>
                    <div class="form-group" style="margin-bottom: 0;">
                        <label class="form-label">Status</label>
                        <select name="statuss" id="audienceStatus" class="form-control">
                            <option value="1">Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </div>
                </div>
            </form>

            <div class="hr" style="margin: 16px 0 14px;"></div>

            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                <h4 style="margin: 0; font-size: 14px;">Select Customers</h4>
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span id="addModal_selectedCount" style="font-size: 12px; color: var(--text-muted);"><strong>0</strong> selected</span>
                    <button type="button" class="btn-ghost-sm" onclick="clearAllSelections()">Clear All</button>
                    <div class="search-wrap" style="width: 220px;">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                        <input type="text" id="customerFilter" placeholder="Filter customers...">
                    </div>
                </div>
            </div>

            <!-- Customer Grid with Infinite Scroll -->
            <div id="customersGridScroll" style="max-height: 380px; overflow-y: auto; border: 1px solid var(--border); border-radius: 12px; background: var(--bg-card); padding: 12px;">
                <div id="customersGrid" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;">
                    <?php foreach ($initial_customers_data as $customer): ?>
                    <div class="customer-card" data-customer-id="<?= $customer['id'] ?>"
                         data-customer-name="<?= strtolower(htmlspecialchars($customer['customer_name'])) ?>"
                         data-business-name="<?= strtolower(htmlspecialchars($customer['business_name'] ?? '')) ?>"
                         style="border: 1px solid var(--border); border-radius: 8px; padding: 9px 11px; cursor: pointer; transition: all 0.2s; background: var(--bg-base);">
                        <div style="display: flex; align-items: start; gap: 8px;">
                            <input type="checkbox" name="selected_customers[]" value="<?= $customer['id'] ?>" class="customer-checkbox-input" style="width: 15px; height: 15px; cursor: pointer; margin-top: 2px; flex-shrink: 0;">
                            <div style="flex: 1; min-width: 0;">
                                <div style="display: flex; justify-content: space-between; align-items: start; gap: 4px;">
                                    <strong style="font-size: 12px; line-height: 1.3; word-break: break-word;"><?= htmlspecialchars($customer['customer_name']) ?></strong>
                                    <div style="font-size: 10px; flex-shrink: 0;"><?= renderStars($customer['priority']) ?></div>
                                </div>
                                <?php if($customer['business_name']): ?>
                                <div class="text-xs text-muted" style="font-size: 11px; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"><?= htmlspecialchars($customer['business_name']) ?></div>
                                <?php endif; ?>
                                <?php if($customer['phone']): ?>
                                <div class="text-muted" style="font-size: 10px; margin-top: 3px;">📞 <?= htmlspecialchars($customer['phone']) ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div id="customersGridLoader" style="text-align: center; padding: 10px; display: none;">
                    <div class="spinner" style="width: 20px; height: 20px; display: inline-block;"></div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeModal('audienceModal')">Cancel</button>
            <button class="btn btn-primary" onclick="saveAudience()">Save Audience</button>
        </div>
    </div>
</div>

<!-- ===================== MANAGE MEMBERS MODAL ===================== -->
<div class="modal-overlay" id="manageMembersModal">
    <div class="modal modal-lg" style="max-width: 1020px;">
        <div class="modal-header">
            <span class="modal-title" id="manageMembersTitle">Manage Audience Members</span>
            <button class="modal-close">✕</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="manageAudienceId">

            <div class="tabs" style="display: flex; gap: 8px; border-bottom: 1px solid var(--border); margin-bottom: 20px;">
                <button class="tab-btn active" onclick="switchMemberTab('current')">Current Members</button>
                <button class="tab-btn" onclick="switchMemberTab('add')">Add Members</button>
            </div>

            <!-- Current Members Tab -->
            <div id="currentMembersTab" class="tab-content active">
                <div id="currentMembersScroll" style="max-height: 520px; overflow-y: auto;">
                    <div id="currentMembersList">
                        <div class="text-center" style="padding: 40px;"><div class="spinner"></div></div>
                    </div>
                    <div id="currentMembersLoader" style="text-align: center; padding: 12px; display: none;">
                        <div class="spinner" style="width: 20px; height: 20px; display: inline-block;"></div>
                    </div>
                </div>
            </div>

            <!-- Add Members Tab -->
            <div id="addMembersTab" class="tab-content" style="display: none;">
                <div class="search-wrap" style="margin-bottom: 14px;">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                    <input type="text" id="addMemberSearch" placeholder="Search customers by name, business, phone or email...">
                </div>
                <div id="availableCustomersScroll" style="max-height: 480px; overflow-y: auto;">
                    <div id="availableCustomersList">
                        <div class="text-center" style="padding: 40px;"><div class="spinner"></div></div>
                    </div>
                    <div id="availableMembersLoader" style="text-align: center; padding: 12px; display: none;">
                        <div class="spinner" style="width: 20px; height: 20px; display: inline-block;"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeModal('manageMembersModal')">Close</button>
        </div>
    </div>
</div>

<!-- ===================== VIEW MEMBERS MODAL ===================== -->
<div class="modal-overlay" id="viewMembersModal">
    <div class="modal modal-lg" style="max-width: 800px; max-height: 80vh; overflow-y: auto;">
        <div class="modal-header">
            <span class="modal-title" id="viewMembersTitle">Audience Members</span>
            <button class="modal-close">✕</button>
        </div>
        <div class="modal-body" id="viewMembersBody" style="min-height: 200px;">
            <div class="text-center" style="padding: 40px;">
                <div class="spinner"></div>
                <p style="margin-top: 12px;">Loading members...</p>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeModal('viewMembersModal')">Close</button>
        </div>
    </div>
</div>

<style>
.customer-card {
    transition: all 0.15s ease;
}
.customer-card:hover {
    border-color: var(--accent) !important;
    background: var(--bg-hover) !important;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.customer-card.selected {
    border-color: var(--accent) !important;
    border-width: 2px !important;
    background: color-mix(in srgb, var(--accent) 6%, var(--bg-base)) !important;
}
.customer-card.selected .customer-checkbox-input {
    accent-color: var(--accent);
}
.btn-icon-sm {
    padding: 6px;
    background: transparent;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    color: var(--text-muted);
    transition: all 0.2s;
}
.btn-icon-sm:hover { background: var(--bg-secondary); color: var(--text); }
.btn-icon-sm.danger:hover { background: #fee2e2; color: #dc2626; }
.btn-ghost-sm {
    padding: 5px 10px;
    background: transparent;
    border: 1px solid var(--border);
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
    transition: background 0.15s;
}
.btn-ghost-sm:hover { background: var(--bg-secondary); }
.action-buttons { display: flex; gap: 4px; }
.member-card {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 12px;
    background: var(--bg-card);
    transition: all 0.15s;
    gap: 10px;
}
.member-card:hover {
    border-color: var(--accent);
    box-shadow: 0 2px 10px rgba(0,0,0,0.07);
}
.avail-customer-card {
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 12px;
    background: var(--bg-card);
    transition: all 0.15s;
}
.avail-customer-card:hover {
    border-color: var(--accent);
    box-shadow: 0 2px 8px rgba(0,0,0,0.07);
}
</style>

<script>
// ============================================================
// Helpers
// ============================================================
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function renderPriority(priority) {
    let stars = '';
    for (let i = 1; i <= 5; i++) {
        stars += `<span style="color:${i <= priority ? 'var(--yellow)' : 'var(--text-muted)'};">★</span>`;
    }
    return stars;
}

function debounce(func, wait) {
    let timeout;
    return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), wait);
    };
}

// ============================================================
// Nice Confirm Modal (replaces browser alert)
// ============================================================
let _confirmCallback = null;

function niceConfirm(message, onAccept, title = 'Are you sure?') {
    document.getElementById('confirmTitle').textContent = title;
    document.getElementById('confirmMessage').textContent = message;
    _confirmCallback = onAccept;
    document.getElementById('confirmAcceptBtn').onclick = () => {
        closeModal('confirmModal');
        if (_confirmCallback) _confirmCallback();
    };
    openModal('confirmModal');
}

// ============================================================
// Add/Edit Audience Modal — Customer Selection with Infinite Scroll
// ============================================================
let selectedCustomers = new Set();
let addModalOffset = <?= count($initial_customers_data) ?>;   // already rendered server-side
let addModalLoading = false;
let addModalAllLoaded = <?= count($initial_customers_data) < 30 ? 'true' : 'false' ?>; // no more pages if < 30 loaded
let addModalFilter = '';
let addModalFilterTimeout = null;

function updateSelectedCount() {
    const el = document.getElementById('addModal_selectedCount');
    if (el) el.innerHTML = `<strong>${selectedCustomers.size}</strong> selected`;
}

function clearAllSelections() {
    selectedCustomers.clear();
    document.querySelectorAll('.customer-checkbox-input').forEach(cb => {
        cb.checked = false;
        cb.closest('.customer-card')?.classList.remove('selected');
    });
    updateSelectedCount();
}

function openAudienceModal() {
    document.getElementById('audienceForm').reset();
    document.getElementById('audienceId').value = '';
    document.getElementById('audienceModalTitle').textContent = 'Create New Audience';

    // Reset infinite scroll state
    addModalOffset = <?= count($initial_customers_data) ?>;
    addModalAllLoaded = <?= count($initial_customers_data) < 30 ? 'true' : 'false' ?>;
    addModalFilter = '';
    document.getElementById('customerFilter').value = '';

    // Clear selections
    selectedCustomers.clear();
    document.querySelectorAll('.customer-checkbox-input').forEach(cb => {
        cb.checked = false;
        cb.closest('.customer-card')?.classList.remove('selected');
    });

    updateSelectedCount();
    openModal('audienceModal');
}

// Infinite scroll — Add/Edit modal
function setupAddModalInfiniteScroll() {
    const scrollEl = document.getElementById('customersGridScroll');
    if (!scrollEl) return;
    scrollEl.addEventListener('scroll', async function() {
        if (addModalLoading || addModalAllLoaded) return;
        if (this.scrollTop + this.clientHeight >= this.scrollHeight - 60) {
            await loadMoreAddModalCustomers();
        }
    });
}

async function loadMoreAddModalCustomers(reset = false) {
    if (addModalLoading) return;
    addModalLoading = true;

    const loader = document.getElementById('customersGridLoader');
    if (loader) loader.style.display = 'block';

    if (reset) {
        addModalOffset = 0;
        addModalAllLoaded = false;
    }

    const fd = new FormData();
    fd.append('action', 'search_customers_paged');
    fd.append('search', addModalFilter);
    fd.append('offset', addModalOffset);
    fd.append('limit', 30);

    const res = await apiCall('handlers/audience.php', fd);

    addModalLoading = false;

    if (!res.success) { if (loader) loader.style.display = 'none'; return; }

    const customers = res.customers || [];
    if (customers.length < 30) {
        addModalAllLoaded = true;
        if (loader) loader.style.display = 'none';
    }

    const grid = document.getElementById('customersGrid');
    if (reset) grid.innerHTML = '';

    customers.forEach(customer => {
        // Don't duplicate existing cards
        if (document.querySelector(`.customer-card[data-customer-id="${customer.id}"]`)) return;

        const card = document.createElement('div');
        card.className = 'customer-card';
        card.dataset.customerId = customer.id;
        card.dataset.customerName = (customer.customer_name || '').toLowerCase();
        card.dataset.businessName = (customer.business_name || '').toLowerCase();
        card.style.cssText = 'border: 1px solid var(--border); border-radius: 8px; padding: 9px 11px; cursor: pointer; transition: all 0.2s; background: var(--bg-base);';

        const isSelected = selectedCustomers.has(customer.id);
        card.innerHTML = `
            <div style="display: flex; align-items: start; gap: 8px;">
                <input type="checkbox" name="selected_customers[]" value="${customer.id}"
                       class="customer-checkbox-input"
                       style="width: 15px; height: 15px; cursor: pointer; margin-top: 2px; flex-shrink: 0;"
                       ${isSelected ? 'checked' : ''}>
                <div style="flex: 1; min-width: 0;">
                    <div style="display: flex; justify-content: space-between; align-items: start; gap: 4px;">
                        <strong style="font-size: 12px; line-height: 1.3; word-break: break-word;">${escapeHtml(customer.customer_name)}</strong>
                        <div style="font-size: 10px; flex-shrink: 0;">${renderPriority(customer.priority)}</div>
                    </div>
                    ${customer.business_name ? `<div class="text-muted" style="font-size: 11px; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${escapeHtml(customer.business_name)}</div>` : ''}
                    ${customer.phone ? `<div class="text-muted" style="font-size: 10px; margin-top: 3px;">📞 ${escapeHtml(customer.phone)}</div>` : ''}
                </div>
            </div>
        `;
        if (isSelected) card.classList.add('selected');
        grid.appendChild(card);
    });

    addModalOffset += customers.length;
}

// Filter customers in add/edit modal (re-fetch from server)
async function filterAddModalCustomers(term) {
    addModalFilter = term;
    addModalOffset = 0;
    addModalAllLoaded = false;

    const grid = document.getElementById('customersGrid');
    grid.innerHTML = `<div style="grid-column:1/-1; text-align:center; padding: 30px;"><div class="spinner"></div></div>`;

    const fd = new FormData();
    fd.append('action', 'search_customers_paged');
    fd.append('search', term);
    fd.append('offset', 0);
    fd.append('limit', 30);

    const res = await apiCall('handlers/audience.php', fd);
    grid.innerHTML = '';

    if (!res.success || !res.customers?.length) {
        grid.innerHTML = `<div style="grid-column:1/-1; text-align:center; color:var(--text-muted); padding:40px;">No customers found</div>`;
        addModalAllLoaded = true;
        document.getElementById('customersGridLoader').style.display = 'none';
        return;
    }

    const customers = res.customers;
    if (customers.length < 30) {
        addModalAllLoaded = true;
        document.getElementById('customersGridLoader').style.display = 'none';
    } else {
        document.getElementById('customersGridLoader').style.display = 'block';
    }

    customers.forEach(customer => {
        const card = document.createElement('div');
        card.className = 'customer-card';
        card.dataset.customerId = customer.id;
        card.dataset.customerName = (customer.customer_name || '').toLowerCase();
        card.dataset.businessName = (customer.business_name || '').toLowerCase();
        card.style.cssText = 'border: 1px solid var(--border); border-radius: 8px; padding: 9px 11px; cursor: pointer; transition: all 0.2s; background: var(--bg-base);';

        const isSelected = selectedCustomers.has(customer.id);
        card.innerHTML = `
            <div style="display: flex; align-items: start; gap: 8px;">
                <input type="checkbox" name="selected_customers[]" value="${customer.id}"
                       class="customer-checkbox-input"
                       style="width: 15px; height: 15px; cursor: pointer; margin-top: 2px; flex-shrink: 0;"
                       ${isSelected ? 'checked' : ''}>
                <div style="flex: 1; min-width: 0;">
                    <div style="display: flex; justify-content: space-between; align-items: start; gap: 4px;">
                        <strong style="font-size: 12px; line-height: 1.3; word-break: break-word;">${escapeHtml(customer.customer_name)}</strong>
                        <div style="font-size: 10px; flex-shrink: 0;">${renderPriority(customer.priority)}</div>
                    </div>
                    ${customer.business_name ? `<div class="text-muted" style="font-size: 11px; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${escapeHtml(customer.business_name)}</div>` : ''}
                    ${customer.phone ? `<div class="text-muted" style="font-size: 10px; margin-top: 3px;">📞 ${escapeHtml(customer.phone)}</div>` : ''}
                </div>
            </div>
        `;
        if (isSelected) card.classList.add('selected');
        grid.appendChild(card);
    });

    addModalOffset = customers.length;
}

// ============================================================
// Audience CRUD
// ============================================================
async function saveAudience() {
    const form = document.getElementById('audienceForm');
    const fd = new FormData(form);
    const audienceId = document.getElementById('audienceId').value;

    // Gather selected customers from the Set (not just visible checkboxes)
    // First sync visible checkboxes into the Set
    document.querySelectorAll('.customer-checkbox-input').forEach(cb => {
        const id = parseInt(cb.value);
        if (cb.checked) selectedCustomers.add(id);
        else selectedCustomers.delete(id);
    });

    selectedCustomers.forEach(customerId => fd.append('selected_customers[]', customerId));

    fd.append('action', audienceId ? 'edit' : 'add');
    if (audienceId) fd.append('audience_id', audienceId);

    const btn = document.querySelector('#audienceModal .btn-primary');
    const origText = btn.textContent;
    btn.textContent = 'Saving...';
    btn.disabled = true;

    const res = await apiCall('handlers/audience.php', fd);
    btn.textContent = origText;
    btn.disabled = false;

    if (res.success) {
        showToast(audienceId ? 'Audience updated!' : 'Audience created!', 'success');
        closeModal('audienceModal');
        setTimeout(() => location.reload(), 600);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function editAudience(id) {
    const res = await apiCall('handlers/audience.php', { action: 'get', id });
    if (!res.success) { showToast('Error loading audience', 'error'); return; }

    const data = res.data;
    document.getElementById('audienceId').value = data.id;
    document.getElementById('audienceName').value = data.name;
    document.getElementById('audienceDescription').value = data.description || '';
    document.getElementById('audienceStatus').value = data.statuss;
    document.getElementById('audienceModalTitle').textContent = 'Edit Audience';

    // Reset filter + scroll state
    addModalFilter = '';
    document.getElementById('customerFilter').value = '';
    addModalAllLoaded = false;

    // Fetch existing selected customers for this audience
    const customersRes = await apiCall('handlers/audience.php', { action: 'get_customers', audience_id: id });

    selectedCustomers.clear();
    if (customersRes.success && customersRes.customers) {
        customersRes.customers.forEach(c => selectedCustomers.add(parseInt(c.id)));
    }

    // Reload the first page of customers (re-renders the grid with correct checked state)
    addModalOffset = 0;
    addModalAllLoaded = false;

    const grid = document.getElementById('customersGrid');
    grid.innerHTML = `<div style="grid-column:1/-1; text-align:center; padding: 30px;"><div class="spinner"></div></div>`;

    const fd = new FormData();
    fd.append('action', 'search_customers_paged');
    fd.append('search', '');
    fd.append('offset', 0);
    fd.append('limit', 30);

    const pageRes = await apiCall('handlers/audience.php', fd);
    grid.innerHTML = '';

    const loader = document.getElementById('customersGridLoader');

    if (pageRes.success && pageRes.customers) {
        const customers = pageRes.customers;
        if (customers.length < 30) { addModalAllLoaded = true; loader.style.display = 'none'; }
        else loader.style.display = 'block';

        customers.forEach(customer => {
            const card = document.createElement('div');
            card.className = 'customer-card';
            card.dataset.customerId = customer.id;
            card.dataset.customerName = (customer.customer_name || '').toLowerCase();
            card.dataset.businessName = (customer.business_name || '').toLowerCase();
            card.style.cssText = 'border: 1px solid var(--border); border-radius: 8px; padding: 9px 11px; cursor: pointer; transition: all 0.2s; background: var(--bg-base);';

            const isSelected = selectedCustomers.has(parseInt(customer.id));
            card.innerHTML = `
                <div style="display: flex; align-items: start; gap: 8px;">
                    <input type="checkbox" name="selected_customers[]" value="${customer.id}"
                           class="customer-checkbox-input"
                           style="width: 15px; height: 15px; cursor: pointer; margin-top: 2px; flex-shrink: 0;"
                           ${isSelected ? 'checked' : ''}>
                    <div style="flex: 1; min-width: 0;">
                        <div style="display: flex; justify-content: space-between; align-items: start; gap: 4px;">
                            <strong style="font-size: 12px; line-height: 1.3; word-break: break-word;">${escapeHtml(customer.customer_name)}</strong>
                            <div style="font-size: 10px; flex-shrink: 0;">${renderPriority(customer.priority)}</div>
                        </div>
                        ${customer.business_name ? `<div class="text-muted" style="font-size: 11px; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${escapeHtml(customer.business_name)}</div>` : ''}
                        ${customer.phone ? `<div class="text-muted" style="font-size: 10px; margin-top: 3px;">📞 ${escapeHtml(customer.phone)}</div>` : ''}
                    </div>
                </div>
            `;
            if (isSelected) card.classList.add('selected');
            grid.appendChild(card);
        });

        addModalOffset = customers.length;
    }

    updateSelectedCount();
    openModal('audienceModal');
}

async function deleteAudience(id) {
    niceConfirm('This will permanently delete this audience and remove all customer associations.', async () => {
        const res = await apiCall('handlers/audience.php', { action: 'delete', id });
        if (res.success) {
            showToast('Audience deleted', 'success');
            document.getElementById(`aud_${id}`)?.remove();
        } else {
            showToast(res.message || 'Error', 'error');
        }
    }, 'Delete Audience?');
}

async function toggleAudienceStatus(id, currentStatus) {
    const newStatus = currentStatus ? 0 : 1;
    const res = await apiCall('handlers/audience.php', { action: 'toggle_status', id, status: newStatus });
    if (res.success) {
        showToast(`Audience ${newStatus ? 'activated' : 'deactivated'}`, 'success');
        const badge = document.querySelector(`.statuss-badge[data-id="${id}"]`);
        if (badge) {
            badge.textContent = newStatus ? 'Active' : 'Inactive';
            badge.className = `badge badge-${newStatus ? 'green' : 'gray'} statuss-badge`;
            badge.setAttribute('data-status', newStatus);
            badge.onclick = () => toggleAudienceStatus(id, newStatus);
        }
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

// ============================================================
// Manage Members — with infinite scroll & grid layout
// ============================================================
let currentMembersOffset = 0;
let currentMembersAllLoaded = false;
let currentMembersLoading = false;

let availMembersOffset = 0;
let availMembersAllLoaded = false;
let availMembersLoading = false;
let availMembersSearch = '';

async function manageAudienceMembers(audienceId, audienceName) {
    document.getElementById('manageAudienceId').value = audienceId;
    document.getElementById('manageMembersTitle').textContent = `Manage Members: ${audienceName}`;

    // Reset state
    currentMembersOffset = 0;
    currentMembersAllLoaded = false;
    availMembersOffset = 0;
    availMembersAllLoaded = false;
    availMembersSearch = '';
    document.getElementById('addMemberSearch').value = '';

    // Show current tab first
    switchMemberTab('current');
    await loadCurrentMembers(audienceId, true);
    await searchAvailableCustomers(audienceId, '', true);

    openModal('manageMembersModal');
}

function switchMemberTab(tab) {
    const currentTab = document.getElementById('currentMembersTab');
    const addTab = document.getElementById('addMembersTab');
    const tabs = document.querySelectorAll('.tab-btn');

    if (tab === 'current') {
        currentTab.style.display = 'block';
        addTab.style.display = 'none';
        tabs[0]?.classList.add('active');
        tabs[1]?.classList.remove('active');
    } else {
        currentTab.style.display = 'none';
        addTab.style.display = 'block';
        tabs[0]?.classList.remove('active');
        tabs[1]?.classList.add('active');
    }
}

async function loadCurrentMembers(audienceId, reset = false) {
    if (currentMembersLoading) return;
    currentMembersLoading = true;

    const container = document.getElementById('currentMembersList');
    const loader = document.getElementById('currentMembersLoader');

    if (reset) {
        currentMembersOffset = 0;
        currentMembersAllLoaded = false;
        container.innerHTML = `<div class="text-center" style="padding: 40px;"><div class="spinner"></div></div>`;
    }

    loader.style.display = 'block';

    const res = await apiCall('handlers/audience.php', {
        action: 'get_customers_paged',
        audience_id: audienceId,
        offset: currentMembersOffset,
        limit: 12
    });

    currentMembersLoading = false;
    loader.style.display = 'none';

    if (!res.success) {
        if (reset) container.innerHTML = `<div class="text-center" style="padding:40px; color:var(--text-muted);">Error loading members</div>`;
        return;
    }

    const customers = res.customers || [];

    if (reset) {
        if (customers.length === 0) {
            container.innerHTML = `
                <div class="text-center text-muted" style="padding: 60px;">
                    <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom: 12px;">
                        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                        <circle cx="9" cy="7" r="4"></circle>
                    </svg>
                    <p style="margin-bottom: 8px;">No members in this audience yet.</p>
                    <p class="text-sm">Switch to "Add Members" tab to add customers.</p>
                </div>
            `;
            currentMembersAllLoaded = true;
            return;
        }
        container.innerHTML = `<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;" id="currentMembersGrid"></div>`;
    }

    if (customers.length < 12) currentMembersAllLoaded = true;

    const grid = document.getElementById('currentMembersGrid');
    customers.forEach(customer => {
        const card = document.createElement('div');
        card.className = 'member-card';
        card.id = `member_${customer.id}`;
        card.innerHTML = `
            <div>
                <div style="display: flex; justify-content: space-between; align-items: start; gap: 6px; flex-wrap: wrap;">
                    <strong style="font-size: 13px; line-height: 1.3;">${escapeHtml(customer.customer_name)}</strong>
                    <div style="font-size: 11px;">${renderPriority(customer.priority)}</div>
                </div>
                ${customer.business_name ? `<div class="text-muted" style="font-size: 11px; margin-top: 3px;">🏢 ${escapeHtml(customer.business_name)}</div>` : ''}
                <div style="margin-top: 5px; font-size: 11px; color: var(--text-muted);">
                    ${customer.phone ? `📞 ${escapeHtml(customer.phone)}<br>` : ''}
                    ${customer.email ? `✉️ ${escapeHtml(customer.email)}` : ''}
                </div>
            </div>
            <button class="btn btn-danger btn-sm" style="width:100%; font-size:12px; padding: 5px 8px;"
                    onclick="removeMember(${audienceId}, ${customer.id})">Remove</button>
        `;
        grid?.appendChild(card);
    });

    currentMembersOffset += customers.length;
}

async function searchAvailableCustomers(audienceId, searchTerm, reset = false) {
    if (availMembersLoading) return;
    availMembersLoading = true;

    const container = document.getElementById('availableCustomersList');
    const loader = document.getElementById('availableMembersLoader');

    if (reset) {
        availMembersOffset = 0;
        availMembersAllLoaded = false;
        container.innerHTML = `<div class="text-center" style="padding: 40px;"><div class="spinner"></div></div>`;
    }

    loader.style.display = 'block';

    const res = await apiCall('handlers/audience.php', {
        action: 'search_customers_paged_excl',
        audience_id: audienceId,
        search: searchTerm,
        offset: availMembersOffset,
        limit: 12
    });

    availMembersLoading = false;
    loader.style.display = 'none';

    if (!res.success) {
        if (reset) container.innerHTML = `<div class="text-center" style="padding:40px; color:var(--text-muted);">Error loading customers</div>`;
        return;
    }

    const customers = res.customers || [];

    if (reset) {
        if (customers.length === 0) {
            container.innerHTML = `
                <div class="text-center text-muted" style="padding: 60px;">
                    <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom: 12px;">
                        <circle cx="12" cy="12" r="10"></circle>
                        <line x1="12" y1="8" x2="12" y2="12"></line>
                        <line x1="12" y1="16" x2="12.01" y2="16"></line>
                    </svg>
                    <p>${searchTerm ? 'No customers match your search.' : 'All customers are already in this audience.'}</p>
                </div>
            `;
            availMembersAllLoaded = true;
            return;
        }
        container.innerHTML = `<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;" id="availableCustomersGrid"></div>`;
    }

    if (customers.length < 12) availMembersAllLoaded = true;

    const grid = document.getElementById('availableCustomersGrid');
    customers.forEach(customer => {
        const card = document.createElement('div');
        card.className = 'avail-customer-card';
        card.id = `avail_${customer.id}`;
        card.innerHTML = `
            <div style="display: flex; justify-content: space-between; align-items: start; gap: 6px; flex-wrap: wrap;">
                <strong style="font-size: 13px;">${escapeHtml(customer.customer_name)}</strong>
                <div style="font-size: 11px;">${renderPriority(customer.priority)}</div>
            </div>
            ${customer.business_name ? `<div class="text-muted" style="font-size: 11px; margin-top: 2px;">🏢 ${escapeHtml(customer.business_name)}</div>` : ''}
            <div style="margin-top: 5px; font-size: 11px; color: var(--text-muted);">
                ${customer.phone ? `📞 ${escapeHtml(customer.phone)}<br>` : ''}
                ${customer.email ? `✉️ ${escapeHtml(customer.email)}` : ''}
            </div>
            <button class="btn btn-primary btn-sm" style="width:100%; font-size:12px; padding: 5px 8px; margin-top: 10px;"
                    onclick="addMember(${audienceId}, ${customer.id})">+ Add</button>
        `;
        grid?.appendChild(card);
    });

    availMembersOffset += customers.length;
}

async function addMember(audienceId, customerId) {
    const res = await apiCall('handlers/audience.php', {
        action: 'add_customer',
        audience_id: audienceId,
        customer_id: customerId
    });

    if (res.success) {
        showToast('Customer added to audience!', 'success');
        // Remove from available list
        document.getElementById(`avail_${customerId}`)?.remove();
        // Refresh current members
        await loadCurrentMembers(audienceId, true);
    } else {
        showToast(res.message || 'Error adding customer', 'error');
    }
}

async function removeMember(audienceId, customerId) {
    niceConfirm('Remove this customer from the audience?', async () => {
        const res = await apiCall('handlers/audience.php', {
            action: 'remove_customer',
            audience_id: audienceId,
            customer_id: customerId
        });

        if (res.success) {
            showToast('Customer removed from audience', 'success');
            document.getElementById(`member_${customerId}`)?.remove();
            // Refresh available list
            const searchTerm = document.getElementById('addMemberSearch').value;
            await searchAvailableCustomers(audienceId, searchTerm, true);
        } else {
            showToast(res.message || 'Error removing customer', 'error');
        }
    }, 'Remove Member?');
}

// ============================================================
// View Members (simple view modal — unchanged logic)
// ============================================================
async function viewAudienceMembers(audienceId, audienceName) {
    openModal('viewMembersModal');
    document.getElementById('viewMembersTitle').textContent = `Members: ${audienceName}`;
    document.getElementById('viewMembersBody').innerHTML = '<div class="text-center" style="padding: 40px;"><div class="spinner"></div><p style="margin-top: 12px;">Loading members...</p></div>';

    const res = await apiCall('handlers/audience.php', { action: 'get_customers', audience_id: audienceId });

    if (res.success && res.customers) {
        if (res.customers.length === 0) {
            document.getElementById('viewMembersBody').innerHTML = `
                <div class="text-center text-muted" style="padding: 60px;">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin-bottom: 12px;">
                        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                        <circle cx="9" cy="7" r="4"></circle>
                        <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                        <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                    </svg>
                    <p>No members in this audience</p>
                    <button class="btn btn-primary btn-sm" onclick="closeModal('viewMembersModal'); manageAudienceMembers(${audienceId}, '${escapeHtml(audienceName)}')">Add Members</button>
                </div>
            `;
        } else {
            let html = `
                <div style="margin-bottom: 16px; padding: 12px; background: var(--bg-secondary); border-radius: 8px;">
                    <strong>Total Members: ${res.customers.length}</strong>
                </div>
                <div style="display: flex; flex-direction: column; gap: 12px;">
            `;
            res.customers.forEach(customer => {
                html += `
                    <div style="padding: 14px; background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border);">
                        <div style="display: flex; justify-content: space-between; align-items: start; flex-wrap: wrap; gap: 12px;">
                            <div style="flex: 1;">
                                <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                                    <strong style="font-size: 15px;">${escapeHtml(customer.customer_name)}</strong>
                                    <div style="font-size: 13px;">${renderPriority(customer.priority)}</div>
                                </div>
                                ${customer.business_name ? `<div class="text-sm text-muted" style="margin-top: 4px;">🏢 ${escapeHtml(customer.business_name)}</div>` : ''}
                                <div style="margin-top: 6px; display: flex; gap: 14px; flex-wrap: wrap; font-size: 13px;">
                                    ${customer.phone ? `<span>📞 ${escapeHtml(customer.phone)}</span>` : ''}
                                    ${customer.email ? `<span>✉️ ${escapeHtml(customer.email)}</span>` : ''}
                                </div>
                            </div>
                            <button class="btn btn-secondary btn-sm" onclick="closeModal('viewMembersModal'); window.location.href='?page=customers&edit_id=${customer.id}'">View Customer</button>
                        </div>
                    </div>
                `;
            });
            html += `</div>
                <div style="margin-top: 16px; text-align: center;">
                    <button class="btn btn-primary" onclick="closeModal('viewMembersModal'); manageAudienceMembers(${audienceId}, '${escapeHtml(audienceName)}')">Manage Members</button>
                </div>
            `;
            document.getElementById('viewMembersBody').innerHTML = html;
        }
    } else {
        document.getElementById('viewMembersBody').innerHTML = `
            <div class="text-center" style="padding: 60px; color: var(--text-muted);">
                <p>Error loading members</p>
                <p class="text-sm">${res?.message || 'Please try again'}</p>
            </div>
        `;
    }
}

// ============================================================
// Event Listeners
// ============================================================
document.addEventListener('DOMContentLoaded', function() {

    // ── Add/Edit modal: checkbox + card selection sync ──
    const grid = document.getElementById('customersGrid');
    if (grid) {
        // Use event delegation on the scroll container
        document.getElementById('customersGridScroll')?.addEventListener('change', function(e) {
            if (e.target.classList.contains('customer-checkbox-input')) {
                const card = e.target.closest('.customer-card');
                const id = parseInt(e.target.value);
                if (e.target.checked) { selectedCustomers.add(id); card?.classList.add('selected'); }
                else { selectedCustomers.delete(id); card?.classList.remove('selected'); }
                updateSelectedCount();
            }
        });

        // Also make whole card clickable to toggle checkbox
        document.getElementById('customersGridScroll')?.addEventListener('click', function(e) {
            const card = e.target.closest('.customer-card');
            if (!card) return;
            if (e.target.classList.contains('customer-checkbox-input')) return; // already handled above
            const cb = card.querySelector('.customer-checkbox-input');
            if (cb) {
                cb.checked = !cb.checked;
                cb.dispatchEvent(new Event('change', { bubbles: true }));
            }
        });
    }

    // ── Add/Edit modal: filter input ──
    const filterInput = document.getElementById('customerFilter');
    if (filterInput) {
        filterInput.addEventListener('input', debounce(function() {
            filterAddModalCustomers(this.value.trim());
        }, 300));
    }

    // ── Add/Edit modal: infinite scroll ──
    setupAddModalInfiniteScroll();

    // ── Manage Members modal: current members infinite scroll ──
    document.getElementById('currentMembersScroll')?.addEventListener('scroll', function() {
        if (currentMembersLoading || currentMembersAllLoaded) return;
        if (this.scrollTop + this.clientHeight >= this.scrollHeight - 60) {
            const audienceId = document.getElementById('manageAudienceId').value;
            loadCurrentMembers(audienceId);
        }
    });

    // ── Manage Members modal: available customers infinite scroll ──
    document.getElementById('availableCustomersScroll')?.addEventListener('scroll', function() {
        if (availMembersLoading || availMembersAllLoaded) return;
        if (this.scrollTop + this.clientHeight >= this.scrollHeight - 60) {
            const audienceId = document.getElementById('manageAudienceId').value;
            searchAvailableCustomers(audienceId, availMembersSearch);
        }
    });

    // ── Manage Members modal: search input ──
    document.getElementById('addMemberSearch')?.addEventListener('input', debounce(function() {
        availMembersSearch = this.value.trim();
        const audienceId = document.getElementById('manageAudienceId').value;
        if (audienceId) searchAvailableCustomers(audienceId, availMembersSearch, true);
    }, 300));

    // ── Main table search ──
    document.getElementById('audienceSearch')?.addEventListener('input', function() {
        const q = this.value.toLowerCase();
        document.querySelectorAll('#audienceTable tbody tr').forEach(row => {
            if (row.cells) row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
        });
    });
});
</script>