const { useState, useEffect } = React;

/* 
 DIALPLAN MODAL — Adım adım wizard tarzı
 */
function DialplanModal({ dp, onClose, onSave }) {
 const [form, setForm] = useState(dp || {
 name: '', description: '', is_active: true,
 gw_name: 'netgsm', gw_username: '', gw_password: '', gw_proxy: 'sip.netgsm.com.tr',
 gw_register: true, gw_caller_id_in_from: true, gw_ping: 25,
 ext_name: 'ai_incoming', dest_number: '', dest_regex_prefix: '^(90)?',
 recording_enabled: true, recording_stereo: false,
 recording_path: '/usr/local/freeswitch/recordings/${strftime(%Y-%m-%d-%H-%M-%S)}_${caller_id_number}.wav',
 mode: 'qc_script', agent_id: null, qc_script_id: null, survey_id: null, 
 ivr_id: null, // EKLENDİ
 policy_years: null,
 ws_host: '127.0.0.1', ws_port: 5000, silence_ms: 500,
 xml_filename: '00_ai_agent.xml', fs_dialplan_dir: '/etc/freeswitch/dialplan/public'
 });

 const [agents, setAgents] = useState([]);
 const [qcScripts, setQcScripts] = useState([]);
 const [surveys, setSurveys] = useState([]);
 const [ivrs, setIvrs] = useState([]); // BU SATIR EKSİKTİ, EKLENDİ
 const [saving, setSaving] = useState(false);
 const [step, setStep] = useState(0);
 const [xmlPreview, setXmlPreview] = useState('');

 const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

 useEffect(() => {
 authFetch('/api/dialplan/options/agents').then(r => r.json()).then(setAgents).catch(() => {});
 authFetch('/api/dialplan/options/qc-scripts').then(r => r.json()).then(setQcScripts).catch(() => {});
 authFetch('/api/dialplan/options/surveys').then(r => r.json()).then(setSurveys).catch(() => {});
 authFetch('/api/dialplan/options/ivrs').then(r => r.json()).then(setIvrs).catch(() => {}); // EKLENDİ
 }, []);

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

 async function loadPreview() {
 if (dp) {
 const r = await authFetch(`/api/dialplan/${dp.id}/preview`);
 const d = await r.json();
 setXmlPreview(d.xml);
 } else {
 setXmlPreview('Önce kaydedin, sonra XML önizleme yapabilirsiniz.');
 }
 }

 const steps = [
 { key: 'general', label: 'Genel', icon: '' },
 { key: 'gateway', label: 'Gateway', icon: '' },
 { key: 'mode', label: 'Çalışma Modu', icon: '' },
 { key: 'advanced', label: 'Gelişmiş', icon: '' },
 ];

 const canNext = () => {
 if (step === 0) return form.name && form.dest_number;
 return true;
 };

 const Toggle = ({ checked, onChange, label }) => (
 <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>
 <div onClick={() => onChange(!checked)} style={{
 width: 40, height: 22, borderRadius: 12, position: 'relative', cursor: 'pointer', transition: 'all .2s',
 background: checked ? 'var(--blue)' : 'var(--border)',
 }}>
 <div style={{
 width: 18, height: 18, borderRadius: '50%', background: '#fff', position: 'absolute', top: 2,
 left: checked ? 20 : 2, transition: 'left .2s', boxShadow: '0 1px 3px rgba(0,0,0,.15)'
 }} />
 </div>
 {label}
 </label>
 );

 function renderStep() {
 switch (steps[step].key) {
 case 'general':
 return (
 <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
 <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
 <div className="form-group">
 <label className="form-label">Dialplan Adı *</label>
 <input className="form-input" value={form.name} onChange={e => set('name', e.target.value)} placeholder="Örn: Kalite Kontrol Hattı" />
 </div>
 <div className="form-group">
 <label className="form-label">DID Numarası *</label>
 <input className="form-input mono" value={form.dest_number} onChange={e => set('dest_number', e.target.value)} placeholder="8503027953" />
 </div>
 </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)} placeholder="Bu hat ne işe yarıyor?" />
 </div>
 <div className="form-group">
 <label className="form-label">Extension Adı</label>
 <input className="form-input mono" value={form.ext_name} onChange={e => set('ext_name', e.target.value)} placeholder="qc_incoming" />
 </div>
 <div style={{ padding: '14px 18px', background: 'var(--surface2)', borderRadius: 12, border: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 10 }}>
 <span style={{ fontSize: 13, color: 'var(--text-dim)', fontWeight: 600 }}>Regex:</span>
 <code className="mono" style={{ fontSize: 13, color: 'var(--blue)', fontWeight: 700 }}>{form.dest_regex_prefix}({form.dest_number || '....'})$</code>
 <input className="form-input mono" value={form.dest_regex_prefix} onChange={e => set('dest_regex_prefix', e.target.value)} style={{ marginLeft: 'auto', width: 120, padding: '6px 10px', fontSize: 13 }} />
 </div>
 <div style={{ display: 'flex', gap: 24 }}>
 <Toggle checked={form.recording_enabled} onChange={v => set('recording_enabled', v)} label="Çağrı Kaydı" />
 {form.recording_enabled && <Toggle checked={form.recording_stereo} onChange={v => set('recording_stereo', v)} label="Stereo" />}
 </div>
 </div>
 );

 case 'gateway':
 return (
 <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
 <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
 <div className="form-group">
 <label className="form-label">Gateway Adı</label>
 <input className="form-input" value={form.gw_name} onChange={e => set('gw_name', e.target.value)} />
 </div>
 <div className="form-group">
 <label className="form-label">SIP Proxy</label>
 <input className="form-input mono" value={form.gw_proxy} onChange={e => set('gw_proxy', e.target.value)} />
 </div>
 </div>
 <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
 <div className="form-group">
 <label className="form-label">Kullanıcı Adı</label>
 <input className="form-input mono" value={form.gw_username} onChange={e => set('gw_username', e.target.value)} placeholder="DID numarası" />
 </div>
 <div className="form-group">
 <label className="form-label">Şifre</label>
 <input className="form-input" type="password" value={form.gw_password} onChange={e => set('gw_password', e.target.value)} />
 </div>
 </div>
 <div className="form-group">
 <label className="form-label">Ping Aralığı (saniye)</label>
 <input className="form-input" type="number" value={form.gw_ping} onChange={e => set('gw_ping', +e.target.value)} style={{ width: 120 }} />
 </div>
 <div style={{ display: 'flex', gap: 24 }}>
 <Toggle checked={form.gw_register} onChange={v => set('gw_register', v)} label="Register" />
 <Toggle checked={form.gw_caller_id_in_from} onChange={v => set('gw_caller_id_in_from', v)} label="Caller ID in From" />
 </div>
 </div>
 );

 case 'mode':
 const modes = [
 { id: 'agent', icon: '', title: 'AI Asistan', desc: 'Serbest konuşma — GPT cevap verir' },
 { id: 'qc_script', icon: '', title: 'Kalite Kontrol', desc: 'Script okunur, cevap beklenir' },
 { id: 'survey', icon: '', title: 'Anket', desc: 'Soru-cevap anketi yapılır' },
 { id: 'ivr', icon: '', title: 'IVR Menü', desc: 'Tuşlamalı yönlendirme sistemi' }, // EKLENDİ
 ];
 return (
 <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
 <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 12 }}>
 {modes.map(m => (
 <div key={m.id} onClick={() => set('mode', m.id)} style={{
 padding: '20px 10px', borderRadius: 14, cursor: 'pointer', textAlign: 'center', transition: 'all .2s',
 border: form.mode === m.id ? '2px solid var(--blue)' : '2px solid var(--border)',
 background: form.mode === m.id ? 'rgba(59,130,246,0.06)' : 'transparent',
 }}>
 <div style={{ fontSize: 28, marginBottom: 8 }}>{m.icon}</div>
 <div style={{ fontSize: 13, fontWeight: 600, color: form.mode === m.id ? 'var(--blue)' : 'var(--text)', marginBottom: 4 }}>{m.title}</div>
 </div>
 ))}
 </div>

 {form.mode === 'agent' && (
 <div className="form-group">
 <label className="form-label">Asistan Seçimi</label>
 <select className="form-select" value={form.agent_id || ''} onChange={e => set('agent_id', e.target.value ? +e.target.value : null)}>
 <option value="">Seçiniz...</option>
 {agents.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
 </select>
 </div>
 )}

 {form.mode === 'qc_script' && (
 <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16 }}>
 <div className="form-group">
 <label className="form-label">QC Script</label>
 <select className="form-select" value={form.qc_script_id || ''} onChange={e => set('qc_script_id', e.target.value ? +e.target.value : null)}>
 <option value="">Seçiniz...</option>
 {qcScripts.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
 </select>
 </div>
 <div className="form-group">
 <label className="form-label">Poliçe Yılı</label>
 <select className="form-select" value={form.policy_years || ''} onChange={e => set('policy_years', e.target.value ? +e.target.value : null)}>
 <option value="">Çağrıda sor</option>
 <option value="6">6 Yıl</option>
 <option value="12">12 Yıl</option>
 </select>
 </div>
 </div>
 )}

 {form.mode === 'survey' && (
 <div className="form-group">
 <label className="form-label">Anket Seçimi</label>
 <select className="form-select" value={form.survey_id || ''} onChange={e => set('survey_id', e.target.value ? +e.target.value : null)}>
 <option value="">Seçiniz...</option>
 {surveys.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
 </select>
 </div>
 )}

 {/* IVR SEÇİMİ EKLENDİ */}
 {form.mode === 'ivr' && (
 <div className="form-group">
 <label className="form-label">IVR Menüsü Seçimi</label>
 <select className="form-select" value={form.ivr_id || ''} onChange={e => set('ivr_id', e.target.value ? +e.target.value : null)}>
 <option value="">Seçiniz...</option>
 {ivrs.map(i => <option key={i.id} value={i.id}>{i.name}</option>)}
 </select>
 </div>
 )}
 </div>
 );

 case 'advanced':
 return (
 <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
 <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.05em' }}>WebSocket Bağlantısı</div>
 <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 16 }}>
 <div className="form-group">
 <label className="form-label">Host</label>
 <input className="form-input mono" value={form.ws_host} onChange={e => set('ws_host', e.target.value)} />
 </div>
 <div className="form-group">
 <label className="form-label">Port</label>
 <input className="form-input mono" type="number" value={form.ws_port} onChange={e => set('ws_port', +e.target.value)} />
 </div>
 <div className="form-group">
 <label className="form-label">Sessizlik (ms)</label>
 <input className="form-input mono" type="number" value={form.silence_ms} onChange={e => set('silence_ms', +e.target.value)} />
 </div>
 </div>

 <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.05em', marginTop: 8 }}>FreeSWITCH Dosya</div>
 <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 16 }}>
 <div className="form-group">
 <label className="form-label">XML Dosya Adı</label>
 <input className="form-input mono" value={form.xml_filename} onChange={e => set('xml_filename', e.target.value)} />
 </div>
 <div className="form-group">
 <label className="form-label">Dialplan Dizini</label>
 <input className="form-input mono" value={form.fs_dialplan_dir} onChange={e => set('fs_dialplan_dir', e.target.value)} />
 </div>
 </div>

 {form.recording_enabled && (
 <div className="form-group">
 <label className="form-label">Kayıt Dosya Yolu</label>
 <input className="form-input mono" value={form.recording_path} onChange={e => set('recording_path', e.target.value)} style={{ fontSize: 12 }} />
 </div>
 )}

 {dp && (
 <div style={{ marginTop: 8 }}>
 <button className="btn outline" onClick={loadPreview} style={{ fontSize: 13, padding: '8px 16px' }}> XML Önizle</button>
 {xmlPreview && (
 <pre style={{ marginTop: 12, padding: 20, borderRadius: 12, background: '#0f172a', color: '#93c5fd', fontSize: 12, fontFamily: 'Space Mono', overflowX: 'auto', maxHeight: 240 }}><code>{xmlPreview}</code></pre>
 )}
 </div>
 )}
 </div>
 );
 }
 }

 return (
 <div className="overlay" onClick={onClose}>
 <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 680, maxHeight: '90vh', display: 'flex', flexDirection: 'column' }}>
 <div className="modal-header">
 <span style={{ fontWeight: 600, fontSize: 18 }}>{dp ? 'Dialplan Düzenle' : 'Yeni Dialplan'}</span>
 <button className="close-btn" onClick={onClose}>×</button>
 </div>
 <div style={{ padding: '0 28px', display: 'flex', gap: 4, marginBottom: 4 }}>
 {steps.map((s, i) => (
 <button key={s.key} onClick={() => setStep(i)} style={{ flex: 1, padding: '10px 0', fontSize: 13, fontWeight: 700, cursor: 'pointer', background: 'none', border: 'none', borderBottom: i === step ? '2px solid var(--blue)' : '2px solid transparent', color: i === step ? 'var(--blue)' : 'var(--text-dim)' }}>
 {s.icon} {s.label}
 </button>
 ))}
 </div>
 <div className="modal-body" style={{ flex: 1, overflow: 'auto', padding: '24px 28px' }}>
 {renderStep()}
 </div>
 <div className="modal-footer" style={{ display: 'flex', justifyContent: 'space-between' }}>
 <button className="btn outline" onClick={() => setStep(s => Math.max(0, s - 1))} disabled={step === 0}>← Geri</button>
 <div style={{ display: 'flex', gap: 10 }}>
 <button className="btn outline" onClick={onClose}>İptal</button>
 {step < steps.length - 1 ? (
 <button className="btn primary" onClick={() => setStep(s => s + 1)} disabled={!canNext()}>Devam →</button>
 ) : (
 <button className="btn primary" onClick={save} disabled={saving || !form.name || !form.dest_number}>{saving ? 'Kaydediliyor...' : ' Kaydet & Deploy'}</button>
 )}
 </div>
 </div>
 </div>
 </div>
 );
}

