const { useState, useEffect, useRef } = React;
const { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell, LineChart, Line, CartesianGrid } = Recharts;

/* 
 QC SESSION DETAIL — Oturum detay sayfası
 */
function QCSessionDetail({ session, onBack, onStatusChange }) {
 const [data, setData] = useState(null);
 const audioRef = useRef(null);

 useEffect(() => {
 authFetch(`/api/qc/sessions/${session.id}`).then(r => r.json()).then(setData);
 }, [session.id]);

 if (!data) return (
 <div className="fade-in" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 300 }}>
 <div style={{ textAlign: 'center', color: 'var(--text-dim)' }}>
  <div style={{ fontSize: 15, fontWeight: 600 }}>Detaylar yükleniyor...</div>
 </div>
 </div>
 );

 const passedCount = data.criteria_scores.filter(c => c.passed).length;
 const totalCount = data.criteria_scores.length;
 const passRate = totalCount > 0 ? Math.round(passedCount / totalCount * 100) : 0;
 const scoreColor = passRate >= 80 ? 'var(--green)' : passRate >= 60 ? 'var(--amber)' : 'var(--red)';

 return (
 <div className="fade-in">
 {/* HEADER */}
 <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 28 }}>
 <button className="btn outline" onClick={onBack} style={{ padding: '7px 14px' }}>← Geri</button>
 <div style={{ flex: 1 }}>
 <div style={{ fontSize: 20, fontWeight: 600, color: 'var(--text)' }}>Oturum Detayı</div>
 <div className="mono" style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 2 }}>{data.call_info.phone_number}</div>
 </div>
 <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 18px', borderRadius: 12, background: scoreColor + '12', border: `1px solid ${scoreColor}30` }}>
 <span style={{ fontSize: 22, fontWeight: 600, color: scoreColor, fontFamily: 'var(--mono)' }}>{passedCount}/{totalCount}</span>
 <span style={{ fontSize: 12, fontWeight: 600, color: scoreColor }}>başarılı</span>
 </div>
 </div>

 <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr', gap: 24 }}>
 {/* SOL: Meta bilgiler */}
 <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
 <div className="panel" style={{ padding: 20 }}>
 <div className="qc-meta-row">
 <span className="qc-meta-label">Müşteri</span>
 <span className="mono" style={{ fontWeight: 700 }}>{data.call_info.phone_number}</span>
 </div>
 <div className="qc-meta-row">
 <span className="qc-meta-label">Asistan</span>
 <span style={{ fontWeight: 600 }}>{data.call_info.agent_name}</span>
 </div>
 <div className="qc-meta-row">
 <span className="qc-meta-label">Tarih</span>
 <span style={{ fontSize: 13 }}>{fmtDateTime(data.call_info.start_time, { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' })}</span>
 </div>
 <div className="qc-meta-row" style={{ borderBottom: 'none', paddingBottom: 0 }}>
 <span className="qc-meta-label">Durum</span>
 {(() => {
   const sc = { completed: { label: 'Tamamlandı', color: 'var(--green)' }, failed: { label: 'Başarısız', color: 'var(--red)' }, abandoned: { label: 'Başarısız', color: 'var(--red)' }, in_progress: { label: 'Devam Ediyor', color: 'var(--amber)' } };
   const cfg = sc[data.status] || sc.in_progress;
   return <span style={{ fontSize: 13, fontWeight: 700, color: cfg.color, padding: '4px 10px', borderRadius: 8, background: cfg.color + '18', border: `1px solid ${cfg.color}30` }}>{cfg.label}</span>;
 })()}
 </div>
 </div>

 {data.call_info.recording_url && (
 <div className="panel" style={{ padding: 20 }}>
 <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-dim)', marginBottom: 12 }}>SES KAYDI</div>
 <audio ref={audioRef} controls src={data.call_info.recording_url} style={{ width: '100%', height: 36 }} />
 </div>
 )}

 {/* Başarı çubuğu */}
 <div className="panel" style={{ padding: 20 }}>
 <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
 <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-dim)' }}>BAŞARI ORANI</span>
 <span className="mono" style={{ fontSize: 15, fontWeight: 600, color: scoreColor }}>%{passRate}</span>
 </div>
 <div style={{ height: 8, borderRadius: 4, background: 'var(--surface2)' }}>
 <div style={{ width: `${passRate}%`, height: '100%', borderRadius: 4, background: scoreColor, transition: 'width .6s ease' }} />
 </div>
 </div>
 </div>

 {/* SAĞ: Adım adım sonuçlar */}
 <div className="panel">
 <div className="panel-header">
 <span className="panel-title">Adım Sonuçları</span>
 </div>
 <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 12 }}>
 {data.criteria_scores.map((c, i) => (
 <div key={i} className="qc-step-result" style={{ borderLeft: `3px solid ${c.passed ? 'var(--green)' : 'var(--red)'}` }}>
 <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: c.reasoning ? 8 : 0 }}>
 <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
 <span style={{ fontSize: 18 }}>{c.passed ? '' : ''}</span>
 <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>{c.name}</span>
 </div>
 <span className="mono" style={{ fontSize: 13, fontWeight: 700, padding: '3px 10px', borderRadius: 6, background: c.passed ? 'rgba(34,197,94,.08)' : 'rgba(239,68,68,.08)', color: c.passed ? 'var(--green)' : 'var(--red)' }}>
 {c.score}/{c.weight}
 </span>
 </div>
 {c.reasoning && (
 <div style={{ fontSize: 13, color: 'var(--text-dim)', lineHeight: 1.5, marginTop: 4, paddingLeft: 28 }}>
 {c.reasoning}
 </div>
 )}
 </div>
 ))}
 </div>

 {data.feedback && (
 <div style={{ padding: '0 20px 20px' }}>
 <div style={{ padding: 16, background: 'var(--surface2)', borderRadius: 10, border: '1px solid var(--border)' }}>
 <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--text-dim)', marginBottom: 8, textTransform: 'uppercase' }}>AI Geri Bildirimi</div>
 <div style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--text)' }}>{data.feedback}</div>
 </div>
 </div>
 )}
 </div>
 </div>
 </div>
 );
}

/* 
 QC SCRIPT MODAL — Senaryo düzenleme
 */
