// ═══════════════════════════════════════════════════════════════
// RoutingTab.jsx — AI Akıllı Yönlendirme
// Gelen çağrıları müşteri geçmişine göre AI ile yönlendirin
// ═══════════════════════════════════════════════════════════════
const { useState, useEffect, useCallback } = React;

// ── Koşul Şablonları ─────────────────────────────────────────
const CONDITION_TEMPLATES = [
  { key: 'customer_identified', label: 'Müşteri tanınıyor', type: 'bool' },
  { key: 'tags_include_any', label: 'Etiket içerir (herhangi biri)', type: 'tags' },
  { key: 'tags_include_all', label: 'Etiket içerir (hepsi)', type: 'tags' },
  { key: 'tags_exclude', label: 'Etiket içermez', type: 'tags' },
  { key: 'call_count_min', label: 'Min. çağrı sayısı', type: 'number' },
  { key: 'call_count_max', label: 'Max. çağrı sayısı', type: 'number' },
  { key: 'last_disposition_in', label: 'Son çağrı sonucu', type: 'tags' },
  { key: 'is_blacklist', label: 'Kara listede', type: 'bool' },
  { key: 'time_range', label: 'Saat aralığı', type: 'time_range' },
  { key: 'weekdays', label: 'Hafta günleri', type: 'weekdays' },
];

const ACTION_TYPES = [
  { value: 'route_queue', label: 'Kuyruğa Yönlendir', icon: '' },
  { value: 'route_ai_agent', label: 'AI Agent\'a Yönlendir', icon: '' },
  { value: 'route_ivr', label: 'IVR Menüye Yönlendir', icon: '' },
  { value: 'set_priority', label: 'Öncelik Ayarla', icon: '⬆' },
  { value: 'reject', label: 'Çağrıyı Reddet', icon: '' },
  { value: 'continue', label: 'Varsayılan Devam', icon: '▶' },
];

const WEEKDAY_NAMES = ['Pzt', 'Sal', 'Çar', 'Per', 'Cum', 'Cmt', 'Paz'];

