/* ══════════════════════════════════════════════════
   QueuesTab.jsx — Kuyruk Tanımları Yönetim Paneli
   Kuyruk adı, extension, açıklama, aktif/pasif
══════════════════════════════════════════════════ */
const { useState, useEffect, useMemo } = React;

/* ── Kuyruk Formu Modal ─────────────────────────── */
function QueueModal({ queue, onClose, onSave }) {
    const empty = { name: '', extension: '', description: '', is_active: true };
    const [form, setForm] = useState(queue ? { ...queue } : empty);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');

    const set = (k, v) => { setForm(f => ({ ...f, [k]: v })); setError(''); };

    async function handleSave() {
        if (!form.name.trim()) { setError('Kuyruk adı zorunludur.'); return; }
        if (!form.extension.trim()) { setError('Extension zorunludur.'); return; }

        setSaving(true);
        try {
            const url = queue ? `/api/queues/${queue.id}` : '/api/queues';
            const method = queue ? 'PUT' : 'POST';
            const r = await authFetch(url, {
                method,
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(form),
            });
            if (r.ok) {
                onSave();
            } else {
                const err = await r.json();
                setError(err.detail || JSON.stringify(err));
            }
        } catch (e) {
            setError('Bağlantı hatası: ' + e.message);
        } finally {
            setSaving(false);
        }
    }

    return (
        <div className="overlay" onClick={onClose}
             style={{ paddingTop: 60, overflowY: 'auto', alignItems: 'flex-start' }}>
            <div className="modal" onClick={e => e.stopPropagation()}
                 style={{ maxWidth: 540, margin: 'auto' }}>

                <div className="modal-header">
                    <span style={{ fontWeight: 600, fontSize: 18 }}>
                        {queue ? 'Kuyruğu Düzenle' : 'Yeni Kuyruk'}
                    </span>
                    <button className="close-btn" onClick={onClose}>×</button>
                </div>

                <div className="modal-body" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                    <div className="form-group">
                        <label className="form-label">Kuyruk Adı *</label>
                        <input
                            className="form-input"
                            value={form.name}
                            onChange={e => set('name', e.target.value)}
                            placeholder="Örn: Satış Kuyruğu"
                        />
                    </div>

                    <div className="form-group">
                        <label className="form-label">Dahili Numara (Extension) *</label>
                        <input
                            className="form-input mono"
                            value={form.extension}
                            onChange={e => set('extension', e.target.value)}
                            placeholder="Örn: 8001"
                            style={{ letterSpacing: 1 }}
                        />
                        <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 5 }}>
                            IVR yönlendirmesi ve FreeSWITCH dialplan'da kullanılır.
                        </div>
                    </div>

                    <div className="form-group">
                        <label className="form-label">Açıklama</label>
                        <input
                            className="form-input"
                            value={form.description}
                            onChange={e => set('description', e.target.value)}
                            placeholder="Bu kuyruk ne için kullanılıyor?"
                        />
                    </div>

                    <div style={{
                        display: 'flex', alignItems: 'center', gap: 12,
                        padding: '12px 14px', borderRadius: 8,
                        background: form.is_active ? 'rgba(34,197,94,.05)' : 'var(--surface2)',
                        border: `1px solid ${form.is_active ? 'rgba(34,197,94,.2)' : 'var(--border)'}`,
                    }}>
                        <input
                            type="checkbox" id="q-active"
                            checked={form.is_active}
                            onChange={e => set('is_active', e.target.checked)}
                            style={{ width: 16, height: 16, cursor: 'pointer' }}
                        />
                        <label htmlFor="q-active" className="form-label"
                               style={{ margin: 0, cursor: 'pointer', fontSize: 13,
                                        color: 'var(--text-dim)' }}>
                            {form.is_active ? 'Aktif — çağrılar bu kuyruğa yönlendirilebilir'
                                            : 'Pasif — yönlendirme devre dışı'}
                        </label>
                    </div>

                    {error && (
                        <div style={{ padding: '10px 14px', borderRadius: 8,
                                      background: 'rgba(248,81,73,.08)',
                                      border: '1px solid rgba(248,81,73,.2)',
                                      color: 'var(--red)', fontSize: 13 }}>
                             {error}
                        </div>
                    )}
                </div>

                <div className="modal-footer">
                    <button className="btn outline" onClick={onClose}>İptal</button>
                    <button className="btn primary" onClick={handleSave} disabled={saving}>
                        {saving ? 'Kaydediliyor...' : (queue ? 'Güncelle' : 'Oluştur')}
                    </button>
                </div>
            </div>
        </div>
    );
}

