// WallboardTab.jsx — Real-time Supervisor Wallboard
// Light theme — App design system (#00478d primary, #f0f4f8 bg)
// Layout: Canlı Çağrı İzleme > KPI Tiles > Kuyruk > Temsilciler

(function () {
  const { useState, useEffect, useCallback, useRef, useMemo } = React;

  const REFRESH_INTERVAL = 5;

  /* ── Helpers ─────────────────────────────────────────────────────────────────── */
  function fmtDur(seconds) {
    if (!seconds && seconds !== 0) return '--:--';
    const s = Math.floor(seconds);
    const m = Math.floor(s / 60);
    const h = Math.floor(m / 60);
    if (h > 0) return `${h}:${String(m % 60).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
    return `${String(m).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
  }

  function fmtShort(seconds) {
    if (!seconds && seconds !== 0) return '--';
    const s = Math.round(seconds);
    if (s < 60) return `${s}s`;
    const m = Math.floor(s / 60);
    if (m < 60) return `${m}dk ${s % 60}s`;
    return `${Math.floor(m / 60)}sa ${m % 60}dk`;
  }

  function padTwo(n) { return String(n).padStart(2, '0'); }
  function fmtTime(d) { return `${padTwo(d.getHours())}:${padTwo(d.getMinutes())}:${padTwo(d.getSeconds())}`; }

  function fmtDate(d) {
    const days = ['Pazar','Pazartesi','Salı','Çarşamba','Perşembe','Cuma','Cumartesi'];
    const months = ['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran','Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'];
    return `${days[d.getDay()]}, ${d.getDate()} ${months[d.getMonth()]}`;
  }

  function slColor(pct) {
    if (pct === null || pct === undefined) return '#64748b';
    if (pct >= 80) return '#10b981';
    if (pct >= 60) return '#f59e0b';
    return '#ef4444';
  }

  function pctColor(pct, invert) {
    if (pct === null || pct === undefined) return '#64748b';
    if (invert) {
      if (pct <= 3) return '#10b981';
      if (pct <= 8) return '#f59e0b';
      return '#ef4444';
    }
    if (pct >= 80) return '#10b981';
    if (pct >= 60) return '#f59e0b';
    return '#ef4444';
  }

  const STATUS_COLORS = {
    'Müsait': '#10b981', 'available': '#10b981',
    'Görüşmede': '#3b82f6', 'busy': '#3b82f6',
    'Çevrimdışı': '#6b7280', 'offline': '#6b7280',
    'Mola': '#f59e0b', 'break': '#f59e0b',
    'Yemek': '#f59e0b',
    'Toplantı': '#8b5cf6',
    'acw': '#f97316', 'ACW': '#f97316',
  };

  function getStatusColor(status, apiColor) {
    return STATUS_COLORS[status] || apiColor || '#6b7280';
  }

  /* ── KPI Tile ────────────────────────────────────────────────────────────────── */
  function KpiTile({ label, value, sub, color, alert }) {
    return (
      <div style={{
        background: '#ffffff',
        border: alert ? `1px solid ${color}40` : 'none',
        borderRadius: 12,
        padding: '16px 20px',
        flex: '1 1 150px',
        minWidth: 140,
        textAlign: 'center',
        boxShadow: alert
          ? `0 0 18px ${color}18, 0 2px 8px rgba(0,71,141,.08)`
          : '0 2px 8px rgba(0,71,141,.06)',
        transition: 'all .3s',
      }}>
        <div style={{ fontSize: 11, color: '#5b7a92', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.05em', marginBottom: 6 }}>
          {label}
        </div>
        <div style={{ fontSize: 32, fontWeight: 600, color, lineHeight: 1, fontFamily: 'monospace' }}>
          {value}
        </div>
        {sub && <div style={{ fontSize: 11, color: '#8fafc5', marginTop: 4 }}>{sub}</div>}
      </div>
    );
  }

  /* ── Live Timer Hook ─────────────────────────────────────────────────────────── */
  function useLiveTimer(baseSec) {
    const [elapsed, setElapsed] = useState(baseSec || 0);
    useEffect(() => {
      setElapsed(baseSec || 0);
      const id = setInterval(() => setElapsed(e => e + 1), 1000);
      return () => clearInterval(id);
    }, [baseSec]);
    return elapsed;
  }

  /* ── Active Call Row ─────────────────────────────────────────────────────────── */
  function ActiveCallRow({ call, supervisorExt, onAction, actionLoading }) {
    const elapsed = useLiveTimer(call.duration_sec);

    const btnStyle = (bg, fg) => ({
      border: 'none', borderRadius: 6, cursor: actionLoading ? 'not-allowed' : 'pointer',
      fontSize: 12, fontWeight: 600, padding: '5px 10px', display: 'flex',
      alignItems: 'center', gap: 4, whiteSpace: 'nowrap', background: bg, color: fg,
      opacity: actionLoading ? 0.5 : 1, transition: 'opacity .15s',
    });

    return (
      <tr style={{ borderBottom: '1px solid #f0f4f8' }}>
        <td style={cellStyle}><span style={{ fontFamily: 'monospace', fontWeight: 600 }}>{call.phone_number || '--'}</span></td>
        <td style={cellStyle}>
          {call.agent_name || '--'}
          {call.agent_extension && <span style={{ fontSize: 11, color: '#8fafc5', marginLeft: 6 }}>({call.agent_extension})</span>}
        </td>
        <td style={{ ...cellStyle, textAlign: 'center' }}>
          <span style={{ fontFamily: 'monospace', fontWeight: 600, color: '#00478d', fontSize: 15 }}>{fmtDur(elapsed)}</span>
        </td>
        <td style={cellStyle}>
          <div style={{ display: 'flex', gap: 4 }}>
            <button disabled={actionLoading} onClick={() => onAction('listen', call.call_uuid)} style={btnStyle('#eff6ff', '#1d4ed8')} title="Dinle">Dinle</button>
            <button disabled={actionLoading} onClick={() => onAction('whisper', call.call_uuid)} style={btnStyle('#f5f3ff', '#6d28d9')} title="Fısılda">Fısılda</button>
            <button disabled={actionLoading} onClick={() => onAction('barge', call.call_uuid)} style={btnStyle('#fef9c3', '#854d0e')} title="Katıl">Katıl</button>
          </div>
        </td>
      </tr>
    );
  }

  /* ── Session Row ─────────────────────────────────────────────────────────────── */
  function SessionRow({ session, onStop, stopLoading }) {
    const modeLabels = { listen: 'Dinleme', whisper: 'Fısıldama', barge: 'Katılma' };
    const modeColors = { listen: '#1d4ed8', whisper: '#6d28d9', barge: '#854d0e' };
    const mode = session.mode || '';
    const mc = modeColors[mode] || '#5b7a92';

    return (
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12, padding: '8px 14px',
        background: '#f5f8fb', borderRadius: 8, border: '1px solid #dce6ef', flexWrap: 'wrap',
      }}>
        <div style={{ flex: 1, minWidth: 100 }}>
          <div style={{ fontSize: 11, color: '#8fafc5' }}>Çağrı UUID</div>
          <div style={{ fontSize: 11, fontFamily: 'monospace', color: '#5b7a92', wordBreak: 'break-all' }}>{session.call_uuid || '--'}</div>
        </div>
        <div style={{ minWidth: 80 }}>
          <div style={{ fontSize: 11, color: '#8fafc5' }}>Süpervizör</div>
          <div style={{ fontSize: 13, fontWeight: 600, color: '#00478d', fontFamily: 'monospace' }}>{session.supervisor_ext || '--'}</div>
        </div>
        <div>
          <span style={{ fontSize: 12, fontWeight: 600, color: mc, background: mc + '18', border: `1px solid ${mc}30`, borderRadius: 4, padding: '2px 8px' }}>
            {modeLabels[mode] || mode || '--'}
          </span>
        </div>
        <button disabled={stopLoading} onClick={() => onStop(session.session_id)} style={{
          background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 6,
          color: '#dc2626', cursor: 'pointer', fontSize: 12, fontWeight: 600,
          padding: '5px 12px', opacity: stopLoading ? 0.5 : 1,
        }}>Durdur</button>
      </div>
    );
  }

  /* ── Table styles ────────────────────────────────────────────────────────────── */
  const cellStyle = { padding: '10px 14px', fontSize: 13, color: '#1a3047', whiteSpace: 'nowrap' };
  const thStyle = {
    padding: '10px 14px', fontSize: 11, fontWeight: 600, color: '#5b7a92',
    textTransform: 'uppercase', letterSpacing: '.04em', textAlign: 'left',
    borderBottom: '1px solid #dce6ef', whiteSpace: 'nowrap',
  };

  /* ═══════════════════════════════════════════════════════════════════════════════
     MAIN: WallboardTab
     ═══════════════════════════════════════════════════════════════════════════════ */
  function WallboardTab({ toast }) {
    const [agents, setAgents] = useState([]);
    const [queues, setQueues] = useState([]);
    const [perfMap, setPerfMap] = useState({});
    const [now, setNow] = useState(new Date());
    const [countdown, setCountdown] = useState(REFRESH_INTERVAL);
    const [loading, setLoading] = useState(true);

    const [liveCalls, setLiveCalls] = useState([]);
    const [activeCalls, setActiveCalls] = useState([]);
    const [monitoringSessions, setMonitoringSessions] = useState([]);
    const [supervisorExt, setSupervisorExt] = useState('');
    const [actionLoadingMap, setActionLoadingMap] = useState({});
    const [stopLoadingMap, setStopLoadingMap] = useState({});
    const [filterQueue, setFilterQueue] = useState('');
    const [filterTeam, setFilterTeam] = useState('');

    const countdownRef = useRef(REFRESH_INTERVAL);
    const refreshTimerRef = useRef(null);

    /* ── Data fetch ──────────────────────────────────────────────────────────────── */
    const fetchData = useCallback(async () => {
      try {
        const [agR, quR, pfR, lcR, acR, ssR] = await Promise.all([
          authFetch('/api/agents/overview'),
          authFetch('/api/queues/wallboard-stats'),
          authFetch('/api/human-agents/perf-stats'),
          authFetch('/api/live-calls'),
          authFetch('/api/monitoring/active-calls'),
          authFetch('/api/monitoring/sessions'),
        ]);
        const [agD, quD, pfD, lcD, acD, ssD] = await Promise.all([
          agR.json().catch(() => []),
          quR.json().catch(() => []),
          pfR.json().catch(() => []),
          lcR.json().catch(() => []),
          acR.json().catch(() => []),
          ssR.json().catch(() => []),
        ]);
        const agentsList = agD && agD.agents ? agD.agents : (Array.isArray(agD) ? agD : []);
        setAgents(agentsList);
        setQueues(Array.isArray(quD) ? quD : []);
        const m = {};
        (Array.isArray(pfD) ? pfD : []).forEach(p => { m[p.id] = p; });
        setPerfMap(m);
        setLiveCalls(Array.isArray(lcD) ? lcD : []);
        setActiveCalls(Array.isArray(acD) ? acD : []);
        setMonitoringSessions(Array.isArray(ssD) ? ssD : []);
      } catch (e) { console.error('Wallboard fetch error:', e); }
      finally { setLoading(false); }
    }, []);

    useEffect(() => {
      fetchData();
      const tick = () => {
        countdownRef.current -= 1;
        setCountdown(countdownRef.current);
        if (countdownRef.current <= 0) { countdownRef.current = REFRESH_INTERVAL; setCountdown(REFRESH_INTERVAL); fetchData(); }
      };
      refreshTimerRef.current = setInterval(tick, 1000);
      return () => clearInterval(refreshTimerRef.current);
    }, [fetchData]);

    useEffect(() => {
      const id = setInterval(() => setNow(new Date()), 1000);
      return () => clearInterval(id);
    }, []);

    /* ── Computed KPIs ────────────────────────────────────────────────────────────── */
    const kpi = useMemo(() => {
      const totalWaiting  = queues.reduce((s, q) => s + (q.waiting_count || 0), 0);
      const totalActive   = queues.reduce((s, q) => s + (q.active_count || 0), 0);
      const totalAnswered = queues.reduce((s, q) => s + (q.today_answered || 0), 0);
      const totalOffered  = queues.reduce((s, q) => s + (q.today_total || 0), 0);
      const totalAbandoned= queues.reduce((s, q) => s + (q.today_abandoned || 0), 0);
      const longestWait   = queues.reduce((mx, q) => Math.max(mx, q.longest_wait_sec || 0), 0);
      const avgWait       = queues.length > 0
        ? queues.reduce((s, q) => s + (q.avg_wait_sec || 0), 0) / queues.length : 0;

      const slPct = totalOffered > 0
        ? Math.round(queues.reduce((s, q) => s + (q.sl_pct || 0) * (q.today_total || 0), 0) / totalOffered)
        : null;

      const abandonPct = totalOffered > 0 ? ((totalAbandoned / totalOffered) * 100).toFixed(1) : '0.0';

      const agentsOnline = agents.filter(a => a.status !== 'Çevrimdışı' && a.status !== 'offline').length;
      const agentsAvail  = agents.filter(a => a.status === 'Müsait' || a.status === 'available' || a.is_routable).length;
      const agentsInCall = agents.filter(a => a.in_call || a.active_call).length;
      const agentsBreak  = agents.filter(a => ['Mola','Yemek','break'].includes(a.status)).length;

      return {
        totalWaiting, totalActive, totalAnswered, totalOffered, totalAbandoned,
        longestWait, avgWait, slPct, abandonPct,
        agentsOnline, agentsAvail, agentsInCall, agentsBreak,
      };
    }, [agents, queues]);

    /* ── Monitor actions ──────────────────────────────────────────────────────────── */
    const handleMonitorAction = useCallback(async (actionType, callUuid) => {
      if (!supervisorExt) { alert('Lütfen önce Süpervizör Dahilisi girin.'); return; }
      const ep = { listen: '/api/monitoring/listen', whisper: '/api/monitoring/whisper', barge: '/api/monitoring/barge' };
      if (!ep[actionType]) return;
      setActionLoadingMap(prev => ({ ...prev, [callUuid]: true }));
      try {
        const res = await authFetch(ep[actionType], {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ call_uuid: callUuid, supervisor_extension: supervisorExt }),
        });
        if (res.ok) {
          const labels = { listen: 'Dinleme', whisper: 'Fısıldama', barge: 'Katılma' };
          if (toast) toast(`${labels[actionType]} başlatıldı.`, 'success');
          try { const sr = await authFetch('/api/monitoring/sessions'); const sd = await sr.json().catch(() => []); setMonitoringSessions(Array.isArray(sd) ? sd : []); } catch (_) {}
        } else {
          const err = await res.json().catch(() => ({}));
          if (toast) toast(err.detail || 'İşlem başarısız.', 'error');
        }
      } catch (e) { if (toast) toast('Bağlantı hatası.', 'error'); }
      finally { setActionLoadingMap(prev => { const n = { ...prev }; delete n[callUuid]; return n; }); }
    }, [supervisorExt, toast]);

    const handleStopSession = useCallback(async (sessionId) => {
      if (!sessionId) return;
      setStopLoadingMap(prev => ({ ...prev, [sessionId]: true }));
      try {
        const res = await authFetch(`/api/monitoring/stop/${sessionId}`, { method: 'POST' });
        if (res.ok) {
          if (toast) toast('Oturum durduruldu.', 'success');
          setMonitoringSessions(prev => prev.filter(s => s.session_id !== sessionId));
        } else {
          const err = await res.json().catch(() => ({}));
          if (toast) toast(err.detail || 'Durdurma başarısız.', 'error');
        }
      } catch (e) { if (toast) toast('Bağlantı hatası.', 'error'); }
      finally { setStopLoadingMap(prev => { const n = { ...prev }; delete n[sessionId]; return n; }); }
    }, [toast]);

    const handleFullscreen = () => {
      if (!document.fullscreenElement) document.documentElement.requestFullscreen().catch(() => {});
      else document.exitFullscreen().catch(() => {});
    };

    /* ══════════════════════════════ RENDER ══════════════════════════════ */
    return (
      <div style={{
        minHeight: '100vh', background: '#f0f4f8', color: '#1a3047',
        display: 'flex', flexDirection: 'column',
        fontFamily: "'Inter', 'Segoe UI', system-ui, sans-serif",
      }}>

        {/* ── HEADER ── */}
        <div style={{
          background: '#00478d',
          padding: '10px 24px', display: 'flex', alignItems: 'center',
          justifyContent: 'space-between', flexWrap: 'wrap', gap: 12,
        }}>
          <div style={{ fontSize: 20, fontWeight: 600, color: '#ffffff', letterSpacing: .5 }}>
            Supervisor Wallboard
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 24, fontWeight: 600, fontFamily: 'monospace', color: '#ffffff', lineHeight: 1 }}>{fmtTime(now)}</div>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,.65)' }}>{fmtDate(now)}</div>
            </div>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 6,
              background: 'rgba(255,255,255,.12)', borderRadius: 8, padding: '4px 10px',
              border: '1px solid rgba(255,255,255,.2)',
            }}>
              <span style={{ fontSize: 10, color: 'rgba(255,255,255,.7)' }}>Yenileme</span>
              <span style={{ fontSize: 16, fontWeight: 600, fontFamily: 'monospace', color: countdown <= 2 ? '#fca5a5' : '#86efac' }}>{countdown}s</span>
              <button onClick={fetchData} style={{
                background: 'rgba(255,255,255,.15)', border: 'none', borderRadius: 4,
                color: '#ffffff', cursor: 'pointer', padding: '2px 6px', fontSize: 12,
              }}>↻</button>
            </div>
            <button onClick={handleFullscreen} style={{
              background: 'rgba(255,255,255,.12)', border: '1px solid rgba(255,255,255,.2)', borderRadius: 6,
              color: '#ffffff', cursor: 'pointer', padding: '5px 12px', fontSize: 12, fontWeight: 500,
            }}>Tam Ekran</button>
          </div>
        </div>

        {loading ? (
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ fontSize: 16, color: '#5b7a92' }}>Veriler yükleniyor...</div>
          </div>
        ) : (
          <div style={{ flex: 1, padding: '16px 24px', display: 'flex', flexDirection: 'column', gap: 16, overflow: 'auto' }}>

            {/* ═══════════ 1. CANLI ÇAĞRI İZLEME ═══════════ */}
            {(() => {
              const ringing = liveCalls.filter(c => c.status === 'ringing');
              const ivr     = liveCalls.filter(c => c.status === 'ivr');
              const queue   = liveCalls.filter(c => c.status === 'queue');
              const active  = liveCalls.filter(c => c.status === 'active');

              const elapsedSec = (c) => {
                const d = parseUTC(c.started_at || c.start_time);
                if (!d) return 0;
                return Math.max(0, Math.floor((Date.now() - d.getTime()) / 1000));
              };

              const liveStatusBadge = (status) => {
                const map = {
                  ringing: { label: 'Çalıyor',  dot: '#f59e0b', bg: 'rgba(245,158,11,.1)',  color: '#92400e' },
                  ivr:     { label: 'IVR / AI', dot: '#8b5cf6', bg: 'rgba(139,92,246,.1)', color: '#5b21b6' },
                  queue:   { label: 'Kuyrukta', dot: '#f97316', bg: 'rgba(249,115,22,.1)', color: '#9a3412' },
                  active:  { label: 'Aktif',    dot: '#10b981', bg: 'rgba(16,185,129,.1)', color: '#065f46' },
                };
                const s = map[status] || { label: status, dot: '#8fafc5', bg: '#f5f8fb', color: '#5b7a92' };
                return (
                  <span style={{
                    padding: '2px 10px', borderRadius: 20, fontSize: 11, fontWeight: 700,
                    display: 'inline-flex', alignItems: 'center', gap: 5,
                    background: s.bg, color: s.color,
                  }}>
                    <span style={{ width: 6, height: 6, borderRadius: '50%', background: s.dot, flexShrink: 0 }} />
                    {s.label}
                  </span>
                );
              };

              const counterBox = (dotColor, label, count, valueColor, isLast) => (
                <div style={{
                  flex: 1, padding: '12px 18px',
                  borderRight: isLast ? 'none' : '1px solid #dce6ef',
                  display: 'flex', alignItems: 'center', gap: 12,
                }}>
                  <span style={{
                    width: 10, height: 10, borderRadius: '50%',
                    background: count > 0 ? dotColor : '#cbd5e1', flexShrink: 0,
                  }} />
                  <div>
                    <div style={{ fontSize: 22, fontWeight: 700, fontFamily: 'monospace', color: count > 0 ? valueColor : '#94a3b8', lineHeight: 1 }}>{count}</div>
                    <div style={{ fontSize: 11, color: '#8fafc5', marginTop: 2 }}>{label}</div>
                  </div>
                </div>
              );

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

              const monitorCallMap = {};
              activeCalls.forEach(ac => { monitorCallMap[ac.call_uuid] = ac; });

              return (
                <div style={{ background: '#ffffff', borderRadius: 12, overflow: 'hidden', boxShadow: '0 2px 8px rgba(0,71,141,.07)' }}>

                  {/* Başlık */}
                  <div style={{
                    padding: '12px 20px', background: '#f5f8fb',
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 10,
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <span style={{ fontSize: 13, fontWeight: 700, color: '#0f2d47', textTransform: 'uppercase', letterSpacing: '.05em' }}>
                        Canlı Çağrı İzleme
                      </span>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, color: '#10b981', fontWeight: 600 }}>
                        <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#10b981', display: 'inline-block', animation: 'wbLivePulse 2s infinite' }} />
                        Canlı
                      </span>
                      <style>{`@keyframes wbLivePulse{0%{box-shadow:0 0 0 0 rgba(16,185,129,.5)}70%{box-shadow:0 0 0 6px rgba(16,185,129,0)}100%{box-shadow:0 0 0 0 rgba(16,185,129,0)}}`}</style>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <label style={{ fontSize: 12, color: '#5b7a92' }}>Süpervizör Dahilisi:</label>
                      <input type="text" value={supervisorExt} onChange={e => setSupervisorExt(e.target.value.trim())}
                        placeholder="9999" maxLength={10}
                        style={{
                          background: '#f0f4f8', border: '1px solid #dce6ef', borderRadius: 6,
                          color: '#00478d', fontSize: 13, fontFamily: 'monospace', fontWeight: 600,
                          padding: '4px 8px', width: 80, outline: 'none',
                        }}
                      />
                    </div>
                  </div>

                  {/* Sayaçlar */}
                  <div style={{ display: 'flex', borderBottom: '1px solid #dce6ef' }}>
                    {counterBox('#f59e0b', 'Çalıyor',  ringing.length, '#92400e', false)}
                    {counterBox('#8b5cf6', 'IVR / AI', ivr.length,     '#5b21b6', false)}
                    {counterBox('#f97316', 'Kuyrukta', queue.length,   '#9a3412', false)}
                    {counterBox('#10b981', 'Aktif',    active.length,  '#065f46', true)}
                  </div>

                  {/* Tablo */}
                  {liveCalls.length === 0 ? (
                    <div style={{ padding: '24px', textAlign: 'center', color: '#8fafc5', fontSize: 13 }}>
                      Şu an aktif çağrı yok
                    </div>
                  ) : (
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                      <thead>
                        <tr style={{ background: '#f5f8fb' }}>
                          <th style={thStyle}>Arayan</th>
                          <th style={thStyle}>Durum</th>
                          <th style={{ ...thStyle, textAlign: 'center' }}>Süre</th>
                          <th style={thStyle}>Kuyruk / Temsilci</th>
                          <th style={thStyle}>İşlem</th>
                        </tr>
                      </thead>
                      <tbody>
                        {liveCalls.map((c, i) => {
                          const sec = elapsedSec(c);
                          const isActive = c.status === 'active';
                          return (
                            <tr key={c.call_uuid || i} style={{
                              borderBottom: '1px solid #f0f4f8',
                              background: i % 2 === 0 ? 'transparent' : '#fafcfe',
                            }}>
                              <td style={cellStyle}>
                                <span style={{ fontFamily: 'monospace', fontWeight: 600, fontSize: 13 }}>
                                  {c.caller_number || c.phone_number || '—'}
                                </span>
                              </td>
                              <td style={cellStyle}>{liveStatusBadge(c.status)}</td>
                              <td style={{ ...cellStyle, textAlign: 'center', fontFamily: 'monospace', fontWeight: 600, color: '#00478d' }}>
                                {fmtDur(sec)}
                              </td>
                              <td style={cellStyle}>
                                <span style={{ fontSize: 13, color: '#5b7a92' }}>{queueOrAgent(c)}</span>
                              </td>
                              <td style={cellStyle}>
                                {isActive && c.call_uuid ? (
                                  <div style={{ display: 'flex', gap: 4 }}>
                                    {[
                                      { act: 'listen',  label: 'Dinle',   bg: '#eff6ff', fg: '#1d4ed8' },
                                      { act: 'whisper', label: 'Fısılda', bg: '#f5f3ff', fg: '#6d28d9' },
                                      { act: 'barge',   label: 'Katıl',   bg: '#fef9c3', fg: '#854d0e' },
                                    ].map(({ act, label, bg, fg }) => (
                                      <button key={act}
                                        onClick={() => handleMonitorAction(act, c.call_uuid)}
                                        disabled={!!actionLoadingMap[c.call_uuid]}
                                        style={{
                                          background: bg, border: 'none', borderRadius: 4,
                                          color: fg, cursor: 'pointer', padding: '3px 8px',
                                          fontSize: 12, fontWeight: 600,
                                          opacity: actionLoadingMap[c.call_uuid] ? .5 : 1,
                                        }}>
                                        {label}
                                      </button>
                                    ))}
                                  </div>
                                ) : (
                                  <span style={{ fontSize: 11, color: '#dce6ef' }}>—</span>
                                )}
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  )}

                  {/* Aktif izleme oturumları */}
                  {monitoringSessions.length > 0 && (
                    <div style={{ padding: '12px 20px 16px', borderTop: '1px solid #dce6ef' }}>
                      <div style={{ fontSize: 12, color: '#6d28d9', fontWeight: 600, marginBottom: 8 }}>
                        Aktif İzleme Oturumları ({monitoringSessions.length})
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                        {monitoringSessions.map(s => (
                          <SessionRow key={s.session_id} session={s} onStop={handleStopSession}
                            stopLoading={!!stopLoadingMap[s.session_id]} />
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              );
            })()}

            {/* ═══════════ 2. KPI TILES ═══════════ */}
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <KpiTile
                label="Bekleyen Çağrı" value={kpi.totalWaiting}
                color={kpi.totalWaiting > 0 ? '#ef4444' : '#10b981'}
                alert={kpi.totalWaiting > 3}
              />
              <KpiTile
                label="Servis Seviyesi" value={kpi.slPct !== null ? `${kpi.slPct}%` : '--'}
                color={slColor(kpi.slPct)}
                sub={`Hedef: 80% / 20sn`}
                alert={kpi.slPct !== null && kpi.slPct < 60}
              />
              <KpiTile
                label="Terk Oranı" value={`%${kpi.abandonPct}`}
                color={pctColor(parseFloat(kpi.abandonPct), true)}
                sub={`${kpi.totalAbandoned} çağrı`}
                alert={parseFloat(kpi.abandonPct) > 8}
              />
              <KpiTile
                label="En Uzun Bekleme" value={kpi.longestWait > 0 ? fmtDur(kpi.longestWait) : '--'}
                color={kpi.longestWait > 60 ? '#ef4444' : kpi.longestWait > 30 ? '#f59e0b' : '#10b981'}
                alert={kpi.longestWait > 60}
              />
              <KpiTile
                label="Aktif Çağrı" value={kpi.totalActive}
                color={kpi.totalActive > 0 ? '#3b82f6' : '#94a3b8'}
              />
              <KpiTile
                label="Toplam Çağrı" value={kpi.totalOffered}
                color="#00478d"
                sub={`${kpi.totalAnswered} cevaplanan`}
              />
              <KpiTile
                label="Müsait Temsilci" value={kpi.agentsAvail}
                color={kpi.agentsAvail === 0 && kpi.agentsOnline > 0 ? '#ef4444' : '#10b981'}
                sub={`${kpi.agentsOnline} çevrimiçi`}
                alert={kpi.agentsAvail === 0 && kpi.agentsOnline > 0}
              />
              <KpiTile
                label="Ort. Bekleme" value={kpi.avgWait > 0 ? fmtDur(Math.round(kpi.avgWait)) : '--'}
                color={kpi.avgWait > 30 ? '#f59e0b' : '#10b981'}
              />
            </div>

            {/* ═══════════ 3. KUYRUK TABLOSU ═══════════ */}
            {queues.length > 0 && (
              <div style={{ background: '#ffffff', borderRadius: 12, overflow: 'hidden', boxShadow: '0 2px 8px rgba(0,71,141,.06)' }}>
                <div style={{ padding: '12px 20px', background: '#f5f8fb', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: '#0f2d47', textTransform: 'uppercase', letterSpacing: '.05em' }}>
                    Kuyruk Performansı
                  </span>
                  <span style={{ fontSize: 11, color: '#8fafc5' }}>{queues.length} kuyruk</span>
                </div>
                <div style={{ overflowX: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                    <thead>
                      <tr style={{ background: '#f5f8fb' }}>
                        <th style={thStyle}>Kuyruk</th>
                        <th style={{ ...thStyle, textAlign: 'center' }}>Bekleyen</th>
                        <th style={{ ...thStyle, textAlign: 'center' }}>En Uzun Bekleme</th>
                        <th style={{ ...thStyle, textAlign: 'center' }}>SL%</th>
                        <th style={{ ...thStyle, textAlign: 'center' }}>Toplam</th>
                        <th style={{ ...thStyle, textAlign: 'center' }}>Cevaplanan</th>
                        <th style={{ ...thStyle, textAlign: 'center' }}>Terk</th>
                        <th style={{ ...thStyle, textAlign: 'center' }}>Terk%</th>
                        <th style={{ ...thStyle, textAlign: 'center' }}>Ort. Bekleme</th>
                        <th style={{ ...thStyle, textAlign: 'center' }}>Aktif</th>
                      </tr>
                    </thead>
                    <tbody>
                      {queues.map((q, i) => {
                        const w = q.waiting_count || 0;
                        const offered = q.today_total || 0;
                        const abandoned = q.today_abandoned || 0;
                        const abPct = offered > 0 ? ((abandoned / offered) * 100).toFixed(1) : '0.0';
                        const sl = q.sl_pct;
                        const lwait = q.longest_wait_sec || 0;
                        return (
                          <tr key={q.queue_id || i} style={{
                            borderBottom: '1px solid #f0f4f8',
                            background: w > 5 ? 'rgba(239,68,68,.04)' : i % 2 === 0 ? 'transparent' : '#fafcfe',
                          }}>
                            <td style={cellStyle}>
                              <div style={{ fontWeight: 600, fontSize: 14, color: '#0f2d47' }}>{q.name}</div>
                              <div style={{ fontSize: 11, color: '#8fafc5' }}>Dahili: {q.extension}</div>
                            </td>
                            <td style={{ ...cellStyle, textAlign: 'center' }}>
                              <span style={{
                                fontSize: 20, fontWeight: 600,
                                color: w > 0 ? (w > 5 ? '#ef4444' : '#f59e0b') : '#94a3b8',
                              }}>{w}</span>
                            </td>
                            <td style={{ ...cellStyle, textAlign: 'center' }}>
                              <span style={{
                                fontFamily: 'monospace', fontWeight: 600, fontSize: 14,
                                color: lwait > 60 ? '#ef4444' : lwait > 30 ? '#f59e0b' : '#5b7a92',
                              }}>{lwait > 0 ? fmtDur(lwait) : '--'}</span>
                            </td>
                            <td style={{ ...cellStyle, textAlign: 'center' }}>
                              <span style={{
                                display: 'inline-block', padding: '3px 10px', borderRadius: 6,
                                fontSize: 14, fontWeight: 600,
                                color: slColor(sl), background: slColor(sl) + '15',
                              }}>
                                {sl !== null && sl !== undefined ? `${sl}%` : '--'}
                              </span>
                            </td>
                            <td style={{ ...cellStyle, textAlign: 'center', fontWeight: 600 }}>{offered}</td>
                            <td style={{ ...cellStyle, textAlign: 'center', fontWeight: 600, color: '#10b981' }}>{q.today_answered || 0}</td>
                            <td style={{ ...cellStyle, textAlign: 'center', fontWeight: 600, color: abandoned > 0 ? '#ef4444' : '#5b7a92' }}>{abandoned}</td>
                            <td style={{ ...cellStyle, textAlign: 'center' }}>
                              <span style={{ fontWeight: 600, color: pctColor(parseFloat(abPct), true) }}>%{abPct}</span>
                            </td>
                            <td style={{ ...cellStyle, textAlign: 'center', fontFamily: 'monospace', fontWeight: 600 }}>
                              {q.avg_wait_sec > 0 ? fmtDur(Math.round(q.avg_wait_sec)) : '--'}
                            </td>
                            <td style={{ ...cellStyle, textAlign: 'center' }}>
                              <span style={{ fontSize: 16, fontWeight: 600, color: (q.active_count || 0) > 0 ? '#3b82f6' : '#94a3b8' }}>
                                {q.active_count || 0}
                              </span>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            )}

            {/* ═══════════ 4. TEMSİLCİ TABLOSU ═══════════ */}
            {(() => {
              const allQueueNames = [...new Set(agents.flatMap(a => a.queues || []).map(q => typeof q === 'string' ? q : q.name))].sort();
              const allTeamNames  = [...new Set(agents.filter(a => a.team_name).map(a => a.team_name))].sort();

              let filteredAgents = agents;
              if (filterQueue) filteredAgents = filteredAgents.filter(a => (a.queues || []).some(q => (typeof q === 'string' ? q : q.name) === filterQueue));
              if (filterTeam)  filteredAgents = filteredAgents.filter(a => a.team_name === filterTeam);

              const fAvail  = filteredAgents.filter(a => a.status === 'Müsait' || a.status === 'available' || a.is_routable).length;
              const fInCall = filteredAgents.filter(a => a.in_call || a.active_call).length;
              const fBreak  = filteredAgents.filter(a => ['Mola','Yemek','break'].includes(a.status)).length;

              const selectStyle = {
                background: '#f0f4f8', border: '1px solid #dce6ef', borderRadius: 6,
                color: '#1a3047', fontSize: 12, fontWeight: 500,
                padding: '4px 10px', outline: 'none', cursor: 'pointer',
              };

              return (
                <div style={{ background: '#ffffff', borderRadius: 12, overflow: 'hidden', boxShadow: '0 2px 8px rgba(0,71,141,.06)' }}>
                  <div style={{ padding: '12px 20px', background: '#f5f8fb', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 10 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                      <span style={{ fontSize: 13, fontWeight: 600, color: '#0f2d47', textTransform: 'uppercase', letterSpacing: '.05em' }}>
                        Temsilci Durumu
                      </span>
                      <select value={filterQueue} onChange={e => setFilterQueue(e.target.value)} style={{ ...selectStyle, color: filterQueue ? '#00478d' : '#1a3047', fontWeight: filterQueue ? 600 : 500 }}>
                        <option value="">Tüm Kuyruklar</option>
                        {allQueueNames.map(qn => <option key={qn} value={qn}>{qn}</option>)}
                      </select>
                      {allTeamNames.length > 0 && (
                        <select value={filterTeam} onChange={e => setFilterTeam(e.target.value)} style={{ ...selectStyle, color: filterTeam ? '#6d28d9' : '#1a3047', fontWeight: filterTeam ? 600 : 500 }}>
                          <option value="">Tüm Takımlar</option>
                          {allTeamNames.map(tn => <option key={tn} value={tn}>{tn}</option>)}
                        </select>
                      )}
                      {(filterQueue || filterTeam) && (
                        <button onClick={() => { setFilterQueue(''); setFilterTeam(''); }} style={{
                          background: '#f0f4f8', border: '1px solid #dce6ef', borderRadius: 4,
                          color: '#5b7a92', cursor: 'pointer', padding: '3px 8px', fontSize: 11, fontWeight: 600,
                        }}>× Temizle</button>
                      )}
                    </div>
                    <div style={{ display: 'flex', gap: 16, fontSize: 12 }}>
                      <span style={{ color: '#10b981', fontWeight: 600 }}>Müsait: {fAvail}</span>
                      <span style={{ color: '#3b82f6', fontWeight: 600 }}>Çağrıda: {fInCall}</span>
                      <span style={{ color: '#f59e0b', fontWeight: 600 }}>Molada: {fBreak}</span>
                      <span style={{ color: '#5b7a92' }}>Toplam: {filteredAgents.length}</span>
                    </div>
                  </div>
                  <div style={{ overflowX: 'auto' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                      <thead>
                        <tr style={{ background: '#f5f8fb' }}>
                          <th style={thStyle}>Temsilci</th>
                          <th style={thStyle}>Dahili</th>
                          <th style={thStyle}>Durum</th>
                          <th style={{ ...thStyle, textAlign: 'center' }}>Durum Süresi</th>
                          <th style={{ ...thStyle, textAlign: 'center' }}>Bugün Çağrı</th>
                          <th style={{ ...thStyle, textAlign: 'center' }}>Ort. Görüşme</th>
                          <th style={thStyle}>Takım</th>
                          <th style={thStyle}>Kuyruklar</th>
                        </tr>
                      </thead>
                      <tbody>
                        {filteredAgents.length === 0 ? (
                          <tr><td colSpan={8} style={{ ...cellStyle, textAlign: 'center', color: '#8fafc5', padding: 24 }}>
                            {filterQueue || filterTeam ? 'Filtreye uygun temsilci bulunamadı' : 'Temsilci bulunamadı'}
                          </td></tr>
                        ) : filteredAgents.map((a, i) => {
                          const color = getStatusColor(a.status, a.status_color);
                          const perf = perfMap[a.id] || {};
                          const hasCall = a.in_call || a.active_call;

                          let stateSeconds = a.status_duration_sec || 0;
                          if (!stateSeconds && a.status_changed_at) {
                            const sc = parseUTC(a.status_changed_at);
                            if (sc) stateSeconds = Math.floor((Date.now() - sc.getTime()) / 1000);
                          }
                          if (hasCall && a.active_call && a.active_call.duration_sec) {
                            stateSeconds = a.active_call.duration_sec;
                          }

                          let durColor = '#5b7a92';
                          if (a.status === 'Mola' || a.status === 'Yemek' || a.status === 'break') {
                            if (stateSeconds > 900) durColor = '#ef4444';
                            else if (stateSeconds > 600) durColor = '#f59e0b';
                          } else if (a.status === 'acw' || a.status === 'ACW') {
                            if (stateSeconds > 120) durColor = '#ef4444';
                            else if (stateSeconds > 60) durColor = '#f59e0b';
                          }

                          return (
                            <tr key={a.id} style={{
                              borderBottom: '1px solid #f0f4f8',
                              background: hasCall ? 'rgba(0,71,141,.03)' : (i % 2 === 0 ? 'transparent' : '#fafcfe'),
                            }}>
                              <td style={cellStyle}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                  <span style={{ fontWeight: 600, fontSize: 14 }}>{a.name}</span>
                                  {hasCall && (
                                    <span style={{
                                      fontSize: 10, padding: '1px 6px', borderRadius: 4,
                                      background: 'rgba(0,71,141,.1)', color: '#00478d', fontWeight: 600,
                                      fontFamily: 'monospace',
                                    }}>
                                      {a.active_call?.caller_number || 'Çağrıda'}
                                    </span>
                                  )}
                                </div>
                              </td>
                              <td style={cellStyle}>
                                <span style={{ fontFamily: 'monospace', fontWeight: 600, color: '#00478d', fontSize: 13 }}>{a.extension}</span>
                              </td>
                              <td style={cellStyle}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: color, flexShrink: 0 }} />
                                  <span style={{ fontWeight: 600, color, fontSize: 13 }}>{a.status_label || a.status || '--'}</span>
                                </div>
                              </td>
                              <td style={{ ...cellStyle, textAlign: 'center' }}>
                                <span style={{ fontFamily: 'monospace', fontWeight: 600, fontSize: 14, color: durColor }}>
                                  {stateSeconds > 0 ? fmtDur(stateSeconds) : '--'}
                                </span>
                              </td>
                              <td style={{ ...cellStyle, textAlign: 'center', fontWeight: 600, fontSize: 16 }}>
                                {perf.today_calls ?? 0}
                              </td>
                              <td style={{ ...cellStyle, textAlign: 'center', fontFamily: 'monospace' }}>
                                {perf.avg_talk_sec ? fmtShort(perf.avg_talk_sec) : '--'}
                              </td>
                              <td style={cellStyle}>
                                {a.team_name ? (
                                  <span style={{
                                    padding: '2px 8px', borderRadius: 4, fontSize: 11, fontWeight: 600,
                                    background: filterTeam && a.team_name === filterTeam ? '#ede9fe' : '#f5f3ff',
                                    color: filterTeam && a.team_name === filterTeam ? '#5b21b6' : '#7c3aed',
                                  }}>{a.team_name}</span>
                                ) : (
                                  <span style={{ fontSize: 11, color: '#8fafc5' }}>--</span>
                                )}
                              </td>
                              <td style={cellStyle}>
                                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 3 }}>
                                  {a.queues && a.queues.length > 0
                                    ? a.queues.map((q, qi) => {
                                        const qName = typeof q === 'string' ? q : q.name;
                                        const isFiltered = filterQueue && qName === filterQueue;
                                        return (
                                          <span key={qi} style={{
                                            padding: '1px 6px', borderRadius: 4, fontSize: 10, fontWeight: 600,
                                            background: isFiltered ? 'rgba(0,71,141,.15)' : 'rgba(0,71,141,.07)',
                                            color: isFiltered ? '#003d7a' : '#00478d',
                                          }}>{qName}</span>
                                        );
                                      })
                                    : <span style={{ fontSize: 11, color: '#8fafc5' }}>--</span>
                                  }
                                </div>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                </div>
              );
            })()}

          </div>
        )}

        {/* ── FOOTER ── */}
        <div style={{
          background: '#00478d',
          padding: '10px 24px', display: 'flex', gap: 28,
          justifyContent: 'center', alignItems: 'center', flexWrap: 'wrap',
        }}>
          {[
            { label: 'Çevrimiçi', value: kpi.agentsOnline, color: '#86efac' },
            { label: 'Müsait',    value: kpi.agentsAvail,  color: '#86efac' },
            { label: 'Çağrıda',   value: kpi.agentsInCall, color: '#93c5fd' },
            { label: 'Bekleyen',  value: kpi.totalWaiting, color: kpi.totalWaiting > 0 ? '#fca5a5' : 'rgba(255,255,255,.6)' },
            { label: 'Aktif',     value: kpi.totalActive,  color: '#93c5fd' },
            { label: 'SL%',       value: kpi.slPct !== null ? `${kpi.slPct}%` : '--', color: slColor(kpi.slPct) === '#10b981' ? '#86efac' : slColor(kpi.slPct) === '#f59e0b' ? '#fcd34d' : '#fca5a5' },
          ].map(item => (
            <div key={item.label} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ fontSize: 11, color: 'rgba(255,255,255,.65)' }}>{item.label}:</span>
              <span style={{ fontSize: 18, fontWeight: 600, color: item.color, fontFamily: 'monospace' }}>{item.value}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  window.WallboardTab = WallboardTab;
})();
