<?php
// Contenido del módulo Escritorios para el layout corporativo
?>
<div class="roles-header">
    <div class="header-left">
        <h1 class="page-title">
            <svg class="title-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="3" y="7" width="18" height="11" rx="2"/>
                <path d="M7 7V4h10v3"/>
            </svg>
            Gestión de Escritorios
        </h1>
        <p class="page-subtitle">Organiza escritorios, usuarios y capacidad operativa.</p>
    </div>
    <div class="header-actions">
        <button type="button" class="btn-primary" onclick="openDeskCreateWizard()">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="12" y1="5" x2="12" y2="19"/>
                <line x1="5" y1="12" x2="19" y2="12"/>
            </svg>
            Nuevo Escritorio
        </button>
    </div>
</div>

<!-- Estadísticas rápidas (estilo corporativo) -->
<div class="stats-grid">
    <?php
    $desks = is_array($desks) ? $desks : [];
    $total_desks = count($desks);
    $active_desks = count(array_filter($desks, function($d) { return ($d['status'] ?? '') === 'active'; }));
    $total_desk_users = array_sum(array_column($desks, 'total_users'));
    $total_desk_leads = array_sum(array_column($desks, 'total_leads'));
    ?>
    <div class="stat-card">
        <div class="stat-icon bg-blue-500">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="3" y="7" width="18" height="11" rx="2"/>
                <path d="M7 7V4h10v3"/>
            </svg>
        </div>
        <div class="stat-content">
            <div class="stat-number" id="total-desks-num"><?php echo number_format($total_desks); ?></div>
            <div class="stat-label">Total Escritorios</div>
        </div>
    </div>

    <div class="stat-card">
        <div class="stat-icon bg-green-500">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M9 12l2 2 4-4"/>
                <circle cx="12" cy="12" r="10"/>
            </svg>
        </div>
        <div class="stat-content">
            <div class="stat-number" id="active-desks-num"><?php echo number_format($active_desks); ?></div>
            <div class="stat-label">Activos</div>
        </div>
    </div>

    <div class="stat-card">
        <div class="stat-icon bg-teal-500">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M16 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                <circle cx="9" cy="7" r="4"/>
            </svg>
        </div>
        <div class="stat-content">
            <div class="stat-number" id="total-users-num"><?php echo number_format($total_desk_users); ?></div>
            <div class="stat-label">Usuarios Asignados</div>
        </div>
    </div>

    <div class="stat-card">
        <div class="stat-icon bg-yellow-500">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="22,12 18,12 15,21 9,3 6,12 2,12"/>
            </svg>
        </div>
        <div class="stat-content">
            <div class="stat-number" id="total-leads-num"><?php echo number_format($total_desk_leads); ?></div>
            <div class="stat-label">Leads Totales</div>
        </div>
    </div>
</div>

<?php if (empty($desks)): ?>
    <div class="empty-state">
        <div class="empty-icon">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="3" y="7" width="18" height="11" rx="2"/>
                <path d="M7 7V4h10v3"/>
            </svg>
        </div>
        <h3>No hay escritorios creados</h3>
        <p>Crea tu primer escritorio para empezar a organizar equipos.</p>
        <a class="btn-primary" href="?module=desks&action=create">Crear Escritorio</a>
    </div>
<?php else: ?>
    <div class="roles-grid">
        <?php foreach ($desks as $desk): ?>
            <div class="role-card" data-desk-id="<?php echo (int)$desk['id']; ?>">
                <div class="role-header">
                    <div class="role-info">
                        <h3 class="role-name"><?php echo htmlspecialchars($desk['name']); ?></h3>
                        <p class="role-description clamp-2">
                            <?php echo htmlspecialchars($desk['description'] ?: 'Sin descripción'); ?>
                        </p>
                        <?php 
                            $managerName = $desk['manager_name'] ? htmlspecialchars($desk['manager_name']) : 'Sin asignar';
                            $managerInitial = strtoupper(substr($desk['manager_name'] ?: 'S', 0, 1));
                            $statusText = ucfirst($desk['status']);
                            $statusClass = ($desk['status'] === 'active') ? 'status-active' : (($desk['status'] === 'suspended') ? 'status-suspended' : 'status-inactive');
                        ?>
                        <div class="role-meta">
                            <div class="manager-chip" title="Manager del escritorio">
                                <div class="avatar-mini"><?php echo $managerInitial; ?></div>
                                <div class="chip-text">
                                    <span class="chip-label">Manager</span>
                                    <span class="chip-value <?php echo $desk['manager_name'] ? '' : 'text-muted'; ?>"><?php echo $managerName; ?></span>
                                </div>
                            </div>
                            <div class="status-pill <?php echo $statusClass; ?>" title="Estado del escritorio">
                                <span class="pill-dot"></span>
                                <span class="pill-text"><?php echo $statusText; ?></span>
                            </div>
                        </div>
                    </div>
                    <div class="role-actions">
                        <button class="action-btn" type="button" title="Usuarios" onclick="openDeskUsersModal(<?php echo $desk['id']; ?>, '<?php echo htmlspecialchars($desk['name']); ?>')">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                        </button>
                        <button class="action-btn edit" type="button" title="Editar" onclick="openDeskEditModal(<?php echo $desk['id']; ?>, '<?php echo htmlspecialchars($desk['name']); ?>')">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>
                        </button>
                        <button class="action-btn" type="button" title="Estados del Desk" onclick="openDeskStatusesModal(<?php echo $desk['id']; ?>, '<?php echo htmlspecialchars($desk['name']); ?>')">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
                        </button>
                        <button class="action-btn delete" type="button" title="Eliminar" onclick="openDeskDeleteModal(<?php echo $desk['id']; ?>, '<?php echo htmlspecialchars($desk['name']); ?>')">
                            <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"/><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"/></svg>
                        </button>
                    </div>
                </div>
                <div class="role-stats">
                    <div class="stat-item">
                        <span class="stat-value"><?php echo (int)$desk['total_users']; ?></span>
                        <span class="stat-text">usuarios</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-value"><?php echo (int)$desk['total_leads']; ?></span>
                        <span class="stat-text">leads</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-value"><?php echo (int)($desk['total_statuses'] ?? 0); ?></span>
                        <span class="stat-text">estados</span>
                    </div>
                </div>
                <div class="role-permissions-preview">
                    <div class="permissions-tags">
                        <span class="permission-tag">Horario: <?php echo htmlspecialchars($desk['working_hours_start']); ?> - <?php echo htmlspecialchars($desk['working_hours_end']); ?></span>
                        <span class="permission-tag">ID: <?php echo (int)$desk['id']; ?></span>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>


