/* SettingsTab.jsx — Tenant Ayarları: API Keys + Kullanım & Limitler */
const { useState, useEffect, useCallback } = React;

function SettingsTab() {
  const user = Auth.getUser();
  const isAdmin = user && (user.role === 'admin' || user.role === 'super_admin');

  /* ── State ── */
  const [keys, setKeys] = useState(null);
  const [usage, setUsage] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState(null); // { type, text }
  const [editKeys, setEditKeys] = useState({}); // Only changed fields
  const [visibleFields, setVisibleFields] = useState({});

  /* ── Load ── */
  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [kRes, uRes] = await Promise.all([
        authFetch(API + '/api/tenant/api-keys'),
        authFetch(API + '/api/tenant/usage'),
      ]);
      if (kRes.ok) setKeys(await kRes.json());
      if (uRes.ok) setUsage(await uRes.json());
    } catch (e) {
      console.error('Settings load error:', e);
    }
    setLoading(false);
  }, []);

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

  /* ── Save API Keys ── */
  const saveKeys = async () => {
    if (!Object.keys(editKeys).length) return;
    setSaving(true);
    setMsg(null);
    try {
      const r = await authFetch(API + '/api/tenant/api-keys', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(editKeys),
      });
      if (r.ok) {
        setKeys(await r.json());
        setEditKeys({});
        setMsg({ type: 'success', text: 'API anahtarları güncellendi.' });
      } else {
        const err = await r.json().catch(() => ({}));
        setMsg({ type: 'error', text: err.detail || 'Kaydetme başarısız.' });
      }
    } catch (e) {
      setMsg({ type: 'error', text: 'Bağlantı hatası.' });
    }
    setSaving(false);
  };

  /* ── Helpers ── */
  const handleKeyChange = (field, value) => {
    setEditKeys(prev => ({ ...prev, [field]: value }));
  };

  const toggleVisible = (field) => {
    setVisibleFields(prev => ({ ...prev, [field]: !prev[field] }));
  };

  const usagePercent = (u) => {
    if (!u || !u.limit) return 0;
    return Math.min(100, Math.round((u.current / u.limit) * 100));
  };

  const usageBarClass = (pct) => {
    if (pct >= 90) return 'danger';
    if (pct >= 70) return 'warn';
    return '';
  };

  /* ── Loading ── */
  if (loading) {
    return (
      <div className="no-data">
        <p>Ayarlar yükleniyor…</p>
      </div>
    );
  }

  /* ── Render ── */
  const keyField = (label, field, placeholder) => {
    const masked = keys ? keys[field] : '';
    const editing = field in editKeys;
    const val = editing ? editKeys[field] : (masked || '');
    const isSecret = field.includes('key');

    return (
      <div className="form-group" style={{ marginBottom: 14 }}>
        <label className="form-label">{label}</label>
        <div className={isSecret ? 'input-with-toggle' : ''}>
          <input
            type={isSecret && !visibleFields[field] ? 'password' : 'text'}
            className="form-input"
            placeholder={placeholder}
            value={val}
            onChange={e =>handleKeyChange(field, e.target.value)}
            readOnly={!isAdmin}
          />
          {isSecret && (
            <button
              type="button"
              className="input-toggle-btn"
              onClick={() =>toggleVisible(field)}
              title={visibleFields[field] ? 'Gizle' : 'Göster'}
            >
              {visibleFields[field] ? 'Gizle' : 'Göster'}
            </button>
          )}
        </div>
      </div>
    );
  };

  const usageRow = (label, u) => {
    if (!u) return null;
    const pct = usagePercent(u);
    return (
      <div style={{ marginBottom: 16 }}>
        <div className="usage-row" style={{ borderBottom: 'none', paddingBottom: 4 }}>
          <span className="usage-label">{label}</span>
          <span className="usage-value">{u.current} / {u.limit}</span>
        </div>
        <div className="usage-bar">
          <div
            className={`usage-bar-fill ${usageBarClass(pct)}`}
            style={{ width: pct + '%' }}
          />
        </div>
      </div>
    );
  };

  return (
    <div className="fade-in">
      {/* Message banner */}
      {msg && (
        <div style={{
          padding: '12px 18px',
          marginBottom: 20,
          borderRadius: 'var(--radius-sm)',
          background: msg.type === 'success' ? 'rgba(34,197,94,.08)' : 'rgba(239,68,68,.08)',
          border: `1px solid ${msg.type === 'success' ? 'rgba(34,197,94,.2)' : 'rgba(239,68,68,.2)'}`,
          color: msg.type === 'success' ? 'var(--green)' : 'var(--red)',
          fontSize: 14,
          fontWeight: 600,
        }}>
          {msg.text}
        </div>
      )}

      <div className="settings-grid">
        {/* ── API Keys ── */}
        <div className="settings-section">
          <div className="settings-section-title">API Anahtarları</div>

          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 13, fontWeight:600, color: 'var(--blue)', marginBottom: 10 }}>
              Azure Speech
            </div>
            {keyField('Speech Key', 'azure_speech_key', 'Azure Speech API Key')}
            {keyField('Speech Region', 'azure_speech_region', 'eastus')}
          </div>

          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 13, fontWeight:600, color: 'var(--green)', marginBottom: 10 }}>
              Azure OpenAI
            </div>
            {keyField('Endpoint', 'azure_openai_endpoint', 'https://xxx.openai.azure.com/')}
            {keyField('API Key', 'azure_openai_key', 'Azure OpenAI Key')}
            {keyField('Deployment', 'azure_openai_deploy', 'gpt-4o')}
            {keyField('Embedding Deployment', 'azure_openai_embed_deploy', 'text-embedding-3-small')}
            {keyField('API Version', 'azure_openai_api_version', '2025-01-01-preview')}
          </div>

          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 13, fontWeight:600, color: 'var(--purple)', marginBottom: 10 }}>
              ElevenLabs / MiniMax TTS
            </div>
            {keyField('ElevenLabs Key', 'elevenlabs_key', 'ElevenLabs API Key')}
            {keyField('MiniMax Key', 'minimax_key', 'MiniMax API Key')}
            {keyField('MiniMax Group ID', 'minimax_group_id', 'MiniMax Group ID')}
          </div>

          {isAdmin && (
            <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
              <button
                className="btn primary"
                onClick={saveKeys}
                disabled={saving || !Object.keys(editKeys).length}
              >
                {saving ? 'Kaydediliyor…' : 'Kaydet'}
              </button>
              {Object.keys(editKeys).length > 0 && (
                <button className="btn outline" onClick={() =>setEditKeys({})}>
                  İptal
                </button>
              )}
            </div>
          )}
        </div>

        {/* ── Usage & Limits ── */}
        <div className="settings-section">
          <div className="settings-section-title">Kullanım & Limitler</div>

          {usage && (
            <>
              <div style={{ marginBottom: 20 }}>
                <span className={`plan-badge ${usage.plan === 'enterprise' ? 'enterprise' : ''}`}>
                  {usage.plan?.toUpperCase() || 'STARTER'}
                </span>
              </div>

              {usageRow('AI Agent', usage.agents)}
              {usageRow('İnsan Agent', usage.human_agents)}
              {usageRow('Kampanya', usage.campaigns)}
              {usageRow('Kuyruk', usage.queues)}
            </>
          )}

          {!usage && (
            <div className="no-data">
              <p>Kullanım bilgisi yüklenemedi.</p>
            </div>
          )}
        </div>
      </div>

      {/* ── Departman Yonetimi ── */}
      {isAdmin && <DepartmentManager />}

      {/* ── Sonuc Kodlari Yonetimi ── */}
      {isAdmin && <DispositionManager />}
    </div>
  );
}


