// 
// AlarmsTab.jsx — Alarm Geçmişi + Otomatik Transfer Ayarları
// 

const { useState, useEffect, useCallback } = React;

const ALARM_META_TAB = {
 angry_detected: { label: 'Sinirli Müşteri', icon: '', color: '#ef4444' },
 score_threshold: { label: 'Yüksek Olumsuzluk', icon: '', color: '#f97316' },
 sustained_negative: { label: 'Sürekli Olumsuz', icon: '', color: '#f59e0b' },
 rapid_drop: { label: 'Ani Duygu Düşüşü', icon: '', color: '#ef4444' },
};

// Küçük Toggle bileşeni 
function Toggle({ value, onChange }) {
 return (
 <button
 onClick={() => onChange(!value)}
 style={{
 width: 52, height: 28, borderRadius: 14, border: 'none', cursor: 'pointer',
 background: value ? '#22c55e' : 'var(--surface2)',
 position: 'relative', transition: 'background .2s', flexShrink: 0,
 }}
 >
 <span style={{
 position: 'absolute', top: 4, left: value ? 28 : 4,
 width: 20, height: 20, borderRadius: '50%',
 background: '#fff', transition: 'left .2s',
 boxShadow: '0 1px 3px rgba(0,0,0,.3)',
 }} />
 </button>
 );
}