// ═══════════════════════════════════════════════════════════════
// Koşul Editörü
// ═══════════════════════════════════════════════════════════════
function ConditionEditor({ conditions, onChange }) {
  const conds = conditions || {};

  const setValue = (key, val) => {
    const next = { ...conds, [key]: val };
    if (val === null || val === undefined || val === '' || (Array.isArray(val) && val.length === 0)) {
      delete next[key];
    }
    onChange(next);
  };

  const addCondition = (key) => {
    const tpl = CONDITION_TEMPLATES.find(t =>t.key === key);
    if (!tpl) return;
    const defaults = { bool: true, tags: [], number: 1, time_range: { start: '09:00', end: '18:00' }, weekdays: [1,2,3,4,5] };
    setValue(key, defaults[tpl.type]);
  };

  const removeCondition = (key) => {
    const next = { ...conds };
    delete next[key];
    onChange(next);
  };

  const activeKeys = Object.keys(conds);
  const availableKeys = CONDITION_TEMPLATES.filter(t => !activeKeys.includes(t.key));

  return (
    <div>
      {activeKeys.map(key => {
        const tpl = CONDITION_TEMPLATES.find(t =>t.key === key);
        if (!tpl) return null;
        return (
          <div key={key} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8, background: 'var(--surface2)', padding: '8px 12px', borderRadius: 8 }}>
            <span style={{ fontSize: 13, fontWeight:600, minWidth: 180 }}>{tpl.label}</span>
            <div style={{ flex: 1 }}>
              {tpl.type === 'bool' && (
                <select className="form-select" style={{ width: 120 }} value={conds[key] ? 'true' : 'false'} onChange={e =>setValue(key, e.target.value === 'true')}>
                  <option value="true">Evet</option>
                  <option value="false">Hayır</option>
                </select>
              )}
              {tpl.type === 'number' && (
                <input type="number" className="form-input" style={{ width: 100 }} value={conds[key] || ''} onChange={e =>setValue(key, parseInt(e.target.value) || 0)} />
              )}
              {tpl.type === 'tags' && (
                <input className="form-input" placeholder="VIP, Premium (virgülle ayırın)" value={(conds[key] || []).join(', ')} onChange={e =>setValue(key, e.target.value.split(',').map(s =>s.trim()).filter(Boolean))} />
              )}
              {tpl.type === 'time_range' && (
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <input type="time" className="form-input" style={{ width: 120 }} value={conds[key]?.start || '09:00'} onChange={e =>setValue(key, { ...conds[key], start: e.target.value })} />
                  <span>—</span>
                  <input type="time" className="form-input" style={{ width: 120 }} value={conds[key]?.end || '18:00'} onChange={e =>setValue(key, { ...conds[key], end: e.target.value })} />
                </div>
              )}
              {tpl.type === 'weekdays' && (
                <div style={{ display: 'flex', gap: 4 }}>
                  {WEEKDAY_NAMES.map((name, i) => {
                    const day = i + 1;
                    const active = (conds[key] || []).includes(day);
                    return (
                      <button key={day} className={`btn btn-sm ${active ? 'primary' : 'outline'}`}
                        style={{ minWidth: 36, padding: '4px 6px', fontSize: 11 }}
                        onClick={() => {
                          const current = conds[key] || [];
                          setValue(key, active ? current.filter(d =>d !== day) : [...current, day].sort());
                        }}>{name}</button>
                    );
                  })}
                </div>
              )}
            </div>
            <button className="btn btn-sm outline" style={{ color: 'var(--red)', padding: '4px 8px' }} onClick={() =>removeCondition(key)} title="Koşulu kaldır">X</button>
          </div>
        );
      })}

      {availableKeys.length > 0 && (
        <select className="form-select" style={{ width: 'auto', marginTop: 8 }} value="" onChange={e => { if (e.target.value) addCondition(e.target.value); e.target.value = ''; }}>
          <option value="">+ Koşul Ekle</option>
          {availableKeys.map(t => <option key={t.key} value={t.key}>{t.label}</option>)}
        </select>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// Kural Düzenleme Modalı
// ═══════════════════════════════════════════════════════════════
function RuleModal({ rule, targets, onClose, onSave }) {
  const empty = { name: '', description: '', priority: 10, is_active: true, conditions: {}, action_type: 'route_queue', target_id: null, priority_boost: 1, welcome_override: '', ai_hint: '' };
  const [form, setForm] = useState(rule ? { ...empty, ...rule } : empty);
  const [saving, setSaving] = useState(false);

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

  const handleSave = async () => {
    if (!form.name) { alert('Kural adını girin'); return; }
    setSaving(true);
    onSave(form);
    setSaving(false);
  };

  const targetOptions = () => {
    switch (form.action_type) {
      case 'route_queue': return (targets.queues || []).map(q => ({ id: q.id, label: `${q.name} (${q.extension})` }));
      case 'route_ai_agent': return (targets.ai_agents || []).map(a => ({ id: a.id, label: `${a.name} (${a.department || '-'})` }));
      case 'route_ivr': return (targets.ivr_menus || []).map(m => ({ id: m.id, label: m.name }));
      default: return [];
    }
  };

  const needsTarget = ['route_queue', 'route_ai_agent', 'route_ivr'].includes(form.action_type);

  return (
    <div className="overlay" onClick={onClose}>
      <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 700 }}>
        <div className="modal-header">
          <span>{rule ? 'Kuralı Düzenle' : 'Yeni Kural'}</span>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>
        <div className="modal-body" style={{ maxHeight: '70vh', overflowY: 'auto' }}>
          {/* Temel Bilgiler */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div className="form-group">
              <label className="form-label">Kural Adı *</label>
              <input className="form-input" value={form.name} onChange={e =>set('name', e.target.value)} placeholder="VIP Öncelikli Yönlendirme" />
            </div>
            <div className="form-group">
              <label className="form-label">Öncelik (yüksek = önce)</label>
              <input type="number" className="form-input" value={form.priority} onChange={e =>set('priority', parseInt(e.target.value) || 0)} />
            </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 kural ne zaman uygulanır?" />
          </div>

          {/* Koşullar */}
          <div style={{ background: 'var(--surface2)', padding: 16, borderRadius: 12, marginTop: 16 }}>
            <div style={{ fontSize: 14, fontWeight:600, marginBottom: 12 }}>Koşullar</div>
            <p style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 12 }}>AI bu koşulları müşteri verisiyle karşılaştırarak kararını verir. Boş bırakılırsa kural her zaman geçerlidir.</p>
            <ConditionEditor conditions={form.conditions} onChange={v =>set('conditions', v)} />
          </div>

          {/* Aksiyon */}
          <div style={{ background: 'var(--surface2)', padding: 16, borderRadius: 12, marginTop: 16 }}>
            <div style={{ fontSize: 14, fontWeight:600, marginBottom: 12 }}>Aksiyon</div>
            <div style={{ display: 'grid', gridTemplateColumns: needsTarget ? '1fr 1fr' : '1fr', gap: 16 }}>
              <div className="form-group">
                <label className="form-label">Aksiyon Tipi</label>
                <select className="form-select" value={form.action_type} onChange={e => { set('action_type', e.target.value); set('target_id', null); }}>
                  {ACTION_TYPES.map(a => <option key={a.value} value={a.value}>{a.icon} {a.label}</option>)}
                </select>
              </div>
              {needsTarget && (
                <div className="form-group">
                  <label className="form-label">Hedef</label>
                  <select className="form-select" value={form.target_id || ''} onChange={e =>set('target_id', parseInt(e.target.value) || null)}>
                    <option value="">-- Seçin --</option>
                    {targetOptions().map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
                  </select>
                </div>
              )}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 12 }}>
              <div className="form-group">
                <label className="form-label">Kuyruk Önceliği (1-5)</label>
                <select className="form-select" value={form.priority_boost} onChange={e =>set('priority_boost', parseInt(e.target.value))}>
                  <option value={1}>1 — Normal</option>
                  <option value={2}>2 — Yüksek</option>
                  <option value={3}>3 — Acil</option>
                  <option value={4}>4 — Kritik</option>
                  <option value={5}>5 — En Yüksek</option>
                </select>
              </div>
              <div className="form-group">
                <label className="form-label">Durum</label>
                <select className="form-select" value={form.is_active ? 'true' : 'false'} onChange={e =>set('is_active', e.target.value === 'true')}>
                  <option value="true">Aktif</option>
                  <option value="false">Pasif</option>
                </select>
              </div>
            </div>
          </div>

          {/* Özelleştirme */}
          <div style={{ background: 'var(--surface2)', padding: 16, borderRadius: 12, marginTop: 16 }}>
            <div style={{ fontSize: 14, fontWeight:600, marginBottom: 12 }}>Özelleştirme</div>
            <div className="form-group">
              <label className="form-label">Özel Karşılama Mesajı</label>
              <input className="form-input" value={form.welcome_override || ''} onChange={e =>set('welcome_override', e.target.value)} placeholder="Değerli VIP müşterimiz, sizi öncelikli hatta yönlendiriyoruz." />
            </div>
            <div className="form-group">
              <label className="form-label">AI Talimatı</label>
              <textarea className="form-textarea" rows={2} value={form.ai_hint} onChange={e =>set('ai_hint', e.target.value)} placeholder="Bu müşteriye öncelikli hizmet ver, mümkünse aynı temsilciye yönlendir." />
            </div>
          </div>
        </div>
        <div className="modal-footer">
          <button className="btn outline" onClick={onClose}>İptal</button>
          <button className="btn primary" onClick={handleSave} disabled={saving}>{saving ? 'Kaydediliyor...' : 'Kaydet'}</button>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// Config Düzenleme Modalı (AI Prompt + Ayarlar)