<style>
    .badge { padding: 0.25rem 0.5rem; border-radius: 3px; font-size: 0.8rem; font-weight: 500; }
    .badge-active { background: #28a745; color: white; }
    .badge-inactive { background: #6c757d; color: white; }
    .badge-suspended { background: #dc3545; color: white; }
    .text-muted { color: #6c757d; }
    .card-body { overflow-x: auto; }
    .table th, .table td { white-space: nowrap; }
    /* Reutilizamos estilos de Roles para tarjetas */
    .roles-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 16px; }
    .role-card { background: var(--bg-primary); border: 1px solid var(--border-light); border-radius: 14px; box-shadow: var(--shadow-md); overflow: hidden; transition: transform .15s ease, box-shadow .15s ease; }
    .role-card:hover { transform: translateY(-2px); box-shadow: var(--shadow-lg); }
    .role-header { display:flex; align-items:center; justify-content:space-between; gap:12px; padding: 14px 16px; background: var(--gradient-secondary); border-bottom: 1px solid var(--border-light); }
    .role-info { flex: 1 1 auto; max-width: none; display:flex; flex-direction:column; gap:6px; }
    .role-name { font-size: 1.05rem; font-weight: 600; color: var(--text-primary); margin: 0; }
    .role-description { font-size: .88rem; color: var(--text-muted); margin-top: 4px; }
    .clamp-2 { display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
    .role-meta { display:flex; gap:10px; align-items:center; justify-content:flex-start; margin-top:6px; flex-wrap: nowrap; }
    .manager-chip { display:flex; align-items:center; gap:8px; background: var(--bg-secondary); border:1px solid var(--border-light); border-radius: 999px; padding: 6px 10px; }
    .avatar-mini { width:22px; height:22px; border-radius:50%; background: var(--primary-blue); color:#fff; display:flex; align-items:center; justify-content:center; font-size:.8rem; font-weight:600; }
    .chip-text { display:flex; gap:6px; align-items:center; }
    .chip-label { color: var(--text-secondary); font-size:.8rem; }
    .chip-value { color: var(--text-primary); font-weight:600; font-size:.85rem; }
    .status-pill { display:inline-flex; align-items:center; gap:8px; border-radius:999px; padding: 6px 10px; font-weight:600; border:1px solid var(--border-light); }
    .status-pill .pill-dot { width:8px; height:8px; border-radius:50%; display:inline-block; }
    .status-active { background:#ecfdf5; color:#065f46; border-color:#a7f3d0; }
    .status-active .pill-dot { background:#10b981; }
    .status-inactive { background:#f3f4f6; color:#374151; border-color:#e5e7eb; }
    .status-inactive .pill-dot { background:#9ca3af; }
    .status-suspended { background:#fef2f2; color:#7f1d1d; border-color:#fecaca; }
    .status-suspended .pill-dot { background:#ef4444; }
    .role-actions { order: 2; display:flex; align-items:center; gap:10px; margin-left:0; width:100%; justify-content:flex-end; margin-top:12px; flex-direction: row-reverse; }
    .action-btn { display:inline-flex; align-items:center; justify-content:center; width:34px; height:34px; border-radius:10px; border:1px solid var(--border-light); background:#fff; color: var(--text-secondary); cursor:pointer; transition: background .15s ease, color .15s ease, transform .15s ease; }
    .action-btn:hover { background: var(--bg-tertiary); color: var(--primary-blue); transform: translateY(-1px); }
    .action-btn.edit svg { stroke: currentColor; }
    .action-btn.delete { color: var(--danger); }
    .role-stats { display:flex; gap: 16px; padding: 12px 16px; }
    .stat-item { display:flex; align-items:center; gap:8px; background: var(--bg-secondary); border:1px solid var(--border-light); border-radius: 10px; padding: 8px 10px; }
    .stat-value { font-weight: 700; color: var(--primary-blue); }
    .stat-text { color: var(--text-secondary); font-size: .85rem; }
    .role-permissions-preview { padding: 8px 16px 16px; }
    .permissions-tags { display:flex; flex-wrap:wrap; gap:8px; }
    .permission-tag { display:inline-block; padding: 6px 10px; font-size:.82rem; color: var(--primary-blue-dark); background: #eef2ff; border: 1px solid #e0e7ff; border-radius: 999px; }
    @media (max-width: 768px) { .roles-header { padding: 1.5rem 1rem; } }

    /* Responsivo para que las tarjetas no se corten */
    .role-card { display: flex; flex-direction: column; }
    .role-header { flex-wrap: wrap; }
    .role-info { max-width: 100%; flex: 1 1 auto; }
    .role-actions { flex: 0 0 auto; }
    .role-stats { flex-wrap: wrap; }
    .stat-item { flex: 1 1 120px; }
    .permissions-tags { flex-wrap: wrap; }
    .permission-tag { white-space: normal; overflow-wrap: anywhere; }

    @media (max-width: 1024px) {
        .roles-grid { grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); }
    }
    @media (max-width: 768px) {
        .roles-grid { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); }
        .role-header { flex-wrap: wrap; }
        .role-actions { order: 3; width: 100%; justify-content: flex-end; margin-top: 12px; flex-direction: row-reverse; }
        .role-meta { justify-content:flex-start; flex-wrap: wrap; }
    }
    @media (max-width: 480px) {
        .roles-grid { grid-template-columns: 1fr; }
        .stat-item { flex: 1 1 100px; }
    }
    /* Wizard premium touches */
    .wizard-steps { display:flex; align-items:center; gap:8px; margin-bottom:8px; }
    .wizard-steps .step { background: var(--bg-secondary); border:1px solid var(--border-light); border-radius: 999px; padding: 6px 10px; font-weight:600; color: var(--text-secondary); }
    .wizard-steps .step.current { color: var(--text-primary); border-color: var(--primary-blue); }
    .field-hint { font-size: 12px; color: #64748b; margin-top: 4px; min-height: 16px; }
    #dw_name.invalid, #dw_status.invalid, #dw_manager_id.invalid, #dw_wh_start.invalid, #dw_wh_end.invalid { border-color: #ef4444; box-shadow: 0 0 0 3px rgba(239,68,68,.12); }
    .preset-row { display:flex; gap:12px; align-items:center; margin: 8px 0; }
    .preset-row select { min-width: 180px; }
    .status-create-row { display:grid; grid-template-columns: 1fr 1fr auto auto; gap:12px; align-items:end; margin: 8px 0 12px; }
    .status-create-row .form-group label { display:block; font-size:12px; color: var(--text-secondary); margin-bottom:4px; }
    .status-create-row .form-group input[type="text"], .status-create-row .form-group input[type="color"] { height:36px; padding:8px 10px; border:1px solid var(--border-light); border-radius:8px; background:#fff; color: var(--text-primary); }
    .permissions-grid { display:grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap:8px; }
    .permission-check { display:flex; align-items:center; gap:10px; background:#fff; border:1px solid var(--border-light); border-radius:10px; padding:10px; }
    .permission-check.is-unallowed { opacity: .85; }
    .permission-check input { width:16px; height:16px; }
    .permission-label { color: var(--text-primary); flex:1; }
    .status-create-row { display:grid; grid-template-columns: 1fr auto; align-items:center; gap:8px; }
    /* Se elimina edición de color; mantener estilos limpios */
    .modal-premium .modal { max-width: 760px; }
    .modal-premium .modal-header { position: sticky; top: 0; }
    .modal-premium .modal-footer { border-top:1px solid var(--border-light); margin-top:12px; padding-top:12px; }
    /* Stepper coherente con Roles/Usuarios */
    .wizard-stepper { display:flex; justify-content:space-between; align-items:center; gap:1rem; margin-bottom:1rem; }
    .wizard-step-item { display:flex; align-items:center; flex:1; position:relative; gap:.25rem; }
    .wizard-step-item .step-index { width:28px; height:28px; min-width:28px; border-radius:50%; border:2px solid var(--border-medium); background:#fff; display:flex; align-items:center; justify-content:center; font-weight:600; color:var(--secondary-gray); position:relative; z-index:1; }
    .wizard-step-item .step-title { margin-left:.5rem; font-weight:600; color:var(--secondary-gray); position:relative; z-index:1; }
    .wizard-step-item.active .step-index { border-color: var(--primary-blue); color: var(--primary-blue); background:#e7f1ff; }
    .wizard-step-item.active .step-title { color: var(--primary-blue); }
    .wizard-step-item.completed .step-index { border-color: var(--primary-blue); background: var(--primary-blue); color:#fff; font-size:0; }
    .wizard-step-item.completed .step-index::after { content:'✓'; color:#fff; font-size:14px; font-weight:700; }
    .wizard-step-item.completed .step-title { color: var(--primary-blue-dark); }
    .wizard-step-item::after { content:''; position:absolute; height:2px; background: var(--border-medium); top:50%; left:40px; width:calc(100% - 52px); transform:translateY(14px); z-index:0; pointer-events:none; }
    .wizard-step-item:last-child::after { display:none; }
</style>

<script>
function openDeskStatusesModal(deskId, deskName) {
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop modal-premium';
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.innerHTML = `
        <div class="modal-header">
            <div class="modal-title"><span class="modal-icon">📋</span><h3>Estados del Desk: ${deskName}</h3></div>
            <button class="btn-ghost" onclick="this.closest('.modal-backdrop').remove()">&times;</button>
        </div>
        <div class="modal-body">
            <div id="ds_feedback" style="display:none; margin-bottom:8px; padding:8px 10px; border-radius:8px; font-size:13px;"></div>
            <div class="status-create-row" style="margin-bottom:8px;">
                <div class="form-group">
                    <label>Nombre del estado</label>
                    <input type="text" id="ds_new_status_name" placeholder="Ej.: demo completada" />
                </div>
                <div>
                    <button class="btn-primary" id="ds_create_status_btn">Crear y permitir</button>
                </div>
            </div>
            <div class="preset-row" style="margin: 4px 0 8px;">
                <input type="text" id="ds_status_filter" placeholder="Buscar estado..." style="flex:1; height:36px; padding:8px 10px; border:1px solid var(--border-light); border-radius:8px;" />
            </div>
            <div id="deskStatusesList" class="permissions-by-module" style="border:1px solid var(--border-light); border-radius:10px; padding:8px; min-height:48px;">
                <em style="color:#64748b">Cargando estados...</em>
            </div>
            <p style="margin-top:8px;color:#64748b;font-size:12px;">Selecciona los estados que este desk podrá usar en sus leads.</p>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary" onclick="(function(el){ el.closest('.modal-backdrop')?.remove(); })(this)">Cancelar</button>
            <button class="btn-primary" id="saveDeskStatusesBtn">Guardar</button>
        </div>
    `;
    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);

    const list = modal.querySelector('#deskStatusesList');
    const saveBtn = modal.querySelector('#saveDeskStatusesBtn');
    const createBtn = modal.querySelector('#ds_create_status_btn');
    const nameInput = modal.querySelector('#ds_new_status_name');
    const filterInput = modal.querySelector('#ds_status_filter');
    const feedback = modal.querySelector('#ds_feedback');

    function showFeedback(kind, msg){
        if (!feedback) return;
        feedback.style.display = 'block';
        feedback.textContent = msg;
        feedback.style.background = kind==='error' ? '#fee2e2' : '#ecfdf5';
        feedback.style.color = kind==='error' ? '#b91c1c' : '#065f46';
        feedback.style.border = '1px solid ' + (kind==='error' ? '#fecaca' : '#a7f3d0');
        setTimeout(() => { feedback.style.display = 'none'; }, 2500);
    }

    function renderStatusRow(s, allowedSet) {
        const row = document.createElement('div');
        row.className = 'permission-check';
        row.style.margin = '4px 0';
        row.setAttribute('data-key', s.key);
        const allowed = allowedSet.has(s.key);
        row.classList.toggle('is-unallowed', !allowed);
        row.innerHTML = `
            <input type="checkbox" class="desk-status-chk" value="${s.key}" ${allowed?'checked':''}>
            <span class="permission-label" data-text="${(s.display_name||s.key).replace('_',' ')}">${(s.display_name||s.key).replace('_',' ')}</span>
            <button type="button" class="btn-ghost ds-rename-btn" data-key="${s.key}" title="Renombrar" style="margin-left:auto;">Renombrar</button>
            ${allowed ? `<button type="button" class="btn-ghost ds-remove-allowed-btn" data-key="${s.key}" title="Quitar del desk" style="color:#ea580c">Quitar del desk</button>` : ''}
            <button type="button" class="btn-ghost ds-delete-btn" data-key="${s.key}" title="Eliminar estado" style="color:#ef4444">Eliminar</button>
        `;
        return row;
    }
    // Cargar permitidos y detalle de estados (con color)
    Promise.all([
        fetch(`/modules/desks/get_allowed_statuses.php?desk_id=${encodeURIComponent(deskId)}`).then(r=>r.json()),
        fetch('/modules/desks/actions.php?action=list_statuses').then(r=>r.json())
    ]).then(([allowedRes, listRes]) => {
        if (!allowedRes.success) { list.innerHTML = `<span style='color:#ef4444'>${allowedRes.message||'No se pudo cargar'}</span>`; return; }
        const allowed = new Set(allowedRes.allowed || []);
        const statuses = (listRes.success && Array.isArray(listRes.statuses)) ? listRes.statuses : (allowedRes.all||[]).map(k => ({ key:k, display_name:k.replace('_',' '), color:'#64748b' }));
        list.innerHTML = '';
        statuses.forEach(s => { list.appendChild(renderStatusRow(s, allowed)); });
    }).catch(e => { list.innerHTML = `<span style='color:#ef4444'>Error de red: ${e.message}</span>`; });

    // Helper para generar key desde nombre
    function slugifyKey(str) {
        return (str||'')
            .toString()
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, '_')
            .replace(/^_+|_+$/g, '')
            .replace(/_{2,}/g, '_')
            .substring(0,50);
    }

    // Crear nuevo estado y permitirlo inmediatamente en el desk
    if (createBtn) createBtn.addEventListener('click', function(){
        const displayName = (nameInput?.value||'').trim();
        if (!displayName) { window.ProfixCRM?.showModalNotification && window.ProfixCRM.showModalNotification('Ingrese un nombre para el estado', 'warning'); return; }
        const key = slugifyKey(displayName);
        const color = '#64748b';
        createBtn.disabled = true; createBtn.textContent = 'Creando...';
        fetch('/modules/desks/actions.php?action=create_status', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ key, display_name: displayName, color })
        }).then(r=>r.json()).then(j => {
            if (!j.success) throw new Error(j.error || 'No se pudo crear el estado');
            const s = j.status || { key, display_name: displayName };
            const allowedSet = new Set(Array.from(modal.querySelectorAll('.desk-status-chk:checked')).map(cb => cb.value));
            allowedSet.add(key);
            list.appendChild(renderStatusRow(s, allowedSet));
            // Persistir inmediatamente selección (incluye nuevo)
            const selected = Array.from(modal.querySelectorAll('.desk-status-chk:checked')).map(cb => cb.value);
            return fetch('/modules/desks/save_allowed_statuses.php', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ desk_id: deskId, statuses: selected })
        }).then(r=>r.json()).then(j2 => {
            if (!j2.success) throw new Error(j2.message || 'No se pudo guardar en el desk');
                // Actualizar contador de estados en la tarjeta
                const card = document.querySelector(`.role-card[data-desk-id="${deskId}"]`);
                if (card) {
                    const items = card.querySelectorAll('.role-stats .stat-item');
                    items.forEach(it => {
                        const label = it.querySelector('.stat-text');
                        const val = it.querySelector('.stat-value');
                        if (label && val && label.textContent.trim().toLowerCase() === 'estados') {
                            val.textContent = String(selected.length);
                        }
                    });
                }
                // Limpiar el formulario
                if (nameInput) nameInput.value = '';
                window.ProfixCRM?.showModalNotification && window.ProfixCRM.showModalNotification('Estado creado y permitido', 'success');
                if (typeof showFeedback === 'function') showFeedback('success', 'Estado creado satisfactoriamente');
            });
        }).catch(e => {
            window.ProfixCRM?.showModalNotification && window.ProfixCRM.showModalNotification('Error: ' + e.message, 'error');
            if (typeof showFeedback === 'function') showFeedback('error', 'Error al crear estado: ' + e.message);
        }).finally(() => { createBtn.disabled = false; createBtn.textContent = 'Crear y permitir'; });
    });

    saveBtn.addEventListener('click', function(){
        const selected = Array.from(modal.querySelectorAll('.desk-status-chk:checked')).map(cb => cb.value);
        saveBtn.disabled = true; saveBtn.textContent = 'Guardando...';
        fetch('/modules/desks/save_allowed_statuses.php', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ desk_id: deskId, statuses: selected })
        }).then(r => r.json()).then(j => {
            if (j.success) {
                if (window.ProfixCRM?.showModalNotification) { window.ProfixCRM.showModalNotification('Estados guardados', 'success'); }
                if (typeof showFeedback === 'function') showFeedback('success', 'Estados guardados satisfactoriamente');
                // Actualizar contador de estados en la tarjeta sin recargar
                const card = document.querySelector(`.role-card[data-desk-id="${deskId}"]`);
                if (card) {
                    const items = card.querySelectorAll('.role-stats .stat-item');
                    items.forEach(it => {
                        const label = it.querySelector('.stat-text');
                        const val = it.querySelector('.stat-value');
                        if (label && val && label.textContent.trim().toLowerCase() === 'estados') {
                            val.textContent = String(selected.length);
                        }
                    });
                }
                backdrop.remove();
            } else {
                if (window.ProfixCRM?.showModalNotification) { window.ProfixCRM.showModalNotification('Error: ' + (j.message || 'No se pudo guardar'), 'error'); }
                if (typeof showFeedback === 'function') showFeedback('error', 'Error al guardar: ' + (j.message || 'No se pudo guardar'));
            }
        }).catch(e => { 
            if (window.ProfixCRM?.showModalNotification) { window.ProfixCRM.showModalNotification('Error de red: ' + e.message, 'error'); }
            if (typeof showFeedback === 'function') showFeedback('error', 'Error de red al guardar: ' + e.message);
        }).finally(() => { saveBtn.disabled = false; saveBtn.textContent = 'Guardar'; });
    });

    // Eliminar (quitar) un estado del desk al instante
    list.addEventListener('click', function(e){
        // Quitar del desk (solo desactivar en este desk)
        const removeBtn = e.target.closest('.ds-remove-allowed-btn');
        if (removeBtn) {
            const key = removeBtn.getAttribute('data-key');
            if (!key) return;
            const cb = list.querySelector(`.desk-status-chk[value="${key}"]`);
            if (cb) cb.checked = false;
            fetch('/modules/desks/actions.php?action=remove_allowed_status', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ desk_id: deskId, key })
            }).then(r=>r.json()).then(j => {
                if (!j.success) throw new Error(j.error || j.message || 'No se pudo quitar del desk');
                const row = removeBtn.closest('.permission-check');
                if (row) row.classList.add('is-unallowed');
                // Ajustar contador
                const selectedCount = modal.querySelectorAll('.desk-status-chk:checked').length;
                const card = document.querySelector(`.role-card[data-desk-id="${deskId}"]`);
                if (card) {
                    const items = card.querySelectorAll('.role-stats .stat-item');
                    items.forEach(it => {
                        const label = it.querySelector('.stat-text');
                        const val = it.querySelector('.stat-value');
                        if (label && val && label.textContent.trim().toLowerCase() === 'estados') {
                            val.textContent = String(selectedCount);
                        }
                    });
                }
                window.ProfixCRM?.showModalNotification && window.ProfixCRM.showModalNotification('Estado quitado de este desk', 'success');
                if (typeof showFeedback === 'function') showFeedback('success', 'Estado quitado del desk');
            }).catch(err => {
                window.ProfixCRM?.showModalNotification && window.ProfixCRM.showModalNotification('Error: ' + err.message, 'error');
                if (typeof showFeedback === 'function') showFeedback('error', 'Error al quitar del desk: ' + err.message);
                // revertir checkbox
                const cb2 = list.querySelector(`.desk-status-chk[value="${key}"]`);
                if (cb2) cb2.checked = true;
            });
            return;
        }

        const btn = e.target.closest('.ds-delete-btn');
        if (!btn) return;
        const key = btn.getAttribute('data-key');
        if (!key) return;
        if (!confirm('¿Eliminar este estado del sistema? Esta acción lo quitará de todos los desks.')) return;
        // si estaba permitido, se descontará luego
        const wasChecked = !!list.querySelector(`.desk-status-chk[value="${key}"]`)?.checked;
        // eliminar globalmente
        fetch('/modules/desks/actions.php?action=delete_status', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ key })
        }).then(r=>r.json()).then(j => {
            if (!j.success) throw new Error(j.error || j.message || 'No se pudo eliminar');
            // Eliminar la fila del listado inmediatamente
            const row = btn.closest('.permission-check');
            row && row.remove();
            // Actualizar contador en tarjeta
            const selectedCount = (wasChecked ? (modal.querySelectorAll('.desk-status-chk:checked').length - 1) : modal.querySelectorAll('.desk-status-chk:checked').length);
            const card = document.querySelector(`.role-card[data-desk-id="${deskId}"]`);
            if (card) {
                const items = card.querySelectorAll('.role-stats .stat-item');
                items.forEach(it => {
                    const label = it.querySelector('.stat-text');
                    const val = it.querySelector('.stat-value');
                    if (label && val && label.textContent.trim().toLowerCase() === 'estados') {
                        val.textContent = String(selectedCount);
                    }
                });
            }
            window.ProfixCRM?.showModalNotification && window.ProfixCRM.showModalNotification('Estado eliminado del desk', 'success');
            if (typeof showFeedback === 'function') showFeedback('success', 'Estado eliminado satisfactoriamente');
        }).catch(err => {
            window.ProfixCRM?.showModalNotification && window.ProfixCRM.showModalNotification('Error: ' + err.message, 'error');
            if (typeof showFeedback === 'function') showFeedback('error', 'Error al eliminar estado: ' + err.message);
            // revertir checkbox si falló
            const cb2 = list.querySelector(`.desk-status-chk[value="${key}"]`);
            if (cb2) cb2.checked = true;
        });
    });

    // Renombrado inline de estados
    list.addEventListener('click', function(e){
        const btn = e.target.closest('.ds-rename-btn');
        if (!btn) return;
        const key = btn.getAttribute('data-key');
        const row = btn.closest('.permission-check');
        const labelEl = row.querySelector('.permission-label');
        const current = labelEl?.textContent?.trim() || '';
        // Construir editor inline
        const editor = document.createElement('div');
        editor.style.display = 'flex';
        editor.style.gap = '8px';
        editor.style.alignItems = 'center';
        editor.innerHTML = `
            <input type="text" class="form-control" value="${current}" style="height:32px; padding:6px 8px;">
            <button type="button" class="btn-primary ds-rename-save">Guardar</button>
            <button type="button" class="btn-secondary ds-rename-cancel">Cancelar</button>
        `;
        // Ocultar label y botón renombrar
        labelEl.style.display = 'none';
        btn.style.display = 'none';
        row.insertBefore(editor, btn);

        const input = editor.querySelector('input');
        editor.querySelector('.ds-rename-cancel').addEventListener('click', () => {
            editor.remove(); labelEl.style.display = ''; btn.style.display = '';
        });
        input.focus();
        input.select();
        input.addEventListener('keydown', (ev) => {
            if (ev.key === 'Escape') { ev.preventDefault(); editor.remove(); labelEl.style.display = ''; btn.style.display = ''; }
            if (ev.key === 'Enter') { ev.preventDefault(); editor.querySelector('.ds-rename-save').click(); }
        });
        editor.querySelector('.ds-rename-save').addEventListener('click', () => {
            const newName = input.value.trim();
            if (!newName) { window.ProfixCRM?.showModalNotification && window.ProfixCRM.showModalNotification('Ingrese un nombre válido', 'warning'); return; }
            fetch('/modules/desks/actions.php?action=update_status', {
                method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key, display_name: newName })
            }).then(r=>r.json()).then(j => {
                if (!j.success) throw new Error(j.error || 'No se pudo renombrar');
                labelEl.textContent = (j.status?.display_name || newName);
                editor.remove(); labelEl.style.display = ''; btn.style.display = '';
                window.ProfixCRM?.showModalNotification && window.ProfixCRM.showModalNotification('Estado renombrado', 'success');
            }).catch(err => {
                window.ProfixCRM?.showModalNotification && window.ProfixCRM.showModalNotification('Error: ' + err.message, 'error');
                if (typeof showFeedback === 'function') showFeedback('error', 'Error al renombrar: ' + err.message);
            });
        });
    });

    // Filtro por texto
    if (filterInput) {
        filterInput.addEventListener('input', function(){
            const q = this.value.trim().toLowerCase();
            list.querySelectorAll('.permission-check').forEach(row => {
                const name = row.querySelector('.permission-label')?.textContent.toLowerCase() || '';
                row.style.display = (!q || name.includes(q)) ? '' : 'none';
            });
        });
    }
}

