<?php
$errors = session()->getFlashdata('errors') ?? [];
?>

<div class="space-y-6">
    <div class="glass rounded-2xl p-6 shadow-sm border border-slate-200/60">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div class="flex flex-col sm:flex-row sm:items-center gap-3">
                <form method="get" action="<?= site_url('/admin/leads') ?>" class="flex items-center gap-2">
                    <label class="text-sm font-medium text-slate-600">Filter by Status:</label>
                    <div class="relative">
                        <select name="status_id" onchange="this.form.submit()" class="appearance-none w-48 pl-4 pr-10 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition">
                            <option value="">All Statuses</option>
                            <?php foreach ($statuses as $s): ?>
                                <option value="<?= esc($s['id']) ?>" <?= ($selectedStatus == $s['id']) ? 'selected' : '' ?>>
                                    <?= esc($s['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-slate-400 absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none" 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>
                    </div>
                    <?php if (!empty($selectedStatus)): ?>
                        <a href="<?= site_url('/admin/leads') ?>" class="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-medium text-slate-600 hover:text-slate-800 bg-slate-100 hover:bg-slate-200 rounded-lg transition">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                            </svg>
                            Clear
                        </a>
                    <?php endif; ?>
                </form>
            </div>

            <a href="<?= site_url('/admin/leads/create') ?>" class="inline-flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-semibold rounded-xl shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
                </svg>
                Add Lead
            </a>
        </div>
    </div>

    <?php if (!empty($errors)): ?>
        <div class="glass rounded-2xl border border-red-200/70 bg-red-50/50 p-4">
            <ul class="list-disc list-inside text-sm text-red-700 space-y-1">
                <?php foreach ($errors as $e): ?>
                    <li><?= esc($e) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="bg-slate-50/70 border-b border-slate-200/60">
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Lead #</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Name</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Email</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Phone</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Company</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Assigned To</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Created</th>
                        <th class="px-6 py-3.5 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php if (empty($leads)): ?>
                        <tr>
                            <td colspan="9" class="px-6 py-16 text-center">
                                <div class="flex flex-col items-center gap-3">
                                    <div class="w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8 text-slate-400" 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="text-sm font-medium text-slate-600">No leads found</p>
                                    <p class="text-xs text-slate-400">Get started by creating your first lead</p>
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($leads as $lead): ?>
                            <tr class="hover:bg-slate-50/50 transition">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="text-sm font-mono font-semibold text-blue-600"><?= esc($lead['lead_number']) ?></span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="flex items-center gap-3">
                                        <div class="w-9 h-9 rounded-full 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']), 0, 1)) ?>
                                        </div>
                                        <span class="text-sm font-medium text-slate-800"><?= esc($lead['name']) ?></span>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php if (!empty($lead['email'])): ?>
                                        <span class="text-sm text-slate-600"><?= esc($lead['email']) ?></span>
                                    <?php else: ?>
                                        <span class="text-sm text-slate-300">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="text-sm text-slate-700"><?= esc($lead['phone']) ?></span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php if (!empty($lead['company_name'])): ?>
                                        <span class="text-sm text-slate-600"><?= esc($lead['company_name']) ?></span>
                                    <?php else: ?>
                                        <span class="text-sm text-slate-300">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <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('/admin/leads/status/' . (int)($lead['id'] ?? 0))) ?>">
                                        <button type="button" class="status-trigger inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold hover:ring-2 hover:ring-offset-1 hover:ring-slate-200 transition"
                                                style="background: <?= esc($lead['status_color'] ?? '#3b82f6') ?>20; color: <?= esc($lead['status_color'] ?? '#3b82f6') ?>;">
                                            <span class="w-1.5 h-1.5 rounded-full" style="background: <?= esc($lead['status_color'] ?? '#3b82f6') ?>;"></span>
                                            <span class="status-label"><?= esc($lead['status_name'] ?? 'No Status') ?></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-[190px] 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 $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 gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-semibold"
                                                          style="background: <?= esc($st['color'] ?? '#3b82f6') ?>20; color: <?= esc($st['color'] ?? '#3b82f6') ?>;">
                                                        <span class="w-1.5 h-1.5 rounded-full" style="background: <?= esc($st['color'] ?? '#3b82f6') ?>;"></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-6 py-4 whitespace-nowrap">
                                    <?php if (!empty($lead['assigned_name'])): ?>
                                        <div class="flex items-center gap-2">
                                            <div class="w-6 h-6 rounded-full bg-gradient-to-br from-emerald-400 to-cyan-500 flex items-center justify-center text-white text-[10px] font-semibold">
                                                <?= strtoupper(substr(esc($lead['assigned_name']), 0, 1)) ?>
                                            </div>
                                            <span class="text-sm text-slate-700"><?= esc($lead['assigned_name']) ?></span>
                                        </div>
                                    <?php else: ?>
                                        <span class="text-sm text-slate-300">Unassigned</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="text-xs text-slate-500"><?= !empty($lead['created_at']) ? date('M j, Y', strtotime($lead['created_at'])) : '—' ?></span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right">
                                    <div class="inline-flex items-center gap-1">
                                        <a href="<?= site_url('/admin/leads/book/' . (int)$lead['id']) ?>" class="p-2 rounded-lg text-slate-500 hover:text-purple-600 hover:bg-purple-50 transition" title="Book assessment">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                <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>
                                        </a>
                                        <button type="button" class="lead-call-btn p-2 rounded-lg text-slate-500 hover:text-emerald-600 hover:bg-emerald-50 transition"
                                                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-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                <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>
                                        </button>
                                        <a href="<?= site_url('/admin/leads/view/' . $lead['id']) ?>" class="p-2 rounded-lg text-slate-500 hover:text-blue-600 hover:bg-blue-50 transition" title="View">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                <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>
                                        </a>
                                        <a href="<?= site_url('/admin/leads/edit/' . $lead['id']) ?>" class="p-2 rounded-lg text-slate-500 hover:text-amber-600 hover:bg-amber-50 transition" title="Edit">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                            </svg>
                                        </a>
                                        <form method="get" action="<?= site_url('/admin/leads/delete/' . $lead['id']) ?>" onsubmit="return confirm('Are you sure you want to delete this lead?');" class="inline">
                                            <button type="submit" class="p-2 rounded-lg text-slate-500 hover:text-red-600 hover:bg-red-50 transition" title="Delete">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                                    <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                </svg>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
(function(){
    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; }

        var original = btn.innerHTML;
        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 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 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;
            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 prevStyleBg = triggerEl ? triggerEl.style.background : '';
                    var prevStyleCol = triggerEl ? triggerEl.style.color : '';
                    var prevText = labelEl ? labelEl.textContent : '';
                    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) {
                                triggerEl.style.background = prevStyleBg;
                                triggerEl.style.color = prevStyleCol;
                            }
                            if (labelEl) labelEl.textContent = prevText;
                            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');
                            triggerEl.style.background = prevStyleBg;
                            triggerEl.style.color = prevStyleCol;
                        }
                        if (labelEl) labelEl.textContent = prevText;
                        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>
