// 
// LiveTranscriptPanel.jsx — Canlı Transkript + Alarm Bileşenleri
// 
// Dışa aktarılan bileşenler:
// window.AlarmBanner — Aktif alarmları üst panelde gösterir
// window.LiveTranscriptPanel — Bir çağrının anlık transkriptini listeler
// 

const { useState, useEffect, useRef, useCallback } = React;

// Alarm tipi Türkçe etiket ve ikon eşlemesi 
const ALARM_META = {
 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' },
};

// Duygu renk ve stil eşlemesi 
const EMOTION_STYLE = {
 positive: { bg: 'rgba(34,197,94,.15)', border: 'rgba(34,197,94,.4)', color: '#22c55e' },
 neutral: { bg: 'rgba(139,148,158,.1)', border: 'var(--border)', color: 'var(--text-dim)' },
 negative: { bg: 'rgba(245,158,11,.15)', border: 'rgba(245,158,11,.4)', color: '#f59e0b' },
 angry: { bg: 'rgba(239,68,68,.15)', border: 'rgba(239,68,68,.4)', color: '#ef4444' },
};

// Web Audio ile alarm sesi (harici dosya gerektirmez) 
function playAlarmSound() {
 try {
 const ctx = new (window.AudioContext || window.webkitAudioContext)();
 [0, 0.18, 0.36].forEach(offset => {
 const osc = ctx.createOscillator();
 const gain = ctx.createGain();
 osc.connect(gain);
 gain.connect(ctx.destination);
 osc.frequency.value = 880;
 osc.type = 'square';
 gain.gain.setValueAtTime(0.12, ctx.currentTime + offset);
 gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + offset + 0.15);
 osc.start(ctx.currentTime + offset);
 osc.stop(ctx.currentTime + offset + 0.15);
 });
 } catch (_) {}
}

// 
// AlarmBanner — Çözümlenmemiş alarmları üstte kırmızı/turuncu banner olarak gösterir
// 
function AlarmBanner({ alarms, onResolve }) {
 if (!alarms || alarms.length === 0) return null;

 return (
 <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 16 }}>
 {alarms.map(alarm => {
 const meta = ALARM_META[alarm.alarm_type] || { label: alarm.alarm_type, icon: '', color: '#ef4444' };
 const emotion = alarm.emotion || {};
 const preview = alarm.trigger_text ? `"${alarm.trigger_text.slice(0, 70)}${alarm.trigger_text.length > 70 ? '…' : ''}"` : '';
 const callShort = alarm.call_uuid ? alarm.call_uuid.slice(0, 8) : '—';

 return (
 <div
 key={alarm.id || alarm.call_uuid + alarm.triggered_at}
 style={{
 display: 'flex', alignItems: 'center', justifyContent: 'space-between',
 padding: '10px 16px',
 background: meta.color + '18',
 border: `1px solid ${meta.color}50`,
 borderLeft: `4px solid ${meta.color}`,
 borderRadius: 10,
 animation: 'alarmFadeIn .3s ease',
 }}
 >
 {/* Sol: ikon + açıklama */}
 <div style={{ display: 'flex', alignItems: 'center', gap: 12, flex: 1, minWidth: 0 }}>
 <span style={{ fontSize: 22, flexShrink: 0 }}>{meta.icon}</span>
 <div style={{ minWidth: 0 }}>
 <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
 <span style={{ fontWeight: 600, fontSize: 13, color: meta.color }}>
 {meta.label}
 </span>
 <span style={{
 background: meta.color + '22', color: meta.color,
 fontSize: 11, fontWeight: 700, padding: '1px 7px',
 borderRadius: 8, border: `1px solid ${meta.color}40`,
 }}>
 {emotion.emoji} {emotion.tr} {emotion.score != null ? `%${emotion.score}` : ''}
 </span>
 <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', background: 'var(--surface2)', padding: '1px 6px', borderRadius: 6 }}>
 #{callShort}
 </span>
 {alarm.call_type === 'human' && (
 <span style={{ fontSize: 11, fontWeight: 700, color: '#06b6d4', background: 'rgba(6,182,212,.12)', padding: '1px 7px', borderRadius: 8 }}>
 Canlı Temsilci
 </span>
 )}
 </div>
 {preview && (
 <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
 {preview}
 </div>
 )}
 </div>
 </div>

 {/* Sağ: zaman + kapat butonu */}
 <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0, marginLeft: 12 }}>
 <span style={{ fontSize: 11, color: 'var(--text-dim)', whiteSpace: 'nowrap' }}>
 {alarm.triggered_at ? fmtTimeSec(alarm.triggered_at) : ''}
 </span>
 <button
 onClick={() => onResolve(alarm)}
 style={{
 background: meta.color + '22', border: `1px solid ${meta.color}50`,
 color: meta.color, borderRadius: 8, padding: '4px 12px',
 fontSize: 12, fontWeight: 700, cursor: 'pointer',
 transition: 'all .15s ease', whiteSpace: 'nowrap',
 }}
 onMouseEnter={e => e.currentTarget.style.background = meta.color + '40'}
 onMouseLeave={e => e.currentTarget.style.background = meta.color + '22'}
 >
 Kapat
 </button>
 </div>
 </div>
 );
 })}
 </div>
 );
}