// 
// AlarmsTab
// 
function AlarmsTab({ toast }) {
 // Alarm listesi 
 const [alarms, setAlarms] = useState([]);
 const [total, setTotal] = useState(0);
 const [loading, setLoading] = useState(false);
 const [filter, setFilter] = useState({ alarm_type: '', offset: 0, limit: 20 });

 // İstatistikler 
 const [stats, setStats] = useState({ total: 0, active: 0, resolved: 0, by_type: {} });

 // Otomatik transfer konfigürasyonu 
 const [config, setConfig] = useState({ enabled: false, threshold: 3, destination: '9999' });
 const [configDirty, setDirty] = useState(false);
 const [configSaving, setSaving] = useState(false);

 // Yükleme fonksiyonları 
 const loadAlarms = useCallback(async () => {
 setLoading(true);
 try {
 const p = new URLSearchParams({
 limit: filter.limit,
 offset: filter.offset,
 ...(filter.alarm_type && { alarm_type: filter.alarm_type }),
 });
 const res = await authFetch(`/api/alarms/history?${p}`);
 const data = await res.json();
 setAlarms(data.items || []);
 setTotal(data.total || 0);
 } catch (_) {
 toast?.('Alarmlar yüklenemedi', 'error');
 } finally {
 setLoading(false);
 }
 }, [filter]);

 const loadStats = useCallback(async () => {
 try {
 const res = await authFetch('/api/alarms/stats');
 const data = await res.json();
 setStats(data);
 } catch (_) {}
 }, []);

 const loadConfig = useCallback(async () => {
 try {
 const res = await authFetch('/api/alarms/config');
 const data = await res.json();
 setConfig(data);
 setDirty(false);
 } catch (_) {}
 }, []);

 useEffect(() => { loadAlarms(); }, [filter]);
 useEffect(() => { loadStats(); loadConfig(); }, []);

 // Alarm çözümleme 
 const resolveAlarm = async (id) => {
 try {
 await authFetch(`/api/alarms/${id}/resolve?resolved_by=Admin`, { method: 'POST' });
 setAlarms(prev => prev.map(a => a.id === id ? { ...a, is_active: false } : a));
 setStats(prev => ({
 ...prev,
 active: Math.max(0, prev.active - 1),
 resolved: prev.resolved + 1,
 }));
 toast?.('Alarm çözümlendi ', 'success');
 } catch (_) {
 toast?.('Alarm çözümlenemedi', 'error');
 }
 };

 // Konfigürasyon kaydetme 
 const saveConfig = async () => {
 setSaving(true);
 try {
 const p = new URLSearchParams({
 enabled: config.enabled,
 threshold: config.threshold,
 destination: config.destination,
 });
 await authFetch(`/api/alarms/config?${p}`, { method: 'POST' });
 setDirty(false);
 toast?.('Ayarlar kaydedildi ', 'success');
 } catch (_) {
 toast?.('Kaydetme başarısız', 'error');
 } finally {
 setSaving(false);
 }
 };

 const updateCfg = (patch) => { setConfig(c => ({ ...c, ...patch })); setDirty(true); };

 // Sayfalama 
 const totalPages = Math.max(1, Math.ceil(total / filter.limit));
 const currentPage = Math.floor(filter.offset / filter.limit) + 1;

 // En sık alarm tipi 
 const topType = Object.entries(stats.by_type || {}).sort((a, b) => b[1] - a[1])[0];
 const topMeta = topType ? (ALARM_META_TAB[topType[0]] || { label: topType[0], icon: '' }) : null;

 // 
 return (
 <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>

 {/* İstatistik Kartları */}
 <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
 {[
 { label: 'Toplam Alarm', value: stats.total, color: '#6366f1', icon: '' },
 { label: 'Aktif', value: stats.active, color: '#ef4444', icon: '' },
 { label: 'Çözümlendi', value: stats.resolved, color: '#22c55e', icon: '' },
 {
 label: 'En Sık Tip',
 value: topMeta ? `${topMeta.icon} ${topMeta.label}` : '—',
 sub: topType ? `${topType[1]} kez` : '',
 color: topMeta ? (ALARM_META_TAB[topType[0]]?.color || '#f97316') : '#f97316',
 small: true,
 },
 ].map(s => (
 <div key={s.label} style={{
 background: 'var(--surface)', border: '1px solid var(--border)',
 borderRadius: 12, padding: '20px 24px',
 borderTop: `3px solid ${s.color}`,
 }}>
 <div style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 600, marginBottom: 8 }}>
 {s.label}
 </div>
 <div style={{ fontSize: s.small ? 13 : 28, fontWeight: 600, color: s.color }}>
 {s.value}
 </div>
 {s.sub && (
 <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4 }}>{s.sub}</div>
 )}
 </div>
 ))}
 </div>

 {/* Otomatik Transfer Ayarları */}
 <div style={{
 background: 'var(--surface)', border: '1px solid var(--border)',
 borderRadius: 12, padding: 24,
 }}>
 <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
 <div>
 <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)' }}>
 Otomatik Transfer
 </div>
 <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 4 }}>
 Alarm eşiği aşılınca çağrıyı otomatik olarak canlı temsilciye bağlar
 </div>
 </div>
 <Toggle value={config.enabled} onChange={v => updateCfg({ enabled: v })} />
 </div>

 <div style={{ display: 'flex', gap: 20, alignItems: 'flex-end', flexWrap: 'wrap' }}>
 {/* Eşik */}
 <div>
 <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-dim)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '.05em' }}>
 Alarm Eşiği
 </div>
 <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
 <input
 type="number" min="1" max="20"
 value={config.threshold}
 onChange={e => updateCfg({ threshold: parseInt(e.target.value) || 1 })}
 disabled={!config.enabled}
 style={{
 width: 72, padding: '8px 12px', borderRadius: 8,
 border: '1px solid var(--border)', background: config.enabled ? 'var(--surface2)' : 'var(--surface)',
 color: 'var(--text)', fontSize: 16, fontWeight: 700, textAlign: 'center',
 opacity: config.enabled ? 1 : .5,
 }}
 />
 <span style={{ fontSize: 13, color: 'var(--text-dim)' }}>alarm sonrası</span>
 </div>
 </div>

 {/* Hedef */}
 <div>
 <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-dim)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '.05em' }}>
 Transfer Hedefi
 </div>
 <input
 type="text"
 value={config.destination}
 placeholder="9999"
 onChange={e => updateCfg({ destination: e.target.value })}
 disabled={!config.enabled}
 style={{
 width: 130, padding: '8px 12px', borderRadius: 8,
 border: '1px solid var(--border)', background: config.enabled ? 'var(--surface2)' : 'var(--surface)',
 color: 'var(--text)', fontSize: 14,
 opacity: config.enabled ? 1 : .5,
 }}
 />
 </div>

 {/* Kaydet butonu */}
 {configDirty && (
 <button
 onClick={saveConfig}
 disabled={configSaving}
 style={{
 padding: '9px 22px', borderRadius: 8, border: 'none',
 background: '#6366f1', color: '#fff',
 fontWeight: 700, cursor: 'pointer', fontSize: 13,
 opacity: configSaving ? .6 : 1,
 }}
 >
 {configSaving ? ' Kaydediliyor...' : ' Kaydet'}
 </button>
 )}
 </div>

 {/* Durum mesajı */}
 {config.enabled ? (
 <div style={{
 marginTop: 16, padding: '10px 14px', borderRadius: 8,
 background: 'rgba(34,197,94,.08)', border: '1px solid rgba(34,197,94,.25)',
 fontSize: 12, color: '#22c55e', fontWeight: 600,
 }}>
 Aktif: Bir çağrıda <strong>{config.threshold}</strong> alarm tetiklenince →{' '}
 <strong>{config.destination}</strong> numarasına transfer
 </div>
 ) : (
 <div style={{
 marginTop: 16, padding: '10px 14px', borderRadius: 8,
 background: 'rgba(239,68,68,.06)', border: '1px solid rgba(239,68,68,.2)',
 fontSize: 12, color: 'var(--text-dim)', fontWeight: 600,
 }}>
 Pasif: Otomatik transfer kapalı. Açmak için toggle'ı kullanın.
 </div>
 )}
 </div>

 {/* Alarm Geçmişi Tablosu */}
 <div style={{
 background: 'var(--surface)', border: '1px solid var(--border)',
 borderRadius: 12, overflow: 'hidden',
 }}>
 {/* Başlık + Filtreler */}
 <div style={{
 padding: '16px 20px', borderBottom: '1px solid var(--border)',
 display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap',
 }}>
 <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', flex: 1 }}>
 Alarm Geçmişi
 <span style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 400, marginLeft: 8 }}>
 ({total} kayıt)
 </span>
 </span>

 {/* Tip filtresi */}
 <select
 value={filter.alarm_type}
 onChange={e => setFilter(f => ({ ...f, alarm_type: e.target.value, offset: 0 }))}
 style={{
 padding: '6px 12px', borderRadius: 8, border: '1px solid var(--border)',
 background: 'var(--surface2)', color: 'var(--text)', fontSize: 13, cursor: 'pointer',
 }}
 >
 <option value="">Tüm Tipler</option>
 {Object.entries(ALARM_META_TAB).map(([k, v]) => (
 <option key={k} value={k}>{v.icon} {v.label}</option>
 ))}
 </select>

 {/* Yenile */}
 <button
 onClick={() => { loadAlarms(); loadStats(); }}
 style={{
 padding: '6px 14px', borderRadius: 8, border: '1px solid var(--border)',
 background: 'var(--surface2)', color: 'var(--text)', cursor: 'pointer', fontSize: 13,
 }}
 >
 Yenile
 </button>
 </div>

 {/* Tablo */}
 <div style={{ overflowX: 'auto' }}>
 {loading ? (
 <div style={{ padding: 48, textAlign: 'center', color: 'var(--text-dim)', fontSize: 14 }}>
 Yükleniyor...
 </div>
 ) : alarms.length === 0 ? (
 <div style={{ padding: 48, textAlign: 'center' }}>
  <div style={{ color: 'var(--text-dim)', fontSize: 14 }}>Alarm bulunamadı</div>
 </div>
 ) : (
 <table style={{ width: '100%', borderCollapse: 'collapse' }}>
 <thead>
 <tr style={{ background: 'var(--surface2)' }}>
 {['Zaman', 'Çağrı', 'Alarm Tipi', 'Duygu', 'Tetikleyen Metin', 'Durum', ''].map(h => (
 <th key={h} style={{
 padding: '10px 16px', textAlign: 'left',
 fontSize: 11, fontWeight: 700, color: 'var(--text-dim)',
 textTransform: 'uppercase', letterSpacing: '.05em', whiteSpace: 'nowrap',
 }}>
 {h}
 </th>
 ))}
 </tr>
 </thead>
 <tbody>
 {alarms.map(alarm => {
 const meta = ALARM_META_TAB[alarm.alarm_type] || { label: alarm.alarm_type, icon: '', color: '#ef4444' };
 const emo = alarm.emotion || {};
 const ts = fmtDateTime(alarm.triggered_at, { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' });
 return (
 <tr
 key={alarm.id}
 style={{ borderBottom: '1px solid var(--border)', transition: 'background .1s' }}
 onMouseEnter={e => e.currentTarget.style.background = 'var(--surface2)'}
 onMouseLeave={e => e.currentTarget.style.background = ''}
 >
 {/* Zaman */}
 <td style={{ padding: '12px 16px', fontSize: 12, color: 'var(--text-dim)', whiteSpace: 'nowrap' }}>
 {ts}
 </td>

 {/* Çağrı UUID */}
 <td style={{ padding: '12px 16px' }}>
 <span className="mono" style={{
 fontSize: 12, color: 'var(--text-dim)',
 background: 'var(--surface2)', padding: '2px 7px', borderRadius: 6,
 }}>
 #{alarm.call_uuid ? alarm.call_uuid.slice(0, 8) : '—'}
 </span>
 </td>

 {/* Alarm Tipi */}
 <td style={{ padding: '12px 16px', whiteSpace: 'nowrap' }}>
 <span style={{
 background: meta.color + '18', color: meta.color,
 border: `1px solid ${meta.color}40`,
 padding: '3px 10px', borderRadius: 8,
 fontSize: 12, fontWeight: 700,
 }}>
 {meta.icon} {meta.label}
 </span>
 </td>

 {/* Duygu */}
 <td style={{ padding: '12px 16px', whiteSpace: 'nowrap' }}>
 <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>
 {emo.emoji || ''} {emo.tr || '—'}
 {emo.score != null && (
 <span style={{ color: meta.color, fontWeight: 700, marginLeft: 4 }}>
 %{emo.score}
 </span>
 )}
 </span>
 </td>

 {/* Tetikleyen Metin */}
 <td style={{ padding: '12px 16px', maxWidth: 300 }}>
 {alarm.trigger_text ? (
 <span style={{
 fontSize: 12, color: 'var(--text)',
 display: 'block', overflow: 'hidden',
 textOverflow: 'ellipsis', whiteSpace: 'nowrap',
 }}>
 "{alarm.trigger_text}"
 </span>
 ) : (
 <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>—</span>
 )}
 </td>

 {/* Durum */}
 <td style={{ padding: '12px 16px', whiteSpace: 'nowrap' }}>
 {alarm.is_active ? (
 <span style={{
 fontSize: 11, fontWeight: 700, color: '#ef4444',
 background: 'rgba(239,68,68,.1)',
 padding: '2px 9px', borderRadius: 6,
 }}>
 Aktif
 </span>
 ) : (
 <span style={{
 fontSize: 11, fontWeight: 700, color: '#22c55e',
 background: 'rgba(34,197,94,.1)',
 padding: '2px 9px', borderRadius: 6,
 }}>
 Çözümlendi
 </span>
 )}
 </td>

 {/* Aksiyon */}
 <td style={{ padding: '12px 16px' }}>
 {alarm.is_active && (
 <button
 onClick={() => resolveAlarm(alarm.id)}
 style={{
 padding: '4px 12px', borderRadius: 6, cursor: 'pointer',
 border: '1px solid rgba(34,197,94,.4)',
 background: 'rgba(34,197,94,.1)',
 color: '#22c55e', fontSize: 12, fontWeight: 700,
 transition: 'all .15s',
 }}
 onMouseEnter={e => e.currentTarget.style.background = 'rgba(34,197,94,.2)'}
 onMouseLeave={e => e.currentTarget.style.background = 'rgba(34,197,94,.1)'}
 >
 Kapat
 </button>
 )}
 </td>
 </tr>
 );
 })}
 </tbody>
 </table>
 )}
 </div>

 {/* Sayfalama */}
 {totalPages > 1 && (
 <div style={{
 padding: '12px 20px', borderTop: '1px solid var(--border)',
 display: 'flex', gap: 8, justifyContent: 'center', alignItems: 'center',
 }}>
 <button
 onClick={() => setFilter(f => ({ ...f, offset: Math.max(0, f.offset - f.limit) }))}
 disabled={currentPage === 1}
 style={{
 padding: '5px 14px', borderRadius: 7, border: '1px solid var(--border)',
 background: 'var(--surface2)', color: 'var(--text)', cursor: currentPage === 1 ? 'not-allowed' : 'pointer',
 opacity: currentPage === 1 ? .4 : 1, fontSize: 13,
 }}
 >
 ← Önceki
 </button>
 <span style={{ fontSize: 13, color: 'var(--text-dim)', minWidth: 60, textAlign: 'center' }}>
 {currentPage} / {totalPages}
 </span>
 <button
 onClick={() => setFilter(f => ({ ...f, offset: f.offset + f.limit }))}
 disabled={currentPage === totalPages}
 style={{
 padding: '5px 14px', borderRadius: 7, border: '1px solid var(--border)',
 background: 'var(--surface2)', color: 'var(--text)', cursor: currentPage === totalPages ? 'not-allowed' : 'pointer',
 opacity: currentPage === totalPages ? .4 : 1, fontSize: 13,
 }}
 >
 Sonraki →
 </button>
 </div>
 )}
 </div>
 </div>
 );
}

window.AlarmsTab = AlarmsTab;