function openDeskViewModal(deskId, deskName) {
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop modal-premium';
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.innerHTML = `
        <div class="modal-header">
            <div class="modal-title"><span class="modal-icon">👁️</span><h3>Ver escritorio: ${deskName}</h3></div>
            <button class="modal-close" onclick="this.closest('.modal').remove(); document.querySelector('.modal-backdrop').remove();">×</button>
        </div>
        <div class="modal-body">
            <p>Accede al detalle completo del escritorio.</p>
        </div>
        <div class="modal-footer">
            <a class="btn-primary" href="?module=desks&action=view&id=${deskId}">Ir a detalle</a>
            <button class="btn-secondary" onclick="this.closest('.modal').remove(); document.querySelector('.modal-backdrop').remove();">Cerrar</button>
        </div>
    `;
    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);
}

function openDeskEditModal(deskId, deskName) {
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop modal-premium';
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.innerHTML = `
        <div class="modal-header">
            <div class="modal-title">
                <span class="modal-icon">✏️</span>
                <div>
                    <h3 style="margin:0;">Editar escritorio</h3>
                    <small style="color:var(--text-muted)">Ajusta nombre, manager y horario</small>
                </div>
            </div>
            <button class="btn-ghost" onclick="this.closest('.modal-backdrop').remove()">×</button>
        </div>
        <div class="modal-body">
            <form id="deskEditForm" class="form-grid" style="display:grid; grid-template-columns: 1fr 1fr; gap:12px;">
                <div class="form-group" style="grid-column: span 2;">
                    <label class="form-label">Nombre</label>
                    <input class="form-control" type="text" id="def_name" placeholder="Nombre del escritorio" required />
                </div>
                <div class="form-group" style="grid-column: span 2;">
                    <label class="form-label">Descripción</label>
                    <textarea class="form-control" id="def_description" rows="3" placeholder="Descripción breve del propósito y alcance"></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">Manager</label>
                    <select class="form-control" id="def_manager_id"></select>
                </div>
                <div class="form-group">
                    <label class="form-label">Estado</label>
                    <select class="form-control" id="def_status">
                        <option value="active">Activo</option>
                        <option value="inactive">Inactivo</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Horario inicio</label>
                    <input class="form-control" type="time" id="def_wh_start" />
                </div>
                <div class="form-group">
                    <label class="form-label">Horario fin</label>
                    <input class="form-control" type="time" id="def_wh_end" />
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary" id="def_cancel">Cancelar</button>
            <button class="btn-primary" id="def_save">Guardar</button>
        </div>
    `;
    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);

    const form = modal.querySelector('#deskEditForm');
    const elName = modal.querySelector('#def_name');
    const elDesc = modal.querySelector('#def_description');
    const elManager = modal.querySelector('#def_manager_id');
    const elStatus = modal.querySelector('#def_status');
    const elWhStart = modal.querySelector('#def_wh_start');
    const elWhEnd = modal.querySelector('#def_wh_end');

    // Cargar detalles y managers en paralelo
    let prevStatus = null;
    Promise.all([
        fetch(`/modules/desks/actions.php?action=get_details&desk_id=${deskId}`).then(r=>r.json()),
        fetch(`/modules/desks/actions.php?action=list_managers`).then(r=>r.json())
    ]).then(([det, mgr]) => {
        if (!det.success) throw new Error(det.error || 'No se pudo cargar el escritorio');
        const d = det.desk;
        prevStatus = d.status;
        elName.value = d.name || '';
        elDesc.value = d.description || '';
        elStatus.value = d.status || 'active';
        elWhStart.value = (d.working_hours_start || '09:00').substring(0,5);
        elWhEnd.value = (d.working_hours_end || '18:00').substring(0,5);
        // Managers
        elManager.innerHTML = '<option value="">Sin asignar</option>';
        if (mgr.success && Array.isArray(mgr.users)) {
            mgr.users.forEach(u => {
                const opt = document.createElement('option');
                opt.value = u.id;
                opt.textContent = u.username;
                if (String(u.id) === String(d.manager_id)) opt.selected = true;
                elManager.appendChild(opt);
            });
        }
    }).catch(e => {
        if (window.ProfixCRM?.showModalNotification) window.ProfixCRM.showModalNotification(`Error: ${e.message}`, 'error');
    });

    modal.querySelector('#def_cancel').addEventListener('click', () => { backdrop.remove(); });
    modal.querySelector('#def_save').addEventListener('click', () => {
        const payload = {
            desk_id: deskId,
            name: elName.value.trim(),
            description: elDesc.value.trim(),
            manager_id: elManager.value || null,
            status: elStatus.value,
            working_hours_start: elWhStart.value || '09:00',
            working_hours_end: elWhEnd.value || '18:00'
        };
        const btn = modal.querySelector('#def_save');
        btn.disabled = true; btn.textContent = 'Guardando...';
        fetch('/modules/desks/actions.php?action=update', {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload)
        }).then(r=>r.json()).then(j => {
            if (!j.success) throw new Error(j.error || 'No se pudo guardar');
            const d = j.desk;
            // Actualizar tarjeta
            const card = document.querySelector(`.role-card[data-desk-id="${deskId}"]`);
            if (card) {
                const nameEl = card.querySelector('.role-name'); if (nameEl) nameEl.textContent = d.name || '';
                const descEl = card.querySelector('.role-description'); if (descEl) descEl.textContent = d.description || 'Sin descripción';
                const chipVal = card.querySelector('.chip-value'); if (chipVal) { chipVal.textContent = d.manager_name || 'Sin asignar'; chipVal.classList.toggle('text-muted', !d.manager_name); }
                const avatar = card.querySelector('.avatar-mini'); if (avatar) avatar.textContent = String((d.manager_name||'S')).charAt(0).toUpperCase();
                const pill = card.querySelector('.status-pill'); if (pill) {
                    pill.classList.remove('status-active','status-inactive','status-suspended');
                    const cls = (d.status === 'active') ? 'status-active' : ((d.status === 'suspended') ? 'status-suspended' : 'status-inactive');
                    pill.classList.add(cls);
                    const t = pill.querySelector('.pill-text'); if (t) t.textContent = (d.status||'').charAt(0).toUpperCase() + (d.status||'').slice(1);
                }
                // Horario en permissions-tags
                const permTags = card.querySelectorAll('.permission-tag');
                permTags.forEach(tag => {
                    if (tag.textContent.trim().startsWith('Horario:')) {
                        tag.textContent = `Horario: ${d.working_hours_start?.substring(0,5) || '09:00'} - ${d.working_hours_end?.substring(0,5) || '18:00'}`;
                    }
                });
            }
            // Actualizar widget Activos si cambia el estado
            if (prevStatus && prevStatus !== d.status) {
                const activeEl = document.getElementById('active-desks-num');
                if (activeEl) {
                    const curr = parseInt((activeEl.textContent||'0').replace(/[^0-9]/g,''), 10) || 0;
                    const next = (d.status === 'active') ? curr + 1 : curr - 1;
                    activeEl.textContent = String(next);
                }
            }
            if (window.ProfixCRM?.showModalNotification) window.ProfixCRM.showModalNotification('Escritorio actualizado', 'success');
            backdrop.remove();
        }).catch(e => {
            if (window.ProfixCRM?.showModalNotification) window.ProfixCRM.showModalNotification(`Error: ${e.message}`, 'error');
        }).finally(() => { const btn2 = modal.querySelector('#def_save'); if (btn2){ btn2.disabled = false; btn2.textContent = 'Guardar'; } });
    });
}

