const { useState, useEffect } = React;

function AgentModal({ agent, onClose, onSave }) {
 const [form, setForm] = useState(agent || {
 name: '', department: 'support', description: '',
 system_prompt: '', welcome_message: 'Merhaba, size nasıl yardımcı olabilirim?',
 voice: 'en-US-NovaMultilingualNeural',
 max_tokens: 150, is_active: true,
 enable_background: true,
 background_volume: 0.15,
 ws_tool_ids: []
 });
 const [wsServices, setWsServices] = useState([]);
 const [departments, setDepartments] = useState([]);
 const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

 // Web servis + departman listesini yükle
 useEffect(() => {
 authFetch('/api/ws/services').then(r => r.ok ? r.json() : []).then(setWsServices).catch(() => {});
 authFetch('/api/departments').then(r => r.ok ? r.json() : []).then(d => {
   setDepartments(d.filter(x => x.is_active));
   // Yeni asistan oluşturulurken ilk departmanı varsayılan yap
   if (!agent && d.length > 0 && !form.department) set('department', d[0].key);
 }).catch(() => {});
 }, []);

 async function save() {
 const url = agent ? `/api/agents/${agent.id}` : '/api/agents';
 const method = agent ? 'PUT' : 'POST';
 const r = await authFetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) });
 if (r.ok) onSave();
 }

 return (
 <div className="overlay" onClick={onClose}>
 <div className="modal" onClick={e => e.stopPropagation()}>
 <div className="modal-header">
 <span style={{ fontWeight: 600, fontSize: 18 }}>{agent ? 'Asistanı Düzenle' : 'Yeni Asistan Oluştur'}</span>
 <button className="close-btn" onClick={onClose}>×</button>
 </div>
 <div className="modal-body">
 <div className="form-group">
 <label className="form-label">Asistan Adı</label>
 <input className="form-input" value={form.name} onChange={e => set('name', e.target.value)} placeholder="Örn: Ayşe — Müşteri Destek" />
 </div>
 <div className="form-group">
 <label className="form-label">Departman</label>
 <select className="form-select" value={form.department} onChange={e => set('department', e.target.value)}>
 <option value="">Departman Seçin</option>
 {departments.map(d => (
   <option key={d.key} value={d.key}>{d.label}</option>
 ))}
 </select>
 </div>
 <div className="form-group">
 <label className="form-label">Yapay Zeka Sesi</label>
 <select className="form-select" value={form.voice} onChange={e => set('voice', e.target.value)}>
 <optgroup label="ElevenLabs — En Gerçekçi Ses (Önerilen)">
 <option value="elevenlabs:Rachel">ElevenLabs · Rachel (Kadın, Sıcak)</option>
 <option value="elevenlabs:Bella">ElevenLabs · Bella (Kadın, Yumuşak)</option>
 <option value="elevenlabs:Elli">ElevenLabs · Elli (Kadın, Genç)</option>
 <option value="elevenlabs:Domi">ElevenLabs · Domi (Kadın, Güçlü)</option>
 <option value="elevenlabs:Charlotte">ElevenLabs · Charlotte (Kadın, Zarif)</option>
 <option value="elevenlabs:Adam">ElevenLabs · Adam (Erkek, Derin)</option>
 <option value="elevenlabs:Antoni">ElevenLabs · Antoni (Erkek, Sıcak)</option>
 <option value="elevenlabs:Josh">ElevenLabs · Josh (Erkek, Genç)</option>
 <option value="elevenlabs:Arnold">ElevenLabs · Arnold (Erkek, Güçlü)</option>
 <option value="elevenlabs:Callum">ElevenLabs · Callum (Erkek, Otoriter)</option>
 </optgroup>
 <optgroup label="MiniMax TTS — Doğal Türkçe">
 <option value="minimax:female-shaonv">MiniMax · Genç Kadın (Doğal, Enerjik)</option>
 <option value="minimax:male-qn-qingse">MiniMax · Genç Erkek (Samimi)</option>
 <option value="minimax:female-yujie">MiniMax · Olgun Kadın (Güvenilir)</option>
 <option value="minimax:male-qn-jingying">MiniMax · Profesyonel Erkek</option>
 <option value="minimax:presenter_female">MiniMax · Sunucu Kadın</option>
 <option value="minimax:presenter_male">MiniMax · Sunucu Erkek</option>
 <option value="minimax:audiobook_female_1">MiniMax · Anlatıcı Kadın</option>
 <option value="minimax:audiobook_male_2">MiniMax · Anlatıcı Erkek</option>
 </optgroup>
 <optgroup label="Azure · Ultra Gerçekçi Multilingual">
 <option value="en-US-NovaMultilingualNeural">Azure · Nova (Kadın, Akıcı)</option>
 <option value="en-US-AlloyMultilingualNeural">Azure · Alloy (Erkek, Profesyonel)</option>
 <option value="en-US-ShimmerMultilingualNeural">Azure · Shimmer (Sakin Kadın)</option>
 <option value="en-US-EchoMultilingualNeural">Azure · Echo (Tok Erkek)</option>
 </optgroup>
 <optgroup label="Azure · Standart Türkçe">
 <option value="tr-TR-EmelNeural">Azure · Emel (Türkçe Kadın)</option>
 <option value="tr-TR-AhmetNeural">Azure · Ahmet (Türkçe Erkek)</option>
 </optgroup>
 </select>
 {form.voice?.startsWith('elevenlabs:') && (
 <div style={{ fontSize: 11, color: 'var(--purple, #7c3aed)', marginTop: 5, display: 'flex', alignItems: 'center', gap: 4 }}>
  ElevenLabs API key gerekli — <code>core/config.py</code> dosyasına <code>ELEVENLABS_API_KEY</code> eklenmiş olmalı.
 </div>
 )}
 {form.voice?.startsWith('minimax:') && (
 <div style={{ fontSize: 11, color: 'var(--amber)', marginTop: 5, display: 'flex', alignItems: 'center', gap: 4 }}>
 MiniMax API key gerekli — sunucuda <code>.env</code> dosyasına <code>MINIMAX_API_KEY</code> ve <code>MINIMAX_GROUP_ID</code> eklenmiş olmalı.
 </div>
 )}
 </div>
 <div className="form-group">
 <label className="form-label">Kısa Açıklama</label>
 <input className="form-input" value={form.description} onChange={e => set('description', e.target.value)} />
 </div>
 <div className="form-group">
 <label className="form-label">Sistem Promptu (Davranış Kuralları)</label>
 <textarea className="form-textarea" rows={5} value={form.system_prompt} onChange={e => set('system_prompt', e.target.value)} placeholder="Senin adın... Görevin..." />
 </div>
 <div className="form-group">
 <label className="form-label">İlk Karşılama Mesajı</label>
 <input className="form-input" value={form.welcome_message} onChange={e => set('welcome_message', e.target.value)} />
 </div>
 <div className="form-group">
 <label className="form-label">Max Token Sınırı ({form.max_tokens})</label>
 <input type="range" min={50} max={500} value={form.max_tokens} onChange={e => set('max_tokens', +e.target.value)} style={{ width: '100%', accentColor: 'var(--cyan)' }} />
 </div>
 <div className="form-group" style={{ padding: '20px', background: 'var(--surface2)', borderRadius: '16px', border: '1px solid var(--border)', marginTop: '16px' }}>
 <label className="form-label" style={{ display: 'flex', justifyContent: 'space-between' }}>
 <span>Konuşma Hızı</span>
 <span className="mono" style={{ color: 'var(--blue)', fontWeight: 600 }}>{form.speech_rate ?? 1.0}x</span>
 </label>
 <input type="range" min={0.5} max={2.0} step={0.05} value={form.speech_rate ?? 1.0} onChange={e => setForm({ ...form, speech_rate: parseFloat(e.target.value) })} style={{ width: '100%', accentColor: 'var(--blue)' }} />
 <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 8, display: 'flex', justifyContent: 'space-between', fontWeight: 500 }}>
 <span>Yavaş</span>
 <span style={{ color: 'var(--green)', fontWeight: 700 }}>Önerilen: 1.10x - 1.15x</span>
 <span>Hızlı</span>
 </div>

 {(form.enable_background ?? true) && (
 <div style={{ marginTop: 24, paddingTop: 20, borderTop: '1px solid var(--border)' }}>
 <label className="form-label" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
 <span>Arka Plan Ses Seviyesi</span>
 <span className="mono" style={{ fontSize: 15, color: 'var(--blue)', fontWeight: 600 }}>
 {Math.round((form.background_volume ?? 0.15) * 100)}%
 </span>
 </label>
 <input
 type="range"
 min={0}
 max={0.3}
 step={0.01}
 value={form.background_volume ?? 0.15}
 onChange={e => set('background_volume', parseFloat(e.target.value))}
 style={{ width: '100%', marginTop: '10px', accentColor: 'var(--blue)' }}
 />
 <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 8, display: 'flex', justifyContent: 'space-between', fontWeight: 500 }}>
 <span>Sessiz</span>
 <span style={{ color: 'var(--green)', fontWeight: 700 }}>Önerilen: 10-20%</span>
 <span>Yüksek</span>
 </div>
 </div>
 )}
 </div>
 {/* Web Servis Entegrasyonu (Function Calling) */}
 {wsServices.length > 0 && (
 <div className="form-group" style={{ padding: '16px', background: 'var(--surface2)', borderRadius: '12px', border: '1px solid var(--border)', marginTop: '8px' }}>
 <label className="form-label" style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
 <span> Web Servis Entegrasyonu</span>
 <span style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 400 }}>
 — Konuşma sırasında AI'ın otomatik çağırabileceği servisler
 </span>
 </label>
 <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
 {wsServices.map(svc => {
 const selected = (form.ws_tool_ids || []).includes(svc.id);
 return (
 <label key={svc.id} style={{
 display: 'flex', alignItems: 'center', gap: 10,
 padding: '8px 12px', borderRadius: 8, cursor: 'pointer',
 background: selected ? 'rgba(59,130,246,0.08)' : 'transparent',
 border: `1px solid ${selected ? 'var(--blue)' : 'var(--border)'}`,
 transition: 'all .15s',
 }}>
 <input
 type="checkbox"
 checked={selected}
 onChange={e => {
 const ids = form.ws_tool_ids || [];
 if (e.target.checked) {
 set('ws_tool_ids', [...ids, svc.id]);
 } else {
 set('ws_tool_ids', ids.filter(x => x !== svc.id));
 }
 }}
 style={{ width: 16, height: 16, accentColor: 'var(--blue)', cursor: 'pointer', flexShrink: 0 }}
 />
 <div style={{ flex: 1, minWidth: 0 }}>
 <div style={{ fontWeight: 700, fontSize: 13, color: 'var(--text)' }}>{svc.name}</div>
 {svc.description && (
 <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
 {svc.description}
 </div>
 )}
 </div>
 <span className="mono" style={{ fontSize: 10, color: 'var(--text-dim)', flexShrink: 0 }}>
 {svc.method} · {svc.content_type}
 </span>
 </label>
 );
 })}
 </div>
 {(form.ws_tool_ids || []).length > 0 && (
 <div style={{ fontSize: 11, color: 'var(--blue)', marginTop: 8, fontWeight: 600 }}>
 {(form.ws_tool_ids || []).length} servis seçili — AI, konuşma sırasında bu servisleri otomatik çağırabilecek
 </div>
 )}
 </div>
 )}

 {agent && (
 <div className="form-group" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '16px', background: 'var(--surface2)', borderRadius: '12px', border: '1px solid var(--border)' }}>
 <input type="checkbox" id="active" checked={form.is_active} onChange={e => set('is_active', e.target.checked)} style={{ width: '20px', height: '20px', accentColor: 'var(--blue)', cursor: 'pointer' }} />
 <label htmlFor="active" className="form-label" style={{ margin: 0, cursor: 'pointer' }}>Bu asistan aktif durumda (çağrı alabilir)</label>
 </div>
 )}
 </div>
 <div className="modal-footer">
 <button className="btn outline" onClick={onClose}>İptal Et</button>
 <button className="btn primary" onClick={save}>Değişiklikleri Kaydet</button>
 </div>
 </div>
 </div>
 );
}