/* ═══════════════════════════════════════════════════════════════════════════
   DepartmentManager — Departman Yönetimi
   ═══════════════════════════════════════════════════════════════════════════ */
function DepartmentManager() {
  const [depts, setDepts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState({ key: '', label: '', sort_order: 0 });
  const [msg, setMsg] = useState(null);

  const loadDepts = async () => {
    try {
      const r = await authFetch(API + '/api/departments');
      if (r.ok) setDepts(await r.json());
    } catch (e) {}
    setLoading(false);
  };

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

  const seedDefaults = async () => {
    try {
      const r = await authFetch(API + '/api/departments/seed', { method: 'POST' });
      const data = await r.json();
      setMsg({ type: 'success', text: data.message || 'Varsayilan departmanlar yuklendi' });
      loadDepts();
    } catch (e) {
      setMsg({ type: 'error', text: 'Hata' });
    }
  };

  const handleSave = async () => {
    if (!form.key || !form.label) return;
    try {
      const url = editingId
        ? API + `/api/departments/${editingId}`
        : API + '/api/departments';
      const method = editingId ? 'PUT' : 'POST';
      const r = await authFetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (r.ok) {
        setMsg({ type: 'success', text: editingId ? 'Guncellendi' : 'Eklendi' });
        setShowForm(false);
        setEditingId(null);
        setForm({ key: '', label: '', sort_order: 0 });
        loadDepts();
      } else {
        const err = await r.json().catch(() => ({}));
        setMsg({ type: 'error', text: err.detail || 'Hata' });
      }
    } catch (e) {
      setMsg({ type: 'error', text: 'Baglanti hatasi' });
    }
  };

  const handleEdit = (d) => {
    setEditingId(d.id);
    setForm({ key: d.key, label: d.label, sort_order: d.sort_order || 0 });
    setShowForm(true);
  };

  const handleDelete = async (id) => {
    if (!confirm('Bu departmani silmek istiyor musunuz?')) return;
    try {
      const r = await authFetch(API + `/api/departments/${id}`, { method: 'DELETE' });
      if (r.ok) {
        setMsg({ type: 'success', text: 'Silindi' });
        loadDepts();
      } else {
        const err = await r.json().catch(() => ({}));
        setMsg({ type: 'error', text: err.detail || 'Silinemedi' });
      }
    } catch (e) {}
  };

  const handleToggle = async (d) => {
    try {
      await authFetch(API + `/api/departments/${d.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: !d.is_active }),
      });
      loadDepts();
    } catch (e) {}
  };

  return (
    <div style={{ marginTop: 24 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div style={{ fontSize: 16, fontWeight: 600 }}>Departmanlar</div>
        <div style={{ display: 'flex', gap: 8 }}>
          {depts.length === 0 && (
            <button className="btn outline" onClick={seedDefaults} style={{ fontSize: 12 }}>
              Varsayilanlari Yukle
            </button>
          )}
          <button className="btn primary" onClick={() => {
            setEditingId(null);
            setForm({ key: '', label: '', sort_order: 0 });
            setShowForm(true);
          }} style={{ fontSize: 12 }}>
            + Yeni Departman
          </button>
        </div>
      </div>

      {msg && (
        <div style={{
          padding: '8px 14px', marginBottom: 12, borderRadius: 8,
          background: msg.type === 'success' ? 'rgba(34,197,94,.08)' : 'rgba(239,68,68,.08)',
          border: `1px solid ${msg.type === 'success' ? 'rgba(34,197,94,.2)' : 'rgba(239,68,68,.2)'}`,
          color: msg.type === 'success' ? 'var(--green)' : 'var(--red)',
          fontSize: 12, fontWeight: 600,
        }}>
          {msg.text}
        </div>
      )}

      {showForm && (
        <div style={{
          background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 12,
          padding: 16, marginBottom: 16,
        }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>
            {editingId ? 'Departman Duzenle' : 'Yeni Departman'}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 80px', gap: 10, marginBottom: 14 }}>
            <div>
              <label style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 600 }}>Kod (benzersiz)</label>
              <input className="form-input" value={form.key} onChange={e => setForm({ ...form, key: e.target.value })}
                placeholder="orn: support" style={{ fontSize: 12, marginTop: 4 }} />
            </div>
            <div>
              <label style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 600 }}>Etiket</label>
              <input className="form-input" value={form.label} onChange={e => setForm({ ...form, label: e.target.value })}
                placeholder="orn: Destek" style={{ fontSize: 12, marginTop: 4 }} />
            </div>
            <div>
              <label style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 600 }}>Sira</label>
              <input type="number" className="form-input" value={form.sort_order}
                onChange={e => setForm({ ...form, sort_order: parseInt(e.target.value) || 0 })}
                style={{ fontSize: 12, marginTop: 4 }} />
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button className="btn outline" onClick={() => { setShowForm(false); setEditingId(null); }} style={{ fontSize: 12 }}>Iptal</button>
            <button className="btn primary" onClick={handleSave} disabled={!form.key || !form.label} style={{ fontSize: 12 }}>
              {editingId ? 'Guncelle' : 'Ekle'}
            </button>
          </div>
        </div>
      )}

      {loading ? (
        <div className="no-data"><p>Yukleniyor...</p></div>
      ) : depts.length === 0 ? (
        <div className="no-data" style={{ padding: 30 }}>
          <p>Henuz departman tanimlanmamis.</p>
          <p style={{ fontSize: 12, color: 'var(--text-dim)' }}>
            "Varsayilanlari Yukle" ile standart departmanlari ekleyebilir veya kendiniz tanimlayabilirsiniz.
          </p>
        </div>
      ) : (
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--border)' }}>
                {['Kod', 'Etiket', 'Sira', 'Durum', ''].map((h, i) => (
                  <th key={i} style={{ textAlign: 'left', padding: '8px 12px', color: 'var(--text-dim)', fontWeight: 600, fontSize: 11 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {depts.map(d => (
                <tr key={d.id} style={{ borderBottom: '1px solid var(--border)22', opacity: d.is_active ? 1 : 0.5 }}>
                  <td style={{ padding: '8px 12px', fontFamily: 'monospace', fontSize: 12 }}>{d.key}</td>
                  <td style={{ padding: '8px 12px', fontWeight: 600 }}>{d.label}</td>
                  <td style={{ padding: '8px 12px', fontSize: 12, color: 'var(--text-dim)' }}>{d.sort_order}</td>
                  <td style={{ padding: '8px 12px' }}>
                    <button onClick={() => handleToggle(d)} style={{
                      padding: '2px 10px', borderRadius: 8, fontSize: 10, fontWeight: 600, border: 'none', cursor: 'pointer',
                      background: d.is_active ? 'rgba(34,197,94,.1)' : 'rgba(239,68,68,.1)',
                      color: d.is_active ? 'var(--green)' : 'var(--red)',
                    }}>
                      {d.is_active ? 'Aktif' : 'Pasif'}
                    </button>
                  </td>
                  <td style={{ padding: '8px 12px', textAlign: 'right' }}>
                    <button onClick={() => handleEdit(d)} style={{
                      padding: '4px 10px', borderRadius: 6, fontSize: 11, border: '1px solid var(--border)',
                      background: 'var(--surface2)', color: 'var(--text)', cursor: 'pointer', marginRight: 4,
                    }}>Duzenle</button>
                    <button onClick={() => handleDelete(d.id)} style={{
                      padding: '4px 10px', borderRadius: 6, fontSize: 11, border: '1px solid rgba(239,68,68,.2)',
                      background: 'rgba(239,68,68,.05)', color: 'var(--red)', cursor: 'pointer',
                    }}>Sil</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}


/* ═══════════════════════════════════════════════════════════════════════════
   DispositionManager — Sonuc Kodu Yonetim Paneli
   ═══════════════════════════════════════════════════════════════════════════ */
function DispositionManager() {
  const [codes, setCodes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState({ code: '', label: '', color: '#9ca3af', icon: '', category: 'general', sort_order: 0 });
  const [msg, setMsg] = useState(null);

  const loadCodes = async () => {
    try {
      const r = await authFetch(API + '/api/dispositions?active_only=false');
      if (r.ok) setCodes(await r.json());
    } catch (e) {}
    setLoading(false);
  };

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

  const seedDefaults = async () => {
    try {
      const r = await authFetch(API + '/api/dispositions/seed', { method: 'POST' });
      const data = await r.json();
      setMsg({ type: 'success', text: data.message || 'Varsayilan kodlar yuklendi' });
      loadCodes();
    } catch (e) {
      setMsg({ type: 'error', text: 'Hata' });
    }
  };

  const handleSave = async () => {
    if (!form.code || !form.label) return;
    try {
      const url = editingId
        ? API + `/api/dispositions/${editingId}`
        : API + '/api/dispositions';
      const method = editingId ? 'PUT' : 'POST';
      const r = await authFetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      if (r.ok) {
        setMsg({ type: 'success', text: editingId ? 'Guncellendi' : 'Eklendi' });
        setShowForm(false);
        setEditingId(null);
        setForm({ code: '', label: '', color: '#9ca3af', icon: '', category: 'general', sort_order: 0 });
        loadCodes();
      } else {
        const err = await r.json().catch(() => ({}));
        setMsg({ type: 'error', text: err.detail || 'Hata' });
      }
    } catch (e) {
      setMsg({ type: 'error', text: 'Baglanti hatasi' });
    }
  };

  const handleEdit = (c) => {
    setEditingId(c.id);
    setForm({ code: c.code, label: c.label, color: c.color || '#9ca3af', icon: c.icon || '', category: c.category || 'general', sort_order: c.sort_order || 0 });
    setShowForm(true);
  };

  const handleDelete = async (id) => {
    if (!confirm('Bu sonuc kodunu silmek istiyor musunuz?')) return;
    try {
      const r = await authFetch(API + `/api/dispositions/${id}`, { method: 'DELETE' });
      if (r.ok) {
        setMsg({ type: 'success', text: 'Silindi' });
        loadCodes();
      } else {
        const err = await r.json().catch(() => ({}));
        setMsg({ type: 'error', text: err.detail || 'Silinemedi' });
      }
    } catch (e) {}
  };

  const handleToggle = async (c) => {
    try {
      await authFetch(API + `/api/dispositions/${c.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: !c.is_active }),
      });
      loadCodes();
    } catch (e) {}
  };

  const categoryLabel = (cat) => {
    return { general: 'Genel', dialer: 'Dialer', inbound: 'Inbound' }[cat] || cat;
  };

  const categoryColor = (cat) => {
    return { general: '#6366f1', dialer: '#f59e0b', inbound: '#3b82f6' }[cat] || '#9ca3af';
  };

  return (
    <div style={{ marginTop: 24 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <div style={{ fontSize: 16, fontWeight:600 }}>Sonuc Kodlari</div>
        <div style={{ display: 'flex', gap: 8 }}>
          {codes.length === 0 && (
            <button className="btn outline" onClick={seedDefaults} style={{ fontSize: 12 }}>
              Varsayilanlari Yukle
            </button>
          )}
          <button className="btn primary" onClick={() => {
            setEditingId(null);
            setForm({ code: '', label: '', color: '#9ca3af', icon: '', category: 'general', sort_order: 0 });
            setShowForm(true);
          }} style={{ fontSize: 12 }}>
            + Yeni Kod
          </button>
        </div>
      </div>

      {msg && (
        <div style={{
          padding: '8px 14px', marginBottom: 12, borderRadius: 8,
          background: msg.type === 'success' ? 'rgba(34,197,94,.08)' : 'rgba(239,68,68,.08)',
          border: `1px solid ${msg.type === 'success' ? 'rgba(34,197,94,.2)' : 'rgba(239,68,68,.2)'}`,
          color: msg.type === 'success' ? 'var(--green)' : 'var(--red)',
          fontSize: 12, fontWeight: 600,
        }}>
          {msg.text}
        </div>
      )}

      {/* Yeni/Duzenle formu */}
      {showForm && (
        <div style={{
          background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 12,
          padding: 16, marginBottom: 16,
        }}>
          <div style={{ fontSize: 14, fontWeight:600, marginBottom: 12 }}>
            {editingId ? 'Sonuc Kodu Duzenle' : 'Yeni Sonuc Kodu'}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginBottom: 12 }}>
            <div>
              <label style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 600 }}>Kod (unique)</label>
              <input className="form-input" value={form.code} onChange={e =>setForm({ ...form, code: e.target.value })}
                placeholder="orn: sale" style={{ fontSize: 12, marginTop: 4 }} disabled={editingId && codes.find(c =>c.id === editingId)?.is_system} />
            </div>
            <div>
              <label style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 600 }}>Etiket</label>
              <input className="form-input" value={form.label} onChange={e =>setForm({ ...form, label: e.target.value })}
                placeholder="orn: Satis" style={{ fontSize: 12, marginTop: 4 }} />
            </div>
            <div>
              <label style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 600 }}>Ikon</label>
              <input className="form-input" value={form.icon} onChange={e =>setForm({ ...form, icon: e.target.value })}
                placeholder="orn: " style={{ fontSize: 12, marginTop: 4 }} />
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '100px 1fr 80px', gap: 10, marginBottom: 14 }}>
            <div>
              <label style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 600 }}>Renk</label>
              <input type="color" value={form.color} onChange={e =>setForm({ ...form, color: e.target.value })}
                style={{ width: '100%', height: 34, border: '1px solid var(--border)', borderRadius: 6, marginTop: 4, cursor: 'pointer' }} />
            </div>
            <div>
              <label style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 600 }}>Kategori</label>
              <select className="form-input" value={form.category} onChange={e =>setForm({ ...form, category: e.target.value })}
                style={{ fontSize: 12, marginTop: 4 }}>
                <option value="general">Genel (Hepsi)</option>
                <option value="dialer">Dialer</option>
                <option value="inbound">Inbound</option>
              </select>
            </div>
            <div>
              <label style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 600 }}>Sira</label>
              <input type="number" className="form-input" value={form.sort_order}
                onChange={e =>setForm({ ...form, sort_order: parseInt(e.target.value) || 0 })}
                style={{ fontSize: 12, marginTop: 4 }} />
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button className="btn outline" onClick={() => { setShowForm(false); setEditingId(null); }} style={{ fontSize: 12 }}>Iptal</button>
            <button className="btn primary" onClick={handleSave} disabled={!form.code || !form.label} style={{ fontSize: 12 }}>
              {editingId ? 'Guncelle' : 'Ekle'}
            </button>
          </div>
        </div>
      )}

      {/* Kod listesi */}
      {loading ? (
        <div className="no-data"><p>Yukleniyor...</p></div>
      ) : codes.length === 0 ? (
        <div className="no-data" style={{ padding: 30 }}>
          <p>Henuz sonuc kodu tanimlanmamis.</p>
          <p style={{ fontSize: 12, color: 'var(--text-dim)' }}>
            "Varsayilanlari Yukle" butonuna tiklayarak standart kodlari ekleyebilirsiniz.
          </p>
        </div>
      ) : (
        <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 12, overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--border)' }}>
                {['', 'Kod', 'Etiket', 'Kategori', 'Durum', ''].map((h, i) => (
                  <th key={i} style={{ textAlign: 'left', padding: '8px 12px', color: 'var(--text-dim)', fontWeight: 600, fontSize: 11 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {codes.map(c => (
                <tr key={c.id} style={{ borderBottom: '1px solid var(--border)22', opacity: c.is_active ? 1 : 0.5 }}>
                  <td style={{ padding: '8px 12px', width: 40 }}>
                    <span style={{
                      display: 'inline-block', width: 24, height: 24, borderRadius: 6,
                      background: c.color || '#9ca3af', textAlign: 'center', lineHeight: '24px', fontSize: 14,
                    }}>{c.icon || ''}</span>
                  </td>
                  <td style={{ padding: '8px 12px', fontFamily: 'monospace', fontSize: 12 }}>{c.code}</td>
                  <td style={{ padding: '8px 12px', fontWeight: 600 }}>{c.label}</td>
                  <td style={{ padding: '8px 12px' }}>
                    <span style={{
                      padding: '2px 8px', borderRadius: 8, fontSize: 10, fontWeight:600,
                      background: categoryColor(c.category) + '15', color: categoryColor(c.category),
                    }}>{categoryLabel(c.category)}</span>
                  </td>
                  <td style={{ padding: '8px 12px' }}>
                    <button onClick={() =>handleToggle(c)} style={{
                      padding: '2px 10px', borderRadius: 8, fontSize: 10, fontWeight:600, border: 'none', cursor: 'pointer',
                      background: c.is_active ? 'rgba(34,197,94,.1)' : 'rgba(239,68,68,.1)',
                      color: c.is_active ? 'var(--green)' : 'var(--red)',
                    }}>
                      {c.is_active ? 'Aktif' : 'Pasif'}
                    </button>
                  </td>
                  <td style={{ padding: '8px 12px', textAlign: 'right' }}>
                    <button onClick={() =>handleEdit(c)} style={{
                      padding: '4px 10px', borderRadius: 6, fontSize: 11, border: '1px solid var(--border)',
                      background: 'var(--surface2)', color: 'var(--text)', cursor: 'pointer', marginRight: 4,
                    }}>Duzenle</button>
                    {!c.is_system && (
                      <button onClick={() =>handleDelete(c.id)} style={{
                        padding: '4px 10px', borderRadius: 6, fontSize: 11, border: '1px solid rgba(239,68,68,.2)',
                        background: 'rgba(239,68,68,.05)', color: 'var(--red)', cursor: 'pointer',
                      }}>Sil</button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}


window.SettingsTab = SettingsTab;