function QCScriptModal({ script, onClose, onSave }) {
 const empty = {
 name: '', description: '', is_active: false,
 welcome_message: '', retry_message: '', voice: 'en-US-NovaMultilingualNeural',
 enable_background: true, background_volume: 0.15, speech_rate: 1.0, steps: [], variables: {},
 phone_mismatch_enabled: false,
 phone_mismatch_variable: 'crm_phone',
 phone_mismatch_message: 'Lütfen kayıt yaptırdığınız telefon ile aramanızı rica ederiz. İyi günler',
 phone_mismatch_announcement_id: null,
 end_webhook_service_id: null,
 end_webhook_only_on_success: true,
 };
 const [form, setForm] = useState(script ? { ...empty, ...script } : empty);
 const [steps, setSteps] = useState(script?.steps ? [...script.steps] : []);
 const [vars, setVars] = useState(script?.variables ? Object.entries(script.variables).map(([k, v]) => ({ key: k, value: v })) : []);
 const [announcements, setAnnouncements] = useState([]);
 const [wsServices, setWsServices] = useState([]);
 const [saving, setSaving] = useState(false);

 useEffect(() => {
 authFetch('/api/announcements').then(r => r.json()).then(d => setAnnouncements(d.items || d || [])).catch(() => {});
 authFetch('/api/ws/services').then(r => r.json()).then(d => setWsServices(d.items || d || [])).catch(() => {});
 }, []);

 const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
 const addStep = () => setSteps(s => [...s, { order: s.length + 1, title: '', text: '', detail_text: '', step_type: 'info', policy_years: null, max_retries: 2 }]);
 const updateS = (i, field, val) => setSteps(s => s.map((item, idx) => idx === i ? { ...item, [field]: val } : item));
 const removeS = (i) => setSteps(s => s.filter((_, idx) => idx !== i));
 const moveS = (i, dir) => {
 const arr = [...steps];
 const j = i + dir;
 if (j < 0 || j >= arr.length) return;
 [arr[i], arr[j]] = [arr[j], arr[i]];
 setSteps(arr);
 };

 const handleSave = async () => {
 setSaving(true);
 try {
 const varObj = {};
 vars.forEach(v => { if (v.key.trim()) varObj[v.key.trim()] = v.value; });
 const payload = {
   ...form,
   steps: steps.map((s, i) => ({ ...s, order: i + 1 })),
   variables: varObj,
 };
 const url = script ? `/api/qc/scripts/${script.id}` : '/api/qc/scripts';
 const method = script ? 'PUT' : 'POST';
 const r = await authFetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
 if (r.ok) onSave();
 } finally { setSaving(false); }
 };

 const stepTypeConfig = {
 info: { label: 'Bilgi', color: 'var(--blue)', desc: 'Cevap beklemez' },
 yesno_end: { label: 'Onay', color: 'var(--red)', desc: 'Hayır → bitiş' },
 detail_if_yes: { label: 'Detay (Evet)', color: 'var(--green)', desc: 'Evet → detay oku' },
 detail_if_no: { label: 'Detay (Hayır)', color: 'var(--amber)', desc: 'Hayır → detay oku' },
 qna_handoff: { label: 'Soru-Cevap', color: 'var(--purple)', desc: 'AI\'a devret' },
 };

 return (
 <div className="overlay" onClick={onClose} style={{ alignItems: 'flex-start', paddingTop: 32 }}>
 <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 820, maxHeight: '90vh' }}>
 <div className="modal-header">
 <span style={{ fontWeight: 600, fontSize: 18 }}>{script ? 'Senaryo Düzenle' : 'Yeni Senaryo'}</span>
 <button className="close-btn" onClick={onClose}>×</button>
 </div>
 <div className="modal-body" style={{ overflow: 'auto' }}>

 {/* GENEL BİLGİLER */}
 <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 20 }}>
 <div className="form-group">
 <label className="form-label">Senaryo Adı</label>
 <input className="form-input" value={form.name} onChange={e => set('name', e.target.value)} placeholder="Örn: Kalite Kontrol Scripti" />
 </div>
 <div className="form-group">
 <label className="form-label">Açıklama</label>
 <input className="form-input" value={form.description} onChange={e => set('description', e.target.value)} />
 </div>
 </div>
 <div className="form-group" style={{ marginBottom: 14 }}>
 <label className="form-label">Açılış Mesajı</label>
 <textarea className="form-textarea" rows={2} value={form.welcome_message} onChange={e => set('welcome_message', e.target.value)} placeholder="Çağrı başladığında söylenecek..." />
 </div>
 <div className="form-group" style={{ marginBottom: 20 }}>
 <label className="form-label">Anlaşılamadı Mesajı</label>
 <input className="form-input" value={form.retry_message} onChange={e => set('retry_message', e.target.value)} />
 </div>

 {/* TELEFON EŞLEŞME KONTROLÜ */}
 <div style={{ marginBottom: 20, padding: 16, background: 'var(--surface2)', borderRadius: 12, border: '1px solid var(--border)' }}>
 <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: form.phone_mismatch_enabled ? 14 : 0 }}>
 <input
 type="checkbox"
 checked={!!form.phone_mismatch_enabled}
 onChange={e => set('phone_mismatch_enabled', e.target.checked)}
 />
 <span style={{ fontSize: 14, fontWeight: 700 }}>Telefon Eşleşme Kontrolü</span>
 <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>
 {form.phone_mismatch_enabled ? 'Aktif' : 'Pasif'}
 </span>
 </div>
 {form.phone_mismatch_enabled && (
 <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
 {/* Servis değişkeni */}
 <div className="form-group" style={{ marginBottom: 0 }}>
 <label className="form-label">Servis Değişkeni</label>
 <input
 className="form-input"
 value={form.phone_mismatch_variable || ''}
 onChange={e => set('phone_mismatch_variable', e.target.value)}
 placeholder="crm_phone"
 style={{ maxWidth: 260 }}
 />
 <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4 }}>
 Web servisinden dönen telefon/kimlik alanı (ör: crm_phone). Boş gelirse müşteri bulunamadı sayılır.
 </div>
 </div>

 {/* Anons seçimi */}
 <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
 <div className="form-group" style={{ marginBottom: 0 }}>
 <label className="form-label">Kayıtlı Anons</label>
 <select
 className="form-select"
 value={form.phone_mismatch_announcement_id || ''}
 onChange={e => set('phone_mismatch_announcement_id', e.target.value ? +e.target.value : null)}
 >
 <option value="">— TTS metnini kullan —</option>
 {announcements.map(a => (
 <option key={a.id} value={a.id}>{a.name}</option>
 ))}
 </select>
 <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4 }}>
 Seçilirse kayıtlı ses dosyası çalınır; boş bırakılırsa aşağıdaki metin TTS ile okunur.
 </div>
 </div>
 <div className="form-group" style={{ marginBottom: 0 }}>
 <label className="form-label" style={{ color: form.phone_mismatch_announcement_id ? 'var(--text-dim)' : 'var(--text)' }}>
 TTS Metni {form.phone_mismatch_announcement_id ? <span style={{ fontWeight: 400, fontSize: 11 }}>(anons seçildi, kullanılmaz)</span> : null}
 </label>
 <textarea
 className="form-textarea"
 rows={2}
 value={form.phone_mismatch_message || ''}
 onChange={e => set('phone_mismatch_message', e.target.value)}
 placeholder="Lütfen kayıt yaptırdığınız telefon ile aramanızı rica ederiz. İyi günler"
 disabled={!!form.phone_mismatch_announcement_id}
 style={{ opacity: form.phone_mismatch_announcement_id ? 0.45 : 1 }}
 />
 </div>
 </div>
 </div>
 )}
 </div>

 {/* BİTİŞ WEBHOOK'U — WebServis Entegrasyonu seçimi */}
 <div style={{ marginBottom: 20, padding: 16, background: 'var(--surface2)', borderRadius: 12, border: '1px solid var(--border)' }}>
 <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
 <span style={{ fontSize: 14, fontWeight: 700 }}>Çağrı Sonu Webhook</span>
 <span style={{ fontSize: 11, color: 'var(--text-dim)', marginLeft: 'auto' }}>
 Script bittikten sonra tetiklenecek WebServis Entegrasyonu
 </span>
 </div>
 <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
 <div className="form-group" style={{ marginBottom: 0 }}>
 <label className="form-label">WebServis Entegrasyonu</label>
 <select
 className="form-select"
 value={form.end_webhook_service_id || ''}
 onChange={e => set('end_webhook_service_id', e.target.value ? +e.target.value : null)}
 >
 <option value="">— Seçim yok (webhook tetiklenmez) —</option>
 {wsServices.filter(s => s.is_active !== false).map(s => (
 <option key={s.id} value={s.id}>
 {s.name} — {(s.method || 'POST')} {s.url}
 </option>
 ))}
 </select>
 <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4 }}>
 Body template, auth ve header'lar WebServis Entegrasyonları sekmesinden yönetilir.
 Çağrı başı servislerinden gelen değişkenler (örn. <code>{'{sozlesme_no}'}</code>) + QC meta otomatik iletilir.
 </div>
 </div>

 {form.end_webhook_service_id && (() => {
 const svc = wsServices.find(s => s.id === form.end_webhook_service_id);
 if (!svc) return null;
 return (
 <div style={{ padding: 10, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12 }}>
 <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
 <span style={{ fontWeight: 700 }}>{svc.name}</span>
 <span className="mono" style={{ fontSize: 11, padding: '1px 6px', borderRadius: 4, background: 'var(--surface2)', color: 'var(--blue)' }}>
 {svc.method || 'POST'}
 </span>
 <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
 {svc.url}
 </span>
 </div>
 {svc.description && (
 <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 4 }}>{svc.description}</div>
 )}
 </div>
 );
 })()}

 <label style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', background: 'rgba(59,109,240,.06)', border: '1px solid var(--border)', borderRadius: 8, cursor: 'pointer' }}>
 <input
 type="checkbox"
 checked={form.end_webhook_only_on_success !== false}
 onChange={e => set('end_webhook_only_on_success', e.target.checked)}
 />
 <div style={{ display: 'flex', flexDirection: 'column' }}>
 <span style={{ fontSize: 13, fontWeight: 700 }}>Sadece başarılı tamamlanmada gönder</span>
 <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>
 Açıkken yalnızca status=completed olan oturumlar webhook'u tetikler.
 </span>
 </div>
 </label>
 </div>
 </div>

 {/* SES & HIZI */}
 <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14, marginBottom: 20, padding: 16, background: 'var(--surface2)', borderRadius: 12, border: '1px solid var(--border)' }}>
 <div className="form-group">
 <label className="form-label">Ses</label>
 <select className="form-select" value={form.voice} onChange={e => set('voice', e.target.value)}>
 <optgroup label="ElevenLabs (Önerilen)">
 <option value="elevenlabs:Rachel">Rachel (Kadın, Sıcak)</option>
 <option value="elevenlabs:Bella">Bella (Kadın, Yumuşak)</option>
 <option value="elevenlabs:Elli">Elli (Kadın, Genç)</option>
 <option value="elevenlabs:Domi">Domi (Kadın, Güçlü)</option>
 <option value="elevenlabs:Charlotte">Charlotte (Kadın, Zarif)</option>
 <option value="elevenlabs:Adam">Adam (Erkek, Derin)</option>
 <option value="elevenlabs:Antoni">Antoni (Erkek, Sıcak)</option>
 <option value="elevenlabs:Josh">Josh (Erkek, Genç)</option>
 <option value="elevenlabs:Arnold">Arnold (Erkek, Güçlü)</option>
 <option value="elevenlabs:Callum">Callum (Erkek, Otoriter)</option>
 </optgroup>
 <optgroup label="MiniMax">
 <option value="minimax:female-shaonv">Genç Kadın (Doğal)</option>
 <option value="minimax:male-qn-qingse">Genç Erkek (Samimi)</option>
 <option value="minimax:female-yujie">Olgun Kadın (Güvenilir)</option>
 <option value="minimax:male-qn-jingying">Profesyonel Erkek</option>
 </optgroup>
 <optgroup label="Azure Multilingual">
 <option value="en-US-NovaMultilingualNeural">Nova (Kadın)</option>
 <option value="en-US-AlloyMultilingualNeural">Alloy (Erkek)</option>
 <option value="en-US-ShimmerMultilingualNeural">Shimmer (Kadın)</option>
 <option value="en-US-EchoMultilingualNeural">Echo (Erkek)</option>
 </optgroup>
 <optgroup label="Azure Türkçe">
 <option value="tr-TR-EmelNeural">Emel (Türkçe Kadın)</option>
 <option value="tr-TR-AhmetNeural">Ahmet (Türkçe Erkek)</option>
 </optgroup>
 </select>
 </div>
 <div className="form-group">
 <label className="form-label">Hız <span className="mono" style={{ color: 'var(--blue)' }}>{form.speech_rate}x</span></label>
 <input type="range" min={0.7} max={1.5} step={0.05} value={form.speech_rate} onChange={e => set('speech_rate', parseFloat(e.target.value))} style={{ width: '100%', marginTop: 6 }} />
 </div>
 <div className="form-group">
 <label className="form-label">Arka Plan</label>
 <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
 <input type="checkbox" checked={form.enable_background} onChange={e => set('enable_background', e.target.checked)} />
 <span style={{ fontSize: 13, fontWeight: 600 }}>{form.enable_background ? 'Aktif' : 'Pasif'}</span>
 </div>
 {form.enable_background && (
 <div style={{ marginTop: 10 }}>
 <label className="form-label">
 Ses Seviyesi&nbsp;
 <span className="mono" style={{ color: 'var(--blue)' }}>{Math.round(form.background_volume * 100)}%</span>
 </label>
 <input
 type="range" min={0.05} max={1.0} step={0.05}
 value={form.background_volume}
 onChange={e => set('background_volume', parseFloat(e.target.value))}
 style={{ width: '100%', marginTop: 4, accentColor: 'var(--blue)' }}
 />
 <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>
 <span>5% (Sessiz)</span>
 <span>100% (Tam)</span>
 </div>
 </div>
 )}
 </div>
 </div>

 {script && (
 <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 24, padding: '12px 16px', background: form.is_active ? 'rgba(59,109,240,.06)' : 'var(--surface2)', border: `1px solid ${form.is_active ? 'var(--blue)' : 'var(--border)'}`, borderRadius: 10 }}>
 <input type="checkbox" checked={form.is_active} onChange={e => set('is_active', e.target.checked)} />
 <span style={{ fontSize: 14, fontWeight: 700, color: form.is_active ? 'var(--blue)' : 'var(--text-dim)' }}>Bu senaryo aktif</span>
 </div>
 )}

 {/* DEĞİŞKENLER (VARIABLES) */}
 <div style={{ borderTop: '1px solid var(--border)', paddingTop: 20, marginBottom: 20 }}>
 <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
 <span style={{ fontWeight: 600, fontSize: 16, color: 'var(--text)' }}>Dinamik Değişkenler</span>
 </div>
 <div style={{ fontSize: 13, color: 'var(--text-dim)', marginBottom: 12 }}>
 Senaryo metinlerinde kullanmak istediğiniz değişkenleri süslü parantez ile (örn: <code>{'{bakiye}'}</code>) yazıp, varsayılan deneme değerlerini buradan tanımlayabilirsiniz.
 </div>
 <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
 {vars.map((v, i) => (
 <div key={i} style={{ display: 'flex', gap: 10 }}>
 <input className="form-input" style={{ width: 150 }} placeholder="Anahtar (örn: bakiye)" value={v.key} onChange={e => setVars(vs => vs.map((item, idx) => idx === i ? { ...item, key: e.target.value } : item))} />
 <input className="form-input" style={{ flex: 1 }} placeholder="Değer (örn: 1500)" value={v.value} onChange={e => setVars(vs => vs.map((item, idx) => idx === i ? { ...item, value: e.target.value } : item))} />
 <button className="btn outline" style={{ color: 'var(--red)', borderColor: 'var(--red)' }} onClick={() => setVars(vs => vs.filter((_, idx) => idx !== i))}>Sil</button>
 </div>
 ))}
 </div>
 <button className="btn outline" onClick={() => setVars(vs => [...vs, { key: '', value: '' }])} style={{ marginTop: 10, fontSize: 12, padding: '6px 12px' }}>+ Yeni Değişken Ekle</button>
 </div>

 {/* ADIMLAR */}
 <div style={{ borderTop: '1px solid var(--border)', paddingTop: 20 }}>
 <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
 <span style={{ fontWeight: 600, fontSize: 16, color: 'var(--text)' }}>Adımlar</span>
 <span className="dash-count-badge">{steps.length}</span>
 </div>

 <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
 {steps.map((s, i) => {
 const tc = stepTypeConfig[s.step_type] || stepTypeConfig.info;
 return (
 <div key={i} className="qc-step-editor">
 <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
 <div className="qc-step-number">{i + 1}</div>
 <input className="form-input" style={{ flex: 1, fontWeight: 700 }} value={s.title} onChange={e => updateS(i, 'title', e.target.value)} placeholder="Adım başlığı..." />
 <select className="form-select" value={s.step_type} onChange={e => updateS(i, 'step_type', e.target.value)} style={{ width: 160, fontSize: 13 }}>
 {Object.entries(stepTypeConfig).map(([k, v]) => (
 <option key={k} value={k}>{v.label}</option>
 ))}
 </select>
 <div style={{ display: 'flex', gap: 2 }}>
 <button onClick={() => moveS(i, -1)} disabled={i === 0} className="qc-step-btn" title="Yukarı">↑</button>
 <button onClick={() => moveS(i, 1)} disabled={i === steps.length - 1} className="qc-step-btn" title="Aşağı">↓</button>
 <button onClick={() => removeS(i)} className="qc-step-btn" style={{ color: 'var(--red)' }} title="Sil"></button>
 </div>
 </div>
 <textarea className="form-textarea" rows={2} value={s.text} onChange={e => updateS(i, 'text', e.target.value)} placeholder="AI'ın söyleyeceği metin..." style={{ fontSize: 13 }} />
 {(s.step_type === 'detail_if_yes' || s.step_type === 'detail_if_no' || s.step_type === 'qna_handoff') && (
 <textarea className="form-textarea" rows={1} value={s.detail_text || ''} onChange={e => updateS(i, 'detail_text', e.target.value)} placeholder="Detay / ek bilgi metni (opsiyonel)" style={{ fontSize: 13, marginTop: 8, borderStyle: 'dashed' }} />
 )}
 <div style={{ display: 'flex', gap: 14, marginTop: 8, fontSize: 12, color: 'var(--text-dim)' }}>
 <span style={{ padding: '2px 8px', borderRadius: 5, background: tc.color + '12', color: tc.color, fontWeight: 700 }}>{tc.label}</span>
 {s.policy_years && <span>Poliçe: {s.policy_years}y</span>}
 <span>Tekrar: {s.max_retries}</span>
 <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, alignItems: 'center' }}>
 <label style={{ display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
 <span>Poliçe yılı:</span>
 <select value={s.policy_years || ''} onChange={e => updateS(i, 'policy_years', e.target.value ? +e.target.value : null)} style={{ border: '1px solid var(--border)', borderRadius: 5, padding: '2px 6px', fontSize: 12, background: '#fff' }}>
 <option value="">Hepsi</option>
 <option value="6">6</option>
 <option value="12">12</option>
 </select>
 </label>
 <label style={{ display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
 <span>Max tekrar:</span>
 <input type="number" min={0} max={5} value={s.max_retries} onChange={e => updateS(i, 'max_retries', +e.target.value)} style={{ width: 44, border: '1px solid var(--border)', borderRadius: 5, padding: '2px 6px', fontSize: 12, background: '#fff', textAlign: 'center' }} />
 </label>
 </div>
 </div>
 </div>
 );
 })}
 </div>

 <button className="btn outline" onClick={addStep} style={{ width: '100%', marginTop: 12, borderStyle: 'dashed', padding: '12px', fontWeight: 700 }}>+ Yeni Adım Ekle</button>
 </div>
 </div>
 <div className="modal-footer">
 <button className="btn outline" onClick={onClose}>İptal</button>
 <button className="btn primary" onClick={handleSave} disabled={saving || !form.name}>
 {saving ? 'Kaydediliyor...' : 'Kaydet'}
 </button>
 </div>
 </div>
 </div>
 );
}

