const { useState, useEffect } = React;

/* ─────────────────────────────────────────────────────────────
   AnnouncementLibrary — WAV upload/playback/delete panel
   shown at the top of the IVR tab
───────────────────────────────────────────────────────────── */
function AnnouncementLibrary({ announcements, onUploaded, onDeleted }) {
  const [uploading, setUploading] = React.useState(false);
  const [expanded, setExpanded] = React.useState(true);
  const fileInputRef = React.useRef(null);
  const [uploadName, setUploadName] = React.useState('');
  const [uploadDesc, setUploadDesc] = React.useState('');
  const [selectedFile, setSelectedFile] = React.useState(null);
  const [playingId, setPlayingId] = React.useState(null);
  const audioRef = React.useRef(null);

  function handleFileSelect(e) {
    const f = e.target.files[0];
    if (!f) return;
    const allowed = ['.wav', '.mp3'];
    const ext = f.name.toLowerCase().slice(f.name.lastIndexOf('.'));
    if (!allowed.includes(ext)) {
      alert('Sadece .wav veya .mp3 dosyaları kabul edilir.');
      return;
    }
    setSelectedFile(f);
    if (!uploadName) setUploadName(f.name.replace(/\.(wav|mp3)$/i, ''));
  }

  async function handleUpload() {
    if (!selectedFile || !uploadName.trim()) {
      alert('Dosya seçin ve anons adı girin.');
      return;
    }
    setUploading(true);
    try {
      const fd = new FormData();
      fd.append('name', uploadName.trim());
      fd.append('description', uploadDesc.trim());
      fd.append('file', selectedFile);
      const r = await authFetch('/api/announcements/upload', { method: 'POST', body: fd });
      if (r.ok) {
        setSelectedFile(null); setUploadName(''); setUploadDesc('');
        fileInputRef.current.value = '';
        onUploaded();
      } else {
        const err = await r.json();
        alert('Yükleme hatası: ' + (err.detail || JSON.stringify(err)));
      }
    } finally {
      setUploading(false);
    }
  }

  function handlePlay(ann) {
    if (playingId === ann.id) {
      audioRef.current?.pause();
      setPlayingId(null);
      return;
    }
    if (audioRef.current) {
      audioRef.current.src = `/api/announcements/${ann.id}/stream`;
      audioRef.current.play().catch(() => {});
      setPlayingId(ann.id);
      audioRef.current.onended = () => setPlayingId(null);
    }
  }

  async function handleDelete(ann) {
    if (!confirm(`"${ann.name}" silinsin mi?`)) return;
    const r = await authFetch(`/api/announcements/${ann.id}`, { method: 'DELETE' });
    if (r.ok) onDeleted();
  }

  function fmtSize(bytes) {
    if (!bytes) return '';
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / 1024 / 1024).toFixed(1) + ' MB';
  }

  return (
    <div style={{ marginBottom: 24, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
      <audio ref={audioRef} hidden />
      {/* Header */}
      <div onClick={() => setExpanded(e => !e)} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 20px', cursor: 'pointer', borderBottom: expanded ? '1px solid var(--border)' : 'none' }}>
        <span style={{ fontWeight: 600, fontSize: 14 }}>📢 Anons Kütüphanesi <span style={{ fontWeight: 400, fontSize: 12, color: 'var(--text-dim)', marginLeft: 8 }}>{announcements.length} anons</span></span>
        <span style={{ color: 'var(--text-dim)', fontSize: 12 }}>{expanded ? '▲' : '▼'}</span>
      </div>

      {expanded && (
        <div style={{ padding: '16px 20px' }}>
          {/* Upload form */}
          <div style={{ display: 'flex', gap: 10, alignItems: 'flex-end', marginBottom: 16, flexWrap: 'wrap' }}>
            <div style={{ flex: '1 1 180px' }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', marginBottom: 4 }}>ANONS ADI</div>
              <input className="form-input" placeholder="Örn: Hoş Geldiniz Anonsu" value={uploadName} onChange={e => setUploadName(e.target.value)} style={{ fontSize: 13 }} />
            </div>
            <div style={{ flex: '1 1 160px' }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', marginBottom: 4 }}>AÇIKLAMA</div>
              <input className="form-input" placeholder="İsteğe bağlı" value={uploadDesc} onChange={e => setUploadDesc(e.target.value)} style={{ fontSize: 13 }} />
            </div>
            <div style={{ flex: '0 0 auto' }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', marginBottom: 4 }}>WAV DOSYASI</div>
              <input ref={fileInputRef} type="file" accept=".wav,.mp3" onChange={handleFileSelect} style={{ display: 'none' }} />
              <button onClick={() => fileInputRef.current.click()} style={{ padding: '8px 14px', borderRadius: 8, border: '1px solid var(--border)', background: 'var(--surface2)', color: 'var(--text)', cursor: 'pointer', fontSize: 13 }}>
                {selectedFile ? `✓ ${selectedFile.name}` : '📁 Dosya Seç'}
              </button>
            </div>
            <button className="btn primary" onClick={handleUpload} disabled={uploading || !selectedFile} style={{ padding: '8px 16px', fontSize: 13 }}>
              {uploading ? 'Yükleniyor...' : '⬆ Yükle'}
            </button>
          </div>

          {/* List */}
          {announcements.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '20px 0', color: 'var(--text-dim)', fontSize: 13 }}>
              Henüz anons yüklenmemiş. WAV dosyası yükleyerek IVR menülerinde kullanabilirsiniz.
            </div>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ borderBottom: '1px solid var(--border)' }}>
                  {['Ad', 'Açıklama', 'Boyut', 'Tarih', ''].map((h, i) => (
                    <th key={i} style={{ padding: '6px 12px', textAlign: 'left', fontSize: 11, fontWeight: 600, color: 'var(--text-dim)', textTransform: 'uppercase' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {announcements.map(ann => (
                  <tr key={ann.id} style={{ borderBottom: '1px solid var(--border)' }}>
                    <td style={{ padding: '10px 12px', fontSize: 13, fontWeight: 500 }}>{ann.name}</td>
                    <td style={{ padding: '10px 12px', fontSize: 12, color: 'var(--text-dim)' }}>{ann.description || '—'}</td>
                    <td style={{ padding: '10px 12px', fontSize: 12, color: 'var(--text-dim)' }}>{fmtSize(ann.file_size)}</td>
                    <td style={{ padding: '10px 12px', fontSize: 12, color: 'var(--text-dim)' }}>{fmtDateOnly(ann.created_at)}</td>
                    <td style={{ padding: '10px 12px', textAlign: 'right' }}>
                      <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                        <button onClick={() => handlePlay(ann)} style={{ padding: '4px 10px', borderRadius: 6, border: '1px solid var(--border)', background: playingId === ann.id ? 'rgba(88,166,255,.15)' : 'var(--surface2)', color: playingId === ann.id ? 'var(--blue)' : 'var(--text)', cursor: 'pointer', fontSize: 12 }}>
                          {playingId === ann.id ? '⏹ Durdur' : '▶ Dinle'}
                        </button>
                        <button onClick={() => handleDelete(ann)} style={{ padding: '4px 10px', borderRadius: 6, border: '1px solid rgba(248,81,73,.2)', background: 'transparent', color: 'var(--red)', cursor: 'pointer', fontSize: 12 }}>Sil</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────
   IVRModal — create / edit a single IVR menu
───────────────────────────────────────────────────────────── */
function IVRModal({ menu, onClose, onSave }) {
  const emptyForm = {
    name: '', description: '',
    greet_text: 'Merhaba, şirketimize hoş geldiniz. Satış için 1\'i, destek için 2\'yi tuşlayınız.',
    invalid_text: 'Hatalı tuşlama yaptınız. Lütfen tekrar deneyin.',
    exit_text: 'İşleminizi gerçekleştiremiyoruz. İyi günler dileriz.',
    timeout_ms: 3000, max_failures: 3, is_active: true,
    greet_announcement_id: null,
    invalid_announcement_id: null,
    exit_announcement_id: null,
  };

  const [form, setForm] = useState(menu ? { ...menu } : emptyForm);
  const [options, setOptions] = useState(menu?.options ? [...menu.options] : []);
  const [wsCalls, setWsCalls] = useState(menu?.ws_pre_calls ? [...menu.ws_pre_calls] : []);
  const [saving, setSaving] = useState(false);
  const [queues, setQueues] = useState([]);
  const [agents, setAgents] = useState([]);
  const [services, setServices] = useState([]);
  const [announcements, setAnnouncements] = useState([]);

  const [greetSource,   setGreetSource]   = useState(menu?.greet_announcement_id   ? 'ann' : 'tts');
  const [invalidSource, setInvalidSource] = useState(menu?.invalid_announcement_id ? 'ann' : 'tts');
  const [exitSource,    setExitSource]    = useState(menu?.exit_announcement_id    ? 'ann' : 'tts');
  const [playingPreview, setPlayingPreview] = useState(null);
  const previewAudioRef = React.useRef(null);

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

  useEffect(() => {
    authFetch('/api/queues?active_only=true')
      .then(r => r.ok ? r.json() : []).then(setQueues).catch(() => {});
    authFetch('/api/agents')
      .then(r => r.ok ? r.json() : []).then(setAgents).catch(() => {});
    authFetch('/api/ws/services')
      .then(r => r.ok ? r.json() : []).then(setServices).catch(() => {});
    authFetch('/api/announcements')
      .then(r => r.ok ? r.json() : []).then(setAnnouncements).catch(() => {});
  }, []);

  function playPreview(annId) {
    if (playingPreview === annId) {
      previewAudioRef.current?.pause();
      setPlayingPreview(null);
      return;
    }
    if (previewAudioRef.current) {
      previewAudioRef.current.src = `/api/announcements/${annId}/stream`;
      previewAudioRef.current.play().catch(() => {});
      setPlayingPreview(annId);
      previewAudioRef.current.onended = () => setPlayingPreview(null);
    }
  }

  /* TTS / Announcement toggle section — defined inside IVRModal
     so it closes over form, set, playPreview, playingPreview    */
  function AudioSourceSection({ label, sourceState, setSourceState, textKey, annIdKey, annotations }) {
    return (
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
          <label className="form-label" style={{ margin: 0 }}>{label}</label>
          <div style={{ display: 'flex', gap: 4, marginLeft: 'auto' }}>
            {[['tts', '🔊 TTS'], ['ann', '📢 Anons']].map(([val, lbl]) => (
              <button key={val} onClick={() => setSourceState(val)} style={{
                padding: '3px 10px', borderRadius: 6, fontSize: 11, fontWeight: 600, cursor: 'pointer',
                border: '1px solid ' + (sourceState === val ? 'var(--blue)' : 'var(--border)'),
                background: sourceState === val ? 'rgba(88,166,255,.1)' : 'var(--surface2)',
                color: sourceState === val ? 'var(--blue)' : 'var(--text-dim)',
              }}>{lbl}</button>
            ))}
          </div>
        </div>
        {sourceState === 'tts' ? (
          <textarea className="form-input" rows={2} value={form[textKey] || ''} onChange={e => set(textKey, e.target.value)} style={{ fontSize: 13, resize: 'vertical' }} />
        ) : (
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <select className="form-input" style={{ flex: 1, fontSize: 13 }}
              value={form[annIdKey] || ''}
              onChange={e => set(annIdKey, e.target.value ? parseInt(e.target.value) : null)}
            >
              <option value="">— Anons seçin —</option>
              {annotations.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
            </select>
            {form[annIdKey] && (
              <button onClick={() => playPreview(form[annIdKey])} style={{ padding: '6px 12px', borderRadius: 8, border: '1px solid var(--border)', background: 'var(--surface2)', cursor: 'pointer', fontSize: 13 }}>
                {playingPreview === form[annIdKey] ? '⏹' : '▶'}
              </button>
            )}
          </div>
        )}
      </div>
    );
  }

  const addOption = () => {
    setOptions([...options, { digit: '', action_type: 'transfer_queue', target: '' }]);
  };

  const updateOption = (i, field, val) => {
    setOptions(opts => opts.map((opt, idx) => {
      if (idx !== i) return opt;
      const updated = { ...opt, [field]: val };
      // Eylem türü değişince hedefi sıfırla
      if (field === 'action_type') updated.target = '';
      return updated;
    }));
  };

  const removeOption = (i) => {
    setOptions(opts => opts.filter((_, idx) => idx !== i));
  };

  async function handleSave() {
    if (!form.name || !form.greet_text) {
      alert('Lütfen menü adını ve karşılama metnini doldurun.');
      return;
    }
    setSaving(true);
    try {
      const payload = {
        ...form,
        greet_announcement_id:   greetSource   === 'ann' ? form.greet_announcement_id   : null,
        invalid_announcement_id: invalidSource === 'ann' ? form.invalid_announcement_id : null,
        exit_announcement_id:    exitSource    === 'ann' ? form.exit_announcement_id    : null,
        options,
        ws_pre_calls: wsCalls.length > 0 ? wsCalls : null,
      };
      const url = menu ? `/api/ivr/${menu.id}` : '/api/ivr';
      const method = menu ? 'PUT' : 'POST';
      const r = await authFetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      if (r.ok) {
        onSave();
      } else {
        const err = await r.json();
        alert('Kaydetme hatası: ' + JSON.stringify(err));
      }
    } finally {
      setSaving(false);
    }
  }

  /* Hedef input — eylem türüne göre farklı kontrol göster */
  function TargetInput({ opt, index }) {
    switch (opt.action_type) {

      /* Kuyruğa Aktar — dropdown */
      case 'transfer_queue':
        return (
          <div className="form-group" style={{ marginBottom: 0 }}>
            <label className="form-label" style={{ fontSize: 10 }}>Hedef Kuyruk</label>
            <select
              className="form-select"
              value={opt.target}
              onChange={e => updateOption(index, 'target', 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>
            {queues.length === 0 && (
              <div style={{ fontSize: 10, color: 'var(--amber)', marginTop: 3 }}>
                Aktif kuyruk bulunamadı. Önce Kuyruklar sekmesinden ekleyin.
              </div>
            )}
          </div>
        );

      /* Başka IVR — ID girin */
      case 'transfer_ivr':
        return (
          <div className="form-group" style={{ marginBottom: 0 }}>
            <label className="form-label" style={{ fontSize: 10 }}>IVR Menü ID</label>
            <input
              className="form-input"
              value={opt.target}
              onChange={e => updateOption(index, 'target', e.target.value)}
              placeholder="Örn: 2"
            />
          </div>
        );

      /* AI Asistana Aktar — dropdown */
      case 'transfer_ai':
        return (
          <div className="form-group" style={{ marginBottom: 0 }}>
            <label className="form-label" style={{ fontSize: 10 }}>AI Asistan</label>
            <select
              className="form-select"
              value={opt.target}
              onChange={e => updateOption(index, 'target', 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>
            {agents.length === 0 && (
              <div style={{ fontSize: 10, color: 'var(--amber)', marginTop: 3 }}>
                AI Asistan bulunamadı. Önce AI Asistanlar sekmesinden ekleyin.
              </div>
            )}
          </div>
        );

      /* Temsilciye Aktar — dahili numara */
      default:
        return (
          <div className="form-group" style={{ marginBottom: 0 }}>
            <label className="form-label" style={{ fontSize: 10 }}>Temsilci Dahili No</label>
            <input
              className="form-input"
              value={opt.target}
              onChange={e => updateOption(index, 'target', e.target.value)}
              placeholder="Örn: 9001"
            />
          </div>
        );
    }
  }

  /* Hedef etiket (kart görünümünde) */
  function targetLabel(opt) {
    if (opt.action_type === 'transfer_queue') {
      const q = queues.find(q => q.extension === opt.target);
      return q ? `${q.name} (${q.extension})` : opt.target;
    }
    if (opt.action_type === 'transfer_ivr') return `Menü #${opt.target}`;
    if (opt.action_type === 'transfer_human') return `Temsilci: ${opt.target}`;
    if (opt.action_type === 'transfer_ai') {
      const a = agents.find(a => String(a.id) === String(opt.target));
      return a ? `AI: ${a.name}` : `AI: ${opt.target}`;
    }
    return opt.target;
  }

  return (
    <div className="overlay" onClick={onClose}
      style={{ paddingTop: 40, paddingBottom: 40, overflowY: 'auto', alignItems: 'flex-start' }}>
      <div className="modal" onClick={e => e.stopPropagation()}
        style={{ maxWidth: 820, margin: 'auto' }}>

        <div className="modal-header">
          <span style={{ fontWeight: 600, fontSize: 18 }}>
            {menu ? 'IVR Menüsünü Düzenle' : 'Yeni IVR Menüsü'}
          </span>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>

        <div className="modal-body">
          {/* Temel Bilgiler */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 24 }}>
            <div className="form-group" style={{ gridColumn: '1/-1' }}>
              <label className="form-label">Menü Adı *</label>
              <input className="form-input" value={form.name}
                onChange={e => set('name', e.target.value)}
                placeholder="Örn: Ana Karşılama Menüsü" />
            </div>
            <div className="form-group" style={{ gridColumn: '1/-1' }}>
              <label className="form-label">Açıklama</label>
              <input className="form-input" value={form.description}
                onChange={e => set('description', e.target.value)}
                placeholder="Bu menü nerelerde kullanılıyor?" />
            </div>
            <div className="form-group">
              <label className="form-label">Zaman Aşımı (ms)</label>
              <input className="form-input" type="number" value={form.timeout_ms}
                onChange={e => set('timeout_ms', +e.target.value)} />
            </div>
            <div className="form-group">
              <label className="form-label">Maks. Hata Hakkı</label>
              <input className="form-input" type="number" value={form.max_failures}
                onChange={e => set('max_failures', +e.target.value)} />
            </div>
          </div>

          {/* Sesli Mesajlar */}
          <div style={{ background: 'var(--surface2)', padding: 20, borderRadius: 12,
            border: '1px solid var(--border)', marginBottom: 24 }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '.05em' }}>Sesli Mesajlar</div>
              <audio ref={previewAudioRef} hidden />
              <AudioSourceSection label="Karşılama Mesajı *" sourceState={greetSource} setSourceState={setGreetSource} textKey="greet_text" annIdKey="greet_announcement_id" annotations={announcements} />
              <AudioSourceSection label="Hatalı Tuş Mesajı" sourceState={invalidSource} setSourceState={setInvalidSource} textKey="invalid_text" annIdKey="invalid_announcement_id" annotations={announcements} />
              <AudioSourceSection label="Çıkış Mesajı" sourceState={exitSource} setSourceState={setExitSource} textKey="exit_text" annIdKey="exit_announcement_id" annotations={announcements} />
            </div>
          </div>

          {/* Web Servis Çağrıları */}
          <div style={{ background: 'var(--surface2)', padding: 20, borderRadius: 12,
            border: '1px solid var(--border)', marginBottom: 24 }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 14 }}>
              <div style={{ fontSize:14, fontWeight:800, color:'#6366f1' }}>
                Web Servis Çağrıları <span style={{ fontSize:12, fontWeight:400, color:'var(--text-dim)' }}>(Menüye girildiğinde otomatik çalışır)</span>
              </div>
              <button className="btn-sm outline" onClick={() =>
                setWsCalls(w => [...w, { service_id: '', variables: { caller_id: '{caller_id_number}' } }])
              }>+ Servis Ekle</button>
            </div>

            {services.length === 0 && (
              <div style={{ fontSize:12, color:'var(--amber)', marginBottom:10 }}>
                Önce "Web Servisler" sekmesinden servis tanımlamalısınız.
              </div>
            )}

            {wsCalls.length === 0 ? (
              <div style={{ textAlign:'center', padding:'16px', color:'var(--text-dim)', fontSize:13 }}>
                Web servis bağlantısı yok. Müşteri tanımlama, bakiye sorgulama vb. için ekleyin.
              </div>
            ) : (
              <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
                {wsCalls.map((wc, i) => (
                  <WsCallRow key={i} call={wc} index={i} services={services}
                    onChange={(field, val) => setWsCalls(list =>
                      list.map((c, idx) => idx===i ? {...c, [field]: val} : c))}
                    onDelete={() => setWsCalls(list => list.filter((_,idx) => idx!==i))}
                  />
                ))}
              </div>
            )}
          </div>

          {/* Tuşlama Seçenekleri */}
          <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 }}>
                Tuşlama Seçenekleri
              </span>
              <button className="btn primary btn-sm" onClick={addOption}>
                + Seçenek Ekle
              </button>
            </div>

            {options.length === 0 ? (
              <div style={{ padding: '20px', background: 'var(--surface2)',
                borderRadius: 12, textAlign: 'center',
                color: 'var(--text-dim)', fontSize: 13 }}>
                Henüz bir tuşlama seçeneği eklenmemiş.
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {options.map((opt, i) => (
                  <div key={i} style={{
                    display: 'grid',
                    gridTemplateColumns: '70px 200px 1fr 36px',
                    gap: 12, alignItems: 'end',
                    background: 'var(--surface2)', padding: 14,
                    borderRadius: 10, border: '1px solid var(--border)'
                  }}>
                    {/* Tuş */}
                    <div className="form-group" style={{ marginBottom: 0 }}>
                      <label className="form-label" style={{ fontSize: 10 }}>
                        Tuş
                      </label>
                      <input
                        className="form-input mono"
                        value={opt.digit}
                        onChange={e => updateOption(i, 'digit', e.target.value)}
                        placeholder="1"
                        style={{ textAlign: 'center', fontWeight: 'bold',
                          fontSize: 18 }}
                      />
                    </div>

                    {/* Eylem Türü */}
                    <div className="form-group" style={{ marginBottom: 0 }}>
                      <label className="form-label" style={{ fontSize: 10 }}>
                        Eylem Türü
                      </label>
                      <select
                        className="form-select"
                        value={opt.action_type}
                        onChange={e => updateOption(i, 'action_type', e.target.value)}
                      >
                        <option value="transfer_queue"> Kuyruğa Aktar</option>
                        <option value="transfer_human"> Temsilciye Aktar</option>
                        <option value="transfer_ai"> AI Asistana Aktar</option>
                        <option value="transfer_ivr"> Başka IVR'a Aktar</option>
                      </select>
                    </div>

                    {/* Hedef — türe göre değişen */}
                    <TargetInput opt={opt} index={i} />

                    {/* Sil */}
                    <button
                      onClick={() => removeOption(i)}
                      style={{ background: 'none', border: 'none',
                        color: 'var(--red)', fontSize: 20,
                        cursor: 'pointer', paddingBottom: 4 }}
                      title="Seçeneği sil"
                    >

                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Aktif / Pasif */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '16px', marginTop: 24, borderRadius: 12,
            background: form.is_active ? 'rgba(34,197,94,.08)' : 'var(--surface2)',
            border: `1px solid ${form.is_active ? 'var(--green)' : 'var(--border)'}`,
          }}>
            <input type="checkbox" id="ivr-active" checked={form.is_active}
              onChange={e => set('is_active', e.target.checked)}
              style={{ width: 20, height: 20, accentColor: 'var(--green)', cursor: 'pointer' }} />
            <label htmlFor="ivr-active" className="form-label"
              style={{ margin: 0, cursor: 'pointer',
                color: form.is_active ? 'var(--green)' : 'var(--text-dim)' }}>
              Bu IVR Menüsü aktif
            </label>
          </div>
        </div>

        <div className="modal-footer">
          <button className="btn outline" onClick={onClose}>İptal Et</button>
          <button className="btn primary" onClick={handleSave} disabled={saving}>
            {saving ? 'Kaydediliyor...' : 'Kaydet ve Güncelle'}
          </button>
        </div>
      </div>
    </div>
  );
}

/* WsCallRow — tek bir web servis çağrı satırı */
function WsCallRow({ call, index, services, onChange, onDelete }) {
  const [showVars, setShowVars] = useState(false);
  const vars = call.variables || {};

  const addVar = () => {
    onChange('variables', { ...vars, '': '' });
  };

  const updateVar = (oldKey, newKey, newVal) => {
    const next = {};
    Object.entries(vars).forEach(([k, v]) => {
      const k2 = k === oldKey ? newKey : k;
      const v2 = k === oldKey ? newVal : v;
      next[k2] = v2;
    });
    onChange('variables', next);
  };

  const delVar = (key) => {
    const next = { ...vars };
    delete next[key];
    onChange('variables', next);
  };

  const selectedSvc = services.find(s => s.id === parseInt(call.service_id));

  return (
    <div style={{ background:'var(--surface)', borderRadius:10, padding:14, border:'1px solid var(--border)' }}>
      <div style={{ display:'flex', gap:12, alignItems:'center', marginBottom: showVars ? 12 : 0 }}>
        {/* Servis Seçimi */}
        <div style={{ flex:1 }}>
          <label style={{ fontSize:11, color:'var(--text-dim)', display:'block', marginBottom:4 }}>Servis</label>
          <select className="form-select" value={call.service_id || ''}
            onChange={e => onChange('service_id', parseInt(e.target.value) || '')}>
            <option value="">— Servis seçin —</option>
            {services.map(s => (
              <option key={s.id} value={s.id}>{s.name}</option>
            ))}
          </select>
        </div>
        {/* Değişkenler toggle */}
        <button className="btn-sm outline" style={{ marginTop:18 }}
          onClick={() => setShowVars(v => !v)}>
          {showVars ? 'Değişkenleri Gizle' : 'Değişkenler'}
          {Object.keys(vars).length > 0 && (
            <span style={{ marginLeft:6, background:'#6366f1', color:'#fff', borderRadius:'50%', padding:'1px 6px', fontSize:11 }}>
              {Object.keys(vars).length}
            </span>
          )}
        </button>
        <button onClick={onDelete} title="Servisi kaldır"
          style={{ marginTop:18, background:'none', border:'1px solid var(--border)', borderRadius:6, color:'var(--red)', fontSize:14, padding:'4px 10px', cursor:'pointer', fontWeight:600 }}>Sil</button>
      </div>

      {/* Servis açıklaması */}
      {selectedSvc && (
        <div style={{ fontSize:12, color:'var(--text-dim)', marginBottom: showVars ? 10 : 0,
          fontFamily:'monospace', background:'var(--surface2)', borderRadius:6, padding:'3px 8px' }}>
          {selectedSvc.method} {selectedSvc.url}
        </div>
      )}

      {/* Değişken eşleme */}
      {showVars && (
        <div style={{ borderTop:'1px solid var(--border)', paddingTop:12 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8 }}>
            <span style={{ fontSize:12, fontWeight:600, color:'var(--text-dim)' }}>
              Gönderilecek Değişkenler
            </span>
            <button className="btn-sm outline" style={{ fontSize:11 }} onClick={addVar}>+ Değişken</button>
          </div>
          <div style={{ fontSize:11, color:'var(--text-dim)', marginBottom:8 }}>
            FreeSWITCH değişkeni: <code style={{ background:'var(--surface2)', padding:'1px 4px', borderRadius:3 }}>{'{caller_id_number}'}</code> &nbsp;
            Sabit değer: <code style={{ background:'var(--surface2)', padding:'1px 4px', borderRadius:3 }}>12345</code>
          </div>
          {Object.entries(vars).map(([k, v], i) => (
            <div key={i} style={{ display:'grid', gridTemplateColumns:'1fr 1fr auto', gap:8, marginBottom:6, alignItems:'center' }}>
              <input className="form-input" style={{ fontSize:12, fontFamily:'monospace' }}
                value={k} placeholder="caller_id"
                onChange={e => updateVar(k, e.target.value, v)} />
              <input className="form-input" style={{ fontSize:12 }}
                value={v} placeholder="{caller_id_number} veya sabit"
                onChange={e => updateVar(k, k, e.target.value)} />
              <button title="Değişkeni sil" style={{ background:'none', border:'1px solid var(--border)', borderRadius:6, padding:'2px 8px', cursor:'pointer', color:'var(--red)', fontSize:13, fontWeight:600 }}
                onClick={() => delVar(k)}>X</button>
            </div>
          ))}
          {Object.keys(vars).length === 0 && (
            <div style={{ fontSize:12, color:'var(--text-dim)' }}>Değişken eklenmemiş — servis parametresiz çağrılır.</div>
          )}
        </div>
      )}
    </div>
  );
}

/* IVR Tab */
function IVRTab({ toast }) {
  const { data: menus, reload } = window.useApi('/api/ivr', []);
  const [modal, setModal] = useState(null);
  // Kuyruk isimlerini kartlarda göstermek için yükle
  const [queues, setQueues] = useState([]);
  const [announcements, setAnnouncements] = useState([]);
  const [services, setServices] = useState([]);

  function loadAnnouncements() {
    authFetch('/api/announcements').then(r => r.ok ? r.json() : []).then(setAnnouncements).catch(() => {});
  }

  useEffect(() => {
    authFetch('/api/queues')
      .then(r => r.ok ? r.json() : [])
      .then(setQueues)
      .catch(() => {});
    authFetch('/api/ws/services')
      .then(r => r.ok ? r.json() : [])
      .then(setServices)
      .catch(() => {});
    loadAnnouncements();
  }, []);

  function queueLabel(extension) {
    const q = queues.find(q => q.extension === extension);
    return q ? `${q.name} (${extension})` : extension;
  }

  function optionLabel(opt) {
    if (opt.action_type === 'transfer_queue') return ` ${queueLabel(opt.target)}`;
    if (opt.action_type === 'transfer_ivr') return ` Menü #${opt.target}`;
    if (opt.action_type === 'transfer_human') return ` ${opt.target}`;
    return ` AI: ${opt.target}`;
  }

  async function handleDelete(id) {
    if (!confirm('Bu IVR menüsünü silmek istediğinize emin misiniz?')) return;
    await authFetch(`/api/ivr/${id}`, { method: 'DELETE' });
    toast('IVR Menüsü başarıyla silindi', 'success');
    reload();
  }

  return (
    <div className="fade-in">
      <div style={{ display: 'flex', justifyContent: 'space-between',
        alignItems: 'flex-start', marginBottom: 36 }}>
        <div>
          <h2 style={{ fontSize: 24, fontWeight: 600, marginBottom: 8 }}>
            Sesli Yanıt Sistemi (IVR)
          </h2>
          <p style={{ fontSize: 15, color: 'var(--text-dim)' }}>
            Gelen çağrıları karşılayacak otomatik menüler oluşturun ve yönlendirmeleri ayarlayın.
          </p>
        </div>
        <button className="btn primary" onClick={() => setModal('new')}>
          + Yeni IVR Menüsü
        </button>
      </div>

      {/* Anons Kütüphanesi */}
      <AnnouncementLibrary announcements={announcements} onUploaded={loadAnnouncements} onDeleted={loadAnnouncements} />

      {(!menus || menus.length === 0) ? (
        <div style={{ textAlign: 'center', padding: 80, color: 'var(--text-dim)',
          background: 'var(--surface)', borderRadius: 20,
          border: '1px solid var(--border)' }}>
           <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 12,
            color: 'var(--text)' }}>
            Henüz IVR Menüsü yok
          </div>
          <div style={{ fontSize: 15 }}>
            Arayanları kuyruklara veya temsilcilere yönlendirmek için ilk IVR'ınızı oluşturun.
          </div>
        </div>
      ) : (
        <div style={{ display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))',
          gap: 20 }}>
          {menus.map(m => (
            <div key={m.id} className="panel"
              style={{ padding: 24,
                borderLeft: `4px solid ${m.is_active
                  ? 'var(--green)' : 'var(--text-dim)'}` }}>

              <div style={{ display: 'flex', justifyContent: 'space-between',
                alignItems: 'flex-start', marginBottom: 12 }}>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 17 }}>{m.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)', marginTop: 3 }}>
                    ID:{' '}
                    <span className="mono" style={{ color: 'var(--blue)' }}>
                      ivr_menu_{m.id}
                    </span>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <span style={{
                    fontSize: 11, padding: '3px 10px', borderRadius: 20,
                    fontWeight: 700,
                    background: m.is_active
                      ? 'rgba(63,185,80,.12)' : 'rgba(139,148,158,.1)',
                    color: m.is_active ? 'var(--green)' : 'var(--text-dim)',
                    border: `1px solid ${m.is_active
                      ? 'rgba(63,185,80,.3)' : 'var(--border)'}`,
                  }}>
                    {m.is_active ? ' Aktif' : ' Pasif'}
                  </span>
                  <button className="btn-sm outline"
                    onClick={() => setModal(m)}>Düzenle</button>
                  <button className="btn-sm outline"
                    style={{ color: 'var(--red)',
                      borderColor: 'rgba(239,68,68,.3)' }}
                    onClick={() => handleDelete(m.id)}>Sil</button>
                </div>
              </div>

              {m.description && (
                <div style={{ fontSize: 13, color: 'var(--text-dim)',
                  marginBottom: 12 }}>
                  {m.description}
                </div>
              )}

              <div style={{
                background: 'rgba(59,109,240,.05)', padding: '10px 14px',
                borderRadius: 8, fontSize: 13, fontStyle: 'italic',
                border: '1px solid rgba(59,109,240,.1)', marginBottom: 16
              }}>
                "{m.greet_text}"
              </div>

              {m.ws_pre_calls?.length > 0 && (
                <div style={{ marginBottom:10, display:'flex', flexWrap:'wrap', gap:6 }}>
                  {m.ws_pre_calls.map((wc, i) => (
                    <span key={i} style={{ fontSize:11, padding:'2px 8px', borderRadius:6,
                      background:'rgba(99,102,241,0.12)', color:'#6366f1', fontWeight:600 }}>
                      {services.find(s => s.id === wc.service_id)?.name || `Servis #${wc.service_id}`}
                    </span>
                  ))}
                </div>
              )}

              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {m.options.map(opt => (
                  <div key={opt.id} style={{
                    background: 'var(--surface2)', padding: '6px 12px',
                    borderRadius: 8, fontSize: 12,
                    border: '1px solid var(--border)',
                    display: 'flex', alignItems: 'center', gap: 6
                  }}>
                    <span className="mono" style={{
                      fontWeight: 600, fontSize: 14,
                      background: 'var(--accent-dim)',
                      padding: '2px 7px', borderRadius: 4,
                      border: '1px solid var(--border)'
                    }}>
                      {opt.digit}
                    </span>
                    <span style={{ color: 'var(--text-dim)' }}>→</span>
                    <span style={{ fontWeight: 600, color: 'var(--text)' }}>
                      {optionLabel(opt)}
                    </span>
                  </div>
                ))}
                {m.options.length === 0 && (
                  <span style={{ fontSize: 12, color: 'var(--amber)' }}>
                    Tuşlama seçeneği eklenmemiş
                  </span>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {modal && (
        <IVRModal
          menu={modal === 'new' ? null : modal}
          onClose={() => setModal(null)}
          onSave={() => {
            setModal(null);
            reload();
            toast('IVR Menüsü kaydedildi ve FreeSWITCH güncellendi.', 'success');
          }}
        />
      )}
    </div>
  );
}

window.IVRTab = IVRTab;