/* ── Temsilci Yönetimi Modal ─────────────────────── */
const MEMBERS_PAGE_SIZE = 20;

function QueueMembersModal({ queue, onClose, toast, onMemberChange }) {
    const [agents, setAgents] = useState(null);
    const [allAgents, setAllAgents] = useState([]);
    const [search, setSearch] = useState('');
    const [tab, setTab] = useState('members'); // 'members' | 'add'
    const [removing, setRemoving] = useState(null);
    const [memberPage, setMemberPage] = useState(1);
    const [addPage, setAddPage] = useState(1);

    function loadMembers() {
        authFetch(`/api/queues/${queue.id}/agents`)
            .then(r => r.ok ? r.json() : [])
            .then(setAgents)
            .catch(() => setAgents([]));
    }

    function loadAllAgents() {
        authFetch('/api/human-agents')
            .then(r => r.ok ? r.json() : [])
            .then(list => setAllAgents(Array.isArray(list) ? list.filter(a => a.is_active) : []))
            .catch(() => setAllAgents([]));
    }

    useEffect(() => { loadMembers(); loadAllAgents(); }, [queue.id]);

    // Reset pages when search or tab changes
    useEffect(() => { setMemberPage(1); setAddPage(1); }, [search, tab]);

    async function addAgent(agentId) {
        try {
            const r = await authFetch(`/api/queues/${queue.id}/agents/${agentId}`, { method: 'POST' });
            if (r.ok) {
                toast('Temsilci kuyruğa eklendi', 'success');
                loadMembers();
                if (onMemberChange) onMemberChange();
            } else {
                const err = await r.json();
                toast(err.detail || 'Ekleme hatası', 'error');
            }
        } catch (e) { toast('Bağlantı hatası', 'error'); }
    }

    async function removeAgent(agentId) {
        setRemoving(agentId);
        try {
            const r = await authFetch(`/api/queues/${queue.id}/agents/${agentId}`, { method: 'DELETE' });
            if (r.ok) {
                toast('Temsilci kuyruktan çıkarıldı', 'success');
                loadMembers();
                if (onMemberChange) onMemberChange();
            } else {
                toast('Çıkarma hatası', 'error');
            }
        } catch (e) { toast('Bağlantı hatası', 'error'); }
        finally { setRemoving(null); }
    }

    const memberIds = new Set((agents || []).map(a => a.id));
    const availableAgents = allAgents.filter(a => !memberIds.has(a.id));

    const filterFn = (a) => {
        if (!search.trim()) return true;
        const s = search.toLowerCase();
        return a.name.toLowerCase().includes(s) ||
               (a.extension || '').toLowerCase().includes(s) ||
               (a.department || '').toLowerCase().includes(s);
    };

    const filteredMembers = (agents || []).filter(filterFn);
    const filteredAvailable = availableAgents.filter(filterFn);

    const memberTotalPages = Math.max(1, Math.ceil(filteredMembers.length / MEMBERS_PAGE_SIZE));
    const addTotalPages = Math.max(1, Math.ceil(filteredAvailable.length / MEMBERS_PAGE_SIZE));

    const pagedMembers = filteredMembers.slice((memberPage - 1) * MEMBERS_PAGE_SIZE, memberPage * MEMBERS_PAGE_SIZE);
    const pagedAvailable = filteredAvailable.slice((addPage - 1) * MEMBERS_PAGE_SIZE, addPage * MEMBERS_PAGE_SIZE);

    function Pagination({ current, total, onChange }) {
        if (total <= 1) return null;
        return React.createElement('div', {
            style: { display: 'flex', alignItems: 'center', justifyContent: 'center',
                     gap: 8, padding: '12px 0', borderTop: '1px solid var(--border)', marginTop: 8 }
        },
            React.createElement('button', {
                onClick: () => onChange(Math.max(1, current - 1)),
                disabled: current <= 1,
                style: { padding: '4px 10px', borderRadius: 6, border: '1px solid var(--border)',
                         background: 'var(--surface2)', color: 'var(--text-dim)', cursor: current <= 1 ? 'default' : 'pointer',
                         fontSize: 12, opacity: current <= 1 ? 0.4 : 1 }
            }, '‹ Önceki'),
            React.createElement('span', {
                style: { fontSize: 12, color: 'var(--text-dim)' }
            }, `${current} / ${total}`),
            React.createElement('button', {
                onClick: () => onChange(Math.min(total, current + 1)),
                disabled: current >= total,
                style: { padding: '4px 10px', borderRadius: 6, border: '1px solid var(--border)',
                         background: 'var(--surface2)', color: 'var(--text-dim)', cursor: current >= total ? 'default' : 'pointer',
                         fontSize: 12, opacity: current >= total ? 0.4 : 1 }
            }, 'Sonraki ›')
        );
    }

    return (
        <div className="overlay" onClick={onClose}
             style={{ paddingTop: 40, overflowY: 'auto', alignItems: 'flex-start' }}>
            <div className="modal" onClick={e => e.stopPropagation()}
                 style={{ maxWidth: 640, margin: 'auto', maxHeight: '80vh', display: 'flex', flexDirection: 'column' }}>

                <div className="modal-header" style={{ flexShrink: 0 }}>
                    <div>
                        <span style={{ fontWeight: 600, fontSize: 16 }}>
                            {queue.name}
                        </span>
                        <span style={{ fontSize: 12, color: 'var(--text-dim)', marginLeft: 8 }}>
                            Temsilci Yönetimi
                        </span>
                    </div>
                    <button className="close-btn" onClick={onClose}>×</button>
                </div>

                {/* Tab switcher + Search */}
                <div style={{ padding: '12px 20px 0', flexShrink: 0 }}>
                    <div style={{ display: 'flex', gap: 0, marginBottom: 12, borderBottom: '1px solid var(--border)' }}>
                        {[
                            { key: 'members', label: `Atanmış (${(agents || []).length})` },
                            { key: 'add', label: `Ekle (${availableAgents.length})` },
                        ].map(t => (
                            <button key={t.key}
                                onClick={() => setTab(t.key)}
                                style={{
                                    padding: '8px 20px', fontSize: 13, fontWeight: 500,
                                    border: 'none', cursor: 'pointer',
                                    background: 'transparent',
                                    color: tab === t.key ? 'var(--text)' : 'var(--text-dim)',
                                    borderBottom: tab === t.key ? '2px solid var(--blue)' : '2px solid transparent',
                                    transition: 'all .15s',
                                    marginBottom: -1,
                                }}
                            >{t.label}</button>
                        ))}
                    </div>
                    <input
                        placeholder="Temsilci ara (ad, dahili, departman)..."
                        value={search}
                        onChange={e => setSearch(e.target.value)}
                        style={{
                            width: '100%', padding: '8px 12px', borderRadius: 6,
                            border: '1px solid var(--border)', background: 'var(--surface2)',
                            fontSize: 13, color: 'var(--text)', outline: 'none', boxSizing: 'border-box',
                        }}
                    />
                </div>

                {/* Content */}
                <div style={{ flex: 1, overflowY: 'auto', padding: '12px 20px 20px' }}>
                    {agents === null ? (
                        <div style={{ textAlign: 'center', padding: 24, color: 'var(--text-dim)', fontSize: 13 }}>
                            Yükleniyor...
                        </div>
                    ) : tab === 'members' ? (
                        <>
                            {filteredMembers.length === 0 ? (
                                <div style={{ textAlign: 'center', padding: 24, color: 'var(--text-dim)', fontSize: 13 }}>
                                    {search.trim() ? 'Aramayla eşleşen temsilci bulunamadı.' : 'Bu kuyruğa henüz temsilci atanmamış.'}
                                </div>
                            ) : (
                                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                    <thead>
                                        <tr style={{ borderBottom: '1px solid var(--border)' }}>
                                            <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: 11, fontWeight: 500, color: 'var(--text-dim)', textTransform: 'uppercase' }}>Ad</th>
                                            <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: 11, fontWeight: 500, color: 'var(--text-dim)', textTransform: 'uppercase' }}>Dahili</th>
                                            <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: 11, fontWeight: 500, color: 'var(--text-dim)', textTransform: 'uppercase' }}>Departman</th>
                                            <th style={{ padding: '8px 12px', textAlign: 'right', fontSize: 11, fontWeight: 500, color: 'var(--text-dim)', textTransform: 'uppercase', width: 80 }}></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {pagedMembers.map(a => (
                                            <tr key={a.id} style={{ borderBottom: '1px solid var(--border)' }}>
                                                <td style={{ padding: '10px 12px', fontSize: 13, fontWeight: 500 }}>{a.name}</td>
                                                <td style={{ padding: '10px 12px' }}>
                                                    <span className="mono" style={{ fontSize: 12, color: 'var(--text-dim)' }}>{a.extension}</span>
                                                </td>
                                                <td style={{ padding: '10px 12px', fontSize: 12, color: 'var(--text-dim)' }}>{a.department || '—'}</td>
                                                <td style={{ padding: '10px 12px', textAlign: 'right' }}>
                                                    <button
                                                        onClick={() => removeAgent(a.id)}
                                                        disabled={removing === a.id}
                                                        style={{
                                                            padding: '4px 10px', borderRadius: 4, fontSize: 11,
                                                            border: '1px solid rgba(248,81,73,.2)',
                                                            background: 'transparent',
                                                            color: 'var(--red)', cursor: 'pointer',
                                                            opacity: removing === a.id ? 0.5 : 1,
                                                            transition: 'all .15s',
                                                        }}
                                                    >
                                                        {removing === a.id ? '...' : 'Çıkar'}
                                                    </button>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}
                            <Pagination current={memberPage} total={memberTotalPages} onChange={setMemberPage} />
                        </>
                    ) : (
                        <>
                            {filteredAvailable.length === 0 ? (
                                <div style={{ textAlign: 'center', padding: 24, color: 'var(--text-dim)', fontSize: 13 }}>
                                    {search.trim() ? 'Aramayla eşleşen temsilci bulunamadı.' : 'Tüm temsilciler zaten bu kuyrukta.'}
                                </div>
                            ) : (
                                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                    <thead>
                                        <tr style={{ borderBottom: '1px solid var(--border)' }}>
                                            <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: 11, fontWeight: 500, color: 'var(--text-dim)', textTransform: 'uppercase' }}>Ad</th>
                                            <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: 11, fontWeight: 500, color: 'var(--text-dim)', textTransform: 'uppercase' }}>Dahili</th>
                                            <th style={{ padding: '8px 12px', textAlign: 'left', fontSize: 11, fontWeight: 500, color: 'var(--text-dim)', textTransform: 'uppercase' }}>Departman</th>
                                            <th style={{ padding: '8px 12px', textAlign: 'right', fontSize: 11, fontWeight: 500, color: 'var(--text-dim)', textTransform: 'uppercase', width: 80 }}></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {pagedAvailable.map(a => (
                                            <tr key={a.id}
                                                style={{ borderBottom: '1px solid var(--border)', cursor: 'pointer', transition: 'background .1s' }}
                                                onMouseEnter={e => e.currentTarget.style.background = 'rgba(88,166,255,.04)'}
                                                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                                            >
                                                <td style={{ padding: '10px 12px', fontSize: 13, fontWeight: 500 }}>{a.name}</td>
                                                <td style={{ padding: '10px 12px' }}>
                                                    <span className="mono" style={{ fontSize: 12, color: 'var(--text-dim)' }}>{a.extension}</span>
                                                </td>
                                                <td style={{ padding: '10px 12px', fontSize: 12, color: 'var(--text-dim)' }}>{a.department || '—'}</td>
                                                <td style={{ padding: '10px 12px', textAlign: 'right' }}>
                                                    <button
                                                        onClick={() => addAgent(a.id)}
                                                        style={{
                                                            padding: '4px 10px', borderRadius: 4, fontSize: 11,
                                                            border: '1px solid rgba(34,197,94,.2)',
                                                            background: 'transparent',
                                                            color: 'var(--green)', cursor: 'pointer',
                                                            transition: 'all .15s',
                                                        }}
                                                    >
                                                        Ekle
                                                    </button>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}
                            <Pagination current={addPage} total={addTotalPages} onChange={setAddPage} />
                        </>
                    )}
                </div>
            </div>
        </div>
    );
}


