const { useState, useEffect, useMemo } = React;

/* ── Modül grupları (permissions checkbox için) ── */
const _MODULE_GROUPS = [
    { label: 'İzleme', modules: [{ id: 'wallboard', label: 'Wallboard' }, { id: 'dashboard', label: 'AI Monitör' }] },
    { label: 'Çağrı Merkezi', modules: [
        { id: 'human_agents', label: 'Temsilciler' }, { id: 'teams', label: 'Takımlar' }, { id: 'queues', label: 'Kuyruklar' },
        { id: 'ivr', label: 'IVR Menüleri' }, { id: 'routing', label: 'AI Yönlendirme' }, { id: 'trunks', label: 'Hat Yönetimi' },
        { id: 'schedules', label: 'Mesai' }, { id: 'callbacks', label: 'Geri Arama' }, { id: 'appointments', label: 'Randevular' },
    ]},
    { label: 'AI & Analiz', modules: [{ id: 'agents', label: 'AI Asistanlar' }, { id: 'speech', label: 'Konuşma Analizi' }, { id: 'qc', label: 'Kalite Kontrol' }, { id: 'surveys', label: 'Anketler' }] },
    { label: 'Raporlar & Veri', modules: [{ id: 'report_builder', label: 'Raporlar' }, { id: 'recordings', label: 'Kayıtlar' }, { id: 'dialer', label: 'Dialer' }, { id: 'alarms', label: 'Alarmlar' }, { id: 'customers', label: 'Müşteriler' }] },
    { label: 'Sistem', modules: [{ id: 'webservices', label: 'Web Servisler' }, { id: 'billing', label: 'Faturalama' }, { id: 'settings', label: 'Ayarlar' }, { id: 'logs', label: 'Sistem Logları' }] },
];
const _ALL_MOD_IDS = _MODULE_GROUPS.flatMap(g => g.modules.map(m => m.id));

const _ROLE_LABELS = { super_admin: 'Süper Admin', admin: 'Admin', supervisor: 'Supervisor', agent: 'Temsilci', viewer: 'İzleyici' };
const _ROLE_COLORS = {
    super_admin: { bg: '#fef3c7', color: '#92400e' }, admin: { bg: '#dbeafe', color: '#1e40af' },
    supervisor: { bg: '#e0e7ff', color: '#3730a3' }, agent: { bg: '#d1fae5', color: '#065f46' }, viewer: { bg: '#f3f4f6', color: '#374151' },
};

/* ── Inline Permissions Grid ── */
function _PermGrid({ permissions, onChange }) {
    const ps = new Set(permissions || []);
    const allSel = _ALL_MOD_IDS.every(id => ps.has(id));
    function tog(id) { const n = new Set(ps); n.has(id) ? n.delete(id) : n.add(id); onChange([...n]); }
    function togGrp(ids) { const n = new Set(ps); const a = ids.every(id => n.has(id)); ids.forEach(id => a ? n.delete(id) : n.add(id)); onChange([...n]); }
    function togAll() { onChange(allSel ? [] : [..._ALL_MOD_IDS]); }
    return (
        <div style={{ marginTop: 8, padding: 12, background: 'var(--surface2)', borderRadius: 10, border: '1px solid var(--border)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                <span style={{ fontSize: 12, fontWeight: 700 }}>Modül İzinleri</span>
                <label style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, cursor: 'pointer' }}>
                    <input type="checkbox" checked={allSel} onChange={togAll} /> Tümü
                </label>
            </div>
            {_MODULE_GROUPS.map(g => {
                const gids = g.modules.map(m => m.id);
                return (
                    <div key={g.label} style={{ marginBottom: 6 }}>
                        <label style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, fontWeight: 700, cursor: 'pointer', marginBottom: 2 }}>
                            <input type="checkbox" checked={gids.every(id => ps.has(id))} onChange={() => togGrp(gids)} /> {g.label}
                        </label>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 2, paddingLeft: 16 }}>
                            {g.modules.map(m => (
                                <label key={m.id} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, cursor: 'pointer', padding: '2px 6px', borderRadius: 4 }}>
                                    <input type="checkbox" checked={ps.has(m.id)} onChange={() => tog(m.id)} /> {m.label}
                                </label>
                            ))}
                        </div>
                    </div>
                );
            })}
        </div>
    );
}

