/* ============================================================
   TrunksTab.jsx — SIP Trunk ve DID Hat Yönetimi
   ============================================================ */
window.TrunksTab = function TrunksTab({ toast }) {
  const { useState, useEffect, useCallback } = React;

  const [trunks, setTrunks] = useState([]);
  const [dids, setDids] = useState([]);
  const [ivrs, setIvrs] = useState([]);
  const [ivrFlows, setIvrFlows] = useState([]);
  const [queues, setQueues] = useState([]);
  const [agents, setAgents] = useState([]);
  const [qcScripts, setQcScripts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [section, setSection] = useState('trunks'); // 'trunks' | 'dids'

  const [trunkModal, setTrunkModal] = useState(null);
  const [didModal, setDidModal] = useState(null);
  const [xmlPreview, setXmlPreview] = useState(null);
  const [testResult, setTestResult] = useState(null);
  const [saving, setSaving] = useState(false);

  /* ── Fetch ─────────────────────────────────────────────── */
  const load = useCallback(async () => {
    setLoading(true);
    const [t, d, i, f, q, a, qc] = await Promise.all([
      apiFetch('/api/trunks'),
      apiFetch('/api/trunks/dids'),
      apiFetch('/api/ivr'),
      apiFetch('/api/flows'),
      apiFetch('/api/queues'),
      apiFetch('/api/agents'),
      apiFetch('/api/qc/scripts'),
    ]);
    setTrunks(t || []);
    setDids(d || []);
    setIvrs(i || []);
    setIvrFlows((f || []).filter(fl => fl.status === 'published'));
    setQueues(q || []);
    setAgents(a || []);
    setQcScripts(qc || []);
    setLoading(false);
  }, []);

  useEffect(() => { load(); }, [load]);

  /* ── Trunk işlemleri ───────────────────────────────────── */
  const saveTrunk = async (data) => {
    setSaving(true);
    const isEdit = !!data.id;
    const res = await apiFetch(isEdit ? `/api/trunks/${data.id}` : '/api/trunks', {
      method: isEdit ? 'PUT' : 'POST', body: JSON.stringify(data)
    });
    setSaving(false);
    if (res?._error) { toast(res.detail || 'Trunk kaydedilemedi', 'error'); }
    else if (res?.id) { toast(isEdit ? 'Trunk güncellendi' : 'Trunk oluşturuldu', 'success'); setTrunkModal(null); load(); }
    else toast('Beklenmeyen bir hata oluştu', 'error');
  };

  const deleteTrunk = async (id) => {
    if (!confirm('Trunk silinsin mi?')) return;
    await apiFetch(`/api/trunks/${id}`, { method: 'DELETE' });
    toast('Trunk silindi', 'success'); load();
  };

  const testTrunk = async (id, name) => {
    setTestResult({ loading: true, name });
    const res = await apiFetch(`/api/trunks/${id}/test`, { method: 'POST' });
    setTestResult({ ...res, name });
  };

  const previewXml = async (id, type) => {
    const url = type === 'trunk' ? `/api/trunks/${id}/xml-preview` : `/api/trunks/dids/${id}/xml-preview`;
    const res = await apiFetch(url);
    if (res?.xml) setXmlPreview({ xml: res.xml, title: type === 'trunk' ? 'Trunk Gateway XML' : 'DID Dialplan XML' });
  };

  /* ── DID işlemleri ─────────────────────────────────────── */
  const saveDid = async (data) => {
    setSaving(true);
    const isEdit = !!data.id;
    const res = await apiFetch(isEdit ? `/api/trunks/dids/${data.id}` : '/api/trunks/dids', {
      method: isEdit ? 'PUT' : 'POST', body: JSON.stringify(data)
    });
    setSaving(false);
    if (res?._error) { toast(res.detail || 'DID kaydedilemedi', 'error'); }
    else if (res?.id) { toast(isEdit ? 'DID güncellendi' : 'DID oluşturuldu', 'success'); setDidModal(null); load(); }
    else toast('Beklenmeyen bir hata oluştu', 'error');
  };

  const deleteDid = async (id) => {
    if (!confirm('DID numarası silinsin mi?')) return;
    await apiFetch(`/api/trunks/dids/${id}`, { method: 'DELETE' });
    toast('DID silindi', 'success'); load();
  };

  /* ── Render ────────────────────────────────────────────── */
  const STATUS_COLORS = { registered:'#10b981', no_register:'#6366f1', failed:'#ef4444', trying:'#f59e0b', unknown:'#9ca3af' };
  const STATUS_LABELS = { registered:'Kayıtlı', no_register:'IP Tabanlı', failed:'Bağlantı Hatası', trying:'Bağlanıyor…', unknown:'Bilinmiyor' };
  const ROUTE_ICONS = { ivr:'IVR', ivr_flow:'Akış', queue:'Kuyruk', agent:'AI', human:'Temsilci', qc_script:'KK' };

  const routeLabel = (type, target) => {
    if (type === 'ivr') return `IVR: ${ivrs.find(i =>String(i.id) === String(target))?.name || 'IVR #'+target}`;
    if (type === 'ivr_flow') return `Akış: ${ivrFlows.find(f =>String(f.id) === String(target))?.name || 'Akış #'+target}`;
    if (type === 'queue') return `Kuyruk: ${queues.find(q =>q.extension === target)?.name || 'Kuyruk '+target}`;
    if (type === 'human') return `Temsilci: ${target}`;
    if (type === 'qc_script') return `KK: ${qcScripts.find(s =>String(s.id) === String(target))?.name || 'Script #'+target}`;
    return `AI: ${target}`;
  };

  return (
    <div style={{ padding:'0 0 40px' }}>
      {/* ── Sayfa başlığı ── */}
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:24 }}>
        <div>
          <h2 style={{ margin:0, fontSize:22, fontWeight:600 }}>Hat Yönetimi</h2>
          <p style={{ margin:'4px 0 0', color:'var(--text-dim)', fontSize:14 }}>
            SIP Trunk bağlantıları ve DID numara yönlendirmeleri
          </p>
        </div>
        <div style={{ display:'flex', gap:10 }}>
          <button className={`btn ${section==='trunks' ? 'btn-primary' : 'btn-secondary'}`} onClick={() =>setSection('trunks')}>
            Trunk'lar ({trunks.length})
          </button>
          <button className={`btn ${section==='dids' ? 'btn-primary' : 'btn-secondary'}`} onClick={() =>setSection('dids')}>
            DID Numaraları ({dids.length})
          </button>
        </div>
      </div>

      {loading ? <div style={{ textAlign:'center', padding:60, color:'var(--text-dim)' }}>Yükleniyor…</div> : (

        section === 'trunks' ? (
          /* ════ TRUNK SECTION ════ */
          <div>
            <div style={{ display:'flex', justifyContent:'flex-end', marginBottom:16 }}>
              <button className="btn btn-primary" onClick={() =>setTrunkModal({})}>+ Yeni Trunk</button>
            </div>

            {trunks.length === 0 ? <EmptyState icon="" text="Henüz SIP trunk tanımlanmamış"
              sub="Operatörünüzün SIP sunucu bilgilerini girerek trunk oluşturun" /> : (
              <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
                {trunks.map(t => (
                  <div key={t.id} className="card" style={{ padding:20, opacity: t.is_active ? 1 : 0.6 }}>
                    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:16 }}>

                      {/* Sol: Bilgiler */}
                      <div style={{ flex:1 }}>
                        <div style={{ display:'flex', alignItems:'center', gap:10, flexWrap:'wrap', marginBottom:8 }}>
                          <span style={{ fontSize:16, fontWeight:600 }}> {t.name}</span>
                          {t.provider && <Badge>{t.provider}</Badge>}
                          <Badge color={t.direction==='both' ? '#10b981' : '#6366f1'}>
                            {t.direction==='both' ? '↕ İki Yönlü' : t.direction==='inbound' ? '↓ Gelen' : '↑ Giden'}
                          </Badge>
                          {!t.is_active && <Badge color="#ef4444">Pasif</Badge>}
                        </div>

                        {/* SIP Bilgileri */}
                        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(200px,1fr))', gap:8 }}>
                          <InfoRow icon="" label="Host" value={`${t.host}:${t.port}`} mono />
                          <InfoRow icon="" label="Kullanıcı" value={t.username || '—'} mono />
                          <InfoRow icon="" label="Transport" value={t.transport.toUpperCase()} />
                          <InfoRow icon="" label="Codec" value={t.codec_string} />
                          <InfoRow icon="" label="Max Kanal" value={`${t.max_channels} kanal`} />
                          <InfoRow icon="" label="CID" value={t.caller_id_number || '—'} mono />
                        </div>

                        {/* Bağlı DID'ler */}
                        {(() => {
                          const bDids = dids.filter(d =>d.trunk_id === t.id);
                          return bDids.length > 0 ? (
                            <div style={{ marginTop:10, display:'flex', flexWrap:'wrap', gap:6 }}>
                              {bDids.map(d => (
                                <span key={d.id} style={{
                                  fontSize:11, padding:'2px 8px', borderRadius:6,
                                  background:'rgba(16,185,129,0.1)', color:'#059669', fontWeight:600
                                }}>{d.number}</span>
                              ))}
                            </div>
                          ) : null;
                        })()}
                      </div>

                      {/* Sağ: Butonlar */}
                      <div style={{ display:'flex', flexDirection:'column', gap:6, flexShrink:0 }}>
                        <button className="btn btn-primary" style={{ fontSize:13, padding:'5px 14px' }} onClick={() =>testTrunk(t.id, t.name)}>Test</button>
                        <button className="btn btn-secondary" style={{ fontSize:13, padding:'5px 14px' }} onClick={() =>previewXml(t.id, 'trunk')}>XML</button>
                        <button className="btn btn-secondary" style={{ fontSize:13, padding:'5px 14px' }} onClick={() =>setTrunkModal(t)}>Düzenle</button>
                        <button className="btn btn-danger" style={{ fontSize:13, padding:'5px 14px' }} onClick={() =>deleteTrunk(t.id)}>Sil</button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        ) : (
          /* ════ DID SECTION ════ */
          <div>
            <div style={{ display:'flex', justifyContent:'flex-end', marginBottom:16 }}>
              <button className="btn btn-primary" onClick={() =>setDidModal({})}>+ Yeni DID Numarası</button>
            </div>

            {dids.length === 0 ? <EmptyState icon="" text="Henüz DID numarası tanımlanmamış"
              sub="Operatöründen aldığınız numaraları IVR veya kuyruklara yönlendirin" /> : (
              <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(380px,1fr))', gap:16 }}>
                {dids.map(d => (
                  <div key={d.id} className="card" style={{ padding:18, opacity: d.is_active ? 1 : 0.6 }}>
                    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
                      <div style={{ flex:1 }}>
                        <div style={{ fontSize:20, fontWeight:600, fontFamily:'monospace', marginBottom:6 }}>
                           {d.number}
                        </div>
                        {d.description && <div style={{ fontSize:13, color:'var(--text-dim)', marginBottom:8 }}>{d.description}</div>}

                        <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                          <div style={{ fontSize:13 }}>
                            <span style={{ color:'var(--text-dim)' }}>Ana Yönlendirme: </span>
                            <strong>{routeLabel(d.route_type, d.route_target)}</strong>
                          </div>
                          {d.off_hours_route_type && (
                            <div style={{ fontSize:12, color:'var(--text-dim)' }}>
                               Mesai dışı: {routeLabel(d.off_hours_route_type, d.off_hours_route_target)}
                            </div>
                          )}
                          {d.trunk_name && (
                            <div style={{ fontSize:12 }}>
                              <span style={{ color:'var(--text-dim)' }}>Trunk: </span>
                              <span style={{ fontWeight:600 }}>{d.trunk_name}</span>
                            </div>
                          )}
                        </div>
                      </div>
                      <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                        <button className="btn btn-secondary" style={{ fontSize:12, padding:'4px 10px' }} onClick={() =>previewXml(d.id, 'did')}>XML</button>
                        <button className="btn btn-secondary" style={{ fontSize:12, padding:'4px 10px' }} onClick={() =>setDidModal(d)}>Düzenle</button>
                        <button className="btn btn-danger" style={{ fontSize:12, padding:'4px 10px' }} onClick={() =>deleteDid(d.id)}>Sil</button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )
      )}

      {/* ── Modals ── */}
      {trunkModal !== null && (
        <TrunkModal initial={trunkModal} onSave={saveTrunk} onClose={() =>setTrunkModal(null)} saving={saving} />
      )}
      {didModal !== null && (
        <DidModal initial={didModal} trunks={trunks} ivrs={ivrs} ivrFlows={ivrFlows} queues={queues} agents={agents} qcScripts={qcScripts}
          onSave={saveDid} onClose={() =>setDidModal(null)} saving={saving} />
      )}
      {xmlPreview && (
        <XmlPreviewModal title={xmlPreview.title} xml={xmlPreview.xml} onClose={() =>setXmlPreview(null)} />
      )}
      {testResult && (
        <TestResultModal result={testResult} onClose={() =>setTestResult(null)} statusColors={STATUS_COLORS} statusLabels={STATUS_LABELS} />
      )}
    </div>
  );
};

/* ============================================================
   TRUNK MODAL
   ============================================================ */
function TrunkModal({ initial, onSave, onClose, saving }) {
  const { useState } = React;
  const [tab, setTab] = useState('basic');
  const [form, setForm] = useState({
    name:'', slug:'', description:'', provider:'',
    host:'', port:5060, transport:'udp',
    username:'', password:'', realm:'', register:true,
    direction:'both',
    caller_id_number:'', caller_id_name:'', outbound_prefix:'',
    max_channels:30, codec_string:'PCMU,PCMA,G729,opus',
    dtmf_mode:'rfc2833', ping_sec:25,
    extra_params:[], is_active:true,
    ...initial
  });
  const set = (k, v) =>setForm(f => ({ ...f, [k]: v }));

  // Slug otomatik üret
  const handleNameChange = (v) => {
    set('name', v);
    if (!form.id) set('slug', v.toLowerCase().replace(/[^a-z0-9]/g,'_').replace(/__+/g,'_'));
  };

  const TABS = [{ id:'basic', label:'Temel' }, { id:'auth', label:'Auth' }, { id:'routing', label:'Yönlendirme' }, { id:'advanced', label:'Gelişmiş' }];

  return (
    <ModalOverlay onClose={onClose} title={form.id ? 'Trunk Düzenle' : 'Yeni SIP Trunk'} width={680}>
      <div style={{ display:'flex', gap:4, marginBottom:20, borderBottom:'1px solid var(--border)', paddingBottom:8 }}>
        {TABS.map(t => (
          <button key={t.id} onClick={() =>setTab(t.id)} style={{
            padding:'5px 14px', borderRadius:8, border:'none', cursor:'pointer', fontSize:13,
            background: tab===t.id ? 'var(--primary)' : 'transparent',
            color: tab===t.id ? '#fff' : 'var(--text-dim)', fontWeight: tab===t.id ? 600 : 400
          }}>{t.label}</button>
        ))}
      </div>

      {tab === 'basic' && (<>
        <FRow label="Trunk Adı *"><input className="form-input" value={form.name} onChange={e =>handleNameChange(e.target.value)} placeholder="Turk Telekom SIP Trunk" /></FRow>
        <FRow label="Slug (Dosya adı) *">
          <input className="form-input" value={form.slug} onChange={e =>set('slug', e.target.value)} style={{ fontFamily:'monospace' }} placeholder="turk_telekom" />
          <div style={{ fontSize:11, color:'var(--text-dim)', marginTop:4 }}>Dosyada kullanılır: <code>external/{form.slug || 'trunk_adi'}.xml</code></div>
        </FRow>
        <FRow label="Sağlayıcı"><input className="form-input" value={form.provider || ''} onChange={e =>set('provider', e.target.value)} placeholder="Turk Telekom, Vodafone…" /></FRow>
        <FRow label="Açıklama"><input className="form-input" value={form.description || ''} onChange={e =>set('description', e.target.value)} /></FRow>
        <div style={{ display:'grid', gridTemplateColumns:'1fr auto', gap:12 }}>
          <FRow label="SIP Sunucu (Host) *"><input className="form-input" value={form.host} onChange={e =>set('host', e.target.value)} placeholder="sip.provider.com veya 1.2.3.4" style={{ fontFamily:'monospace' }} /></FRow>
          <FRow label="Port"><input className="form-input" type="number" value={form.port} onChange={e =>set('port', parseInt(e.target.value))} style={{ width:90 }} /></FRow>
        </div>
        <FRow label="Transport">
          <select className="form-select" value={form.transport} onChange={e =>set('transport', e.target.value)}>
            <option value="udp">UDP (Varsayılan)</option>
            <option value="tcp">TCP</option>
            <option value="tls">TLS (Güvenli)</option>
          </select>
        </FRow>
        <FRow label="Yön">
          <select className="form-select" value={form.direction} onChange={e =>set('direction', e.target.value)}>
            <option value="both">↕ İki Yönlü (Gelen + Giden)</option>
            <option value="inbound">↓ Sadece Gelen</option>
            <option value="outbound">↑ Sadece Giden</option>
          </select>
        </FRow>
        <FRow label="Aktif">
          <label style={{ display:'flex', alignItems:'center', gap:8, cursor:'pointer' }}>
            <input type="checkbox" checked={!!form.is_active} onChange={e =>set('is_active', e.target.checked)} />
            <span>Trunk aktif</span>
          </label>
        </FRow>
      </>)}

      {tab === 'auth' && (<>
        <div style={{ background:'rgba(99,102,241,0.06)', borderRadius:10, padding:14, marginBottom:16, fontSize:13 }}>
          <strong>IP Tabanlı Trunk</strong> — Kullanıcı adı/şifre gerektirmeyen trunk'lar için "Kayıt Yap"ı kapatın.
        </div>
        <FRow label="Kayıt Yap (REGISTER)">
          <label style={{ display:'flex', alignItems:'center', gap:8, cursor:'pointer' }}>
            <input type="checkbox" checked={!!form.register} onChange={e =>set('register', e.target.checked)} />
            <span>{form.register ? 'Evet — SIP REGISTER gönderilir' : 'Hayır — IP tabanlı trunk'}</span>
          </label>
        </FRow>
        {form.register && (<>
          <FRow label="Kullanıcı Adı"><input className="form-input" value={form.username || ''} onChange={e =>set('username', e.target.value)} style={{ fontFamily:'monospace' }} placeholder="1001 veya username" /></FRow>
          <FRow label="Şifre"><input className="form-input" type="password" value={form.password || ''} onChange={e =>set('password', e.target.value)} /></FRow>
          <FRow label="Realm (Boşsa host kullanılır)"><input className="form-input" value={form.realm || ''} onChange={e =>set('realm', e.target.value)} style={{ fontFamily:'monospace' }} placeholder="sip.provider.com" /></FRow>
        </>)}
      </>)}

      {tab === 'routing' && (<>
        <FRow label="Arayan ID Numarası (CID)"><input className="form-input" value={form.caller_id_number || ''} onChange={e =>set('caller_id_number', e.target.value)} style={{ fontFamily:'monospace' }} placeholder="+905321234567" /></FRow>
        <FRow label="Arayan ID Adı"><input className="form-input" value={form.caller_id_name || ''} onChange={e =>set('caller_id_name', e.target.value)} placeholder="Şirket Adı" /></FRow>
        <FRow label="Giden Çağrı Öneki"><input className="form-input" value={form.outbound_prefix || ''} onChange={e =>set('outbound_prefix', e.target.value)} placeholder="9 (dışarı çevirirken 9 ile başla)" /></FRow>
        <FRow label="Maks. Eş Zamanlı Kanal"><input className="form-input" type="number" min={1} max={500} value={form.max_channels} onChange={e =>set('max_channels', parseInt(e.target.value))} /></FRow>
      </>)}

      {tab === 'advanced' && (<>
        <FRow label="Codec Listesi"><input className="form-input" value={form.codec_string} onChange={e =>set('codec_string', e.target.value)} style={{ fontFamily:'monospace' }} placeholder="PCMU,PCMA,G729,opus" /></FRow>
        <FRow label="DTMF Modu">
          <select className="form-select" value={form.dtmf_mode} onChange={e =>set('dtmf_mode', e.target.value)}>
            <option value="rfc2833">RFC 2833 (Önerilen)</option>
            <option value="info">SIP INFO</option>
            <option value="inband">Inband</option>
          </select>
        </FRow>
        <FRow label="Ping Aralığı (sn)"><input className="form-input" type="number" value={form.ping_sec} onChange={e =>set('ping_sec', parseInt(e.target.value))} /></FRow>
      </>)}

      <div style={{ display:'flex', justifyContent:'flex-end', gap:10, marginTop:24 }}>
        <button className="btn btn-secondary" onClick={onClose} disabled={saving}>İptal</button>
        <button className="btn btn-primary" onClick={() =>onSave(form)} disabled={saving}>
          {saving ? 'Kaydediliyor…' : 'Kaydet'}
        </button>
      </div>
    </ModalOverlay>
  );
}

/* ============================================================
   DID MODAL
   ============================================================ */
function DidModal({ initial, trunks, ivrs, ivrFlows, queues, agents, qcScripts, onSave, onClose, saving }) {
  const { useState } = React;
  const [form, setForm] = useState({
    number:'', description:'', trunk_id:null,
    route_type:'ivr', route_target:'',
    off_hours_route_type:null, off_hours_route_target:'',
    recording_enabled:true, recording_stereo:false, recording_path:'',
    is_active:true,
    ...initial
  });
  const set = (k, v) =>setForm(f => ({ ...f, [k]: v }));

  return (
    <ModalOverlay onClose={onClose} title={form.id ? 'DID Düzenle' : 'Yeni DID Numarası'} width={580}>
      <FRow label="Telefon Numarası *">
        <input className="form-input" value={form.number} onChange={e =>set('number', e.target.value)}
          style={{ fontFamily:'monospace', fontSize:18 }} placeholder="+905321234567 veya 08501234567" />
        <div style={{ fontSize:11, color:'var(--text-dim)', marginTop:4 }}>Operatörden gelen çağrıdaki hedef numara formatında girin</div>
      </FRow>
      <FRow label="Açıklama"><input className="form-input" value={form.description || ''} onChange={e =>set('description', e.target.value)} placeholder="Satış Hattı, Destek Hattı…" /></FRow>
      <FRow label="Bağlı Trunk">
        <select className="form-select" value={form.trunk_id || ''} onChange={e =>set('trunk_id', e.target.value ? parseInt(e.target.value) : null)}>
          <option value="">— Trunk seçin (opsiyonel) —</option>
          {trunks.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
        </select>
      </FRow>

      {/* Ana Yönlendirme */}
      <div style={{ background:'var(--bg-hover)', borderRadius:10, padding:14, marginBottom:14 }}>
        <div style={{ fontWeight:600, marginBottom:10 }}>Ana Yönlendirme (Mesai Saatleri)</div>
        <RouteSelector label="Yönlendirme Tipi" type={form.route_type} target={form.route_target}
          ivrs={ivrs} ivrFlows={ivrFlows} queues={queues} agents={agents} qcScripts={qcScripts}
          onTypeChange={v =>set('route_type', v)}
          onTargetChange={v =>set('route_target', v)} />
      </div>

      {/* Mesai Dışı */}
      <div style={{ background:'var(--bg-hover)', borderRadius:10, padding:14, marginBottom:14 }}>
        <div style={{ fontWeight:600, marginBottom:10 }}>Mesai Dışı Yönlendirme (Opsiyonel)</div>
        <label style={{ display:'flex', alignItems:'center', gap:8, marginBottom:10, cursor:'pointer', fontSize:13 }}>
          <input type="checkbox" checked={!!form.off_hours_route_type}
            onChange={e =>set('off_hours_route_type', e.target.checked ? 'ivr' : null)} />
          <span>Mesai dışı farklı yere yönlendir</span>
        </label>
        {form.off_hours_route_type && (
          <RouteSelector type={form.off_hours_route_type} target={form.off_hours_route_target || ''}
            ivrs={ivrs} ivrFlows={ivrFlows} queues={queues} agents={agents} qcScripts={qcScripts}
            onTypeChange={v =>set('off_hours_route_type', v)}
            onTargetChange={v =>set('off_hours_route_target', v)} />
        )}
      </div>

      {/* Çağrı Kaydı */}
      <div style={{ background:'var(--bg-hover)', borderRadius:10, padding:14, marginBottom:14 }}>
        <div style={{ fontWeight:600, marginBottom:10 }}>Çağrı Kaydı</div>
        <label style={{ display:'flex', alignItems:'center', gap:8, marginBottom:10, cursor:'pointer', fontSize:13 }}>
          <input type="checkbox" checked={form.recording_enabled !== false}
            onChange={e =>set('recording_enabled', e.target.checked)} />
          <span>Bu hat için ses kaydı al</span>
        </label>
        {form.recording_enabled !== false && (
          <>
            <label style={{ display:'flex', alignItems:'center', gap:8, marginBottom:10, cursor:'pointer', fontSize:13 }}>
              <input type="checkbox" checked={!!form.recording_stereo}
                onChange={e =>set('recording_stereo', e.target.checked)} />
              <span>Stereo kayıt (dosya boyutu artar)</span>
            </label>
            <div>
              <label style={{ fontSize:11, color:'var(--text-dim)', display:'block', marginBottom:4 }}>Kayıt Dosya Yolu (boş bırakılırsa varsayılan kullanılır)</label>
              <input className="form-input" style={{ fontFamily:'monospace', fontSize:12 }}
                value={form.recording_path || ''}
                onChange={e =>set('recording_path', e.target.value)}
                placeholder="/usr/local/freeswitch/recordings/${strftime(%Y-%m-%d-%H-%M-%S)}_${caller_id_number}.wav" />
            </div>
          </>
        )}
      </div>

      <FRow label="Aktif">
        <label style={{ display:'flex', alignItems:'center', gap:8, cursor:'pointer' }}>
          <input type="checkbox" checked={!!form.is_active} onChange={e =>set('is_active', e.target.checked)} />
          <span>DID aktif</span>
        </label>
      </FRow>

      <div style={{ display:'flex', justifyContent:'flex-end', gap:10, marginTop:24 }}>
        <button className="btn btn-secondary" onClick={onClose} disabled={saving}>İptal</button>
        <button className="btn btn-primary" onClick={() =>onSave(form)} disabled={saving}>
          {saving ? 'Kaydediliyor…' : 'Kaydet'}
        </button>
      </div>
    </ModalOverlay>
  );
}

/* ── Yönlendirme seçici ── */
function RouteSelector({ type, target, ivrs, ivrFlows, queues, agents, qcScripts, onTypeChange, onTargetChange }) {
  return (
    <div style={{ display:'grid', gridTemplateColumns:'160px 1fr', gap:10 }}>
      <div>
        <label style={{ fontSize:11, color:'var(--text-dim)', display:'block', marginBottom:4 }}>Tip</label>
        <select className="form-select" value={type} onChange={e => { onTypeChange(e.target.value); onTargetChange(''); }}>
          <option value="ivr">IVR Menüsü</option>
          <option value="ivr_flow">Akış Tasarımcısı</option>
          <option value="queue">Kuyruk</option>
          <option value="agent">AI Asistan</option>
          <option value="qc_script">Kalite Kontrol</option>
          <option value="human">Temsilci</option>
        </select>
      </div>
      <div>
        <label style={{ fontSize:11, color:'var(--text-dim)', display:'block', marginBottom:4 }}>Hedef</label>
        {type === 'ivr' ? (
          <select className="form-select" value={target} onChange={e =>onTargetChange(e.target.value)}>
            <option value="">— IVR seçin —</option>
            {ivrs.map(i => <option key={i.id} value={i.id}>{i.name}</option>)}
          </select>
        ) : type === 'ivr_flow' ? (
          <select className="form-select" value={target} onChange={e =>onTargetChange(e.target.value)}>
            <option value="">— Akış seçin —</option>
            {(ivrFlows || []).map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
          </select>
        ) : type === 'queue' ? (
          <select className="form-select" value={target} onChange={e =>onTargetChange(e.target.value)}>
            <option value="">— Kuyruk seçin —</option>
            {queues.map(q => <option key={q.id} value={q.extension}>{q.name} ({q.extension})</option>)}
          </select>
        ) : type === 'agent' ? (
          <select className="form-select" value={target} onChange={e =>onTargetChange(e.target.value)}>
            <option value="">— AI Asistan seçin —</option>
            {(agents || []).map(a => <option key={a.id} value={a.id}>{a.name}{a.department ? ` (${a.department})` : ''}</option>)}
          </select>
        ) : type === 'qc_script' ? (
          <select className="form-select" value={target} onChange={e =>onTargetChange(e.target.value)}>
            <option value="">— KK Scripti seçin —</option>
            {(qcScripts || []).map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
        ) : (
          <input className="form-input" value={target} onChange={e =>onTargetChange(e.target.value)}
            placeholder="Temsilci ext: 9001"
            style={{ fontFamily:'monospace' }} />
        )}
      </div>
    </div>
  );
}

/* ============================================================
   XML PREVIEW MODAL
   ============================================================ */
function XmlPreviewModal({ title, xml, onClose }) {
  return (
    <ModalOverlay onClose={onClose} title={title} width={700}>
      <pre style={{
        background:'#1e1e2e', color:'#cdd6f4', borderRadius:10, padding:16,
        fontSize:12, fontFamily:'monospace', overflowX:'auto',
        maxHeight:500, overflowY:'auto', lineHeight:1.5
      }}>{xml}</pre>
      <div style={{ textAlign:'right', marginTop:12 }}>
        <button className="btn btn-secondary" onClick={() => { navigator.clipboard.writeText(xml); }}>Kopyala</button>
      </div>
    </ModalOverlay>
  );
}

/* ============================================================
   TEST RESULT MODAL
   ============================================================ */
function TestResultModal({ result, onClose, statusColors, statusLabels }) {
  if (result.loading) return (
    <ModalOverlay onClose={onClose} title={`Test — ${result.name}`} width={480}>
      <div style={{ textAlign:'center', padding:40, color:'var(--text-dim)' }}>Trunk test ediliyor…</div>
    </ModalOverlay>
  );

  const color = statusColors[result.status] || '#9ca3af';
  return (
    <ModalOverlay onClose={onClose} title={`Trunk Test — ${result.name}`} width={520}>
      <div style={{ textAlign:'center', padding:'20px 0' }}>
        <div style={{ fontSize:20, fontWeight:600, marginBottom:12, color }}>{result.status === 'registered' ? 'Basarili' : result.status === 'failed' ? 'Basarisiz' : 'Uyari'}</div>
        <div style={{ fontSize:20, fontWeight:600, color }}>{statusLabels[result.status] || result.status}</div>
      </div>
      {result.raw && (
        <pre style={{ background:'#1e1e2e', color:'#cdd6f4', borderRadius:8, padding:12, fontSize:12, fontFamily:'monospace', overflowX:'auto' }}>
          {result.raw}
        </pre>
      )}
      <div style={{ textAlign:'right', marginTop:16 }}>
        <button className="btn btn-secondary" onClick={onClose}>Kapat</button>
      </div>
    </ModalOverlay>
  );
}

/* ============================================================
   SHARED HELPERS
   ============================================================ */
function ModalOverlay({ children, onClose, title, width=600 }) {
  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)',
      display:'flex', alignItems:'center', justifyContent:'center', zIndex:1000 }}
      onClick={e =>e.target===e.currentTarget && onClose()}>
      <div style={{ background:'var(--bg-card)', borderRadius:16, padding:28,
        width:Math.min(width, window.innerWidth-32), maxWidth:'100%',
        maxHeight:'90vh', overflowY:'auto', boxShadow:'0 24px 60px rgba(0,0,0,0.35)' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:20 }}>
          <h3 style={{ margin:0, fontSize:17, fontWeight:600 }}>{title}</h3>
          <button style={{ background:'none', border:'none', cursor:'pointer', fontSize:20, color:'var(--text-dim)' }} onClick={onClose}>X</button>
        </div>
        {children}
      </div>
    </div>
  );
}

function FRow({ label, children }) {
  return (
    <div style={{ marginBottom:14 }}>
      <label style={{ display:'block', fontSize:13, fontWeight:600, marginBottom:5, color:'var(--text-dim)' }}>{label}</label>
      {children}
    </div>
  );
}

function Badge({ children, color='#6b7280' }) {
  return (
    <span style={{ fontSize:11, padding:'2px 8px', borderRadius:6, fontWeight:600,
      background: color + '20', color, border: `1px solid ${color}40` }}>
      {children}
    </span>
  );
}

function InfoRow({ icon, label, value, mono }) {
  return (
    <div style={{ fontSize:12 }}>
      <span style={{ color:'var(--text-dim)' }}>{icon} {label}: </span>
      <span style={{ fontWeight:600, fontFamily: mono ? 'monospace' : undefined }}>{value}</span>
    </div>
  );
}

function EmptyState({ icon, text, sub }) {
  return (
    <div style={{ textAlign:'center', padding:'60px 20px', color:'var(--text-dim)' }}>
      {icon && <div style={{ fontSize:16, marginBottom:12 }}>{icon}</div>}
      <div style={{ fontSize:16, fontWeight:600 }}>{text}</div>
      {sub && <div style={{ fontSize:14, marginTop:6 }}>{sub}</div>}
    </div>
  );
}

async function apiFetch(url, opts = {}) {
  // Content-Type header'ını her zaman ekle (body varsa)
  if (opts.body && !opts.headers?.['Content-Type']) {
    opts.headers = { 'Content-Type': 'application/json', ...(opts.headers || {}) };
  }
  async function _parseError(res) {
    try {
      const body = await res.json();
      return body.detail || body.message || null;
    } catch { return null; }
  }
  if (window.authFetch) {
    try {
      const res = await window.authFetch(url, opts);
      if (!res.ok) { const detail = await _parseError(res); return { _error: true, detail }; }
      return await res.json();
    } catch { return { _error: true, detail: null }; }
  }
  const token = localStorage.getItem('ai_cc_access_token');
  try {
    const res = await fetch(url, {
      headers: { 'Content-Type':'application/json', 'Authorization':`Bearer ${token}`, ...(opts.headers||{}) },
      ...opts,
    });
    if (!res.ok) { const detail = await _parseError(res); return { _error: true, detail }; }
    return await res.json();
  } catch { return { _error: true, detail: null }; }
}