// Bilgi Bankası (Knowledge Base) Paneli 

function KBPanel({ agentId, toast }) {
 const [open, setOpen] = useState(false);
 const [kb, setKb] = useState(null); // null=yüklenmedi, false=yok, obj=mevcut
 const [srcType, setSrcType] = useState('text');
 const [content, setContent] = useState('');
 const [kbUrl, setKbUrl] = useState('');
 const [selFile, setSelFile] = useState(null); // File object
 const [saving, setSaving] = useState(false);
 const [indexing, setIndexing] = useState(false);
 const [searchQ, setSearchQ] = useState('');
 const [results, setResults] = useState([]);
 const [searching, setSearching] = useState(false);
 const [loaded, setLoaded] = useState(false);

 function pollIndexStatus() {
   let retries = 0;
   const maxRetries = 30; // 30 * 2s = 60 saniye max
   const interval = setInterval(async () => {
     retries++;
     try {
       const r = await authFetch(`/api/agents/${agentId}/kb`);
       if (r.ok) {
         const d = await r.json();
         if (d.is_indexed || d.last_error) {
           setKb(d);
           setIndexing(false);
           setLoaded(true);
           clearInterval(interval);
           if (d.last_error) toast('İndeksleme hatası: ' + d.last_error, 'error');
           return;
         }
       }
     } catch (_) {}
     if (retries >= maxRetries) {
       setIndexing(false);
       setLoaded(false);
       clearInterval(interval);
     }
   }, 2000);
 }

 async function loadKb() {
 try {
 const r = await authFetch(`/api/agents/${agentId}/kb`);
 if (r.status === 404) { setKb(false); setLoaded(true); return; }
 if (!r.ok) { setLoaded(true); return; }
 const d = await r.json();
 setKb(d);
 setSrcType(d.source_type || 'text');
 setKbUrl(d.source_url || '');
 } finally {
 setLoaded(true);
 }
 }

 useEffect(() => { if (open && !loaded) loadKb(); }, [open, loaded]);

 async function save() {
 setSaving(true);
 try {
 if (srcType === 'file') {
 // Dosya yükleme 
 const formData = new FormData();
 formData.append('file', selFile);
 const r = await authFetch(`/api/agents/${agentId}/kb/upload`, {
 method: 'POST', body: formData,
 });
 if (r.ok) {
 const d = await r.json();
 toast(` ${d.filename} yüklendi (${(d.text_length || 0).toLocaleString()} karakter), indeksleniyor...`, 'success');
 setSelFile(null);
 setIndexing(true);
 pollIndexStatus();
 setTimeout(() => { setLoaded(false); setIndexing(false); }, 8000);
 } else {
 const err = await r.json().catch(() => ({ detail: 'Yükleme başarısız' }));
 toast(err.detail || 'Yükleme başarısız', 'error');
 }
 } else {
 // Metin / URL kaydet 
 const body = { source_type: srcType, auto_index: true };
 if (srcType === 'text') body.raw_content = content;
 else body.source_url = kbUrl;
 const r = await authFetch(`/api/agents/${agentId}/kb`, {
 method: 'POST', headers: { 'Content-Type': 'application/json' },
 body: JSON.stringify(body),
 });
 if (r.ok) {
 toast('Bilgi bankası kaydedildi, indeksleniyor...', 'success');
 setContent('');
 setIndexing(true);

 pollIndexStatus();
 setTimeout(() => { setLoaded(false); setIndexing(false); }, 6000);
 } else {
 toast('Kayıt başarısız', 'error');
 }
 }
 } finally { setSaving(false); }
 }

 async function reindex() {
 setIndexing(true);
 await authFetch(`/api/agents/${agentId}/kb/index`, { method: 'POST' });
 toast('Yeniden indeksleme başladı', 'info');

 pollIndexStatus();
 setTimeout(() => { setLoaded(false); setIndexing(false); }, 8000);


 }

 async function deleteKb() {
 if (!confirm('Bilgi bankasını ve tüm indeks verilerini silmek istediğinize emin misiniz?')) return;
 await authFetch(`/api/agents/${agentId}/kb`, { method: 'DELETE' });
 setKb(false); setContent(''); setKbUrl(''); setSelFile(null); setResults([]);
 toast('Bilgi bankası silindi', 'success');
 }

 async function doSearch() {
 if (!searchQ.trim()) return;
 setSearching(true);
 try {
 const r = await authFetch(`/api/agents/${agentId}/kb/search?q=${encodeURIComponent(searchQ)}&top_k=3`);
 if (r.ok) {
 const d = await r.json();
 setResults(d.results);
 if (d.results.length === 0) toast('Eşleşen sonuç bulunamadı', 'info');
 } else {
 toast('Arama başarısız', 'error');
 }
 } finally { setSearching(false); }
 }

 // Yardımcı: kaynak tipi ikonu
 const srcIcon = { text: '', url: '', file: '' };

 // Status badge
 const statusBadge = kb
 ? <span style={{
 fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 99,
 background: kb.last_error ? 'rgba(239,68,68,0.15)' : kb.is_indexed ? 'rgba(34,197,94,0.15)' : indexing ? 'rgba(251,191,36,0.15)' : 'rgba(156,163,175,0.15)',
 color: kb.last_error ? 'var(--red)' : kb.is_indexed ? 'var(--green)' : indexing ? 'var(--amber)' : 'var(--text-dim)',
 }}>
 {kb.last_error
 ? ' İndeksleme hatası'
 : kb.is_indexed
 ? ` ${kb.chunk_count} parça${kb.source_filename ? ` · ${kb.source_filename}` : ''}`
 : indexing ? ' İndeksleniyor...' : ' Henüz indekslenmedi'}
 </span>
 : kb === false
 ? <span style={{ fontSize: 11, color: 'var(--text-dim)', fontStyle: 'italic' }}>Henüz eklenmedi</span>
 : <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>...</span>;

 // canSave
 const canSave = saving || indexing ? false
 : srcType === 'text' ? content.trim().length > 0
 : srcType === 'url' ? kbUrl.trim().length > 0
 : selFile !== null;

 return (
 <div style={{ marginTop: 16, border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
 {/* Toggle header */}
 <button
 onClick={() => setOpen(o => !o)}
 style={{
 width: '100%', padding: '12px 16px', background: 'var(--surface2)',
 border: 'none', cursor: 'pointer', color: 'var(--text)', textAlign: 'left',
 }}
 >
 <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
 <span style={{ fontWeight: 700, fontSize: 13, display: 'flex', alignItems: 'center', gap: 8 }}>
 Bilgi Bankası (Semantic Search)
 {statusBadge}
 </span>
 <span style={{ color: 'var(--text-dim)', fontSize: 14 }}>{open ? '' : ''}</span>
 </div>
 </button>

 {open && (
 <div style={{ padding: 16, background: 'var(--surface)', display: 'flex', flexDirection: 'column', gap: 12 }}>

 {/* Hata bandı — son indeksleme başarısızsa */}
 {kb && kb.last_error && (
 <div style={{
 fontSize: 12, color: 'var(--red)', background: 'rgba(239,68,68,0.08)',
 border: '1px solid rgba(239,68,68,0.25)', padding: '10px 12px', borderRadius: 8, lineHeight: 1.5,
 }}>
 <strong>İndeksleme başarısız:</strong> {kb.last_error}
 <div style={{ marginTop: 6, color: 'var(--text-dim)' }}>
 Sistem Ayarları &rarr; Azure OpenAI &rarr; <em>Embedding Deployment</em> alanını kontrol edin
 ve Azure portalındaki gerçek deployment adıyla eşleştiğinden emin olun.
 </div>
 </div>
 )}

 {/* Source type selector — 3 seçenek */}
 <div style={{ display: 'flex', gap: 6 }}>
 {[
 { key: 'text', label: ' Metin' },
 { key: 'url', label: ' URL' },
 { key: 'file', label: ' Dosya' },
 ].map(({ key, label }) => (
 <button key={key} onClick={() => { setSrcType(key); setSelFile(null); }} style={{
 flex: 1, padding: '8px 4px', borderRadius: 8, cursor: 'pointer',
 fontWeight: 700, fontSize: 12,
 border: `1px solid ${srcType === key ? 'var(--blue)' : 'var(--border)'}`,
 background: srcType === key ? 'rgba(59,130,246,0.1)' : 'transparent',
 color: srcType === key ? 'var(--blue)' : 'var(--text-dim)',
 }}>
 {label}
 </button>
 ))}
 </div>

 {/* Mevcut içerik bilgisi (text modunda) */}
 {kb && srcType === 'text' && (
 <div style={{ fontSize: 12, color: 'var(--text-dim)', background: 'var(--surface2)', padding: '8px 12px', borderRadius: 8, lineHeight: 1.5 }}>
 Mevcut içerik: <strong>{(kb.content_len || 0).toLocaleString()} karakter</strong>
 {' — '}Değiştirmek için aşağıya yapıştırın. Boş bırakırsanız mevcut içerik korunur.
 </div>
 )}

 {/* Mevcut dosya bilgisi (file modunda, henüz yeni dosya seçilmemişse) */}
 {kb && srcType === 'file' && kb.source_filename && !selFile && (
 <div style={{ fontSize: 12, color: 'var(--text-dim)', background: 'var(--surface2)', padding: '8px 12px', borderRadius: 8 }}>
 Mevcut dosya: <strong>{kb.source_filename}</strong>
 {' · '}{(kb.content_len || 0).toLocaleString()} karakter
 {' — '}Değiştirmek için yeni dosya seçin.
 </div>
 )}

 {/* Input alanları */}
 {srcType === 'text' && (
 <textarea rows={7} className="form-textarea"
 placeholder={"Bilgi bankasına eklenecek metni buraya yapıştırın\n(Ürün açıklamaları, SSS, politikalar, yönetmelikler vb.)"}
 value={content} onChange={e => setContent(e.target.value)}
 style={{ fontSize: 13, resize: 'vertical', fontFamily: 'inherit', lineHeight: 1.6 }}
 />
 )}

 {srcType === 'url' && (
 <div>
 <input className="form-input"
 placeholder="https://example.com/sss-sayfasi"
 value={kbUrl} onChange={e => setKbUrl(e.target.value)}
 />
 <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 6 }}>
 Sayfa içeriği otomatik çekilip indekslenir. JavaScript ile yüklenen dinamik içerikler desteklenmez.
 </div>
 </div>
 )}

 {srcType === 'file' && (
 <label style={{
 display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
 padding: '20px 16px', borderRadius: 10, cursor: 'pointer', transition: 'all .2s',
 border: `2px dashed ${selFile ? 'var(--green)' : 'var(--border)'}`,
 background: selFile ? 'rgba(34,197,94,0.05)' : 'var(--surface2)',
 }}>
 <input
 type="file"
 accept=".pdf,.docx,.txt"
 style={{ display: 'none' }}
 onChange={e => setSelFile(e.target.files[0] || null)}
 />
 {selFile ? (
 <>
 <span style={{ fontSize: 32 }}>
 {selFile.name.endsWith('.pdf') ? '' : selFile.name.endsWith('.docx') ? '' : ''}
 </span>
 <div style={{ textAlign: 'center' }}>
 <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--text)' }}>{selFile.name}</div>
 <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2 }}>
 {selFile.size < 1024 * 1024
 ? `${(selFile.size / 1024).toFixed(1)} KB`
 : `${(selFile.size / 1024 / 1024).toFixed(2)} MB`}
 </div>
 </div>
 <span style={{ fontSize: 12, color: 'var(--green)', fontWeight: 700 }}> Hazır — Kaydet & İndeksle'ye basın</span>
 </>
 ) : (
 <>
  <div style={{ textAlign: 'center', color: 'var(--text-dim)', lineHeight: 1.5 }}>
 <strong style={{ color: 'var(--text)', fontSize: 13 }}>Dosya seçmek için tıklayın</strong><br />
 <span style={{ fontSize: 12 }}>PDF, DOCX veya TXT · Maks. 20 MB</span>
 </div>
 </>
 )}
 </label>
 )}

 {/* Aksiyon butonları */}
 <div style={{ display: 'flex', gap: 8 }}>
 <button className="btn primary" onClick={save}
 disabled={!canSave}
 style={{ flex: 1, fontSize: 13 }}>
 {saving ? ' Yükleniyor...' : indexing ? ' İndeksleniyor...' : ' Kaydet & İndeksle'}
 </button>
 {kb && (
 <>
 <button className="btn outline" onClick={reindex} disabled={indexing}
 title="Mevcut içeriği yeniden indeksle"
 style={{ padding: '0 12px', fontSize: 12, whiteSpace: 'nowrap' }}>
 &#x21BA; Yeniden İndeksle
 </button>
 <button className="btn outline" onClick={deleteKb}
 title="Bilgi bankasını tamamen sil"
 style={{ padding: '0 12px', fontSize: 12, whiteSpace: 'nowrap', color: 'var(--red)', borderColor: 'rgba(239,68,68,0.3)' }}>
 &#x2715; Sil
 </button>
 </>
 )}
 </div>

 {/* Semantic search test — sadece indekslendiyse */}
 {kb && kb.is_indexed && (
 <div style={{ borderTop: '1px solid var(--border)', paddingTop: 12 }}>
 <div style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 700, marginBottom: 8 }}>
 Semantic Arama Testi
 </div>
 <div style={{ display: 'flex', gap: 8 }}>
 <input className="form-input"
 placeholder="Test sorusu girin ve Enter'a basın..."
 value={searchQ} onChange={e => setSearchQ(e.target.value)}
 onKeyDown={e => e.key === 'Enter' && doSearch()}
 style={{ flex: 1, fontSize: 13 }}
 />
 <button className="btn primary" onClick={doSearch}
 disabled={searching || !searchQ.trim()}
 style={{ padding: '0 18px' }}>
 {searching ? '...' : 'Ara'}
 </button>
 </div>

 {results.length > 0 && (
 <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
 {results.map((res, i) => (
 <div key={i} style={{ background: 'var(--surface2)', borderRadius: 8, padding: '10px 12px' }}>
 <div style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 700, marginBottom: 4, display: 'flex', justifyContent: 'space-between' }}>
 <span>Sonuç #{i + 1}</span>
 <span style={{ color: res.score >= 0.6 ? 'var(--green)' : res.score >= 0.4 ? 'var(--amber)' : 'var(--text-dim)' }}>
 Benzerlik: {Math.round(res.score * 100)}%
 </span>
 </div>
 <div style={{ fontSize: 12, color: 'var(--text)', lineHeight: 1.6, display: '-webkit-box', WebkitLineClamp: 4, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
 {res.text}
 </div>
 </div>
 ))}
 </div>
 )}
 </div>
 )}
 </div>
 )}
 </div>
 );
}