/* 
 SCRIPT STATS PANEL — Script bazlı istatistik
 */
function fmtDuration(sec) {
 if (!sec) return '—';
 const h = Math.floor(sec / 3600);
 const m = Math.floor((sec % 3600) / 60);
 const s = Math.floor(sec % 60);
 if (h > 0) return `${h}sa ${m}dk`;
 if (m > 0) return `${m}dk ${s}sn`;
 return `${s}sn`;
}

function ScriptStatsPanel({ scriptId }) {
 const [stats, setStats] = useState(null);
 useEffect(() => {
 if (!scriptId) return;
 authFetch(`/api/qc/scripts/${scriptId}/stats`).then(r => r.json()).then(setStats);
 }, [scriptId]);

 if (!stats) return null;

 const fmtDay = (dateStr) => {
 const d = new Date(dateStr);
 return `${d.getDate()}/${d.getMonth() + 1}`;
 };

 const dailyData = (stats.daily_stats || []).map(d => ({ ...d, label: fmtDay(d.date) }));

 return (
 <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 24 }}>
 {/* Sol: İstatistik kartları */}
 <div className="panel" style={{ padding: 24 }}>
 <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 20, color: 'var(--text)' }}>Genel Bakış</div>
 <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
 <div className="qc-mini-stat">
 <div className="qc-mini-stat-value">{stats.total}</div>
 <div className="qc-mini-stat-label">Toplam Çağrı</div>
 </div>
 <div className="qc-mini-stat">
 <div className="qc-mini-stat-value" style={{ color: 'var(--green)' }}>{stats.completed}</div>
 <div className="qc-mini-stat-label">Başarılı</div>
 </div>
 <div className="qc-mini-stat">
 <div className="qc-mini-stat-value" style={{ color: 'var(--red)' }}>{stats.failed}</div>
 <div className="qc-mini-stat-label">Başarısız</div>
 </div>
 <div className="qc-mini-stat">
 <div className="qc-mini-stat-value" style={{ color: 'var(--blue)' }}>%{stats.completion_rate}</div>
 <div className="qc-mini-stat-label">Tamamlanma</div>
 </div>
 <div className="qc-mini-stat">
 <div className="qc-mini-stat-value" style={{ color: 'var(--purple)', fontSize: 18 }}>{fmtDuration(stats.total_duration_sec)}</div>
 <div className="qc-mini-stat-label">Toplam Konuşma</div>
 </div>
 <div className="qc-mini-stat">
 <div className="qc-mini-stat-value" style={{ color: 'var(--cyan)', fontSize: 18 }}>{fmtDuration(stats.avg_duration_sec)}</div>
 <div className="qc-mini-stat-label">Ortalama Süre</div>
 </div>
 </div>
 </div>

 {/* Sağ: Günlük başarı oranları */}
 <div className="panel" style={{ padding: 24 }}>
 <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 16, color: 'var(--text)' }}>Günlük Başarı Oranları</div>
 {dailyData.length > 0 ? (
 <div style={{ height: 200 }}>
 <ResponsiveContainer width="100%" height="100%">
 <BarChart data={dailyData} margin={{ top: 4, right: 0, left: -20, bottom: 0 }}>
 <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
 <XAxis dataKey="label" tick={{ fontSize: 11, fill: '#94a3b8' }} axisLine={false} tickLine={false} />
 <YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} axisLine={false} tickLine={false} domain={[0, 100]} tickFormatter={v => `${v}%`} />
 <Tooltip
 contentStyle={{ background: '#fff', border: '1px solid #e2e6ee', borderRadius: 10, fontSize: 13, boxShadow: '0 4px 12px rgba(0,0,0,.08)' }}
 formatter={(v, _, p) => [`%${v}  (${p.payload.calls} çağrı)`, 'Başarı']}
 labelFormatter={v => v}
 />
 <Bar dataKey="pass_rate" radius={[4, 4, 0, 0]}>
 {dailyData.map((d, i) => (
 <Cell key={i} fill={d.pass_rate >= 80 ? '#22c55e' : d.pass_rate >= 60 ? '#f59e0b' : '#ef4444'} />
 ))}
 </Bar>
 </BarChart>
 </ResponsiveContainer>
 </div>
 ) : (
 <div className="dash-empty" style={{ minHeight: 100 }}>
 <div style={{ fontSize: 13, color: 'var(--text-dim)' }}>Henüz yeterli veri yok</div>
 </div>
 )}
 </div>
 </div>
 );
}