function openDeskDeleteModal(deskId, deskName) {
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop modal-premium';
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.innerHTML = `
        <div class="modal-header">
            <div class="modal-title"><span class="modal-icon">🗑️</span><h3>Eliminar escritorio</h3></div>
            <button class="modal-close" onclick="this.closest('.modal').remove(); document.querySelector('.modal-backdrop').remove();">×</button>
        </div>
        <div class="modal-body">
            <p>¿Confirma eliminar <strong>${deskName}</strong>? Esta acción no se puede deshacer.</p>
        </div>
        <div class="modal-footer">
            <a class="btn-danger" href="?module=desks&action=delete&id=${deskId}">Sí, eliminar</a>
            <button class="btn-secondary" onclick="this.closest('.modal').remove(); document.querySelector('.modal-backdrop').remove();">Cancelar</button>
        </div>
    `;
    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);
}

// ====== Wizard de creación de Escritorios ======
function openDeskCreateWizard() {
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop modal-premium';
    const modal = document.createElement('div');
    modal.className = 'modal modal-premium';
    modal.innerHTML = `
        <div class="modal-header">
            <div class="modal-title"><span class="modal-icon">🧭</span><h3>Asistente: Crear Escritorio</h3></div>
            <button class="modal-close" onclick="this.closest('.modal').remove(); document.querySelector('.modal-backdrop').remove();">×</button>
        </div>
        <div class="modal-body">
            <div id="deskWizardSteps" class="wizard-stepper">
                <div class="wizard-step-item active" data-step="1">
                    <span class="step-index">1</span>
                    <span class="step-title">Información</span>
                </div>
                <div class="wizard-step-item" data-step="2">
                    <span class="step-index">2</span>
                    <span class="step-title">Manager y Horario</span>
                </div>
                <div class="wizard-step-item" data-step="3">
                    <span class="step-index">3</span>
                    <span class="step-title">Estados</span>
                </div>
            </div>
            <div id="dw_step1" class="wizard-step">
                <h4>1. Información del Escritorio</h4>
                <div class="form-grid">
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label" for="dw_name">Nombre</label>
                            <input class="form-control" type="text" id="dw_name" maxlength="100" required />
                            <div id="dw_name_hint" class="field-hint"></div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="dw_status">Estado</label>
                            <select class="form-control" id="dw_status">
                                <option value="active">Activo</option>
                                <option value="inactive">Inactivo</option>
                                <option value="suspended">Suspendido</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group" style="grid-column: 1 / -1;">
                            <label class="form-label" for="dw_description">Descripción</label>
                            <textarea class="form-control" id="dw_description" rows="3" placeholder="Descripción..."></textarea>
                        </div>
                    </div>
                </div>
            </div>
            <div id="dw_step2" class="wizard-step" style="display:none;">
                <h4>2. Manager y Horario</h4>
                <div class="form-grid">
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label" for="dw_manager_id">Manager</label>
                            <select class="form-control" id="dw_manager_id"><option value="">Sin asignar</option></select>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="dw_wh_start">Horario Inicio</label>
                            <input class="form-control" type="time" id="dw_wh_start" value="09:00" />
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="dw_wh_end">Horario Fin</label>
                            <input class="form-control" type="time" id="dw_wh_end" value="18:00" />
                        </div>
                    </div>
                </div>
            </div>
            <div id="dw_step3" class="wizard-step" style="display:none;">
                <h4>3. Estados del Desk</h4>
                <p>Selecciona y/o crea los estados permitidos para este escritorio:</p>
                <div id="dw_new_statuses">
                    <div class="status-create-row">
                        <div class="form-group">
                            <label class="form-label">Nombre del estado</label>
                            <input class="form-control status-name-input" type="text" placeholder="Ej: seguimiento programado" />
                        </div>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn-primary" id="dw_add_status">Agregar estado</button>
                    </div>
                </div>
                <div id="dw_statuses" class="permissions-grid" style="padding-top:.5rem;"></div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary" id="dw_prev" disabled>Anterior</button>
            <button class="btn-primary" id="dw_next">Siguiente</button>
        </div>
    `;
    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);

    // Cargar managers
    fetch('/modules/desks/actions.php?action=list_managers').then(r=>r.json()).then(j=>{
        const sel = modal.querySelector('#dw_manager_id');
        if (j.success) sel.innerHTML = '<option value="">Sin asignar</option>' + (j.users||[]).map(u=>`<option value="${u.id}">${u.username}</option>`).join('');
    }).catch(()=>{});

    // Render estados dinámicos desde API y presets
    const list = modal.querySelector('#dw_statuses');
    function addStatusCheckbox(key, label){
        const row = document.createElement('label');
        row.className = 'permission-check';
        row.style.margin = '4px 0';
        row.innerHTML = `
            <input type="checkbox" class="desk-status-chk" value="${key}">
            <span class="permission-label" data-text="${label}">${label}</span>
        `;
        list.appendChild(row);
        return row.querySelector('input');
    }
    fetch('/modules/desks/actions.php?action=list_statuses').then(r=>r.json()).then(j=>{
        list.innerHTML = '';
        if (j.success && Array.isArray(j.statuses)) {
            j.statuses.forEach(st => {
                const chk = addStatusCheckbox(st.key, st.display_name);
                if (st.key==='new' || st.key==='contacted') chk.checked = true;
            });
        } else {
            ['new','contacted','qualified','demo_scheduled','demo_completed','deposit_pending','deposited','active_trader','inactive','closed_lost'].forEach(k=>{
                const label = k.replace(/_/g,' ');
                const chk = addStatusCheckbox(k, label);
                if (k==='new' || k==='contacted') chk.checked = true;
            });
        }
    }).catch(()=>{
        ['new','contacted','qualified','demo_scheduled','demo_completed','deposit_pending','deposited','active_trader','inactive','closed_lost'].forEach(k=>{
            const label = k.replace(/_/g,' ');
            const chk = addStatusCheckbox(k, label);
            if (k==='new' || k==='contacted') chk.checked = true;
        });
    });
    // Crear nuevo estado desde el wizard (solo nombre) y agregar una fila nueva
    function slugify(str){ return (str||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'').replace(/\s+/g,'_').replace(/[^a-z0-9_]/g,'').replace(/_+/g,'_').replace(/^_|_$/g,''); }
    const statusesContainer = modal.querySelector('#dw_new_statuses');
    function addBlankStatusRow(){
        const row = document.createElement('div');
        row.className = 'status-create-row';
        row.innerHTML = '<div class="form-group">\n<label class="form-label">Nombre del estado</label>\n<input class="form-control status-name-input" type="text" placeholder="Ej: seguimiento programado" />\n</div>';
        statusesContainer.appendChild(row);
        const input = row.querySelector('input.status-name-input');
        input && input.focus();
    }
    modal.querySelector('#dw_add_status').addEventListener('click', async ()=>{
        const rows = statusesContainer.querySelectorAll('.status-create-row');
        const last = rows[rows.length-1];
        const nameInput = last?.querySelector('input.status-name-input');
        const name = (nameInput?.value||'').trim();
        if (!name) { if (window.ProfixCRM?.showModalNotification) window.ProfixCRM.showModalNotification({type:'warning', title:'Falta nombre', message:'Ingresa el nombre del estado'}); else alert('Ingresa el nombre del estado'); return; }
        const key = slugify(name);
        const color = '#64748b';
        // Evitar duplicados en la lista local
        const existing = list.querySelector(`input.desk-status-chk[value="${key}"]`);
        if (existing) { existing.checked = true; if (window.ProfixCRM?.showModalNotification) window.ProfixCRM.showModalNotification({type:'info', title:'Estado existente', message:'Estado ya existe, marcado como permitido'}); addBlankStatusRow(); return; }
        try {
            const resp = await fetch('/modules/desks/actions.php?action=create_status', { method: 'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ key, display_name: name, color }) });
            const j = await resp.json();
            if (!j.success) throw new Error(j.error||'No se pudo crear el estado');
            const chk = addStatusCheckbox(j.status.key, j.status.display_name);
            chk.checked = true;
            if (window.ProfixCRM?.showModalNotification) window.ProfixCRM.showModalNotification({type:'success', title:'Estado creado', message:'El estado fue creado y marcado como permitido'});
            addBlankStatusRow();
        } catch (e) {
            if (window.ProfixCRM?.showModalNotification) window.ProfixCRM.showModalNotification({type:'error', title:'Error al crear estado', message: e.message }); else alert(e.message);
        }
    });
    var STATUS_PRESETS = window.STATUS_PRESETS || {
        general: ['new','contacted','qualified','inactive'],
        ventas: ['new','contacted','qualified','demo_scheduled','demo_completed','deposit_pending','deposited','active_trader','closed_lost'],
        soporte: ['new','contacted','inactive','closed_lost'],
        retencion: ['contacted','deposit_pending','active_trader','inactive'],
        ib: ['new','qualified','active_trader','inactive']
    };
    window.STATUS_PRESETS = STATUS_PRESETS;
    function applyStatusPreset(key) {
        const preset = STATUS_PRESETS[key] || [];
        modal.querySelectorAll('.desk-status-chk').forEach(cb => { cb.checked = preset.includes(cb.value); });
    }
    const presetSel = modal.querySelector('#dw_preset');
    if (presetSel) presetSel.addEventListener('change', e => applyStatusPreset(e.target.value));

    let step = 1;
    const prevBtn = modal.querySelector('#dw_prev');
    const nextBtn = modal.querySelector('#dw_next');
    const stepper = modal.querySelector('#deskWizardSteps');
    function updateStepUI(){
        modal.querySelector('#dw_step1').style.display = step===1?'block':'none';
        modal.querySelector('#dw_step2').style.display = step===2?'block':'none';
        modal.querySelector('#dw_step3').style.display = step===3?'block':'none';
        prevBtn.disabled = step===1;
        nextBtn.textContent = step===3 ? 'Crear Escritorio' : 'Siguiente';
        if (stepper) {
            stepper.querySelectorAll('.wizard-step-item').forEach(item => {
                const s = parseInt(item.getAttribute('data-step'), 10);
                item.classList.toggle('active', s === step);
                item.classList.toggle('completed', s < step);
            });
        }
    }
    // Validación de nombre duplicado en vivo
    const nameEl = modal.querySelector('#dw_name');
    const nameHint = modal.querySelector('#dw_name_hint');
    async function checkNameUnique(){
        const v = (nameEl.value||'').trim();
        if (v.length < 3) { nameHint.textContent = 'Debe tener al menos 3 caracteres.'; nameEl.classList.add('invalid'); return false; }
        nameHint.textContent = 'Verificando disponibilidad...';
        try {
            const r = await fetch('/modules/desks/actions.php?action=check_name&name=' + encodeURIComponent(v));
            const j = await r.json();
            if (j.success && !j.exists) { nameHint.textContent = 'Nombre disponible.'; nameEl.classList.remove('invalid'); return true; }
            nameHint.textContent = 'Ya existe un escritorio con este nombre.'; nameEl.classList.add('invalid'); return false;
        } catch(e) {
            nameHint.textContent = 'No se pudo validar el nombre.'; return false;
        }
    }
    nameEl.addEventListener('blur', checkNameUnique);
    nameEl.addEventListener('input', ()=>{ nameEl.classList.remove('invalid'); nameHint.textContent = ''; });
    prevBtn.addEventListener('click', ()=>{ if (step>1){ step--; updateStepUI(); } });
    nextBtn.addEventListener('click', async ()=>{
        if (step === 1) { if (!(await checkNameUnique())) return; step++; updateStepUI(); return; }
        if (step === 2) {
            const start = modal.querySelector('#dw_wh_start').value;
            const end = modal.querySelector('#dw_wh_end').value;
        if (!start || !end) { if (window.ProfixCRM?.showModalNotification) window.ProfixCRM.showModalNotification({type:'warning', title:'Horario incompleto', message:'Define horario de inicio y fin'}); else alert('Define horario de inicio y fin'); return; }
            step++; updateStepUI(); return;
        }
        // Crear
        try {
            const name = modal.querySelector('#dw_name').value.trim();
            if (!name) { alert('El nombre es obligatorio'); return; }
            nextBtn.disabled = true; nextBtn.textContent = 'Creando...';
            const payload = {
                name,
                description: modal.querySelector('#dw_description').value.trim(),
                manager_id: modal.querySelector('#dw_manager_id').value,
                status: modal.querySelector('#dw_status').value,
                working_hours_start: modal.querySelector('#dw_wh_start').value || '09:00',
                working_hours_end: modal.querySelector('#dw_wh_end').value || '18:00'
            };
            const resp = await fetch('/modules/desks/actions.php?action=create', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(payload)});
            const data = await resp.json();
            if (!data.success) throw new Error(data.error || 'No se pudo crear');
            const deskId = data.desk.id;
            const selected = Array.from(modal.querySelectorAll('.desk-status-chk:checked')).map(cb => cb.value);
        if (selected.length === 0) { if (window.ProfixCRM?.showModalNotification) window.ProfixCRM.showModalNotification({type:'warning', title:'Selecciona estados', message:'Selecciona al menos un estado permitido'}); else alert('Selecciona al menos un estado'); nextBtn.disabled=false; nextBtn.textContent='Crear Escritorio'; return; }
            const saveResp = await fetch('/modules/desks/save_allowed_statuses.php', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ desk_id: deskId, statuses: selected }) });
            const saveData = await saveResp.json();
            if (!saveData.success) throw new Error(saveData.message || 'No se pudieron guardar los estados');
            addNewDeskCard(data.desk);
            if (window.ProfixCRM && typeof window.ProfixCRM.showNotification === 'function') {
            window.ProfixCRM.showModalNotification({type:'success', title:'Escritorio creado', message:'El escritorio se creó correctamente'});
            }
            modal.remove(); const bd = document.querySelector('.modal-backdrop'); if (bd) bd.remove();
        } catch (err) {
            if (window.ProfixCRM && typeof window.ProfixCRM.showNotification === 'function') {
        window.ProfixCRM.showModalNotification({type:'error', title:'Error al crear escritorio', message: err.message});
            } else { alert(err.message); }
        } finally {
            nextBtn.disabled = false; nextBtn.textContent = 'Crear Escritorio';
        }
    });
    updateStepUI();
}