// Ana AgentsTab Bileşeni 

function AgentsTab({ toast }) {
 const { data: agents, reload } = window.useApi('/api/agents', []);
 const [modal, setModal] = useState(null);

 async function del(id) {
 if (!confirm('Bu asistanı silmek istediğinize emin misiniz?')) return;
 await authFetch(`/api/agents/${id}`, { method: 'DELETE' });
 toast('Asistan başarıyla silindi', 'success');
 reload();
 }

 return (
 <div className="fade-in">
 <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 36 }}>
 <div>
 <h2 style={{ fontSize: 24, fontWeight: 600, color: 'var(--text)' }}>AI Asistan Yönetimi</h2>
 <p style={{ fontSize: 15, color: 'var(--text-dim)', marginTop: 8 }}>
 Departmanlara özel sesli asistanları yapılandırın. FreeSWITCH dialplan'da <span className="mono" style={{ color: 'var(--blue)', background: 'var(--surface2)', padding: '2px 8px', borderRadius: '6px', border: '1px solid var(--border)' }}>?agent_id=N</span> parametresi ile çağırılır.
 </p>
 </div>
 <button className="btn primary" onClick={() => setModal('new')}>+ Yeni Asistan Ekle</button>
 </div>

 <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(400px,1fr))', gap: 24 }}>
 {agents && agents.map(a => (
 <div key={a.id} className="agent-card">
 <div className="agent-card-header">
 <div>
 <div style={{ fontWeight: 600, fontSize: 18, marginBottom: 8, color: 'var(--text)' }}>{a.name}</div>
 <div style={{ display: 'flex', gap: 8 }}>
 <window.DeptBadge dept={a.department} />
 {!a.is_active && <span className="badge ended">Devre Dışı</span>}
 </div>
 </div>
 <div className="agent-card-actions">
 <button className="btn-sm" onClick={() => setModal(a)}>Düzenle</button>
 <button className="btn-sm outline" style={{ color: 'var(--red)', borderColor: 'rgba(239, 68, 68, 0.3)' }} onClick={() => del(a.id)}>Sil</button>
 </div>
 </div>
 <div style={{ fontSize: 14, color: 'var(--text-dim)', marginBottom: 20, lineHeight: 1.5 }}>{a.description}</div>

 <div style={{ background: 'rgba(248, 250, 252, 0.5)', border: '1px solid var(--border)', borderRadius: 12, padding: '16px', marginBottom: 20 }}>
 <div style={{ fontSize: 12, color: 'var(--blue)', fontWeight: 700, marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.05em' }}>Sistem Promptu (Davranış)</div>
 <div style={{ fontSize: 13, color: 'var(--text)', lineHeight: 1.6, display: '-webkit-box', WebkitLineClamp: 4, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
 {a.system_prompt}
 </div>
 </div>

 <div style={{ fontSize: 13, color: 'var(--text-dim)', display: 'flex', gap: 24, marginBottom: 20, fontWeight: 600 }}>
 <span className="mono" style={{ background: 'var(--surface2)', padding: '4px 10px', borderRadius: '6px' }}>Token: <span style={{ color: 'var(--text)' }}>{a.max_tokens}</span></span>
 <span className="mono" style={{ background: 'var(--surface2)', padding: '4px 10px', borderRadius: '6px' }}>Sistem ID: <span style={{ color: 'var(--text)' }}>{a.id}</span></span>
 </div>

 {/* Bağlı Web Servisler (Function Calling) */}
 {a.ws_tool_ids && a.ws_tool_ids.length > 0 && (
 <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 16 }}>
 <span style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 700, marginRight: 4 }}> Servisler:</span>
 {a.ws_tool_ids.map(sid => (
 <span key={sid} style={{
 fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 99,
 background: 'rgba(59,130,246,0.1)', color: 'var(--blue)',
 border: '1px solid rgba(59,130,246,0.2)'
 }}>
 #{sid}
 </span>
 ))}
 </div>
 )}

 {/* Bilgi Bankası (Knowledge Base) paneli */}
 <KBPanel agentId={a.id} toast={toast} />
 </div>
 ))}
 </div>

 {modal && (
 <AgentModal
 agent={modal === 'new' ? null : modal}
 onClose={() => setModal(null)}
 onSave={() => { toast('Asistan başarıyla kaydedildi', 'success'); setModal(null); reload(); }}
 />
 )}
 </div>
 );
}


window.AgentsTab = AgentsTab;