/*
 QC TAB — Ana sayfa
 */
function QCTab({ toast }) {
 const [view, setView] = useState('sessions');
 const [activeSession, setActiveSession] = useState(null);
 const [selectedScript, setSelectedScript] = useState('');
 const [filterStatus, setFilterStatus] = useState('');
 const [dateFrom, setDateFrom] = useState('');
 const [dateTo, setDateTo] = useState('');
 const [page, setPage] = useState(0);
 const [sessions, setSessions] = useState([]);
 const [sessionsTotal, setSessionsTotal] = useState(0);
 const [loadingSessions, setLoadingSessions] = useState(false);
 const [hasSearched, setHasSearched] = useState(false);
 const [showStats, setShowStats] = useState(false);
 const PAGE_SIZE = 25;

 const { data: scripts, reload: reloadScripts } = window.useApi('/api/qc/scripts', [view]);
 const [scriptModal, setScriptModal] = useState(null);

 const buildSessionUrl = (offset, limit) => {
  let url = `/api/qc/sessions?offset=${offset}&limit=${limit}`;
  if (selectedScript) url += `&script_id=${selectedScript}`;
  if (filterStatus) url += `&status=${filterStatus}`;
  if (dateFrom) url += `&date_from=${dateFrom}`;
  if (dateTo) url += `&date_to=${dateTo}`;
  return url;
 };

 const loadSessions = async (p = page) => {
  setLoadingSessions(true);
  setHasSearched(true);
  try {
   const r = await authFetch(buildSessionUrl(p * PAGE_SIZE, PAGE_SIZE));
   const data = await r.json();
   setSessions(data.items || []);
   setSessionsTotal(data.total || 0);
  } catch (e) { console.error(e); }
  setLoadingSessions(false);
 };

 const handleSearch = () => { setPage(0); loadSessions(0); };

 const handlePageChange = (np) => { setPage(np); loadSessions(np); };

 const handleClear = () => {
  setSelectedScript(''); setFilterStatus(''); setDateFrom(''); setDateTo('');
  setPage(0); setSessions([]); setSessionsTotal(0); setHasSearched(false);
 };

 const exportCSV = async () => {
  let url = `/api/qc/sessions/export?`;
  const params = [];
  if (selectedScript) params.push(`script_id=${selectedScript}`);
  if (filterStatus) params.push(`status=${filterStatus}`);
  if (dateFrom) params.push(`date_from=${dateFrom}`);
  if (dateTo) params.push(`date_to=${dateTo}`);
  url += params.join('&');
  try {
   const r = await authFetch(url);
   const blob = await r.blob();
   const a = document.createElement('a');
   a.href = URL.createObjectURL(blob);
   a.download = 'qc_sessions.csv';
   a.click();
   URL.revokeObjectURL(a.href);
   toast && toast('CSV indirildi', 'success');
  } catch (e) { toast && toast('CSV indirme hatası', 'error'); }
 };

 const statusConfig = {
  completed:   { label: 'Tamamlandı',   color: 'var(--green)', dot: '#22c55e' },
  failed:      { label: 'Başarısız',    color: 'var(--red)',   dot: '#ef4444' },
  abandoned:   { label: 'Başarısız',    color: 'var(--red)',   dot: '#ef4444' },
  in_progress: { label: 'Devam Ediyor', color: 'var(--amber)', dot: '#f59e0b' },
 };

 const stepColor = { no: '#ef4444', info: '#3b6df0', detail: '#f59e0b', yes: '#22c55e' };

 const totalPages = Math.max(1, Math.ceil(sessionsTotal / PAGE_SIZE));
 const hasFilters = selectedScript || filterStatus || dateFrom || dateTo;

 if (activeSession) {
  return <QCSessionDetail session={activeSession} onBack={() => setActiveSession(null)} onStatusChange={() => loadSessions(page)} />;
 }

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

   {/* ── HEADER ── */}
   <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
    <div>
     <h2 style={{ fontSize: 22, fontWeight: 700, color: 'var(--text)', margin: 0 }}>Kalite Kontrol</h2>
     <p style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 4, margin: '4px 0 0' }}>
      Script oturumlarını inceleyin ve senaryoları yönetin.
     </p>
    </div>
    <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
     <div style={{ display: 'flex', background: 'var(--surface2)', padding: 3, borderRadius: 10, border: '1px solid var(--border)', gap: 2 }}>
      {[{ id: 'sessions', label: 'Oturumlar' }, { id: 'scripts', label: 'Senaryolar' }].map(t => (
       <button key={t.id} onClick={() => setView(t.id)} style={{
        padding: '6px 18px', borderRadius: 8, border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer',
        background: view === t.id ? 'var(--blue)' : 'transparent',
        color: view === t.id ? '#fff' : 'var(--text-dim)',
        transition: 'all .15s',
       }}>{t.label}</button>
      ))}
     </div>
     {view === 'scripts' && (
      <button className="btn primary" style={{ fontSize: 13 }} onClick={() => setScriptModal('new')}>+ Yeni Senaryo</button>
     )}
    </div>
   </div>

   {/* ── OTURUMLAR ── */}
   {view === 'sessions' && (
    <>
     {/* Filtre kartı */}
     <div className="panel" style={{ padding: '18px 20px', marginBottom: 16, borderRadius: 14 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr)) 120px 120px auto', gap: 10, alignItems: 'flex-end' }}>

       {/* Senaryo */}
       <div>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-dim)', marginBottom: 5, textTransform: 'uppercase', letterSpacing: '.04em' }}>Senaryo</div>
        <select className="form-select" value={selectedScript} onChange={e => setSelectedScript(e.target.value)}
         style={{ fontSize: 13, padding: '7px 10px', width: '100%' }}>
         <option value="">Tümü</option>
         {(scripts || []).map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
        </select>
       </div>

       {/* Durum */}
       <div>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-dim)', marginBottom: 5, textTransform: 'uppercase', letterSpacing: '.04em' }}>Durum</div>
        <select className="form-select" value={filterStatus} onChange={e => setFilterStatus(e.target.value)}
         style={{ fontSize: 13, padding: '7px 10px', width: '100%' }}>
         <option value="">Tümü</option>
         <option value="completed">Tamamlandı</option>
         <option value="failed">Başarısız</option>
         <option value="in_progress">Devam Ediyor</option>
        </select>
       </div>

       {/* Başlangıç tarihi */}
       <div>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-dim)', marginBottom: 5, textTransform: 'uppercase', letterSpacing: '.04em' }}>Başlangıç</div>
        <input type="date" className="form-input" value={dateFrom} onChange={e => setDateFrom(e.target.value)}
         style={{ fontSize: 13, padding: '7px 10px', width: '100%' }} />
       </div>

       {/* Bitiş tarihi */}
       <div>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-dim)', marginBottom: 5, textTransform: 'uppercase', letterSpacing: '.04em' }}>Bitiş</div>
        <input type="date" className="form-input" value={dateTo} onChange={e => setDateTo(e.target.value)}
         style={{ fontSize: 13, padding: '7px 10px', width: '100%' }} />
       </div>

       {/* Aksiyonlar */}
       <div style={{ display: 'flex', gap: 6, alignItems: 'flex-end' }}>
        <button className="btn primary" onClick={handleSearch}
         style={{ padding: '7px 20px', fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap' }}>
         Ara
        </button>
        {hasFilters && (
         <button className="btn outline" onClick={handleClear}
          style={{ padding: '7px 12px', fontSize: 12, color: 'var(--text-dim)', whiteSpace: 'nowrap' }}>
          Temizle
         </button>
        )}
       </div>
      </div>

      {/* Script stats toggle */}
      {hasSearched && selectedScript && (
       <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <button className="btn-sm" onClick={() => setShowStats(s => !s)}
         style={{ fontSize: 12, color: 'var(--blue)', padding: '4px 12px' }}>
         {showStats ? '▲ İstatistikleri Gizle' : '▼ İstatistikleri Göster'}
        </button>
        {hasSearched && <span style={{ fontSize: 12, color: 'var(--text-dim)', marginLeft: 'auto' }}>{sessionsTotal} kayıt</span>}
       </div>
      )}
      {!selectedScript && hasSearched && (
       <div style={{ marginTop: 10, fontSize: 12, color: 'var(--text-dim)', textAlign: 'right' }}>
        {sessionsTotal} kayıt
       </div>
      )}
     </div>

     {/* İstatistik paneli */}
     {showStats && selectedScript && <div style={{ marginBottom: 16 }}><ScriptStatsPanel scriptId={selectedScript} /></div>}

     {/* ── RESULTS ── */}
     {!hasSearched ? (
      /* İlk yüklemede boş durum */
      <div className="panel" style={{ padding: '60px 40px', textAlign: 'center', borderRadius: 14 }}>
       <div style={{ fontSize: 36, marginBottom: 16, opacity: .35 }}>🔍</div>
       <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', marginBottom: 8 }}>Arama yapmaya hazır</div>
       <div style={{ fontSize: 13, color: 'var(--text-dim)', maxWidth: 340, margin: '0 auto' }}>
        Filtreleri seçin ve <strong>Ara</strong> butonuna basın. Sonuçlar burada görünecek.
       </div>
      </div>
     ) : (
      <div className="panel" style={{ borderRadius: 14, overflow: 'hidden' }}>
       {/* Tablo araç çubuğu */}
       <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 20px', borderBottom: '1px solid var(--border)', background: 'var(--surface2)' }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)' }}>
         {loadingSessions ? 'Yükleniyor…' : `${sessionsTotal} oturum`}
        </span>
        <div style={{ display: 'flex', gap: 6 }}>
         <button className="btn-sm" onClick={() => loadSessions(page)} style={{ fontSize: 12, padding: '4px 12px' }}>↻ Yenile</button>
         <button className="btn-sm" onClick={exportCSV} style={{ fontSize: 12, padding: '4px 12px' }}>CSV İndir</button>
        </div>
       </div>

       <div style={{ overflowX: 'auto' }}>
        <table className="dash-table" style={{ fontSize: 13 }}>
         <thead>
          <tr>
           <th style={{ width: 150 }}>Tarih</th>
           <th>Telefon</th>
           <th>Senaryo</th>
           <th style={{ width: 70 }}>Poliçe</th>
           <th style={{ width: 130 }}>Durum</th>
           <th>Adım Özeti</th>
           <th style={{ width: 70 }}></th>
          </tr>
         </thead>
         <tbody>
          {loadingSessions ? (
           <tr><td colSpan={7} className="dash-table-empty" style={{ padding: '40px 0' }}>
            <div style={{ fontSize: 13, color: 'var(--text-dim)' }}>Yükleniyor…</div>
           </td></tr>
          ) : sessions.length === 0 ? (
           <tr><td colSpan={7} className="dash-table-empty" style={{ padding: '40px 0' }}>
            <div style={{ fontSize: 13, color: 'var(--text-dim)' }}>Seçilen kriterlere uyan oturum bulunamadı.</div>
           </td></tr>
          ) : sessions.map(s => {
           const sc = statusConfig[s.status] || statusConfig.in_progress;
           const passed = s.steps?.filter(st => st.answer !== 'no').length ?? 0;
           const total  = s.steps?.length ?? 0;
           return (
            <tr key={s.id} style={{ cursor: 'pointer' }} onClick={() => setActiveSession(s)}>
             <td style={{ color: 'var(--text-dim)', whiteSpace: 'nowrap' }}>{window.fmtDate(s.started_at)}</td>
             <td><span className="mono" style={{ fontWeight: 700 }}>{s.phone}</span></td>
             <td style={{ fontWeight: 600, maxWidth: 180, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.script_name}</td>
             <td style={{ textAlign: 'center' }}>
              {s.policy_years
               ? <span className="mono" style={{ fontSize: 11, padding: '2px 7px', borderRadius: 5, background: 'var(--surface2)', fontWeight: 700 }}>{s.policy_years}y</span>
               : <span style={{ color: 'var(--text-dim)' }}>—</span>}
             </td>
             <td>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, fontWeight: 700,
               padding: '3px 10px', borderRadius: 20, background: sc.dot + '14', color: sc.color }}>
               <span style={{ width: 6, height: 6, borderRadius: '50%', background: sc.dot, flexShrink: 0 }} />
               {sc.label}
              </span>
             </td>
             <td>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
               <div style={{ display: 'flex', gap: 2 }}>
                {s.steps?.map((st, i) => (
                 <div key={i} title={`${st.title}: ${st.answer}`}
                  style={{ width: 16, height: 16, borderRadius: 4, fontSize: 9, display: 'flex', alignItems: 'center', justifyContent: 'center',
                   background: (stepColor[st.answer] || '#22c55e') + '20', color: stepColor[st.answer] || '#22c55e', fontWeight: 700 }}>
                  {st.answer === 'no' ? '✗' : '✓'}
                 </div>
                ))}
               </div>
               {total > 0 && (
                <span style={{ fontSize: 11, color: 'var(--text-dim)', whiteSpace: 'nowrap' }}>{passed}/{total}</span>
               )}
              </div>
             </td>
             <td onClick={e => { e.stopPropagation(); setActiveSession(s); }}>
              <button className="btn-sm" style={{ fontSize: 11, padding: '3px 10px' }}>Detay</button>
             </td>
            </tr>
           );
          })}
         </tbody>
        </table>
       </div>

       {/* Pagination */}
       {totalPages > 1 && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 20px', borderTop: '1px solid var(--border)', background: 'var(--surface2)' }}>
         <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>
          {page * PAGE_SIZE + 1}–{Math.min((page + 1) * PAGE_SIZE, sessionsTotal)} / {sessionsTotal}
         </span>
         <div style={{ display: 'flex', gap: 4 }}>
          <button className="btn-sm" disabled={page === 0} onClick={() => handlePageChange(0)} style={{ fontSize: 12, padding: '4px 9px' }}>«</button>
          <button className="btn-sm" disabled={page === 0} onClick={() => handlePageChange(page - 1)} style={{ fontSize: 12, padding: '4px 9px' }}>‹</button>
          <span className="mono" style={{ fontSize: 12, color: 'var(--text-dim)', padding: '4px 10px', background: 'var(--surface)', borderRadius: 6, border: '1px solid var(--border)' }}>
           {page + 1} / {totalPages}
          </span>
          <button className="btn-sm" disabled={page >= totalPages - 1} onClick={() => handlePageChange(page + 1)} style={{ fontSize: 12, padding: '4px 9px' }}>›</button>
          <button className="btn-sm" disabled={page >= totalPages - 1} onClick={() => handlePageChange(totalPages - 1)} style={{ fontSize: 12, padding: '4px 9px' }}>»</button>
         </div>
        </div>
       )}
      </div>
     )}
    </>
   )}

   {/* ── SENARYOLAR ── */}
   {view === 'scripts' && (
    <>
     {(!scripts || scripts.length === 0) ? (
      <div className="panel" style={{ padding: '60px 40px', textAlign: 'center', borderRadius: 14 }}>
       <div style={{ fontSize: 36, marginBottom: 16, opacity: .35 }}>📋</div>
       <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)', marginBottom: 8 }}>Henüz senaryo oluşturulmamış</div>
       <div style={{ fontSize: 13, color: 'var(--text-dim)', marginBottom: 24 }}>İlk kalite kontrol senaryonuzu oluşturun.</div>
       <button className="btn primary" onClick={() => setScriptModal('new')}>+ Yeni Senaryo</button>
      </div>
     ) : (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(400px, 1fr))', gap: 16 }}>
       {scripts.map(s => {
        const stepColors = { info: '#3b6df0', yesno_end: '#ef4444', detail_if_yes: '#22c55e', detail_if_no: '#f59e0b', qna_handoff: '#8b5cf6' };
        return (
         <div key={s.id} style={{
          background: 'var(--surface)', borderRadius: 14, border: `1px solid ${s.is_active ? 'rgba(59,109,240,.35)' : 'var(--border)'}`,
          padding: 20, display: 'flex', flexDirection: 'column', gap: 14,
          boxShadow: s.is_active ? '0 0 0 3px rgba(59,109,240,.06)' : 'none',
          transition: 'box-shadow .2s',
         }}>
          {/* Kart başlığı */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
           <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
             <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.name}</span>
             <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 7px', borderRadius: 20, flexShrink: 0,
              background: s.is_active ? 'rgba(59,109,240,.1)' : 'var(--surface2)',
              color: s.is_active ? 'var(--blue)' : 'var(--text-dim)',
              border: `1px solid ${s.is_active ? 'rgba(59,109,240,.2)' : 'var(--border)'}`,
             }}>
              {s.is_active ? 'AKTİF' : 'PASİF'}
             </span>
            </div>
            {s.description && <div style={{ fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.description}</div>}
           </div>
           <button className="btn-sm" onClick={() => setScriptModal(s)} style={{ fontSize: 12, padding: '5px 14px', flexShrink: 0 }}>Düzenle</button>
          </div>

          {/* Adım zinciri */}
          {s.steps?.length > 0 && (
           <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
            {s.steps.slice(0, 5).map((step, i) => (
             <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 10, fontWeight: 700, width: 16, textAlign: 'right', color: 'var(--text-dim)', fontFamily: 'var(--mono)' }}>{step.order}</span>
              <div style={{ width: 8, height: 8, borderRadius: 3, background: stepColors[step.step_type] || 'var(--text-dim)', flexShrink: 0 }} />
              <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>{step.title || '—'}</span>
              {step.policy_years && <span style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--mono)', flexShrink: 0 }}>{step.policy_years}y</span>}
             </div>
            ))}
            {s.steps.length > 5 && <div style={{ fontSize: 11, color: 'var(--text-dim)', paddingLeft: 24 }}>+{s.steps.length - 5} adım daha</div>}
           </div>
          )}

          {/* Alt bilgi */}
          <div style={{ display: 'flex', gap: 0, borderTop: '1px solid var(--border)', paddingTop: 12, marginTop: 'auto' }}>
           {[
            { label: 'Adım',    value: s.step_count },
            { label: 'Oturum',  value: s.session_count },
            { label: 'Hız',     value: `${s.speech_rate}x`, mono: true },
           ].map((item, i) => (
            <div key={i} style={{ flex: 1, textAlign: 'center', borderRight: i < 2 ? '1px solid var(--border)' : 'none' }}>
             <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text)', fontFamily: item.mono ? 'var(--mono)' : 'inherit' }}>{item.value}</div>
             <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 2 }}>{item.label}</div>
            </div>
           ))}
          </div>
         </div>
        );
       })}
      </div>
     )}
    </>
   )}

   {/* MODAL */}
   {scriptModal && (
    <QCScriptModal
     script={scriptModal === 'new' ? null : scriptModal}
     onClose={() => setScriptModal(null)}
     onSave={() => { setScriptModal(null); reloadScripts(); toast && toast('Senaryo kaydedildi', 'success'); }}
    />
   )}
  </div>
 );
}

window.QCSessionDetail = QCSessionDetail;
window.QCScriptModal = QCScriptModal;
window.QCTab = QCTab;