/* ── Human Agent Modal ── */
function HumanAgentModal({ agent, onClose, onSave }) {
    const isEdit = !!agent;
    const [form, setForm] = useState({
        name: agent?.name || '', extension: agent?.extension || '', sip_password: agent?.sip_password || '',
        department: agent?.department || '', priority: agent?.priority ?? 1, max_concurrent_calls: agent?.max_concurrent_calls ?? 1,
        is_active: agent?.is_active ?? true, auto_answer: agent?.auto_answer ?? true,
        acw_timeout_sec: agent?.acw_timeout_sec ?? 30, team_id: agent?.team_id ?? null,
        role: agent?.role || '', email: agent?.email || '', password: '', permissions: agent?.permissions || [],
    });
    const [selectedQueues, setSelectedQueues] = useState(agent?.queues ? agent.queues.map(q => typeof q === 'object' ? q.id : q) : []);
    const [allQueues, setAllQueues] = useState([]);
    const [allTeams, setAllTeams] = useState([]);
    const [allDepts, setAllDepts] = useState([]);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');

    const set = (k, v) =>setForm(f => ({ ...f, [k]: v }));
    const showPerms = form.role === 'supervisor' || form.role === 'viewer';

    useEffect(() => {
        authFetch('/api/queues').then(r =>r.ok ? r.json() : []).then(setAllQueues).catch(() => {});
        authFetch('/api/teams').then(r =>r.ok ? r.json() : []).then(setAllTeams).catch(() => {});
        authFetch('/api/departments').then(r =>r.ok ? r.json() : []).then(d => setAllDepts(d.filter(x => x.is_active))).catch(() => {});
    }, []);
    function toggleQueue(qid) { setSelectedQueues(p =>p.includes(qid) ? p.filter(id =>id !== qid) : [...p, qid]); }

    async function save() {
        setError('');
        if (!form.name.trim()) { setError('Ad Soyad zorunludur.'); return; }
        if (!form.extension.trim()) { setError('Extension zorunludur.'); return; }
        // Rol seçildiyse email ve şifre zorunlu (yeni kullanıcı oluştururken)
        if (form.role && !isEdit && !agent?.user_id) {
            if (!form.email.trim()) { setError('Rol seçildiğinde e-posta zorunludur.'); return; }
            if (!form.password || form.password.length < 6) { setError('Panel şifresi en az 6 karakter olmalıdır.'); return; }
        }
        setSaving(true);
        try {
            const payload = { ...form };
            // Permissions sadece supervisor/viewer için gönder
            payload.permissions = showPerms ? form.permissions : null;
            // Boş şifre gönderme (düzenleme modunda değiştirmek istemiyorsa)
            if (isEdit && !payload.password) delete payload.password;
            // Rol seçilmemişse kullanıcı alanlarını gönderme
            if (!payload.role) { delete payload.role; delete payload.email; delete payload.password; delete payload.permissions; }

            const r = await authFetch(isEdit ? `/api/human-agents/${agent.id}` : '/api/human-agents', {
                method: isEdit ? 'PUT' : 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload),
            });
            if (!r.ok) { const err = await r.json(); throw new Error(err.detail || JSON.stringify(err)); }
            const saved = await r.json();
            await authFetch(`/api/human-agents/${saved.id}/queues`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(selectedQueues) });
            onSave();
        } catch (e) { setError(e.message); } finally { setSaving(false); }
    }

    return (
        <div className="overlay" onClick={onClose} style={{ paddingTop: 40, paddingBottom: 40, overflowY: 'auto', alignItems: 'flex-start' }}>
            <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 680, margin: 'auto' }}>
                <div className="modal-header"><span style={{ fontWeight:600, fontSize: 18 }}>{isEdit ? 'Temsilci Düzenle' : 'Yeni Temsilci'}</span><button className="close-btn" onClick={onClose}>×</button></div>
                <div className="modal-body">
                    <div className="form-group"><label className="form-label">Ad Soyad *</label><input className="form-input" value={form.name} onChange={e =>set('name', e.target.value)} /></div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                        <div className="form-group"><label className="form-label">Extension *</label><input className="form-input mono" value={form.extension} onChange={e =>set('extension', e.target.value)} /></div>
                        <div className="form-group"><label className="form-label">SIP Sifresi</label><input className="form-input" type="password" value={form.sip_password} onChange={e =>set('sip_password', e.target.value)} placeholder="••••••" /></div>
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16 }}>
                        <div className="form-group">
                            <label className="form-label">Departman</label>
                            <select className="form-select" value={form.department} onChange={e =>set('department', e.target.value)}>
                                <option value="">Seciniz</option>
                                {allDepts.map(d => <option key={d.key} value={d.label}>{d.label}</option>)}
                            </select>
                        </div>
                        <div className="form-group">
                            <label className="form-label">Oncelik</label>
                            <select className="form-select" value={form.priority} onChange={e =>set('priority', parseInt(e.target.value))}><option value={1}>1 - Normal</option><option value={2}>2 - Yuksek</option></select>
                        </div>
                        <div className="form-group"><label className="form-label">ACW Suresi (sn)</label><input className="form-input" type="number" min={0} value={form.acw_timeout_sec} onChange={e =>set('acw_timeout_sec', parseInt(e.target.value))} title="Cagri bittikten sonraki bekleme suresi" /></div>
                    </div>
                    <div className="form-group">
                        <label className="form-label">Takım</label>
                        <select className="form-select" value={form.team_id || ''} onChange={e =>set('team_id', e.target.value ? parseInt(e.target.value) : null)}>
                            <option value="">Takım Yok</option>
                            {allTeams.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
                        </select>
                    </div>
                    <div style={{ marginBottom: 16 }}>
                        <label className="form-label" style={{ marginBottom: 10, display: 'block' }}>Kuyruk Uyelikleri</label>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                            {allQueues.map(q => {
                                const sel = selectedQueues.includes(q.id);
                                return (
                                    <label key={q.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 14px', borderRadius: 8, cursor: 'pointer', border: `1px solid ${sel ? 'rgba(88,166,255,.5)' : 'var(--border)'}`, background: sel ? 'rgba(88,166,255,.1)' : 'var(--surface2)', transition: 'all .15s' }}>
                                        <input type="checkbox" checked={sel} onChange={() =>toggleQueue(q.id)} style={{ accentColor: 'var(--blue)' }} />
                                        <span style={{ fontWeight: sel ? 700 : 400, color: sel ? 'var(--blue)' : 'var(--text)' }}>{q.name}</span>
                                    </label>
                                );
                            })}
                        </div>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', background: 'var(--surface2)', borderRadius: 10, border: '1px solid var(--border)' }}>
                            <input type="checkbox" id="ha-autoanswer" checked={form.auto_answer} onChange={e =>set('auto_answer', e.target.checked)} style={{ width: 18, height: 18, accentColor: 'var(--green)', cursor: 'pointer' }} />
                            <label htmlFor="ha-autoanswer" className="form-label" style={{ margin: 0, cursor: 'pointer' }}><span style={{ color: 'var(--green)', fontWeight:600 }}>Otomatik Cevaplama</span> (Gelen cagrilar zil calmadan acilir)</label>
                        </div>
                    </div>

                    {/* ── Panel Kullanıcı Bilgileri ── */}
                    <div style={{ marginTop: 20, padding: 16, background: 'var(--surface2)', borderRadius: 12, border: '1px solid var(--border)' }}>
                        <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 12, color: 'var(--text)' }}>Panel Kullanıcı Bilgileri</div>
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                            <div className="form-group">
                                <label className="form-label">Rol</label>
                                <select className="form-select" value={form.role} onChange={e => set('role', e.target.value)}>
                                    <option value="">Rol Atama</option>
                                    <option value="admin">Admin — Tam yetki</option>
                                    <option value="supervisor">Supervisor — Seçili modüller</option>
                                    <option value="agent">Temsilci — Temsilci paneli</option>
                                    <option value="viewer">İzleyici — Salt okunur</option>
                                </select>
                            </div>
                            <div className="form-group">
                                <label className="form-label">E-posta {form.role ? '*' : ''}</label>
                                <input className="form-input" type="email" value={form.email} onChange={e => set('email', e.target.value)} placeholder="ornek@sirket.com" />
                            </div>
                        </div>
                        {(!isEdit || !agent?.user_id) && form.role && (
                            <div className="form-group">
                                <label className="form-label">Panel Şifresi *</label>
                                <input className="form-input" type="password" value={form.password} onChange={e => set('password', e.target.value)} placeholder="En az 6 karakter" />
                            </div>
                        )}
                        {isEdit && agent?.user_id && (
                            <div className="form-group">
                                <label className="form-label">Yeni Şifre (değiştirmek isterseniz)</label>
                                <input className="form-input" type="password" value={form.password} onChange={e => set('password', e.target.value)} placeholder="Boş bırakırsanız değişmez" />
                            </div>
                        )}
                        {form.role && (
                            <div style={{ fontSize: 11, color: 'var(--text-dim)', padding: '6px 0' }}>
                                {form.role === 'admin' && 'Admin tüm modüllere tam erişime sahiptir.'}
                                {form.role === 'supervisor' && 'Supervisor sadece aşağıda seçtiğiniz modüllere erişebilir.'}
                                {form.role === 'viewer' && 'İzleyici seçtiğiniz modülleri salt okunur olarak görür.'}
                            </div>
                        )}
                        {showPerms && (
                            <_PermGrid permissions={form.permissions} onChange={p => set('permissions', p)} />
                        )}
                    </div>

                    {error && <div style={{ color: 'var(--red)', marginTop: 12 }}>! {error}</div>}
                </div>
                <div className="modal-footer">
                    <button className="btn outline" onClick={onClose}>Iptal Et</button>
                    <button className="btn primary" onClick={save} disabled={saving}>{saving ? 'Kaydediliyor...' : 'Olustur / Guncelle'}</button>
                </div>
            </div>
        </div>
    );
}

