<?= $this->extend('layout/app') ?>

<?= $this->section('title') ?>Leads<?= $this->endSection() ?>
<?= $this->section('pageTitle') ?>Leads Management<?= $this->endSection() ?>

<?= $this->section('content') ?>

<?php
$currentStatusId = request()->getGet('status_id');
$statusColorsMap = [
    'gray'    => 'bg-slate-100 text-slate-700 border-slate-200',
    'blue'    => 'bg-blue-100 text-blue-700 border-blue-200',
    'green'   => 'bg-emerald-100 text-emerald-700 border-emerald-200',
    'yellow'  => 'bg-amber-100 text-amber-700 border-amber-200',
    'orange'  => 'bg-orange-100 text-orange-700 border-orange-200',
    'red'     => 'bg-red-100 text-red-700 border-red-200',
    'purple'  => 'bg-purple-100 text-purple-700 border-purple-200',
    'pink'    => 'bg-pink-100 text-pink-700 border-pink-200',
    'indigo'  => 'bg-indigo-100 text-indigo-700 border-indigo-200',
    'cyan'    => 'bg-cyan-100 text-cyan-700 border-cyan-200',
];
?>

<div class="glass rounded-2xl border border-white/60 shadow-sm mb-5 p-4">
    <div class="flex flex-wrap items-center justify-between gap-3">
        <div class="flex flex-wrap items-center gap-2">
            <span class="inline-flex items-center gap-1.5 text-xs font-medium text-slate-700 px-1">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 text-slate-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
                </svg>
                Filter by Status:
            </span>
            <a href="<?= esc(site_url('/agent/leads')) ?>" class="inline-flex items-center px-3 py-1.5 rounded-xl text-xs font-medium transition-all <?= empty($currentStatusId) ? 'bg-slate-900 text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50 hover:border-slate-300' ?>">
                All
                <span class="ml-1.5 inline-flex items-center justify-center w-4.5 h-4.5 rounded-full text-[10px] font-bold <?= empty($currentStatusId) ? 'bg-white/20 text-white' : 'bg-slate-100 text-slate-600' ?>"><?= count($leads) ?></span>
            </a>
            <?php foreach ($statuses as $status): ?>
                <?php $count = 0; foreach ($leads as $l) { if ((int)($l['status_id'] ?? 0) === (int)$status['id']) $count++; } ?>
                <?php
                    $colorKey = strtolower($status['color'] ?? 'gray');
                    $dotStyle = $statusColorsMap[$colorKey] ?? $statusColorsMap['gray'];
                ?>
                <a href="<?= esc(site_url('/agent/leads?status_id=' . $status['id'])) ?>" class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-medium transition-all <?= (string)$currentStatusId === (string)$status['id'] ? 'bg-slate-900 text-white shadow-md' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50 hover:border-slate-300' ?>">
                    <span class="inline-flex w-2 h-2 rounded-full border <?= $dotStyle ?>"></span>
                    <?= esc($status['name']) ?>
                    <span class="inline-flex items-center justify-center w-4.5 h-4.5 rounded-full text-[10px] font-bold <?= (string)$currentStatusId === (string)$status['id'] ? 'bg-white/20 text-white' : 'bg-slate-100 text-slate-600' ?>"><?= $count ?></span>
                </a>
            <?php endforeach; ?>
        </div>

        <div class="flex items-center gap-2.5">
            <div class="relative">
                <input type="text" id="leadSearch" placeholder="Search leads..." class="w-60 pl-9 pr-3.5 py-2 rounded-xl bg-white border border-slate-200 focus:border-blue-400 focus:ring-2 focus:ring-blue-100 outline-none text-xs transition-all placeholder:text-slate-500">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
            </div>
        </div>
    </div>
</div>