function addNewDeskCard(d) {
    const grid = document.querySelector('.roles-grid');
    if (!grid) { location.reload(); return; }
    const card = document.createElement('div');
    card.className = 'role-card';
    card.setAttribute('data-desk-id', String(d.id));
    const managerName = d.manager_name || 'Sin asignar';
    const managerInitial = (d.manager_name ? d.manager_name[0] : 'S').toUpperCase();
    const statusText = (d.status||'active');
    const statusClass = (statusText === 'active') ? 'status-active' : (statusText === 'suspended' ? 'status-suspended' : 'status-inactive');
    card.innerHTML = `
        <div class="role-header">
            <div class="role-info">
                <h3 class="role-name">${d.name || ''}</h3>
                <p class="role-description clamp-2">${d.description || 'Sin descripción'}</p>
                <div class="role-meta">
                    <div class="manager-chip" title="Manager del escritorio">
                        <div class="avatar-mini">${managerInitial}</div>
                        <div class="chip-text">
                            <span class="chip-label">Manager</span>
                            <span class="chip-value">${managerName}</span>
                        </div>
                    </div>
                    <div class="status-pill ${statusClass}" title="Estado del escritorio">
                        <span class="pill-dot"></span>
                        <span class="pill-text">${statusText.charAt(0).toUpperCase()+statusText.slice(1)}</span>
                    </div>
                </div>
            </div>
            <div class="role-actions">
                <button class="action-btn" type="button" title="Usuarios" onclick="openDeskUsersModal(${d.id}, '${(d.name||'').replace(/'/g, "\'")}')">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                </button>
                <button class="action-btn edit" type="button" title="Editar" onclick="openDeskEditModal(${d.id}, '${(d.name||'').replace(/'/g, "\'")}')">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>
                </button>
                <button class="action-btn" type="button" title="Estados del Desk" onclick="openDeskStatusesModal(${d.id}, '${(d.name||'').replace(/'/g, "\'")}')">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
                </button>
                <button class="action-btn delete" type="button" title="Eliminar" onclick="openDeskDeleteModal(${d.id}, '${(d.name||'').replace(/'/g, "\'")}')">
                    <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"/><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"/></svg>
                </button>
            </div>
        </div>
        <div class="role-stats">
            <div class="stat-item"><span class="stat-value">0</span><span class="stat-text">usuarios</span></div>
            <div class="stat-item"><span class="stat-value">0</span><span class="stat-text">leads</span></div>
            <div class="stat-item"><span class="stat-value">0</span><span class="stat-text">estados</span></div>
            <div class="role-footer"><span class="schedule">Horario: ${d.working_hours_start||'09:00'} - ${d.working_hours_end||'18:00'}</span><span class="id">ID: ${d.id}</span></div>
        </div>`;
    grid.insertAdjacentElement('afterbegin', card);
}
</script>
<script>
function openDeskUsersModal(deskId, deskName) {
    const backdrop = document.createElement('div');
    backdrop.className = 'modal-backdrop modal-premium';
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.innerHTML = `
        <div class="modal-header">
            <div class="modal-title"><span class="modal-icon">👥</span><h3>Usuarios del Desk: ${deskName}</h3></div>
            <button class="btn-ghost" onclick="this.closest('.modal-backdrop').remove()">×</button>
        </div>
        <div class="modal-body">
            <div id="deskUsersList" style="border:1px solid var(--border-light); border-radius:10px; padding:8px; min-height:64px;">
                <em style="color:#64748b">Cargando usuarios...</em>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn-secondary" onclick="this.closest('.modal-backdrop').remove()">Cerrar</button>
        </div>
    `;
    backdrop.appendChild(modal);
    document.body.appendChild(backdrop);

    const list = modal.querySelector('#deskUsersList');
    fetch(`/modules/desks/actions.php?action=list_desk_users&desk_id=${encodeURIComponent(deskId)}`)
        .then(r=>r.json())
        .then(j=>{
            if (!j.success) { list.innerHTML = `<span style='color:#ef4444'>${j.error||'No se pudo cargar'}</span>`; return; }
            const users = j.users || [];
            if (users.length === 0) { list.innerHTML = `<span style='color:#64748b'>No hay usuarios asociados a este escritorio</span>`; return; }
            const ul = document.createElement('ul');
            ul.style.listStyle = 'none'; ul.style.padding = '0'; ul.style.margin = '0';
            users.forEach(u => {
                const li = document.createElement('li');
                li.style.display = 'flex'; li.style.alignItems = 'center'; li.style.gap = '8px'; li.style.padding = '6px 4px';
                const initials = (u.first_name && u.last_name) ? (u.first_name[0] + u.last_name[0]).toUpperCase() : (u.username||'U')[0].toUpperCase();
                li.innerHTML = `
                    <div class="avatar-mini" style="background:#4f46e5;color:#fff;">${initials}</div>
                    <div style="display:flex; flex-direction:column;">
                        <strong>${(u.first_name||'')+' '+(u.last_name||'')}</strong>
                        <small style="color:#64748b">@${u.username}</small>
                    </div>
                    <span class="badge badge-${u.status}" style="margin-left:auto;">${u.status}</span>
                `;
                ul.appendChild(li);
            });
            list.innerHTML = ''; list.appendChild(ul);
        })
        .catch(e => { list.innerHTML = `<span style='color:#ef4444'>Error de red: ${e.message}</span>`; });
}
</script>