/* ── Bulk Import Modal ── */
function BulkImportModal({ onClose, onDone, toast }) {
    const [file, setFile] = useState(null);
    const [uploading, setUploading] = useState(false);
    const [result, setResult] = useState(null);
    const [dragOver, setDragOver] = useState(false);

    function handleFile(f) {
        if (!f) return;
        const name = f.name.toLowerCase();
        if (!name.endsWith('.csv') && !name.endsWith('.xlsx') && !name.endsWith('.xls')) {
            toast('Sadece CSV veya Excel (.xlsx) desteklenir', 'error');
            return;
        }
        setFile(f);
        setResult(null);
    }

    async function upload() {
        if (!file) return;
        setUploading(true);
        try {
            const fd = new FormData();
            fd.append('file', file);
            const r = await authFetch('/api/human-agents/bulk-import', { method: 'POST', body: fd });
            const data = await r.json();
            if (!r.ok) throw new Error(data.detail || 'Yukleme basarisiz');
            setResult(data);
            if (data.inserted > 0) {
                toast(`${data.inserted} temsilci basariyla eklendi`, 'success');
            }
        } catch (e) {
            toast(e.message, 'error');
        } finally {
            setUploading(false);
        }
    }

    return (
        <div className="overlay" onClick={onClose}>
            <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 600 }}>
                <div className="modal-header">
                    <span style={{ fontWeight:600, fontSize: 18 }}>Toplu Temsilci Yukle</span>
                    <button className="close-btn" onClick={onClose}>×</button>
                </div>
                <div className="modal-body">
                    <div style={{ fontSize: 13, color: 'var(--text-dim)', marginBottom: 16, lineHeight: 1.6 }}>
                        CSV veya Excel dosyasi ile toplu temsilci ekleyin.<br />
                        <strong>Zorunlu sutunlar:</strong> <code style={{ background: 'var(--surface2)', padding: '2px 6px', borderRadius: 4 }}>ad</code>ve <code style={{ background: 'var(--surface2)', padding: '2px 6px', borderRadius: 4 }}>dahili</code><br />
                        <strong>Opsiyonel:</strong>sifre, departman, acw, oto_cevap
                    </div>

                    <label
                        className={`import-dropzone ${dragOver ? 'dragover' : ''} ${file ? 'has-file' : ''}`}
                        onDragOver={e => { e.preventDefault(); setDragOver(true); }}
                        onDragLeave={() =>setDragOver(false)}
                        onDrop={e => { e.preventDefault(); setDragOver(false); handleFile(e.dataTransfer.files[0]); }}
                    >
                        <input type="file" accept=".csv,.xlsx,.xls" style={{ display: 'none' }} onChange={e =>handleFile(e.target.files[0])} />
                        {file ? (
                            <>
                                <span style={{ fontSize: 13, fontWeight: 600 }}>{file.name.endsWith('.csv') ? 'CSV' : 'XLS'}</span>
                                <div>
                                    <div style={{ fontWeight:600, fontSize: 14, color: 'var(--text)' }}>{file.name}</div>
                                    <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2 }}>
                                        {file.size < 1024*1024 ? `${(file.size/1024).toFixed(1)} KB` : `${(file.size/1024/1024).toFixed(2)} MB`}
                                    </div>
                                </div>
                                <span style={{ fontSize: 12, color: 'var(--green)', fontWeight:600 }}>Hazir</span>
                            </>
                        ) : (
                            <>
                                <span style={{ fontSize: 13, color: 'var(--text-dim)' }}>Dosya</span>
                                <div style={{ color: 'var(--text-dim)', lineHeight: 1.5 }}>
                                    <strong style={{ color: 'var(--text)', fontSize: 13 }}>Dosya secmek icin tiklayin veya surukleyin</strong><br />
                                    <span style={{ fontSize: 12 }}>CSV veya Excel (.xlsx)</span>
                                </div>
                            </>
                        )}
                    </label>

                    {result && (
                        <div className={`import-result ${result.errors?.length > 0 ? 'has-errors' : 'success'}`}>
                            <div style={{ fontWeight:600, fontSize: 14, marginBottom: 6 }}>
                                {result.inserted > 0 ? `${result.inserted} temsilci eklendi` : 'Hic temsilci eklenemedi'}
                                {result.skipped > 0 && ` — ${result.skipped} satir atlandi`}
                            </div>
                            {result.errors?.length > 0 && (
                                <div style={{ marginTop: 8, maxHeight: 150, overflowY: 'auto' }}>
                                    {result.errors.map((e, i) => (
                                        <div key={i} style={{ fontSize: 12, padding: '3px 0' }}>
                                            Satir {e.row}: {e.reason}
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>
                    )}
                </div>
                <div className="modal-footer">
                    {result?.inserted > 0 ? (
                        <button className="btn primary" onClick={() => { onDone(); onClose(); }}>Tamam</button>
                    ) : (
                        <>
                            <button className="btn outline" onClick={onClose}>Iptal</button>
                            <button className="btn primary" onClick={upload} disabled={!file || uploading}>
                                {uploading ? 'Yukleniyor...' : 'Yukle'}
                            </button>
                        </>
                    )}
                </div>
            </div>
        </div>
    );
}

/* ── Bulk Queue Modal ── */
function BulkQueueModal({ selectedIds, onClose, onDone, toast }) {
    const [allQueues, setAllQueues] = useState([]);
    const [selectedQueues, setSelectedQueues] = useState([]);
    const [saving, setSaving] = useState(false);

    useEffect(() => { authFetch('/api/queues').then(r =>r.ok ? r.json() : []).then(setAllQueues).catch(() => {}); }, []);

    function toggleQueue(qid) {
        setSelectedQueues(p =>p.includes(qid) ? p.filter(id =>id !== qid) : [...p, qid]);
    }

    async function apply() {
        setSaving(true);
        try {
            const r = await authFetch('/api/human-agents/bulk-queues', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ ids: selectedIds, queue_ids: selectedQueues }),
            });
            const data = await r.json();
            if (!r.ok) throw new Error(data.detail || 'Hata');
            toast(`${data.updated} temsilcinin kuyrulari guncellendi`, 'success');
            onDone();
            onClose();
        } catch (e) { toast(e.message, 'error'); } finally { setSaving(false); }
    }

    return (
        <div className="overlay" onClick={onClose}>
            <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 480 }}>
                <div className="modal-header">
                    <span style={{ fontWeight:600, fontSize: 18 }}>Toplu Kuyruk Atama</span>
                    <button className="close-btn" onClick={onClose}>×</button>
                </div>
                <div className="modal-body">
                    <p style={{ fontSize: 13, color: 'var(--text-dim)', marginBottom: 16 }}>
                        <strong>{selectedIds.length}</strong>temsilcinin kuyruk uyeligini secin:
                    </p>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                        {allQueues.map(q => {
                            const sel = selectedQueues.includes(q.id);
                            return (
                                <label key={q.id} style={{
                                    display: 'flex', alignItems: 'center', gap: 8, padding: '10px 16px',
                                    borderRadius: 8, cursor: 'pointer',
                                    border: `1px solid ${sel ? 'rgba(88,166,255,.5)' : 'var(--border)'}`,
                                    background: sel ? 'rgba(88,166,255,.1)' : 'var(--surface2)',
                                    transition: 'all .15s',
                                }}>
                                    <input type="checkbox" checked={sel} onChange={() =>toggleQueue(q.id)} style={{ accentColor: 'var(--blue)' }} />
                                    <span style={{ fontWeight: sel ? 700 : 400, color: sel ? 'var(--blue)' : 'var(--text)' }}>{q.name}</span>
                                </label>
                            );
                        })}
                        {allQueues.length === 0 && <span style={{ color: 'var(--text-dim)', fontSize: 13 }}>Tanimli kuyruk bulunamadi.</span>}
                    </div>
                </div>
                <div className="modal-footer">
                    <button className="btn outline" onClick={onClose}>Iptal</button>
                    <button className="btn primary" onClick={apply} disabled={saving}>
                        {saving ? 'Uygulaniyor...' : 'Ata'}
                    </button>
                </div>
            </div>
        </div>
    );
}