// ═══════════════════════════════════════════════════════════════
function ConfigModal({ config, queues, agents, onClose, onSave }) {
  const empty = { name: '', description: '', ai_prompt: '', fallback_queue_id: null, fallback_ai_agent_id: null, ai_timeout_ms: 3000, routing_enabled: true, is_active: true };
  const [form, setForm] = useState(config ? { ...empty, ...config } : empty);
  const [saving, setSaving] = useState(false);

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

  const handleSave = async () => {
    if (!form.name) { alert('Profil adını girin'); return; }
    setSaving(true);
    try {
      const url = config ? `/api/routing/configs/${config.id}` : '/api/routing/configs';
      const method = config ? 'PUT' : 'POST';
      const r = await authFetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) });
      if (r.ok) { onSave(); }
      else { const err = await r.json(); alert('Hata: ' + JSON.stringify(err)); }
    } finally { setSaving(false); }
  };

  return (
    <div className="overlay" onClick={onClose}>
      <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 750 }}>
        <div className="modal-header">
          <span>{config ? 'Profili Düzenle' : 'Yeni Routing Profili'}</span>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>
        <div className="modal-body" style={{ maxHeight: '70vh', overflowY: 'auto' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div className="form-group">
              <label className="form-label">Profil Adı *</label>
              <input className="form-input" value={form.name} onChange={e =>set('name', e.target.value)} placeholder="Ana Yönlendirme Profili" />
            </div>
            <div className="form-group">
              <label className="form-label">AI Zaman Aşımı (ms)</label>
              <input type="number" className="form-input" value={form.ai_timeout_ms} onChange={e =>set('ai_timeout_ms', parseInt(e.target.value) || 3000)} />
            </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)} />
          </div>

          {/* AI Prompt */}
          <div style={{ background: 'var(--surface2)', padding: 16, borderRadius: 12, marginTop: 16 }}>
            <div style={{ fontSize: 14, fontWeight:600, marginBottom: 8 }}>AI Yönlendirme Prompt'u</div>
            <p style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 8 }}>Yapay zekanın çağrıları nasıl yönlendireceğini belirleyen talimat. Boş bırakılırsa varsayılan prompt kullanılır.</p>
            <textarea className="form-textarea" rows={10} value={form.ai_prompt} onChange={e =>set('ai_prompt', e.target.value)}
              placeholder="Sen bir çağrı yönlendirme uzmanısın. Gelen çağrıyı müşteri bilgilerine göre en uygun hedefe yönlendirmelisin..." style={{ fontFamily: 'var(--mono)', fontSize: 12 }} />
          </div>

          {/* Fallback Ayarları */}
          <div style={{ background: 'var(--surface2)', padding: 16, borderRadius: 12, marginTop: 16 }}>
            <div style={{ fontSize: 14, fontWeight:600, marginBottom: 12 }}>Fallback Ayarları</div>
            <p style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 12 }}>AI karar veremezse veya zaman aşımına uğrarsa çağrı nereye yönlendirilsin?</p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div className="form-group">
                <label className="form-label">Fallback Kuyruk</label>
                <select className="form-select" value={form.fallback_queue_id || ''} onChange={e =>set('fallback_queue_id', parseInt(e.target.value) || null)}>
                  <option value="">-- Yok --</option>
                  {(queues || []).map(q => <option key={q.id} value={q.id}>{q.name} ({q.extension})</option>)}
                </select>
              </div>
              <div className="form-group">
                <label className="form-label">Fallback AI Agent</label>
                <select className="form-select" value={form.fallback_ai_agent_id || ''} onChange={e =>set('fallback_ai_agent_id', parseInt(e.target.value) || null)}>
                  <option value="">-- Yok --</option>
                  {(agents || []).map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
                </select>
              </div>
            </div>
          </div>

          {/* Durum */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }}>
            <div className="form-group">
              <label className="form-label">Routing Motoru</label>
              <select className="form-select" value={form.routing_enabled ? 'true' : 'false'} onChange={e =>set('routing_enabled', e.target.value === 'true')}>
                <option value="true">Aktif</option>
                <option value="false">Pasif (Klasik IVR akışı)</option>
              </select>
            </div>
            <div className="form-group">
              <label className="form-label">Profil Durumu</label>
              <select className="form-select" value={form.is_active ? 'true' : 'false'} onChange={e =>set('is_active', e.target.value === 'true')}>
                <option value="true">Aktif</option>
                <option value="false">Pasif</option>
              </select>
            </div>
          </div>
        </div>
        <div className="modal-footer">
          <button className="btn outline" onClick={onClose}>İptal</button>
          <button className="btn primary" onClick={handleSave} disabled={saving}>{saving ? 'Kaydediliyor...' : 'Kaydet'}</button>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// Test Modalı — Routing kararını test et