// 
// LiveTranscriptPanel — Tek bir çağrının anlık transkriptini gösterir
// 
function LiveTranscriptPanel({ callUuid, entries = [], callType = 'ai' }) {
 const bottomRef = useRef(null);

 // Yeni mesaj gelince otomatik aşağı kaydır
 useEffect(() => {
 if (bottomRef.current) {
 bottomRef.current.scrollIntoView({ behavior: 'smooth' });
 }
 }, [entries.length]);

 if (entries.length === 0) {
 return (
 <div style={{
 padding: '20px 0', textAlign: 'center',
 color: 'var(--text-dim)', fontSize: 13, fontWeight: 600, opacity: .6,
 }}>
 Transkript bekleniyor…
 </div>
 );
 }

 return (
 <div style={{
 maxHeight: 280,
 overflowY: 'auto',
 display: 'flex',
 flexDirection: 'column',
 gap: 6,
 padding: '4px 2px',
 }}>
 {entries.map((entry, i) => {
 const isCustomer = entry.speaker === 'customer';
 const isBot = entry.speaker === 'bot';
 const isAgent = entry.speaker === 'agent';
 const emotion = entry.emotion;
 const emoStyle = emotion ? (EMOTION_STYLE[emotion.label] || EMOTION_STYLE.neutral) : null;

 return (
 <div
 key={i}
 style={{
 display: 'flex',
 flexDirection: 'column',
 alignItems: isCustomer ? 'flex-start' : 'flex-end',
 }}
 >
 {/* Konuşmacı etiketi */}
 <div style={{
 fontSize: 10, fontWeight: 700, marginBottom: 2,
 color: isCustomer ? 'var(--text-dim)' : isBot ? '#3b6df0' : '#06b6d4',
 textTransform: 'uppercase', letterSpacing: '.06em',
 }}>
 {isCustomer ? ' Müşteri' : isBot ? ' Asistan' : ' Temsilci'}
 </div>

 {/* Balon */}
 <div style={{
 maxWidth: '85%',
 padding: '8px 12px',
 borderRadius: isCustomer ? '4px 12px 12px 12px' : '12px 4px 12px 12px',
 background: isCustomer
 ? (emoStyle ? emoStyle.bg : 'var(--surface2)')
 : isBot
 ? 'rgba(59,109,240,.1)'
 : 'rgba(6,182,212,.1)',
 border: `1px solid ${
 isCustomer
 ? (emoStyle ? emoStyle.border : 'var(--border)')
 : isBot
 ? 'rgba(59,109,240,.25)'
 : 'rgba(6,182,212,.25)'
 }`,
 fontSize: 13,
 lineHeight: 1.5,
 color: 'var(--text)',
 wordBreak: 'break-word',
 }}>
 {entry.text}
 </div>

 {/* Duygu badge + zaman */}
 <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3 }}>
 {isCustomer && emotion && emotion.label !== 'neutral' && (
 <span style={{
 fontSize: 10, fontWeight: 700, padding: '1px 7px',
 borderRadius: 8, whiteSpace: 'nowrap',
 background: emoStyle.bg,
 border: `1px solid ${emoStyle.border}`,
 color: emoStyle.color,
 }}>
 {emotion.emoji} {emotion.tr} %{emotion.score}
 </span>
 )}
 {entry.timestamp && (
 <span style={{ fontSize: 10, color: 'var(--text-dim)', opacity: .7 }}>
 {fmtTimeSec(entry.timestamp)}
 </span>
 )}
 </div>
 </div>
 );
 })}
 <div ref={bottomRef} />
 </div>
 );
}

// Dışa aktar
window.AlarmBanner = AlarmBanner;
window.LiveTranscriptPanel = LiveTranscriptPanel;
window.playAlarmSound = playAlarmSound;