/* ── KALDIRILDI: LiveQueueMonitor Wallboard'a taşındı ── */
function _REMOVED_LiveQueueMonitor() {
    const [calls, setCalls] = useState(null);   // null = ilk yükleme
    const [lastUpdate, setLastUpdate] = useState(null);
    const [tick, setTick] = useState(0);        // bekleme sürelerini yenilemek için

    function fetchQueue() {
        authFetch('/api/live-calls')
            .then(r => r.ok ? r.json() : [])
            .then(data => {
                setCalls(Array.isArray(data) ? data : []);
                setLastUpdate(new Date());
            })
            .catch(() => setCalls(prev => prev === null ? [] : prev));
    }

    useEffect(() => {
        fetchQueue();
        const poll = setInterval(fetchQueue, 5000);
        return () => clearInterval(poll);
    }, []);

    // Bekleme sürelerini her saniye yenile
    useEffect(() => {
        const t = setInterval(() => setTick(n => n + 1), 1000);
        return () => clearInterval(t);
    }, []);

    const ringingCalls = (calls || []).filter(c => c.status === 'ringing');
    const ivrCalls     = (calls || []).filter(c => c.status === 'ivr');
    const queueCalls   = (calls || []).filter(c => c.status === 'queue');
    const activeCalls  = (calls || []).filter(c => c.status === 'active');
    const visibleCalls = calls || [];

    const fmtTime = (d) => d
        ? d.toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit', second: '2-digit' })
        : '';

    const queueOrAgent = (c) => {
        if (c.status === 'active') return c.agent_name || c.queue_name || '—';
        if (c.status === 'queue') return c.queue_name || '—';
        return '—';
    };

    return (
        <div style={{
            marginBottom: 28,
            border: '1px solid var(--border)',
            borderRadius: 10,
            background: 'var(--surface)',
            overflow: 'hidden',
        }}>
            {/* Panel başlık çubuğu */}
            <div style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '10px 16px',
                background: 'var(--surface2)',
                borderBottom: '1px solid var(--border)',
            }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span style={{ fontWeight: 600, fontSize: 14, color: 'var(--text)' }}>
                        Canlı Çağrı İzleme
                    </span>
                    {/* Canlı yeşil nokta — CSS animasyonu inline keyframes yerine style tag ile */}
                    <span style={{
                        display: 'inline-flex', alignItems: 'center', gap: 5,
                        fontSize: 11, color: 'var(--green)', fontWeight: 500,
                    }}>
                        <span style={{
                            width: 7, height: 7, borderRadius: '50%',
                            background: 'var(--green)',
                            boxShadow: '0 0 0 0 rgba(34,197,94,.4)',
                            animation: 'liveQueuePulse 2s infinite',
                            display: 'inline-block',
                        }} />
                        Canlı
                    </span>
                    <style>{`
                        @keyframes liveQueuePulse {
                            0%   { box-shadow: 0 0 0 0 rgba(34,197,94,.5); }
                            70%  { box-shadow: 0 0 0 6px rgba(34,197,94,0); }
                            100% { box-shadow: 0 0 0 0 rgba(34,197,94,0); }
                        }
                    `}</style>
                </div>
                <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>
                    {lastUpdate ? `Son güncelleme: ${fmtTime(lastUpdate)}` : ''}
                </span>
            </div>

            {/* Özet sayaçlar */}
            <div style={{
                display: 'flex', gap: 0,
                borderBottom: '1px solid var(--border)',
            }}>
                <div style={{
                    flex: 1, padding: '10px 18px',
                    borderRight: '1px solid var(--border)',
                    display: 'flex', alignItems: 'center', gap: 10,
                }}>
                    <span style={{ fontSize: 18 }}>🔔</span>
                    <div>
                        <div style={{ fontSize: 20, fontWeight: 700, color: '#b45309', lineHeight: 1.1 }}>
                            {calls === null ? '–' : ringingCalls.length}
                        </div>
                        <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 1 }}>Çalıyor</div>
                    </div>
                </div>
                <div style={{
                    flex: 1, padding: '10px 18px',
                    borderRight: '1px solid var(--border)',
                    display: 'flex', alignItems: 'center', gap: 10,
                }}>
                    <span style={{ fontSize: 18 }}>🤖</span>
                    <div>
                        <div style={{ fontSize: 20, fontWeight: 700, color: '#7c3aed', lineHeight: 1.1 }}>
                            {calls === null ? '–' : ivrCalls.length}
                        </div>
                        <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 1 }}>IVR / AI</div>
                    </div>
                </div>
                <div style={{
                    flex: 1, padding: '10px 18px',
                    borderRight: '1px solid var(--border)',
                    display: 'flex', alignItems: 'center', gap: 10,
                }}>
                    <span style={{ fontSize: 18 }}>⏳</span>
                    <div>
                        <div style={{ fontSize: 20, fontWeight: 700, color: '#c2410c', lineHeight: 1.1 }}>
                            {calls === null ? '–' : queueCalls.length}
                        </div>
                        <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 1 }}>Kuyrukta</div>
                    </div>
                </div>
                <div style={{
                    flex: 1, padding: '10px 18px',
                    display: 'flex', alignItems: 'center', gap: 10,
                }}>
                    <span style={{ fontSize: 18 }}>🟢</span>
                    <div>
                        <div style={{ fontSize: 20, fontWeight: 700, color: '#15803d', lineHeight: 1.1 }}>
                            {calls === null ? '–' : activeCalls.length}
                        </div>
                        <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 1 }}>Aktif</div>
                    </div>
                </div>
            </div>

            {/* İçerik */}
            <div style={{ padding: '0' }}>
                {calls === null ? (
                    <div style={{ padding: '20px 16px', textAlign: 'center',
                                  color: 'var(--text-dim)', fontSize: 13 }}>
                        Yükleniyor...
                    </div>
                ) : visibleCalls.length === 0 ? (
                    <div style={{ padding: '20px 16px', textAlign: 'center',
                                  color: 'var(--text-dim)', fontSize: 13 }}>
                        Aktif çağrı bulunmuyor.
                    </div>
                ) : (
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                        <thead>
                            <tr style={{ background: 'var(--surface2)',
                                         borderBottom: '1px solid var(--border)' }}>
                                {['Arayan', 'Aranan', 'Kuyruk/Temsilci', 'Süre', 'Durum'].map((h, i) => (
                                    <th key={i} style={{
                                        padding: '7px 14px', textAlign: 'left',
                                        fontSize: 10, fontWeight: 500,
                                        color: 'var(--text-dim)', textTransform: 'uppercase',
                                        letterSpacing: '.05em',
                                    }}>{h}</th>
                                ))}
                            </tr>
                        </thead>
                        <tbody>
                            {visibleCalls.map((c, i) => (
                                <tr key={c.call_uuid || i} style={{
                                    borderBottom: i < visibleCalls.length - 1
                                        ? '1px solid var(--border)' : 'none',
                                    transition: 'background .1s',
                                }}
                                    onMouseEnter={e => e.currentTarget.style.background = 'rgba(88,166,255,.03)'}
                                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                                >
                                    {/* Arayan */}
                                    <td style={{ padding: '9px 14px' }}>
                                        <span className="mono" style={{ fontSize: 13, color: 'var(--text)' }}>
                                            {c.caller_number || '—'}
                                        </span>
                                    </td>

                                    {/* Aranan */}
                                    <td style={{ padding: '9px 14px' }}>
                                        <span className="mono" style={{ fontSize: 12, color: 'var(--text-dim)' }}>
                                            {c.callee || '—'}
                                        </span>
                                    </td>

                                    {/* Kuyruk/Temsilci */}
                                    <td style={{ padding: '9px 14px', fontSize: 12,
                                                 color: 'var(--text-dim)' }}>
                                        {queueOrAgent(c)}
                                    </td>

                                    {/* Süre */}
                                    <td style={{ padding: '9px 14px' }}>
                                        <span className="mono" style={{
                                            fontSize: 12,
                                            color: 'var(--text-dim)',
                                        }}>
                                            {fmtWait(c.started_at)}
                                        </span>
                                    </td>

                                    {/* Durum badge */}
                                    <td style={{ padding: '9px 14px' }}>
                                        {statusBadge(c.status)}
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                )}
            </div>
        </div>
    );
}

/* ── Ana Tab ────────────────────────────────────── */
function QueuesTab({ toast }) {
    const { data: queues, reload } = window.useApi('/api/queues', []);
    const [modal, setModal] = useState(null);
    const [membersModal, setMembersModal] = useState(null);

    async function handleDelete(q) {
        if (!confirm(`"${q.name}" kuyruğunu silmek istediğinize emin misiniz?\nIVR menülerinde bu kuyruğa yapılan yönlendirmeler etkilenebilir.`)) return;
        const r = await authFetch(`/api/queues/${q.id}`, { method: 'DELETE' });
        if (r.ok) {
            toast(`"${q.name}" silindi.`, 'success');
            reload();
        } else {
            toast('Silme işlemi başarısız.', 'error');
        }
    }

    async function handleToggle(q) {
        const r = await authFetch(`/api/queues/${q.id}/toggle`, { method: 'PATCH' });
        if (r.ok) {
            toast(`"${q.name}" ${q.is_active ? 'pasif' : 'aktif'} yapıldı.`, 'success');
            reload();
        }
    }

    const totalCount = queues ? queues.length : 0;
    const activeCount = queues ? queues.filter(q => q.is_active).length : 0;
    const passiveCount = totalCount - activeCount;

    return (
        <div className="fade-in">

            {/* Başlık */}
            <div style={{ display: 'flex', justifyContent: 'space-between',
                          alignItems: 'center', marginBottom: 24 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                    <h2 style={{ fontSize: 20, fontWeight: 600, margin: 0 }}>
                        Kuyruk Tanımları
                    </h2>
                    {totalCount > 0 && (
                        <div style={{ display: 'flex', gap: 8, fontSize: 12, color: 'var(--text-dim)' }}>
                            <span>{totalCount} toplam</span>
                            <span style={{ opacity: 0.3 }}>·</span>
                            <span>{activeCount} aktif</span>
                            <span style={{ opacity: 0.3 }}>·</span>
                            <span>{passiveCount} pasif</span>
                        </div>
                    )}
                </div>
                <button className="btn primary" onClick={() => setModal('new')}>
                    + Yeni Kuyruk
                </button>
            </div>

            {/* Liste */}
            {(!queues || queues.length === 0) ? (
                <div style={{ textAlign: 'center', padding: 60, color: 'var(--text-dim)',
                              background: 'var(--surface)', borderRadius: 12,
                              border: '1px solid var(--border)' }}>
                    <div style={{ fontSize: 16, fontWeight: 500, marginBottom: 8,
                                  color: 'var(--text)' }}>
                        Henüz kuyruk tanımlanmamış
                    </div>
                    <div style={{ fontSize: 14, marginBottom: 20 }}>
                        IVR menülerinde kullanmak için çağrı kuyruklarınızı oluşturun.
                    </div>
                    <button className="btn primary" onClick={() => setModal('new')}>
                        + İlk Kuyruğu Oluştur
                    </button>
                </div>
            ) : (
                <div className="panel" style={{ padding: 0, overflow: 'hidden' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                        <thead>
                            <tr style={{ background: 'var(--surface2)',
                                         borderBottom: '1px solid var(--border)' }}>
                                {['Kuyruk Adı', 'Extension', 'Açıklama', 'Temsilci', 'Durum', ''].map((h, idx) => (
                                    <th key={idx} style={{
                                        padding: '10px 16px', textAlign: 'left',
                                        fontSize: 11, fontWeight: 500,
                                        color: 'var(--text-dim)', textTransform: 'uppercase',
                                        letterSpacing: '.04em'
                                    }}>{h}</th>
                                ))}
                            </tr>
                        </thead>
                        <tbody>
                            {queues.map((q, i) => (
                                <tr key={q.id} style={{
                                    borderBottom: i < queues.length - 1 ? '1px solid var(--border)' : 'none',
                                    transition: 'background .1s'
                                }}
                                    onMouseEnter={e => e.currentTarget.style.background = 'rgba(88,166,255,.03)'}
                                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                                >
                                    {/* Ad */}
                                    <td style={{ padding: '12px 16px' }}>
                                        <span style={{ fontWeight: 500, fontSize: 13, color: 'var(--text)' }}>
                                            {q.name}
                                        </span>
                                    </td>

                                    {/* Extension */}
                                    <td style={{ padding: '12px 16px' }}>
                                        <span className="mono" style={{ fontSize: 13, color: 'var(--text-dim)' }}>
                                            {q.extension}
                                        </span>
                                    </td>

                                    {/* Açıklama */}
                                    <td style={{ padding: '12px 16px', color: 'var(--text-dim)', fontSize: 13 }}>
                                        {q.description || <span style={{ opacity: 0.3 }}>—</span>}
                                    </td>

                                    {/* Temsilci Sayısı */}
                                    <td style={{ padding: '12px 16px' }}>
                                        <span
                                            onClick={() => setMembersModal(q)}
                                            style={{
                                                cursor: 'pointer', fontSize: 12,
                                                color: 'var(--text-dim)',
                                                textDecoration: 'underline',
                                                textDecorationColor: 'rgba(139,148,158,.3)',
                                                textUnderlineOffset: 2,
                                            }}
                                            title="Temsilcileri yönet"
                                        >
                                            {q.agent_count || 0} temsilci
                                        </span>
                                    </td>

                                    {/* Durum */}
                                    <td style={{ padding: '12px 16px' }}>
                                        <span style={{
                                            padding: '3px 10px', borderRadius: 4, fontSize: 11,
                                            fontWeight: 500,
                                            background: q.is_active ? 'rgba(34,197,94,.06)' : 'rgba(139,148,158,.06)',
                                            color: q.is_active ? 'var(--green)' : 'var(--text-dim)',
                                        }}>
                                            {q.is_active ? 'Aktif' : 'Pasif'}
                                        </span>
                                    </td>

                                    {/* İşlemler */}
                                    <td style={{ padding: '12px 16px', textAlign: 'right' }}>
                                        <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                                            <button
                                                className="btn-sm outline"
                                                onClick={() => setModal(q)}
                                                style={{ fontSize: 11, padding: '4px 10px' }}
                                            >
                                                Düzenle
                                            </button>
                                            <button
                                                className="btn-sm outline"
                                                style={{
                                                    fontSize: 11, padding: '4px 10px',
                                                    color: 'var(--text-dim)',
                                                    borderColor: 'var(--border)',
                                                }}
                                                onClick={() => handleToggle(q)}
                                                title={q.is_active ? 'Pasif yap' : 'Aktif yap'}
                                            >
                                                {q.is_active ? 'Pasif Yap' : 'Aktif Yap'}
                                            </button>
                                            <button
                                                className="btn-sm outline"
                                                style={{
                                                    fontSize: 11, padding: '4px 10px',
                                                    color: 'var(--red)',
                                                    borderColor: 'rgba(248,81,73,.2)',
                                                }}
                                                onClick={() => handleDelete(q)}
                                            >
                                                Sil
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}

            {/* Kuyruk Formu Modal */}
            {modal && (
                <QueueModal
                    queue={modal === 'new' ? null : modal}
                    onClose={() => setModal(null)}
                    onSave={() => {
                        setModal(null);
                        reload();
                        toast('Kuyruk başarıyla kaydedildi.', 'success');
                    }}
                />
            )}

            {/* Temsilci Yönetimi Modal */}
            {membersModal && (
                <QueueMembersModal
                    queue={membersModal}
                    onClose={() => setMembersModal(null)}
                    toast={toast}
                    onMemberChange={reload}
                />
            )}
        </div>
    );
}

window.QueuesTab = QueuesTab;