<div class="glass rounded-2xl border border-white/60 shadow-sm overflow-hidden">
    <div class="px-5 py-3 border-b border-slate-200/60 flex items-center justify-between">
        <h3 class="font-semibold text-slate-800 flex items-center gap-2 text-sm">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
            </svg>
            Leads List
        </h3>
        <span class="text-xs text-slate-500">Showing <?= count($leads) ?> lead<?= count($leads) !== 1 ? 's' : '' ?></span>
    </div>

    <div class="overflow-x-auto">
        <table class="w-full">
            <thead class="bg-slate-50/80">
                <tr>
                    <th class="text-left px-5 py-3 text-[10px] font-semibold text-slate-500 uppercase tracking-wider">Lead</th>
                    <th class="text-left px-5 py-3 text-[10px] font-semibold text-slate-500 uppercase tracking-wider">Contact</th>
                    <th class="text-left px-5 py-3 text-[10px] font-semibold text-slate-500 uppercase tracking-wider">Company</th>
                    <th class="text-left px-5 py-3 text-[10px] font-semibold text-slate-500 uppercase tracking-wider">Status</th>
                    <th class="text-left px-5 py-3 text-[10px] font-semibold text-slate-500 uppercase tracking-wider">Assigned To</th>
                    <th class="text-left px-5 py-3 text-[10px] font-semibold text-slate-500 uppercase tracking-wider">Created</th>
                    <th class="text-right px-5 py-3 text-[10px] font-semibold text-slate-500 uppercase tracking-wider">Actions</th>
                </tr>
            </thead>
            <tbody id="leadsTbody" class="divide-y divide-slate-100">
                <?php if (empty($leads)): ?>
                    <tr>
                        <td colspan="7" class="px-5 py-12 text-center">
                            <div class="w-12 h-12 mx-auto mb-3 rounded-xl bg-slate-100 flex items-center justify-center">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-slate-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                                </svg>
                            </div>
                            <p class="font-medium text-slate-700 text-sm">No leads found</p>
                            <p class="text-xs text-slate-500 mt-1">Try adjusting your filters or check back later.</p>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($leads as $lead): ?>
                        <?php
                            $colorKey = strtolower($lead['status_color'] ?? 'gray');
                            $badgeClass = $statusColorsMap[$colorKey] ?? $statusColorsMap['gray'];
                        ?>
                        <tr class="hover:bg-slate-50/60 transition-colors lead-row"
                            data-name="<?= esc(strtolower($lead['name'] ?? '')) ?>"
                            data-email="<?= esc(strtolower($lead['email'] ?? '')) ?>"
                            data-phone="<?= esc(strtolower($lead['phone'] ?? '')) ?>"
                            data-company="<?= esc(strtolower($lead['company_name'] ?? '')) ?>">
                            <td class="px-5 py-3.5">
                                <div class="flex items-center gap-2.5">
                                    <div class="w-8 h-8 rounded-lg bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white font-semibold text-xs shadow-sm">
                                        <?= strtoupper(substr(esc($lead['name'] ?? 'U'), 0, 1)) ?>
                                    </div>
                                    <div class="min-w-0">
                                        <div class="flex items-center gap-2">
                                            <p class="font-semibold text-slate-800 truncate text-sm"><?= esc($lead['name']) ?></p>
                                        </div>
                                        <p class="text-[11px] text-slate-500 font-mono"><?= esc($lead['lead_number']) ?></p>
                                    </div>
                                </div>
                            </td>
                            <td class="px-5 py-3.5">
                                <div class="space-y-1">
                                    <?php if (!empty($lead['email'])): ?>
                                        <div class="flex items-center gap-1.5 text-xs text-slate-600">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 text-slate-600 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                            </svg>
                                            <span class="truncate max-w-[200px]"><?= esc($lead['email']) ?></span>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (!empty($lead['phone'])): ?>
                                        <div class="flex items-center gap-1.5 text-xs text-slate-600">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 text-slate-600 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                            </svg>
                                            <span class="truncate max-w-[200px]"><?= esc($lead['phone']) ?></span>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (empty($lead['email']) && empty($lead['phone'])): ?>
                                        <span class="text-xs text-slate-500 italic">No contact info</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="px-5 py-3.5">
                                <div class="space-y-1">
                                    <?php if (!empty($lead['company_name'])): ?>
                                        <div class="flex items-center gap-1.5 text-xs text-slate-700 font-medium">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 text-slate-600 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                                            </svg>
                                            <span class="truncate max-w-[180px]"><?= esc($lead['company_name']) ?></span>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (!empty($lead['license_number'])): ?>
                                        <div class="flex items-center gap-1.5 text-[11px] text-slate-500">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 text-slate-600 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M10 6H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V8a2 2 0 00-2-2h-5m-4 0V5a2 2 0 114 0v1m-4 0a2 2 0 104 0" />
                                            </svg>
                                            <span class="truncate max-w-[180px]"><?= esc($lead['license_number']) ?></span>
                                        </div>
                                    <?php endif; ?>
                                    <?php if (empty($lead['company_name']) && empty($lead['license_number'])): ?>
                                        <span class="text-xs text-slate-500 italic">—</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="px-5 py-3.5">
                                <div class="relative inline-block status-picker"
                                     data-lead-id="<?= (int)($lead['id'] ?? 0) ?>"
                                     data-current-id="<?= (int)($lead['status_id'] ?? 0) ?>"
                                     data-endpoint="<?= esc(site_url('/agent/leads/status/' . (int)($lead['id'] ?? 0))) ?>">
                                    <button type="button" class="status-trigger inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-semibold border <?= $badgeClass ?> hover:ring-2 hover:ring-offset-1 hover:ring-slate-200 transition">
                                        <span class="w-1.5 h-1.5 rounded-full" style="background:<?= esc($lead['status_color'] ?? '#64748b') ?>"></span>
                                        <span class="status-label"><?= esc($lead['status_name'] ?? 'Unknown') ?></span>
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 opacity-60" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
                                        </svg>
                                    </button>
                                    <div class="status-menu hidden absolute left-0 mt-1.5 min-w-[170px] z-40 rounded-xl border border-slate-200 bg-white shadow-xl shadow-slate-900/10 p-1.5">
                                        <?php foreach ($statuses as $st): ?>
                                            <?php
                                                $ck = strtolower($st['color'] ?? 'gray');
                                                $stBadge = $statusColorsMap[$ck] ?? $statusColorsMap['gray'];
                                                $active = (int)($lead['status_id'] ?? 0) === (int)$st['id'];
                                            ?>
                                            <button type="button"
                                                    class="status-option w-full flex items-center gap-2 px-2.5 py-1.5 rounded-lg text-[11px] font-medium transition hover:bg-slate-50 <?= $active ? 'bg-slate-50' : '' ?>"
                                                    data-status-id="<?= (int)$st['id'] ?>"
                                                    data-status-name="<?= esc($st['name']) ?>"
                                                    data-status-color="<?= esc($st['color'] ?? '#64748b') ?>">
                                                <span class="inline-flex items-center px-2 py-0.5 rounded-md border text-[10px] font-semibold <?= $stBadge ?>">
                                                    <span class="w-1.5 h-1.5 rounded-full mr-1" style="background:<?= esc($st['color'] ?? '#64748b') ?>"></span>
                                                    <?= esc($st['name']) ?>
                                                </span>
                                                <?php if ($active): ?>
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 ml-auto text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
                                                        <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
                                                    </svg>
                                                <?php endif; ?>
                                            </button>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </td>
                            <td class="px-5 py-3.5">
                                <?php if (!empty($lead['assigned_name'])): ?>
                                    <div class="flex items-center gap-2">
                                        <div class="w-6 h-6 rounded-md bg-gradient-to-br from-emerald-400 to-cyan-500 flex items-center justify-center text-white text-[10px] font-bold shadow-sm">
                                            <?= strtoupper(substr(esc($lead['assigned_name']), 0, 1)) ?>
                                        </div>
                                        <span class="text-xs text-slate-700 font-medium"><?= esc($lead['assigned_name']) ?></span>
                                    </div>
                                <?php else: ?>
                                    <span class="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] font-medium bg-slate-100 text-slate-500 border border-slate-200">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
                                        </svg>
                                        Unassigned
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-5 py-3.5 text-xs text-slate-500">
                                <?= date('M j, Y', strtotime($lead['created_at'])) ?>
                            </td>
                            <td class="px-5 py-3.5 text-right">
                                <div class="inline-flex items-center gap-1.5">
                                    <a href="<?= esc(site_url('/agent/leads/book/' . (int) $lead['id'])) ?>" class="inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg bg-purple-600 text-white text-[11px] font-medium hover:bg-purple-700 transition-colors shadow-sm"
                                       title="Book assessment">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5" />
                                        </svg>
                                        Book
                                    </a>
                                    <button type="button" class="lead-call-btn inline-flex items-center gap-1 px-2.5 py-1.5 rounded-lg bg-emerald-600 text-white text-[11px] font-medium hover:bg-emerald-700 transition-colors shadow-sm"
                                            title="Call lead"
                                            data-lead-id="<?= (int) $lead['id'] ?>"
                                            data-lead-phone="<?= esc($lead['phone']) ?>"
                                            data-lead-name="<?= esc($lead['name']) ?>"
                                            data-lead-email="<?= esc($lead['email'] ?? '') ?>"
                                            data-lead-company="<?= esc($lead['company_name'] ?? '') ?>">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                        </svg>
                                        Call
                                    </button>
                                    <a href="<?= esc(site_url('/agent/leads/view/' . $lead['id'])) ?>" class="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg bg-slate-900 text-white text-[11px] font-medium hover:bg-slate-800 transition-colors shadow-sm">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                    </svg>
                                    View
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const searchInput = document.getElementById('leadSearch');
    if (!searchInput) return;
    searchInput.addEventListener('input', function () {
        const q = this.value.toLowerCase().trim();
        const rows = document.querySelectorAll('.lead-row');
        rows.forEach(row => {
            const name = row.getAttribute('data-name') || '';
            const email = row.getAttribute('data-email') || '';
            const phone = row.getAttribute('data-phone') || '';
            const company = row.getAttribute('data-company') || '';
            const show = q === '' || name.includes(q) || email.includes(q) || phone.includes(q) || company.includes(q);
            row.style.display = show ? '' : 'none';
        });
    });

    var INITIATE_URL = <?= json_encode(site_url('/leads/call/initiate')) ?>;
    document.addEventListener('click', function(e){
        var btn = e.target.closest && e.target.closest('.lead-call-btn');
        if (!btn) return;
        e.preventDefault();
        var leadId    = parseInt(btn.getAttribute('data-lead-id') || '0', 10);
        var phone     = btn.getAttribute('data-lead-phone') || '';
        var name      = btn.getAttribute('data-lead-name') || '';
        var email     = btn.getAttribute('data-lead-email') || '';
        var company   = btn.getAttribute('data-lead-company') || '';
        if (!phone) { alert('This lead has no phone number.'); return; }

        btn.disabled = true;
        btn.classList.add('opacity-60');
        var fd = new FormData();
        fd.append('lead_id', leadId);
        fd.append('phone',   phone);
        fd.append('name',    name);
        fd.append('email',   email);
        fd.append('company', company);
        fetch(INITIATE_URL, {
            method: 'POST',
            body: fd,
            credentials: 'same-origin',
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        }).then(function(r){ return r.json(); }).then(function(j){
            btn.disabled = false;
            btn.classList.remove('opacity-60');
            if (j && j.ok) {
                console.log('[CloudTalk Call] OK:', j);
                alert('Call initiated! Check your CloudTalk phone/softphone. Call ID: ' + (j.cloudtalk_call_id || 'n/a'));
            } else {
                var errText = (j && j.error) ? j.error : 'Unknown error';
                console.error('[CloudTalk Call] FAILED — full diagnostic: ', { response: j, errorText: errText });
                var pretty = String(errText).replace(/ Attempted variants \(/, "\n\nAttempted variants (").replace(/ — #/g, "\n#").replace(/ — All variants send/g, "\n\nAll variants send").replace(/ — If every variant/g, "\n\nIf every variant");
                alert('Failed to initiate CloudTalk call:\n\n' + pretty);
            }
        }).catch(function(err){
            btn.disabled = false;
            btn.classList.remove('opacity-60');
            console.error('[CloudTalk Call] Request exception:', err);
            alert('Request error: ' + err);
        });
    });

    (function initStatusPicker(){
        var STATUS_COLORS_MAP = {
            'gray':'bg-slate-100 text-slate-700 border-slate-200','blue':'bg-blue-100 text-blue-700 border-blue-200',
            'green':'bg-emerald-100 text-emerald-700 border-emerald-200','yellow':'bg-amber-100 text-amber-700 border-amber-200',
            'orange':'bg-orange-100 text-orange-700 border-orange-200','red':'bg-red-100 text-red-700 border-red-200',
            'purple':'bg-purple-100 text-purple-700 border-purple-200','pink':'bg-pink-100 text-pink-700 border-pink-200',
            'indigo':'bg-indigo-100 text-indigo-700 border-indigo-200','cyan':'bg-cyan-100 text-cyan-700 border-cyan-200',
            'slate':'bg-slate-100 text-slate-700 border-slate-200','emerald':'bg-emerald-100 text-emerald-700 border-emerald-200',
            'amber':'bg-amber-100 text-amber-700 border-amber-200','teal':'bg-emerald-100 text-emerald-700 border-emerald-200'
        };
        var COLOR_CLASSES = ['bg-slate-100','text-slate-700','border-slate-200','bg-blue-100','text-blue-700','border-blue-200','bg-emerald-100','text-emerald-700','border-emerald-200','bg-amber-100','text-amber-700','border-amber-200','bg-orange-100','text-orange-700','border-orange-200','bg-red-100','text-red-700','border-red-200','bg-purple-100','text-purple-700','border-purple-200','bg-pink-100','text-pink-700','border-pink-200','bg-indigo-100','text-indigo-700','border-indigo-200','bg-cyan-100','text-cyan-700','border-cyan-200'];
        function colorKeyFromHex(hex){
            if (!hex) return 'gray';
            var h = String(hex).replace('#','').trim().toLowerCase();
            if (h.length === 3) h = h.split('').map(function(c){return c+c;}).join('');
            if (!/^[0-9a-f]{6}$/.test(h)) return 'gray';
            var r = parseInt(h.substr(0,2),16), g = parseInt(h.substr(2,2),16), b = parseInt(h.substr(4,2),16);
            if (r > 180 && g < 120 && b < 120) return 'red';
            if (r > 200 && g > 120 && g < 190 && b < 100) return 'orange';
            if (r > 210 && g > 170 && b < 120) return 'amber';
            if (r > 210 && g > 210 && b < 140) return 'yellow';
            if (r < 120 && g > 160 && b < 120) return 'green';
            if (r < 130 && g > 180 && b > 170) return 'teal';
            if (r < 120 && g < 160 && b > 190) return 'blue';
            if (r < 110 && g < 120 && b > 180) return 'indigo';
            if (r > 140 && g < 140 && b > 170) return 'purple';
            if (r > 180 && g < 140 && b > 170) return 'pink';
            if (r < 110 && g > 170 && b > 190) return 'cyan';
            if (r < 140 && g < 140 && b < 140) return 'gray';
            return 'gray';
        }
        function getPortal(){
            var p = document.getElementById('status-menu-portal');
            if (!p) {
                p = document.createElement('div');
                p.id = 'status-menu-portal';
                document.body.appendChild(p);
            }
            return p;
        }
        function closeMenu(){
            var p = getPortal();
            p.innerHTML = '';
            p._picker = null;
        }
        function openMenuFor(picker){
            var portal = getPortal();
            var template = picker.querySelector('.status-menu');
            if (!template) return;
            var clone = template.cloneNode(true);
            clone.classList.remove('hidden');
            clone.classList.add('portal-menu');
            clone.style.position = 'fixed';
            clone.style.zIndex = '9999';
            clone.style.pointerEvents = 'auto';
            var trigger = picker.querySelector('.status-trigger');
            var tb = trigger.getBoundingClientRect();
            clone.style.top  = (tb.bottom + 6) + 'px';
            clone.style.left = tb.left + 'px';
            portal.innerHTML = '';
            portal.appendChild(clone);
            portal._picker = picker;
            var cb = clone.getBoundingClientRect();
            var pad = 8;
            var vpW = window.innerWidth || document.documentElement.clientWidth;
            var vpH = window.innerHeight || document.documentElement.clientHeight;
            if (cb.right + pad > vpW) clone.style.left = Math.max(pad, vpW - cb.width - pad) + 'px';
            if (cb.bottom + pad > vpH) clone.style.top = Math.max(pad, tb.top - cb.height - 6) + 'px';
        }
        function showToast(msg, type){
            type = type || 'success';
            var el = document.getElementById('lead-status-toast');
            if (!el) {
                el = document.createElement('div');
                el.id = 'lead-status-toast';
                el.className = 'fixed top-4 right-4 z-[100] pointer-events-none';
                document.body.appendChild(el);
            }
            var toast = document.createElement('div');
            var colors = type === 'error'
                ? 'bg-red-600 border-red-500 text-white'
                : (type === 'info' ? 'bg-slate-800 border-slate-700 text-white' : 'bg-emerald-600 border-emerald-500 text-white');
            toast.className = 'pointer-events-auto mb-2 px-4 py-2.5 rounded-xl border shadow-lg shadow-slate-900/10 flex items-center gap-2 text-xs font-medium transition-all transform translate-y-[-8px] opacity-0 ' + colors;
            toast.innerHTML = (type === 'success'
                ? '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" /></svg>'
                : (type === 'error'
                    ? '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>'
                    : '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5"><path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M12 2a10 10 0 100 20 10 10 0 000-20z" /></svg>'))
                + '<span class="leading-tight">' + msg + '</span>';
            el.appendChild(toast);
            requestAnimationFrame(function(){ toast.classList.remove('translate-y-[-8px]','opacity-0'); });
            setTimeout(function(){
                toast.classList.add('opacity-0','translate-y-[-8px]');
                setTimeout(function(){ if (toast.parentNode) toast.parentNode.removeChild(toast); }, 250);
            }, 2600);
        }
        function applyStatusToPicker(picker, id, name, color){
            var triggerEl = picker.querySelector('.status-trigger');
            if (!triggerEl) return;
            var dotEl = triggerEl.querySelector('.rounded-full');
            var labelEl = picker.querySelector('.status-label');
            picker.setAttribute('data-current-id', String(id || 0));
            if (labelEl) labelEl.textContent = name || 'Unknown';
            var hex = color || '#64748b';
            if (dotEl) dotEl.style.background = hex;
            triggerEl.style.background = hex + '20';
            triggerEl.style.color = hex;
            var ck = colorKeyFromHex(hex);
            var cls = STATUS_COLORS_MAP[ck] || STATUS_COLORS_MAP.gray;
            COLOR_CLASSES.forEach(function(c){ triggerEl.classList.remove(c); });
            cls.split(/\s+/).forEach(function(c){ if (c) triggerEl.classList.add(c); });
            picker.querySelectorAll('.status-option').forEach(function(o){
                var chk = o.querySelector('.text-emerald-600');
                var isActive = parseInt(o.getAttribute('data-status-id') || '0', 10) === (id || 0);
                o.classList.toggle('bg-slate-50', isActive);
                if (isActive && !chk) {
                    var icon = document.createElementNS('http://www.w3.org/2000/svg','svg');
                    icon.setAttribute('xmlns','http://www.w3.org/2000/svg');
                    icon.setAttribute('class','w-3.5 h-3.5 ml-auto text-emerald-600');
                    icon.setAttribute('fill','none');
                    icon.setAttribute('viewBox','0 0 24 24');
                    icon.setAttribute('stroke','currentColor');
                    icon.setAttribute('stroke-width','2.5');
                    icon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />';
                    o.appendChild(icon);
                } else if (!isActive && chk && chk.parentNode === o) {
                    o.removeChild(chk);
                }
            });
        }
        function safeParseJsonOrText(r){
            return r.text().then(function(t){
                var trimmed = (t || '').trim();
                if (!trimmed) return { _raw: '', _ok: r.ok, _status: r.status, ok: r.ok };
                if (/^\s*[\{\[]/.test(trimmed)) {
                    try { return Object.assign(JSON.parse(trimmed), { _raw: trimmed, _ok: r.ok, _status: r.status }); }
                    catch(e){ return { _raw: trimmed, _ok: r.ok, _status: r.status, ok: false, error: 'Invalid server reply (' + r.status + ')' }; }
                }
                var snippet = trimmed.length > 260 ? trimmed.substr(0, 260) + '\n…' : trimmed;
                return { _raw: trimmed, _ok: r.ok, _status: r.status, ok: false, error: snippet };
            });
        }
        window.addEventListener('scroll', function(){ if (getPortal()._picker) closeMenu(); }, true);
        window.addEventListener('resize', closeMenu, true);
        document.addEventListener('click', function(e){
            var portal = getPortal();
            var clickedInPortal = !!(e.target.closest && e.target.closest('#status-menu-portal'));
            var trigger = e.target.closest && e.target.closest('.status-trigger');
            var picker  = trigger ? trigger.closest('.status-picker') : (e.target.closest ? e.target.closest('.status-picker') : null);

            if (clickedInPortal) {
                var attachedPicker = portal._picker;
                if (!attachedPicker) { closeMenu(); return; }
                var opt = e.target.closest && e.target.closest('.status-option');
                if (opt) {
                    e.preventDefault();
                    e.stopPropagation();
                    var newId = parseInt(opt.getAttribute('data-status-id') || '0', 10);
                    var newName = opt.getAttribute('data-status-name') || '';
                    var newColor = opt.getAttribute('data-status-color') || '#64748b';
                    var currentId = parseInt(attachedPicker.getAttribute('data-current-id') || '0', 10);
                    if (!newId || newId === currentId) { closeMenu(); return; }
                    var endpoint = attachedPicker.getAttribute('data-endpoint') || '';
                    if (!endpoint) { showToast('Missing endpoint', 'error'); closeMenu(); return; }
                    var triggerEl = attachedPicker.querySelector('.status-trigger');
                    var labelEl = attachedPicker.querySelector('.status-label');
                    var prevInner = triggerEl ? triggerEl.innerHTML : '';
                    var prevCurrentId = currentId;
                    if (triggerEl) {
                        triggerEl.disabled = true;
                        triggerEl.classList.add('opacity-60','pointer-events-none','cursor-wait');
                    }
                    if (labelEl) labelEl.textContent = 'Saving…';
                    applyStatusToPicker(attachedPicker, newId, newName, newColor);
                    closeMenu();
                    var fd = new FormData();
                    fd.append('status_id', String(newId));
                    var csrfName  = <?= json_encode(csrf_token()) ?>;
                    var csrfValue = <?= json_encode(csrf_hash()) ?>;
                    if (csrfName) fd.append(csrfName, csrfValue);
                    fetch(endpoint, {
                        method: 'POST',
                        body: fd,
                        credentials: 'same-origin',
                        headers: { 'X-Requested-With': 'XMLHttpRequest' }
                    }).then(safeParseJsonOrText).then(function(j){
                        if (triggerEl) {
                            triggerEl.disabled = false;
                            triggerEl.classList.remove('opacity-60','pointer-events-none','cursor-wait');
                        }
                        if (j && j.ok) {
                            var got = (j && j.status) ? j.status : { id: newId, name: newName, color: newColor };
                            applyStatusToPicker(attachedPicker, ((got && got.id) || newId), ((got && got.name) || newName), ((got && got.color) || newColor));
                            showToast('Status saved: ' + ((got && got.name) || newName), 'success');
                        } else {
                            if (triggerEl && prevInner) triggerEl.innerHTML = prevInner;
                            attachedPicker.setAttribute('data-current-id', String(prevCurrentId));
                            var err = (j && j.error) ? j.error : ('Server replied with status ' + (j && j._status || 'unknown'));
                            console.error('[Status save] server response:', j);
                            showToast(err, 'error');
                        }
                    }).catch(function(err){
                        if (triggerEl) {
                            triggerEl.disabled = false;
                            triggerEl.classList.remove('opacity-60','pointer-events-none','cursor-wait');
                            if (prevInner) triggerEl.innerHTML = prevInner;
                        }
                        attachedPicker.setAttribute('data-current-id', String(prevCurrentId));
                        console.error('[Status save] request exception:', err);
                        showToast('Network error: ' + (err && err.message ? err.message : String(err)), 'error');
                    });
                    return;
                }
                return;
            }

            if (picker) {
                var inPortal = portal._picker === picker;
                if (trigger) {
                    e.preventDefault();
                    if (inPortal) closeMenu(); else openMenuFor(picker);
                    return;
                }
            }
            closeMenu();
        });
    })();
});
</script>

<?= $this->endSection() ?>