/* ═══════════════════════════════════════════════════════════════════════════════
   MAIN: HumanAgentsTab — Sadece Tablo Gorunumu
   ═══════════════════════════════════════════════════════════════════════════════ */

function HumanAgentsTab({ toast }) {
    // ── Data
    const { data: agents, reload: reloadAgents } = window.useApi('/api/human-agents', []);

    // ── Teams list (for display)
    const [allTeams, setAllTeams] = useState([]);


    // Load teams list
    useEffect(() => {
        authFetch('/api/teams').then(r =>r.ok ? r.json() : []).then(d =>setAllTeams(Array.isArray(d) ? d : [])).catch(() => {});
    }, [agents]);

    // Active agents list
    const agentsWithStats = useMemo(() => {
        const activeList = Array.isArray(agents) ? agents.filter(a => a.is_active) : [];
        return activeList.map(a => {
            const merged = { ...a };
            if (merged.queues && merged.queues.length > 0) {
                merged.queues = merged.queues.map(q => typeof q === 'string' ? q : q.name);
            }
            return merged;
        });
    }, [agents]);

    // ── Modals
    const [agentModal, setAgentModal] = useState(null);
    const [importModal, setImportModal] = useState(false);
    const [bulkQueueModal, setBulkQueueModal] = useState(false);

    // ── Search, filter, sort, pagination
    const [search, setSearch] = useState('');
    const [filterDept, setFilterDept] = useState('');
    const [sortKey, setSortKey] = useState('name');
    const [sortDir, setSortDir] = useState('asc');
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(25);

    // ── Selection
    const [selected, setSelected] = useState(new Set());

    // ── Active agents
    const activeAgents = agentsWithStats;

    // ── Departments from data
    const departments = useMemo(() => {
        const depts = new Set();
        activeAgents.forEach(a => { if (a.department) depts.add(a.department); });
        return [...depts].sort();
    }, [activeAgents]);

    // ── Filtered + sorted
    const filteredAgents = useMemo(() => {
        let list = [...activeAgents];

        if (search.trim()) {
            const q = search.toLowerCase();
            list = list.filter(a =>
                a.name.toLowerCase().includes(q) ||
                a.extension.toLowerCase().includes(q) ||
                (a.department || '').toLowerCase().includes(q)
            );
        }

        if (filterDept) list = list.filter(a =>a.department === filterDept);

        list.sort((a, b) => {
            let va = a[sortKey] || '';
            let vb = b[sortKey] || '';
            if (typeof va === 'number' && typeof vb === 'number') {
                return sortDir === 'asc' ? va - vb : vb - va;
            }
            if (typeof va === 'string') va = va.toLowerCase();
            if (typeof vb === 'string') vb = vb.toLowerCase();
            if (va < vb) return sortDir === 'asc' ? -1 : 1;
            if (va >vb) return sortDir === 'asc' ? 1 : -1;
            return 0;
        });

        return list;
    }, [activeAgents, search, filterDept, sortKey, sortDir]);

    // ── Paginated
    const totalPages = Math.max(1, Math.ceil(filteredAgents.length / pageSize));
    const currentPage = Math.min(page, totalPages);
    const paginatedAgents = useMemo(() => {
        const start = (currentPage - 1) * pageSize;
        return filteredAgents.slice(start, start + pageSize);
    }, [filteredAgents, currentPage, pageSize]);

    useEffect(() => { setPage(1); }, [search, filterDept, pageSize]);
    useEffect(() => { setSelected(new Set()); }, [agents]);

    // ── Handlers
    function toggleSort(key) {
        if (sortKey === key) setSortDir(d =>d === 'asc' ? 'desc' : 'asc');
        else { setSortKey(key); setSortDir('asc'); }
    }

    function toggleSelect(id) {
        setSelected(prev => {
            const next = new Set(prev);
            if (next.has(id)) next.delete(id); else next.add(id);
            return next;
        });
    }

    function toggleSelectAll() {
        if (selected.size === paginatedAgents.length) {
            setSelected(new Set());
        } else {
            setSelected(new Set(paginatedAgents.map(a =>a.id)));
        }
    }

    async function delAgent(id) {
        if (!confirm('Temsilciyi pasife almak istediginize emin misiniz?')) return;
        await authFetch(`/api/human-agents/${id}`, { method: 'DELETE' });
        toast('Temsilci pasife alindi', 'success');
        reloadAgents();
    }

    async function bulkDelete() {
        const ids = [...selected];
        if (!confirm(`${ids.length} temsilciyi pasife almak istediginize emin misiniz?`)) return;
        try {
            const r = await authFetch('/api/human-agents/bulk-delete', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ ids }),
            });
            const data = await r.json();
            toast(`${data.deleted} temsilci pasife alindi`, 'success');
            setSelected(new Set());
            reloadAgents();
        } catch (e) { toast('Hata: ' + e.message, 'error'); }
    }

    async function exportCSV() {
        try {
            const r = await authFetch('/api/human-agents/export');
            const blob = await r.blob();
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url; a.download = 'temsilciler.csv'; a.click();
            URL.revokeObjectURL(url);
            toast('CSV indirildi', 'success');
        } catch (e) { toast('Indirme hatasi', 'error'); }
    }

    // ── Sort arrow helper
    const SortArrow = ({ col }) => (
        <span className="sort-arrow">{sortKey === col ? (sortDir === 'asc' ? '▲' : '▼') : '↕'}</span>
    );

    // ── Page buttons
    function pageButtons() {
        const btns = [];
        const maxVisible = 7;
        let start = Math.max(1, currentPage - 3);
        let end = Math.min(totalPages, start + maxVisible - 1);
        if (end - start < maxVisible - 1) start = Math.max(1, end - maxVisible + 1);

        btns.push(
            <button key="prev" className="page-btn" disabled={currentPage <= 1} onClick={() =>setPage(p =>p - 1)}>‹</button>
        );
        if (start > 1) {
            btns.push(<button key={1} className="page-btn" onClick={() =>setPage(1)}>1</button>);
            if (start > 2) btns.push(<span key="dots1" style={{ padding: '0 4px', color: 'var(--text-dim)' }}>…</span>);
        }
        for (let i = start; i <= end; i++) {
            btns.push(
                <button key={i} className={`page-btn ${i === currentPage ? 'active' : ''}`} onClick={() =>setPage(i)}>{i}</button>
            );
        }
        if (end < totalPages) {
            if (end < totalPages - 1) btns.push(<span key="dots2" style={{ padding: '0 4px', color: 'var(--text-dim)' }}>…</span>);
            btns.push(<button key={totalPages} className="page-btn" onClick={() =>setPage(totalPages)}>{totalPages}</button>);
        }
        btns.push(
            <button key="next" className="page-btn" disabled={currentPage >= totalPages} onClick={() =>setPage(p =>p + 1)}>›</button>
        );
        return btns;
    }

    // ═══════════════════════════ RENDER ═══════════════════════════

    return (
        <div className="fade-in">
            {/* ── Header ── */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                    <h2 style={{ fontSize: 20, fontWeight: 600, margin: 0 }}>Temsilci Tanımları</h2>
                    <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>
                        {activeAgents.length} aktif temsilci
                    </span>
                </div>
                <button className="btn primary" onClick={() => setAgentModal('new')}>
                    + Yeni Temsilci
                </button>
            </div>

            {/* ── Toolbar ── */}
            <div className="agent-toolbar">
                <div className="search-box">
                    <span className="search-icon"></span>
                    <input
                        placeholder="Temsilci ara (ad, dahili, departman)..."
                        value={search}
                        onChange={e =>setSearch(e.target.value)}
                    />
                </div>

                <select className="filter-select" value={filterDept} onChange={e =>setFilterDept(e.target.value)}>
                    <option value="">Tum Departmanlar</option>
                    {departments.map(d => <option key={d} value={d}>{d}</option>)}
                </select>

                <div style={{ flex: 1 }} />

                <button className="btn-sm" onClick={() =>setImportModal(true)} title="CSV/Excel ile toplu ekle">
                    Toplu Yukle
                </button>
                <button className="btn-sm" onClick={exportCSV} title="CSV olarak indir">
                    Indir
                </button>
            </div>

            {/* ── Bulk Action Bar ── */}
            {selected.size > 0 && (
                <div className="bulk-bar">
                    <span className="bulk-count">{selected.size} temsilci secili</span>
                    <button className="bulk-btn danger" onClick={bulkDelete}>Pasife Al</button>
                    <button className="bulk-btn" onClick={() =>setBulkQueueModal(true)}>Kuyruk Ata</button>
                    <div style={{ flex: 1 }} />
                    <button className="bulk-btn" onClick={() =>setSelected(new Set())} style={{ border: 'none', color: 'var(--text-dim)' }}>Secimi Kaldir ×</button>
                </div>
            )}

            {/* ── Table ── */}
            <div style={{ overflowX: 'auto' }}>
            <table className="agent-table">
                <thead>
                    <tr>
                        <th style={{ width: 40, textAlign: 'center' }}>
                            <input type="checkbox"
                                checked={paginatedAgents.length > 0 && selected.size === paginatedAgents.length}
                                onChange={toggleSelectAll}
                            />
                        </th>
                        <th className={`sortable ${sortKey === 'name' ? 'sorted' : ''}`} onClick={() => toggleSort('name')}>Temsilci <SortArrow col="name" /></th>
                        <th className={`sortable ${sortKey === 'extension' ? 'sorted' : ''}`} onClick={() => toggleSort('extension')}>Dahili <SortArrow col="extension" /></th>
                        <th className={`sortable ${sortKey === 'department' ? 'sorted' : ''}`} onClick={() => toggleSort('department')}>Departman <SortArrow col="department" /></th>
                        <th>Rol</th>
                        <th>Takım</th>
                        <th>Kuyruklar</th>
                        <th style={{ width: 140, minWidth: 140 }}></th>
                    </tr>
                </thead>
                <tbody>
                    {paginatedAgents.length === 0 && (
                        <tr><td colSpan={8} className="dash-table-empty">
                            {search || filterDept ? 'Filtreye uygun temsilci bulunamadı.' : 'Henüz temsilci tanımlanmamış.'}
                        </td></tr>
                    )}
                    {paginatedAgents.map(a => (
                        <tr key={a.id} className={selected.has(a.id) ? 'selected' : ''}>
                            <td style={{ textAlign: 'center' }}>
                                <input type="checkbox" checked={selected.has(a.id)} onChange={() => toggleSelect(a.id)} />
                            </td>
                            <td>
                                <span style={{ fontWeight: 500, fontSize: 13 }}>{a.name}</span>
                            </td>
                            <td>
                                <span className="mono" style={{ fontSize: 13, color: 'var(--text-dim)' }}>{a.extension}</span>
                            </td>
                            <td>
                                {a.department
                                    ? <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>{a.department}</span>
                                    : <span style={{ fontSize: 12, color: 'var(--text-dim)', opacity: 0.4 }}>—</span>
                                }
                            </td>
                            <td>
                                {a.role && _ROLE_LABELS[a.role] ? (
                                    <span style={{ padding: '2px 8px', borderRadius: 4, fontSize: 11, fontWeight: 600, background: (_ROLE_COLORS[a.role] || {}).bg || '#f3f4f6', color: (_ROLE_COLORS[a.role] || {}).color || '#374151' }}>
                                        {_ROLE_LABELS[a.role]}
                                    </span>
                                ) : <span style={{ fontSize: 12, color: 'var(--text-dim)', opacity: 0.4 }}>—</span>}
                            </td>
                            <td>
                                {a.team_id ? (
                                    <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>
                                        {(allTeams || []).find(t => t.id === a.team_id)?.name || `Takım #${a.team_id}`}
                                    </span>
                                ) : <span style={{ fontSize: 12, color: 'var(--text-dim)', opacity: 0.4 }}>—</span>}
                            </td>
                            <td>
                                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                                    {a.queues && a.queues.length > 0
                                        ? a.queues.map((q, i) => (
                                            <span key={i} style={{ padding: '2px 8px', borderRadius: 4, fontSize: 11, background: 'rgba(139,148,158,.08)', color: 'var(--text-dim)' }}>{typeof q === 'string' ? q : q.name}</span>
                                          ))
                                        : <span style={{ fontSize: 12, color: 'var(--text-dim)', opacity: 0.4 }}>—</span>
                                    }
                                </div>
                            </td>
                            <td style={{ whiteSpace: 'nowrap' }}>
                                <div style={{ display: 'flex', gap: 6, alignItems: 'center', justifyContent: 'flex-end' }}>
                                    <button onClick={() => setAgentModal(a)} title="Düzenle" style={{ padding: '4px 10px', borderRadius: 4, border: '1px solid var(--border)', background: 'transparent', cursor: 'pointer', fontSize: 11, color: 'var(--text-dim)', whiteSpace: 'nowrap' }}>Düzenle</button>
                                    <button onClick={() => delAgent(a.id)} title="Pasife Al" style={{ padding: '4px 10px', borderRadius: 4, border: '1px solid rgba(248,81,73,.2)', background: 'transparent', cursor: 'pointer', fontSize: 11, color: 'var(--red)', whiteSpace: 'nowrap' }}>Sil</button>
                                </div>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
            </div>

            {/* ── Pagination ── */}
            {filteredAgents.length > 0 && (
                <div className="pagination">
                    <span className="page-info">
                        Toplam {filteredAgents.length} temsilci
                        {filteredAgents.length !== activeAgents.length && ` (${activeAgents.length} kayittan filtrelendi)`}
                    </span>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                        <select className="page-size-select" value={pageSize} onChange={e =>setPageSize(+e.target.value)}>
                            <option value={25}>25 / sayfa</option>
                            <option value={50}>50 / sayfa</option>
                            <option value={100}>100 / sayfa</option>
                        </select>
                        <div className="page-buttons">{pageButtons()}</div>
                    </div>
                </div>
            )}

            {/* ══════════════ MODALS ══════════════ */}
            {agentModal && <HumanAgentModal agent={agentModal === 'new' ? null : agentModal} onClose={() =>setAgentModal(null)} onSave={() => { toast('Temsilci kaydedildi', 'success'); setAgentModal(null); reloadAgents(); }} />}
            {importModal && <BulkImportModal onClose={() =>setImportModal(false)} onDone={reloadAgents} toast={toast} />}
            {bulkQueueModal && <BulkQueueModal selectedIds={[...selected]} onClose={() =>setBulkQueueModal(false)} onDone={() => { setSelected(new Set()); reloadAgents(); }} toast={toast} />}
        </div>
    );
}

window.HumanAgentsTab = HumanAgentsTab;