// ═══════════════════════════════════════════════════════════════
function TestModal({ onClose }) {
  const [phone, setPhone] = useState('');
  const [testing, setTesting] = useState(false);
  const [result, setResult] = useState(null);

  const handleTest = async () => {
    if (!phone) { alert('Telefon numarası girin'); return; }
    setTesting(true);
    setResult(null);
    try {
      const r = await authFetch('/api/routing/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone }),
      });
      if (r.ok) setResult(await r.json());
      else alert('Test hatası');
    } finally { setTesting(false); }
  };

  const actionLabel = (action) => {
    const a = ACTION_TYPES.find(t =>t.value === action);
    return a ? `${a.icon} ${a.label}` : action;
  };

  return (
    <div className="overlay" onClick={onClose}>
      <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 550 }}>
        <div className="modal-header">
          <span>Routing Testi</span>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <p style={{ fontSize: 13, color: 'var(--text-dim)', marginBottom: 16 }}>Bir telefon numarası girerek AI routing kararını test edin. Gerçek transfer yapılmaz.</p>
          <div style={{ display: 'flex', gap: 12 }}>
            <input className="form-input" value={phone} onChange={e =>setPhone(e.target.value)} placeholder="05321234567" style={{ flex: 1 }} onKeyDown={e =>e.key === 'Enter' && handleTest()} />
            <button className="btn primary" onClick={handleTest} disabled={testing}>{testing ? 'Test ediliyor...' : 'Test Et'}</button>
          </div>

          {result && (
            <div style={{ marginTop: 20, background: 'var(--surface2)', padding: 16, borderRadius: 12 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
                <div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight:600 }}>MÜŞTERI</div>
                  <div style={{ fontSize: 15, fontWeight:600, marginTop: 4 }}>
                    {result.customer_found ? `${result.customer_name || 'Adsız'}` : 'Tanınmıyor'}
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight:600 }}>ÇAĞRI GEÇMİŞİ</div>
                  <div style={{ fontSize: 15, fontWeight:600, marginTop: 4 }}>{result.call_count} çağrı</div>
                </div>
              </div>

              <div style={{ borderTop: '1px solid var(--border)', paddingTop: 16 }}>
                <div style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight:600, marginBottom: 8 }}>AI KARARI</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
                  <span className="badge" style={{ background: result.decision.action === 'reject' ? 'var(--red)' : result.decision.action === 'continue' ? 'var(--blue)' : 'var(--green)', color: '#fff', fontSize: 13, padding: '6px 12px' }}>
                    {actionLabel(result.decision.action)}
                  </span>
                  {result.decision.target_id && <span style={{ fontSize: 13 }}>Hedef ID: {result.decision.target_id}</span>}
                  <span className="badge" style={{ background: 'var(--amber)', color: '#fff' }}>Öncelik: {result.decision.priority}</span>
                </div>
                <div style={{ fontSize: 13, marginBottom: 8 }}>
                  <strong>Gerekçe:</strong> {result.decision.reason}
                </div>
                {result.decision.matched_rules && result.decision.matched_rules.length > 0 && (
                  <div style={{ fontSize: 13, marginBottom: 8 }}>
                    <strong>Eşleşen Kurallar:</strong> {result.decision.matched_rules.join(', ')}
                  </div>
                )}
                {result.decision.welcome_override && (
                  <div style={{ fontSize: 13, marginBottom: 8 }}>
                    <strong>Karşılama:</strong> "{result.decision.welcome_override}"
                  </div>
                )}
                <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>
                  Güven: %{Math.round((result.decision.confidence || 0) * 100)}
                </div>
              </div>
            </div>
          )}
        </div>
        <div className="modal-footer">
          <button className="btn outline" onClick={onClose}>Kapat</button>
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// Karar Logları Paneli
// ═══════════════════════════════════════════════════════════════
function LogsPanel() {
  const [logs, setLogs] = useState([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const r = await authFetch(`/api/routing/logs?page=${page}&per_page=15`);
      if (r.ok) { const d = await r.json(); setLogs(d.items); setTotal(d.total); }
    } finally { setLoading(false); }
  }, [page]);

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

  const actionBadge = (action) => {
    const colors = { route_queue: 'var(--green)', route_ai_agent: 'var(--blue)', route_ivr: 'var(--purple)', reject: 'var(--red)', continue: 'var(--text-dim)' };
    return (
      <span className="badge" style={{ background: colors[action] || 'var(--text-dim)', color: '#fff', fontSize: 11 }}>
        {action}
      </span>
    );
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <div style={{ fontSize: 14, fontWeight:600 }}>Routing Karar Logları ({total})</div>
        <button className="btn btn-sm outline" onClick={load} disabled={loading}>{loading ? '...' : 'Yenile'}</button>
      </div>

      {logs.length === 0 ? (
        <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-dim)' }}>Henüz karar logu yok</div>
      ) : (
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', fontSize: 13, borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ borderBottom: '2px solid var(--border)', textAlign: 'left' }}>
                <th style={{ padding: '8px 12px' }}>Zaman</th>
                <th style={{ padding: '8px 12px' }}>Telefon</th>
                <th style={{ padding: '8px 12px' }}>Müşteri</th>
                <th style={{ padding: '8px 12px' }}>Karar</th>
                <th style={{ padding: '8px 12px' }}>Hedef</th>
                <th style={{ padding: '8px 12px' }}>Öncelik</th>
                <th style={{ padding: '8px 12px' }}>Gerekçe</th>
                <th style={{ padding: '8px 12px' }}>Güven</th>
              </tr>
            </thead>
            <tbody>
              {logs.map(log => (
                <tr key={log.id} style={{ borderBottom: '1px solid var(--border)' }}>
                  <td style={{ padding: '8px 12px', whiteSpace: 'nowrap' }}>{fmtDate(log.created_at)}</td>
                  <td style={{ padding: '8px 12px', fontFamily: 'var(--mono)' }}>{log.phone}</td>
                  <td style={{ padding: '8px 12px' }}>{log.customer_name || '—'}</td>
                  <td style={{ padding: '8px 12px' }}>{actionBadge(log.action)}</td>
                  <td style={{ padding: '8px 12px' }}>{log.target_id || '—'}</td>
                  <td style={{ padding: '8px 12px' }}>{log.priority}</td>
                  <td style={{ padding: '8px 12px', maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={log.reason}>{log.reason || '—'}</td>
                  <td style={{ padding: '8px 12px' }}>%{Math.round((log.confidence || 0) * 100)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {total > 15 && (
        <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginTop: 12 }}>
          <button className="btn btn-sm outline" disabled={page <= 1} onClick={() =>setPage(p =>p - 1)}>Önceki</button>
          <span style={{ padding: '6px 12px', fontSize: 13 }}>Sayfa {page}/{Math.ceil(total / 15)}</span>
          <button className="btn btn-sm outline" disabled={page >= Math.ceil(total / 15)} onClick={() =>setPage(p =>p + 1)}>Sonraki</button>
        </div>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// ANA TAB BİLEŞENİ
// ═══════════════════════════════════════════════════════════════
function RoutingTab({ toast }) {
  const [configs, setConfigs] = useState([]);
  const [selectedConfig, setSelectedConfig] = useState(null);
  const [rules, setRules] = useState([]);
  const [targets, setTargets] = useState({});
  const [configModal, setConfigModal] = useState(null);
  const [ruleModal, setRuleModal] = useState(null);
  const [testModal, setTestModal] = useState(false);
  const [activeView, setActiveView] = useState('rules'); // 'rules' | 'logs'
  const [loading, setLoading] = useState(true);

  // Hedefleri yükle (kuyruk, agent, IVR)
  useEffect(() => {
    authFetch('/api/routing/targets').then(r =>r.ok ? r.json() : {}).then(setTargets).catch(() => {});
  }, []);

  // Config listesini yükle
  const loadConfigs = useCallback(async () => {
    setLoading(true);
    try {
      const r = await authFetch('/api/routing/configs');
      if (r.ok) {
        const data = await r.json();
        setConfigs(data);
        if (data.length > 0 && !selectedConfig) setSelectedConfig(data[0]);
        else if (selectedConfig) {
          const updated = data.find(c =>c.id === selectedConfig.id);
          if (updated) setSelectedConfig(updated);
        }
      }
    } finally { setLoading(false); }
  }, []);

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

  // Kuralları yükle
  const loadRules = useCallback(async () => {
    if (!selectedConfig) { setRules([]); return; }
    const r = await authFetch(`/api/routing/configs/${selectedConfig.id}/rules`);
    if (r.ok) setRules(await r.json());
  }, [selectedConfig?.id]);

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

  // Config sil
  const deleteConfig = async (id) => {
    if (!confirm('Bu routing profilini ve tüm kurallarını silmek istediğinize emin misiniz?')) return;
    await authFetch(`/api/routing/configs/${id}`, { method: 'DELETE' });
    toast('Profil silindi', 'success');
    setSelectedConfig(null);
    loadConfigs();
  };

  // Kural kaydet (create/update)
  const saveRule = async (form) => {
    const isEdit = !!form.id;
    const url = isEdit ? `/api/routing/rules/${form.id}` : `/api/routing/configs/${selectedConfig.id}/rules`;
    const method = isEdit ? 'PUT' : 'POST';
    const r = await authFetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) });
    if (r.ok) {
      setRuleModal(null);
      loadRules();
      toast(isEdit ? 'Kural güncellendi' : 'Kural eklendi', 'success');
    } else { alert('Hata!'); }
  };

  // Kural sil
  const deleteRule = async (id) => {
    if (!confirm('Bu kuralı silmek istediğinize emin misiniz?')) return;
    await authFetch(`/api/routing/rules/${id}`, { method: 'DELETE' });
    toast('Kural silindi', 'success');
    loadRules();
  };

  // Kural toggle
  const toggleRule = async (rule) => {
    await authFetch(`/api/routing/rules/${rule.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ is_active: !rule.is_active }),
    });
    loadRules();
  };

  const actionIcon = (type) => {
    const a = ACTION_TYPES.find(t =>t.value === type);
    return a ? a.icon : '?';
  };

  const actionLabel = (type) => {
    const a = ACTION_TYPES.find(t =>t.value === type);
    return a ? a.label : type;
  };

  const targetLabel = (rule) => {
    if (!rule.target_id) return '';
    if (rule.action_type === 'route_queue') {
      const q = (targets.queues || []).find(q =>q.id === rule.target_id);
      return q ? `→ ${q.name}` : `→ ID:${rule.target_id}`;
    }
    if (rule.action_type === 'route_ai_agent') {
      const a = (targets.ai_agents || []).find(a =>a.id === rule.target_id);
      return a ? `→ ${a.name}` : `→ ID:${rule.target_id}`;
    }
    if (rule.action_type === 'route_ivr') {
      const m = (targets.ivr_menus || []).find(m =>m.id === rule.target_id);
      return m ? `→ ${m.name}` : `→ ID:${rule.target_id}`;
    }
    return '';
  };

  const conditionSummary = (conditions) => {
    if (!conditions || Object.keys(conditions).length === 0) return 'Her zaman';
    const parts = [];
    if (conditions.customer_identified !== undefined) parts.push(conditions.customer_identified ? 'Tanınan müşteri' : 'Tanınmayan müşteri');
    if (conditions.tags_include_any?.length) parts.push(`Etiket: ${conditions.tags_include_any.join(', ')}`);
    if (conditions.tags_exclude?.length) parts.push(`Hariç: ${conditions.tags_exclude.join(', ')}`);
    if (conditions.call_count_min) parts.push(`Min ${conditions.call_count_min} çağrı`);
    if (conditions.last_disposition_in?.length) parts.push(`Son sonuç: ${conditions.last_disposition_in.join(', ')}`);
    if (conditions.is_blacklist) parts.push('Kara liste');
    if (conditions.time_range) parts.push(`${conditions.time_range.start}-${conditions.time_range.end}`);
    if (conditions.weekdays?.length && conditions.weekdays.length < 7) parts.push(`${conditions.weekdays.map(d =>WEEKDAY_NAMES[d-1]).join(',')}`);
    return parts.join(' + ') || 'Her zaman';
  };

  return (
    <div className="fade-in">
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 24 }}>
        <div>
          <h2 style={{ fontSize: 24, fontWeight:600, margin: 0 }}>AI Akıllı Yönlendirme</h2>
          <p style={{ fontSize: 14, color: 'var(--text-dim)', marginTop: 6 }}>Gelen çağrıları müşteri geçmişine göre yapay zeka ile yönlendirin</p>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn outline" onClick={() =>setTestModal(true)}>Test Et</button>
          <button className="btn primary" onClick={() =>setConfigModal('new')}>+ Yeni Profil</button>
        </div>
      </div>

      {/* Config seçici */}
      {configs.length > 0 && (
        <div style={{ display: 'flex', gap: 12, marginBottom: 20, flexWrap: 'wrap' }}>
          {configs.map(c => (
            <button key={c.id}
              className={`btn ${selectedConfig?.id === c.id ? 'primary' : 'outline'}`}
              style={{ position: 'relative' }}
              onClick={() =>setSelectedConfig(c)}>
              {c.routing_enabled ? '' : ''} {c.name}
              <span style={{ fontSize: 11, marginLeft: 6, opacity: 0.7 }}>({c.rules_count} kural)</span>
            </button>
          ))}
        </div>
      )}

      {/* Boş durum */}
      {configs.length === 0 && !loading && (
        <div className="panel" style={{ textAlign: 'center', padding: 80 }}>
          <div style={{ fontSize: 18, fontWeight:600, marginBottom: 8 }}>Henüz Routing Profili yok</div>
          <p style={{ color: 'var(--text-dim)', marginBottom: 20 }}>AI yönlendirme kuralları tanımlayarak gelen çağrıları akıllıca yönlendirin.</p>
          <button className="btn primary" onClick={() =>setConfigModal('new')}>+ İlk Profili Oluştur</button>
        </div>
      )}

      {/* Seçili config detayı */}
      {selectedConfig && (
        <div>
          {/* Config bilgi kartı */}
          <div className="panel" style={{ padding: 20, marginBottom: 20 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: 16, fontWeight:600 }}>
                  {selectedConfig.routing_enabled ? '' : ''} {selectedConfig.name}
                </div>
                {selectedConfig.description && <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 4 }}>{selectedConfig.description}</div>}
                <div style={{ display: 'flex', gap: 16, marginTop: 8, fontSize: 12, color: 'var(--text-dim)' }}>
                  <span>AI Timeout: {selectedConfig.ai_timeout_ms}ms</span>
                  <span>Kurallar: {rules.length}</span>
                  {selectedConfig.fallback_queue_id && <span>Fallback Kuyruk: #{selectedConfig.fallback_queue_id}</span>}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                <button className="btn btn-sm outline" onClick={() =>setConfigModal(selectedConfig)}>Düzenle</button>
                <button className="btn btn-sm outline" style={{ color: 'var(--red)' }} onClick={() =>deleteConfig(selectedConfig.id)}>Sil</button>
              </div>
            </div>
          </div>

          {/* Tab: Kurallar / Loglar */}
          <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
            <button className={`btn btn-sm ${activeView === 'rules' ? 'primary' : 'outline'}`} onClick={() =>setActiveView('rules')}>Kurallar ({rules.length})</button>
            <button className={`btn btn-sm ${activeView === 'logs' ? 'primary' : 'outline'}`} onClick={() =>setActiveView('logs')}>Karar Logları</button>
          </div>

          {activeView === 'rules' && (
            <div>
              {/* Kural listesi */}
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 12 }}>
                <button className="btn btn-sm primary" onClick={() =>setRuleModal('new')}>+ Yeni Kural</button>
              </div>

              {rules.length === 0 ? (
                <div className="panel" style={{ textAlign: 'center', padding: 40, color: 'var(--text-dim)' }}>
                  Henüz kural tanımlı değil. Yeni bir kural ekleyin.
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {rules.map((rule, idx) => (
                    <div key={rule.id} className="panel" style={{ padding: 16, opacity: rule.is_active ? 1 : 0.5, borderLeft: `4px solid ${rule.is_active ? 'var(--green)' : 'var(--border)'}` }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <div style={{ flex: 1 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <span style={{ fontSize: 11, fontWeight:600, color: 'var(--text-dim)', minWidth: 24 }}>#{rule.priority}</span>
                            <span style={{ fontSize: 15, fontWeight:600 }}>{rule.name}</span>
                            {!rule.is_active && <span className="badge" style={{ background: 'var(--text-dim)', color: '#fff', fontSize: 10 }}>Pasif</span>}
                          </div>
                          {rule.description && <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2, marginLeft: 32 }}>{rule.description}</div>}
                          <div style={{ display: 'flex', gap: 12, marginTop: 8, marginLeft: 32, fontSize: 12 }}>
                            <span style={{ background: 'var(--surface2)', padding: '3px 8px', borderRadius: 6 }}>
                               {conditionSummary(rule.conditions)}
                            </span>
                            <span style={{ background: 'var(--surface2)', padding: '3px 8px', borderRadius: 6 }}>
                              {actionIcon(rule.action_type)} {actionLabel(rule.action_type)} {targetLabel(rule)}
                            </span>
                            {rule.priority_boost > 1 && (
                              <span style={{ background: 'var(--amber)', color: '#fff', padding: '3px 8px', borderRadius: 6 }}>
                                Öncelik: {rule.priority_boost}
                              </span>
                            )}
                          </div>
                        </div>
                        <div style={{ display: 'flex', gap: 6 }}>
                          <button className="btn btn-sm outline" onClick={() =>toggleRule(rule)} title={rule.is_active ? 'Pasife Al' : 'Aktif Et'}>
                            {rule.is_active ? '' : '▶'}
                          </button>
                          <button className="btn btn-sm outline" onClick={() =>setRuleModal(rule)}>Düzenle</button>
                          <button className="btn btn-sm outline" style={{ color: 'var(--red)' }} onClick={() =>deleteRule(rule.id)}>Sil</button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {activeView === 'logs' && (
            <div className="panel" style={{ padding: 20 }}>
              <LogsPanel />
            </div>
          )}
        </div>
      )}

      {/* Modaller */}
      {configModal && (
        <ConfigModal
          config={configModal === 'new' ? null : configModal}
          queues={targets.queues || []}
          agents={targets.ai_agents || []}
          onClose={() =>setConfigModal(null)}
          onSave={() => { setConfigModal(null); loadConfigs(); toast('Profil kaydedildi', 'success'); }}
        />
      )}

      {ruleModal && (
        <RuleModal
          rule={ruleModal === 'new' ? null : ruleModal}
          targets={targets}
          onClose={() =>setRuleModal(null)}
          onSave={saveRule}
        />
      )}

      {testModal && <TestModal onClose={() =>setTestModal(false)} />}
    </div>
  );
}

window.RoutingTab = RoutingTab;