function SetupTab({ toast }) {
 const [dialplans, setDialplans] = useState([]);
 const [editing, setEditing] = useState(null);
 const [deploying, setDeploying] = useState(null);

 const load = () => authFetch('/api/dialplan').then(r => r.json()).then(setDialplans).catch(() => setDialplans([]));
 useEffect(() => { load(); }, []);

 async function handleDelete(id) {
 if (!confirm('Bu dialplanı silmek istediğinize emin misiniz?')) return;
 await authFetch(`/api/dialplan/${id}`, { method: 'DELETE' });
 toast('Dialplan silindi', 'success');
 load();
 }

 async function handleDeploy(id) {
 setDeploying(id);
 try {
 const r = await authFetch(`/api/dialplan/${id}/deploy`, { method: 'POST' });
 const d = await r.json();
 toast(d.reload ? 'FreeSWITCH güncellendi' : 'XML yazıldı, reload başarısız', d.reload ? 'success' : 'warning');
 } finally { setDeploying(null); }
 }

 const modeConfig = {
 agent: { label: 'AI Asistan', color: 'var(--cyan)', icon: '' },
 qc_script: { label: 'Kalite Kontrol', color: 'var(--blue)', icon: '' },
 survey: { label: 'Anket', color: 'var(--green)', icon: '' },
 ivr: { label: 'IVR Menü', color: 'var(--purple)', icon: '' }, // EKLENDİ
 };

 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)' }}>Dialplan Yönetimi</h2>
 <p style={{ fontSize: 15, color: 'var(--text-dim)', marginTop: 8 }}>FreeSWITCH yapılandırmalarını yönetin. Değişiklikler otomatik deploy edilir.</p>
 </div>
 <button className="btn primary" onClick={() => setEditing(false)}>+ Yeni Dialplan</button>
 </div>

 {dialplans.length === 0 ? (
 <div className="panel" style={{ padding: '64px 40px', textAlign: 'center' }}>
  <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--text)', marginBottom: 8 }}>Henüz dialplan eklenmemiş</div>
 <button className="btn primary" onClick={() => setEditing(false)}>+ İlk Dialplanı Oluştur</button>
 </div>
 ) : (
 <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(400px, 1fr))', gap: 20 }}>
 {dialplans.map(dp => {
 const mc = modeConfig[dp.mode] || modeConfig.agent;
 return (
 <div key={dp.id} className="agent-card">
 <div className="agent-card-header">
 <div style={{ flex: 1, minWidth: 0 }}>
 <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
 <div style={{ width: 8, height: 8, borderRadius: '50%', background: dp.is_active ? 'var(--green)' : 'var(--text-dim)' }} />
 <div style={{ fontWeight: 600, fontSize: 17, color: 'var(--text)' }}>{dp.name}</div>
 </div>
 <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
 <span className="badge" style={{ background: mc.color + '18', color: mc.color }}>{mc.icon} {mc.label}</span>
 <span className="mono badge" style={{ background: 'var(--surface2)', color: 'var(--text-dim)', border: '1px solid var(--border)' }}>{dp.dest_number}</span>
 </div>
 </div>
 <div className="agent-card-actions">
 <button className="btn-sm" onClick={() => setEditing(dp)}>Düzenle</button>
 <button className="btn-sm outline" style={{ color: 'var(--red)', borderColor: 'rgba(239, 68, 68, 0.3)' }} onClick={() => handleDelete(dp.id)}>Sil</button>
 </div>
 </div>
 <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
 <code style={{ fontSize: 11, color: 'var(--blue)', fontFamily: 'Space Mono', opacity: .7 }}>{dp.xml_filename}</code>
 <button className="btn-sm" onClick={() => handleDeploy(dp.id)} disabled={deploying === dp.id} style={{ background: 'var(--green)', color: '#fff', border: 'none', opacity: deploying === dp.id ? .5 : 1 }}>{deploying === dp.id ? '' : ''} Deploy</button>
 </div>
 </div>
 );
 })}
 </div>
 )}

 {editing !== null && (
 <DialplanModal dp={editing || null} onClose={() => setEditing(null)} onSave={() => { setEditing(null); load(); toast('Dialplan kaydedildi', 'success'); }} />
 )}
 </div>
 );
}

window.SetupTab = SetupTab;