// CustomersTab.jsx — Müşteri Kartları (Customer CRM) UI
// Exported as window.CustomersTab

(function () {
  const { useState, useEffect, useCallback, useRef } = React;

  /* ── Format helpers ─────────────────────────────────────────────────────── */
  // Backend naive UTC döndüğü için parseUTC ile yerel saate çevirilir.
  function formatTR(iso) {
    return fmtDateTime(iso, {
      day: '2-digit', month: '2-digit', year: 'numeric',
      hour: '2-digit', minute: '2-digit',
    });
  }

  function formatDuration(seconds) {
    if (!seconds && seconds !== 0) return '—';
    const m = Math.floor(seconds / 60);
    const s = Math.floor(seconds % 60);
    if (m === 0) return `${s}sn`;
    return `${m}dk ${s}sn`;
  }

  function formatDate(iso) {
    return fmtDateOnly(iso);
  }

  /* ── Tag badges ─────────────────────────────────────────────────────────── */
  const TAG_COLORS = [
    { bg: '#1e3a5f', border: '#3b82f6', text: '#93c5fd' },
    { bg: '#064e3b', border: '#10b981', text: '#6ee7b7' },
    { bg: '#4a1942', border: '#a855f7', text: '#d8b4fe' },
    { bg: '#451a03', border: '#f59e0b', text: '#fcd34d' },
    { bg: '#3b0764', border: '#8b5cf6', text: '#c4b5fd' },
    { bg: '#0f172a', border: '#64748b', text: '#94a3b8' },
  ];

  function tagColor(tag) {
    let h = 0;
    for (let i = 0; i < tag.length; i++) h = (h * 31 + tag.charCodeAt(i)) & 0xffffffff;
    return TAG_COLORS[Math.abs(h) % TAG_COLORS.length];
  }

  function TagBadge({ tag }) {
    const c = tagColor(tag);
    return (
      <span style={{
        display: 'inline-block',
        background: c.bg,
        border: `1px solid ${c.border}`,
        color: c.text,
        borderRadius: 20,
        padding: '2px 9px',
        fontSize: 11,
        fontWeight: 600,
        whiteSpace: 'nowrap',
      }}>
        {tag}
      </span>
    );
  }

  function BlacklistBadge() {
    return (
      <span style={{
        display: 'inline-block',
        background: '#7f1d1d20',
        border: '1px solid #ef4444',
        color: '#f87171',
        borderRadius: 20,
        padding: '2px 9px',
        fontSize: 11,
        fontWeight:600,
        whiteSpace: 'nowrap',
      }}>
        Kara Liste
      </span>
    );
  }

  function StatusBadge({ status }) {
    const map = {
      completed: { bg: '#064e3b20', border: '#10b981', text: '#34d399', label: 'Tamamlandı' },
      missed: { bg: '#7f1d1d20', border: '#ef4444', text: '#f87171', label: 'Cevapsız' },
      failed: { bg: '#7f1d1d20', border: '#ef4444', text: '#f87171', label: 'Başarısız' },
      answered: { bg: '#064e3b20', border: '#10b981', text: '#34d399', label: 'Yanıtlandı' },
      busy: { bg: '#451a0320', border: '#f59e0b', text: '#fcd34d', label: 'Meşgul' },
      voicemail: { bg: '#1e3a5f20', border: '#3b82f6', text: '#93c5fd', label: 'Sesli Mesaj' },
    };
    const s = map[status] || { bg: '#1f293720', border: '#6b7280', text: '#9ca3af', label: status || '—' };
    return (
      <span style={{
        display: 'inline-block',
        background: s.bg,
        border: `1px solid ${s.border}`,
        color: s.text,
        borderRadius: 20,
        padding: '2px 9px',
        fontSize: 11,
        fontWeight: 600,
        whiteSpace: 'nowrap',
      }}>
        {s.label}
      </span>
    );
  }

  /* ── Stat Card ──────────────────────────────────────────────────────────── */
  function StatCard({ label, value, color, icon }) {
    return (
      <div style={{
        background: 'var(--surface)',
        border: '1px solid var(--border)',
        borderRadius: 14,
        padding: '16px 22px',
        display: 'flex',
        alignItems: 'center',
        gap: 14,
        minWidth: 160,
        flex: '1 1 160px',
      }}>
        {icon && <div style={{
          width: 42, height: 42, borderRadius: 12,
          background: color + '18',
          border: `1px solid ${color}30`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 20, flexShrink: 0,
        }}>
          {icon}
        </div>}
        <div>
          <div style={{ fontSize: 22, fontWeight:600, color: 'var(--text)', lineHeight: 1.1 }}>{value ?? '—'}</div>
          <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2, fontWeight: 500 }}>{label}</div>
        </div>
      </div>
    );
  }

  /* ── Confirm Delete Modal ───────────────────────────────────────────────── */
  function ConfirmDeleteModal({ customer, onConfirm, onCancel }) {
    return (
      <div className="overlay" onClick={onCancel} style={{ zIndex: 1100 }}>
        <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 420, width: '90vw', padding: 0 }}>
          <div className="modal-header" style={{ padding: '20px 24px 16px' }}>
            <span style={{ fontWeight:600, fontSize: 17, color: 'var(--text)' }}>Müşteriyi Sil</span>
            <button className="close-btn" onClick={onCancel}>×</button>
          </div>
          <div style={{ padding: '0 24px 24px' }}>
            <p style={{ color: 'var(--text-dim)', fontSize: 14, marginBottom: 20, lineHeight: 1.6 }}>
              <strong style={{ color: 'var(--text)' }}>{customer.name || customer.phone}</strong>adlı müşteriyi kalıcı olarak silmek istediğinizden emin misiniz? Bu işlem geri alınamaz.
            </p>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
              <button className="btn outline" onClick={onCancel}>İptal</button>
              <button
                className="btn"
                onClick={onConfirm}
                style={{ background: 'var(--red)', color: '#fff', border: 'none' }}
              >
                Sil
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ── New Customer Modal ─────────────────────────────────────────────────── */
  function NewCustomerModal({ onClose, onSaved, toast }) {
    const [form, setForm] = useState({ phone: '', name: '', company: '', email: '', tags: '' });
    const [saving, setSaving] = useState(false);
    const set = (k, v) =>setForm(f => ({ ...f, [k]: v }));

    async function handleSave() {
      if (!form.phone.trim()) {
        toast('Hata', 'Telefon numarası zorunludur.', 'error');
        return;
      }
      setSaving(true);
      try {
        const payload = {
          phone: form.phone.trim(),
          name: form.name.trim(),
          company: form.company.trim(),
          email: form.email.trim(),
          tags: form.tags ? form.tags.split(',').map(t =>t.trim()).filter(Boolean) : [],
        };
        const r = await authFetch('/api/customers', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        if (r.ok) {
          toast('Başarılı', 'Müşteri oluşturuldu.', 'success');
          onSaved();
        } else {
          const e = await r.json().catch(() => ({}));
          toast('Hata', e.error || e.message || 'Müşteri oluşturulamadı.', 'error');
        }
      } finally {
        setSaving(false);
      }
    }

    return (
      <div className="overlay" onClick={onClose} style={{ zIndex: 1100 }}>
        <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 500, width: '92vw', padding: 0 }}>
          <div className="modal-header" style={{ padding: '20px 24px 16px' }}>
            <span style={{ fontWeight:600, fontSize: 18, color: 'var(--text)' }}>Yeni Müşteri Ekle</span>
            <button className="close-btn" onClick={onClose}>×</button>
          </div>
          <div className="modal-body" style={{ padding: '0 24px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div className="form-group">
              <label className="form-label">Telefon Numarası <span style={{ color: 'var(--red)' }}>*</span></label>
              <input
                className="form-input"
                value={form.phone}
                onChange={e =>set('phone', e.target.value)}
                placeholder="+90 5XX XXX XX XX"
                autoFocus
              />
            </div>
            <div className="form-group">
              <label className="form-label">Ad Soyad</label>
              <input className="form-input" value={form.name} onChange={e =>set('name', e.target.value)} placeholder="Müşteri adı" />
            </div>
            <div className="form-group">
              <label className="form-label">Şirket</label>
              <input className="form-input" value={form.company} onChange={e =>set('company', e.target.value)} placeholder="Şirket adı" />
            </div>
            <div className="form-group">
              <label className="form-label">E-posta</label>
              <input className="form-input" type="email" value={form.email} onChange={e =>set('email', e.target.value)} placeholder="ornek@sirket.com" />
            </div>
            <div className="form-group">
              <label className="form-label">Etiketler <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>(virgülle ayırın)</span></label>
              <input className="form-input" value={form.tags} onChange={e =>set('tags', e.target.value)} placeholder="vip, kurumsal, aktif" />
            </div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 6 }}>
              <button className="btn outline" onClick={onClose} disabled={saving}>İptal</button>
              <button
                className="btn btn-primary"
                onClick={handleSave}
                disabled={saving}
                style={{ minWidth: 100 }}
              >
                {saving ? 'Kaydediliyor...' : 'Kaydet'}
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ── Customer Detail/Edit Modal ─────────────────────────────────────────── */
  function CustomerDetailModal({ customerId, initialTab, onClose, onSaved, toast }) {
    const [activeTab, setActiveTab] = useState(initialTab || 'info');
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [calls, setCalls] = useState([]);
    const [callsLoading, setCallsLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [noteText, setNoteText] = useState('');
    const [addingNote, setAddingNote] = useState(false);

    // Edit form state
    const [form, setForm] = useState(null);
    const setField = (k, v) =>setForm(f => ({ ...f, [k]: v }));

    useEffect(() => {
      loadCustomer();
    }, [customerId]);

    useEffect(() => {
      if (activeTab === 'calls' && calls.length === 0 && data) {
        loadCalls();
      }
    }, [activeTab, data]);

    async function loadCustomer() {
      setLoading(true);
      try {
        const r = await authFetch(`/api/customers/lookup?phone=${encodeURIComponent('')}&id=${customerId}`);
        // fallback: try direct GET if lookup by id not supported
        const r2 = await authFetch(`/api/customers/${customerId}`);
        if (r2.ok) {
          const d = await r2.json();
          setData(d);
          setForm({
            name: d.name || '',
            company: d.company || '',
            email: d.email || '',
            tags: (d.tags || []).join(', '),
            notes: d.notes || '',
            is_blacklist: !!d.is_blacklist,
          });
        } else if (r.ok) {
          const d = await r.json();
          const c = d.customer || d;
          setData(c);
          setForm({
            name: c.name || '',
            company: c.company || '',
            email: c.email || '',
            tags: (c.tags || []).join(', '),
            notes: c.notes || '',
            is_blacklist: !!c.is_blacklist,
          });
        }
      } finally {
        setLoading(false);
      }
    }

    async function loadCalls() {
      setCallsLoading(true);
      try {
        const r = await authFetch(`/api/customers/${customerId}/calls`);
        if (r.ok) {
          const d = await r.json();
          setCalls(Array.isArray(d) ? d : (d.items || d.calls || []));
        }
      } finally {
        setCallsLoading(false);
      }
    }

    async function handleSave() {
      setSaving(true);
      try {
        const payload = {
          name: form.name.trim(),
          company: form.company.trim(),
          email: form.email.trim(),
          tags: form.tags ? form.tags.split(',').map(t =>t.trim()).filter(Boolean) : [],
          notes: form.notes,
          is_blacklist: form.is_blacklist,
        };
        const r = await authFetch(`/api/customers/${customerId}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        if (r.ok) {
          toast('Başarılı', 'Müşteri bilgileri güncellendi.', 'success');
          onSaved();
          loadCustomer();
        } else {
          const e = await r.json().catch(() => ({}));
          toast('Hata', e.error || e.message || 'Güncelleme başarısız.', 'error');
        }
      } finally {
        setSaving(false);
      }
    }

    async function handleAddNote() {
      if (!noteText.trim()) return;
      setAddingNote(true);
      try {
        const r = await authFetch(`/api/customers/${customerId}/notes`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ note: noteText.trim() }),
        });
        if (r.ok) {
          toast('Başarılı', 'Not eklendi.', 'success');
          setNoteText('');
          loadCustomer();
        } else {
          const e = await r.json().catch(() => ({}));
          toast('Hata', e.error || e.message || 'Not eklenemedi.', 'error');
        }
      } finally {
        setAddingNote(false);
      }
    }

    const TABS = [
      { key: 'info', label: 'Bilgiler' },
      { key: 'calls', label: 'Çağrı Geçmişi' },
      { key: 'notes', label: 'Notlar' },
    ];

    const tabStyle = (key) => ({
      padding: '9px 18px',
      fontSize: 13,
      fontWeight: 600,
      border: 'none',
      borderBottom: activeTab === key ? '2px solid var(--blue)' : '2px solid transparent',
      background: 'transparent',
      color: activeTab === key ? 'var(--blue)' : 'var(--text-dim)',
      cursor: 'pointer',
      transition: 'color .15s, border-color .15s',
    });

    return (
      <div className="overlay" onClick={onClose} style={{ zIndex: 1100, alignItems: 'flex-start', paddingTop: 40, paddingBottom: 40, overflowY: 'auto' }}>
        <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 720, width: '94vw', padding: 0, margin: 'auto' }}>
          {/* Header */}
          <div className="modal-header" style={{ padding: '20px 24px 0', borderBottom: 'none' }}>
            <div style={{ flex: 1 }}>
              {loading || !data ? (
                <div style={{ fontWeight:600, fontSize: 18, color: 'var(--text)' }}>Yükleniyor...</div>
              ) : (
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span style={{ fontWeight:600, fontSize: 18, color: 'var(--text)' }}>
                      {data.name || '(İsimsiz Müşteri)'}
                    </span>
                    {data.is_blacklist && <BlacklistBadge />}
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 2, fontFamily: 'var(--mono, monospace)' }}>
                    {data.phone}
                  </div>
                </div>
              )}
            </div>
            <button className="close-btn" onClick={onClose}>×</button>
          </div>

          {/* Tab bar */}
          <div style={{ display: 'flex', borderBottom: '1px solid var(--border)', padding: '0 24px', marginTop: 8 }}>
            {TABS.map(t => (
              <button key={t.key} style={tabStyle(t.key)} onClick={() =>setActiveTab(t.key)}>
                {t.label}
              </button>
            ))}
          </div>

          {/* Tab content */}
          <div style={{ padding: '24px 24px 8px', minHeight: 320 }}>
            {loading ? (
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 200 }}>
                <div style={{ textAlign: 'center', color: 'var(--text-dim)' }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>Yükleniyor...</div>
                </div>
              </div>
            ) : (
              <>
                {/* ── INFO TAB ── */}
                {activeTab === 'info' && form && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                      <div className="form-group">
                        <label className="form-label">Ad Soyad</label>
                        <input
                          className="form-input"
                          value={form.name}
                          onChange={e =>setField('name', e.target.value)}
                          placeholder="Müşteri adı"
                        />
                      </div>
                      <div className="form-group">
                        <label className="form-label">Şirket</label>
                        <input
                          className="form-input"
                          value={form.company}
                          onChange={e =>setField('company', e.target.value)}
                          placeholder="Şirket adı"
                        />
                      </div>
                    </div>
                    <div className="form-group">
                      <label className="form-label">E-posta</label>
                      <input
                        className="form-input"
                        type="email"
                        value={form.email}
                        onChange={e =>setField('email', e.target.value)}
                        placeholder="ornek@sirket.com"
                      />
                    </div>
                    <div className="form-group">
                      <label className="form-label">Telefon</label>
                      <input
                        className="form-input"
                        value={data.phone}
                        disabled
                        style={{ opacity: 0.6, cursor: 'not-allowed' }}
                      />
                    </div>
                    <div className="form-group">
                      <label className="form-label">
                        Etiketler <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>(virgülle ayırın)</span>
                      </label>
                      <input
                        className="form-input"
                        value={form.tags}
                        onChange={e =>setField('tags', e.target.value)}
                        placeholder="vip, kurumsal, aktif"
                      />
                      {form.tags && (
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 8 }}>
                          {form.tags.split(',').map(t =>t.trim()).filter(Boolean).map(t => (
                            <TagBadge key={t} tag={t} />
                          ))}
                        </div>
                      )}
                    </div>
                    <div style={{
                      display: 'flex', alignItems: 'center', gap: 12,
                      padding: '14px 16px',
                      background: form.is_blacklist ? '#7f1d1d15' : 'var(--surface2)',
                      border: `1px solid ${form.is_blacklist ? '#ef444440' : 'var(--border)'}`,
                      borderRadius: 10,
                    }}>
                      <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', flex: 1, margin: 0 }}>
                        <input
                          type="checkbox"
                          checked={form.is_blacklist}
                          onChange={e =>setField('is_blacklist', e.target.checked)}
                          style={{ width: 16, height: 16, accentColor: 'var(--red)', cursor: 'pointer' }}
                        />
                        <span style={{ fontSize: 14, fontWeight: 600, color: form.is_blacklist ? 'var(--red)' : 'var(--text)' }}>
                          Kara Listeye Al
                        </span>
                      </label>
                      {form.is_blacklist && (
                        <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>
                          Bu müşteri kara listede — gelen/giden aramalar engellenir.
                        </span>
                      )}
                    </div>
                    <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', paddingBottom: 8, marginTop: 4 }}>
                      <button className="btn outline" onClick={onClose} disabled={saving}>İptal</button>
                      <button
                        className="btn btn-primary"
                        onClick={handleSave}
                        disabled={saving}
                        style={{ minWidth: 110 }}
                      >
                        {saving ? 'Kaydediliyor...' : 'Değişiklikleri Kaydet'}
                      </button>
                    </div>
                  </div>
                )}

                {/* ── CALLS TAB ── */}
                {activeTab === 'calls' && (
                  <div>
                    {callsLoading ? (
                      <div style={{ textAlign: 'center', padding: '40px 0', color: 'var(--text-dim)' }}>
                        <div style={{ fontSize: 13 }}>Çağrı geçmişi yükleniyor...</div>
                      </div>
                    ) : calls.length === 0 ? (
                      <div style={{ textAlign: 'center', padding: '40px 0', color: 'var(--text-dim)' }}>
                        <div style={{ fontSize: 14, fontWeight: 600 }}>Henüz çağrı kaydı yok</div>
                      </div>
                    ) : (
                      <div style={{ overflowX: 'auto' }}>
                        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                          <thead>
                            <tr style={{ borderBottom: '1px solid var(--border)' }}>
                              {['Tarih', 'Süre', 'Durum', 'Asistan', 'Disposisyon', 'Özet'].map(h => (
                                <th key={h} style={{
                                  padding: '8px 12px', textAlign: 'left',
                                  fontSize: 11, fontWeight:600,
                                  color: 'var(--text-dim)', textTransform: 'uppercase',
                                  letterSpacing: '0.05em',
                                }}>{h}</th>
                              ))}
                            </tr>
                          </thead>
                          <tbody>
                            {calls.map((call, i) => (
                              <tr key={call.id || i} style={{
                                borderBottom: '1px solid var(--border)',
                                transition: 'background .12s',
                              }}
                              onMouseEnter={e =>e.currentTarget.style.background = 'var(--surface2)'}
                              onMouseLeave={e =>e.currentTarget.style.background = ''}
                              >
                                <td style={{ padding: '10px 12px', color: 'var(--text-dim)', whiteSpace: 'nowrap' }}>
                                  {formatTR(call.start_time)}
                                </td>
                                <td style={{ padding: '10px 12px', fontFamily: 'var(--mono, monospace)', fontSize: 12 }}>
                                  {formatDuration(call.duration)}
                                </td>
                                <td style={{ padding: '10px 12px' }}>
                                  <StatusBadge status={call.status} />
                                </td>
                                <td style={{ padding: '10px 12px', color: 'var(--text-dim)' }}>
                                  {call.agent_name || '—'}
                                </td>
                                <td style={{ padding: '10px 12px' }}>
                                  {call.disposition_code ? (
                                    <span style={{
                                      display: 'inline-block',
                                      background: 'var(--surface2)',
                                      border: '1px solid var(--border)',
                                      borderRadius: 6,
                                      padding: '2px 8px',
                                      fontSize: 11,
                                      color: 'var(--text-dim)',
                                    }}>{call.disposition_code}</span>
                                  ) : '—'}
                                </td>
                                <td style={{ padding: '10px 12px', color: 'var(--text-dim)', maxWidth: 200 }}>
                                  {call.summary ? (
                                    <span style={{
                                      display: '-webkit-box',
                                      WebkitLineClamp: 2,
                                      WebkitBoxOrient: 'vertical',
                                      overflow: 'hidden',
                                      lineHeight: 1.4,
                                    }}>{call.summary}</span>
                                  ) : '—'}
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                    <div style={{ paddingBottom: 8 }} />
                  </div>
                )}

                {/* ── NOTES TAB ── */}
                {activeTab === 'notes' && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                    {/* Existing notes */}
                    <div>
                      <div style={{ fontSize: 12, fontWeight:600, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>
                        Mevcut Notlar
                      </div>
                      {data.notes ? (
                        <div style={{
                          background: 'var(--surface2)',
                          border: '1px solid var(--border)',
                          borderRadius: 10,
                          padding: '14px 16px',
                          fontSize: 13,
                          color: 'var(--text)',
                          lineHeight: 1.7,
                          whiteSpace: 'pre-wrap',
                          maxHeight: 220,
                          overflowY: 'auto',
                        }}>
                          {data.notes}
                        </div>
                      ) : (
                        <div style={{
                          padding: '20px 16px',
                          background: 'var(--surface2)',
                          border: '1px solid var(--border)',
                          borderRadius: 10,
                          color: 'var(--text-dim)',
                          fontSize: 13,
                          textAlign: 'center',
                        }}>
                          Henüz not eklenmemiş.
                        </div>
                      )}
                    </div>

                    {/* Add new note */}
                    <div>
                      <div style={{ fontSize: 12, fontWeight:600, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>
                        Yeni Not Ekle
                      </div>
                      <textarea
                        className="form-input"
                        value={noteText}
                        onChange={e =>setNoteText(e.target.value)}
                        placeholder="Not metnini buraya girin..."
                        rows={4}
                        style={{ resize: 'vertical', minHeight: 80, fontFamily: 'inherit', lineHeight: 1.5 }}
                      />
                      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 10 }}>
                        <button
                          className="btn btn-primary"
                          onClick={handleAddNote}
                          disabled={addingNote || !noteText.trim()}
                          style={{ minWidth: 110 }}
                        >
                          {addingNote ? 'Ekleniyor...' : '+ Not Ekle'}
                        </button>
                      </div>
                    </div>
                    <div style={{ paddingBottom: 4 }} />
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    );
  }

  /* ── Main CustomersTab ──────────────────────────────────────────────────── */
  function CustomersTab({ toast }) {
    const [customers, setCustomers] = useState([]);
    const [total, setTotal] = useState(0);
    const [blacklistCount, setBlacklistCount] = useState(0);
    const [page, setPage] = useState(1);
    const perPage = 20;
    const [loading, setLoading] = useState(false);

    // Filters
    const [filterPhone, setFilterPhone] = useState('');
    const [filterName, setFilterName] = useState('');
    const [filterBlacklist, setFilterBlacklist] = useState(false);

    // Modals
    const [showNewModal, setShowNewModal] = useState(false);
    const [detailCustomerId, setDetailCustomerId] = useState(null);
    const [detailInitialTab, setDetailInitialTab] = useState('info');
    const [deleteTarget, setDeleteTarget] = useState(null);

    const searchTimer = useRef(null);

    const loadCustomers = useCallback(async (p = page) => {
      setLoading(true);
      try {
        const params = new URLSearchParams({
          page: p,
          per_page: perPage,
        });
        if (filterPhone.trim()) params.set('phone', filterPhone.trim());
        if (filterName.trim()) params.set('name', filterName.trim());
        if (filterBlacklist) params.set('is_blacklist', 'true');

        const r = await authFetch(`/api/customers?${params.toString()}`);
        if (r.ok) {
          const d = await r.json();
          setCustomers(d.items || []);
          setTotal(d.total || 0);
        }
      } finally {
        setLoading(false);
      }
    }, [page, filterPhone, filterName, filterBlacklist]);

    const loadBlacklistCount = useCallback(async () => {
      try {
        const r = await authFetch('/api/customers?page=1&per_page=1&is_blacklist=true');
        if (r.ok) {
          const d = await r.json();
          setBlacklistCount(d.total || 0);
        }
      } catch { /* ignore */ }
    }, []);

    useEffect(() => {
      loadCustomers(page);
    }, [page, filterBlacklist]);

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

    // Debounced search on text inputs
    function handleSearchChange(setter, value) {
      setter(value);
      clearTimeout(searchTimer.current);
      searchTimer.current = setTimeout(() => {
        setPage(1);
        // loadCustomers will fire via effect when page resets, but page may not change
        // So trigger directly
        loadCustomersWithValues(1, filterPhone, filterName, filterBlacklist, setter === setFilterPhone ? value : null, setter === setFilterName ? value : null);
      }, 400);
    }

    const loadCustomersWithValues = useCallback(async (p, phone, name, bl, overridePhone, overrideName) => {
      setLoading(true);
      try {
        const ph = overridePhone !== null && overridePhone !== undefined ? overridePhone : phone;
        const nm = overrideName !== null && overrideName !== undefined ? overrideName : name;
        const params = new URLSearchParams({ page: p, per_page: perPage });
        if (ph.trim()) params.set('phone', ph.trim());
        if (nm.trim()) params.set('name', nm.trim());
        if (bl) params.set('is_blacklist', 'true');
        const r = await authFetch(`/api/customers?${params.toString()}`);
        if (r.ok) {
          const d = await r.json();
          setCustomers(d.items || []);
          setTotal(d.total || 0);
        }
      } finally {
        setLoading(false);
      }
    }, []);

    async function handleDelete(customer) {
      const r = await authFetch(`/api/customers/${customer.id}`, { method: 'DELETE' });
      if (r.ok) {
        toast('Silindi', `${customer.name || customer.phone} silindi.`, 'success');
        setDeleteTarget(null);
        loadBlacklistCount();
        loadCustomers(page);
      } else {
        const e = await r.json().catch(() => ({}));
        toast('Hata', e.error || e.message || 'Silinemedi.', 'error');
      }
    }

    const totalPages = Math.max(1, Math.ceil(total / perPage));

    const thStyle = {
      padding: '10px 14px',
      textAlign: 'left',
      fontSize: 11,
      fontWeight:600,
      color: 'var(--text-dim)',
      textTransform: 'uppercase',
      letterSpacing: '0.06em',
      borderBottom: '1px solid var(--border)',
      whiteSpace: 'nowrap',
    };

    const tdStyle = {
      padding: '11px 14px',
      borderBottom: '1px solid var(--border)',
      fontSize: 13,
      color: 'var(--text)',
      verticalAlign: 'middle',
    };

    return (
      <div className="fade-in" style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

        {/* ── Stats bar ── */}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
          <StatCard label="Toplam Müşteri" value={total} color="var(--blue)" />
          <StatCard label="Kara Listede" value={blacklistCount} color="var(--red)" />
        </div>

        {/* ── Search & Filter bar ── */}
        <div style={{
          background: 'var(--surface)',
          border: '1px solid var(--border)',
          borderRadius: 14,
          padding: '16px 20px',
          display: 'flex',
          flexWrap: 'wrap',
          gap: 12,
          alignItems: 'center',
        }}>
          <div style={{ flex: '1 1 180px', position: 'relative' }}>
            <span style={{
              position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)',
              fontSize: 15, color: 'var(--text-dim)', pointerEvents: 'none',
            }}></span>
            <input
              className="form-input"
              value={filterPhone}
              onChange={e =>handleSearchChange(setFilterPhone, e.target.value)}
              placeholder="Telefon ara..."
              style={{ paddingLeft: 32, fontFamily: 'var(--mono, monospace)' }}
            />
          </div>
          <div style={{ flex: '1 1 180px', position: 'relative' }}>
            <span style={{
              position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)',
              fontSize: 15, color: 'var(--text-dim)', pointerEvents: 'none',
            }}></span>
            <input
              className="form-input"
              value={filterName}
              onChange={e =>handleSearchChange(setFilterName, e.target.value)}
              placeholder="İsim ara..."
              style={{ paddingLeft: 32 }}
            />
          </div>
          <label style={{
            display: 'flex', alignItems: 'center', gap: 8,
            cursor: 'pointer', fontSize: 13, fontWeight: 600,
            color: filterBlacklist ? 'var(--red)' : 'var(--text-dim)',
            padding: '8px 14px',
            background: filterBlacklist ? '#7f1d1d18' : 'var(--surface2)',
            border: `1px solid ${filterBlacklist ? '#ef444440' : 'var(--border)'}`,
            borderRadius: 8,
            transition: 'all .15s',
            userSelect: 'none',
            whiteSpace: 'nowrap',
          }}>
            <input
              type="checkbox"
              checked={filterBlacklist}
              onChange={e => { setFilterBlacklist(e.target.checked); setPage(1); }}
              style={{ accentColor: 'var(--red)', width: 14, height: 14 }}
            />
            Sadece Kara Liste
          </label>
          <button
            className="btn btn-primary"
            onClick={() =>setShowNewModal(true)}
            style={{ whiteSpace: 'nowrap', marginLeft: 'auto' }}
          >
            + Yeni Müşteri Ekle
          </button>
        </div>

        {/* ── Customer table ── */}
        <div style={{
          background: 'var(--surface)',
          border: '1px solid var(--border)',
          borderRadius: 14,
          overflow: 'hidden',
        }}>
          {loading ? (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 220 }}>
              <div style={{ textAlign: 'center', color: 'var(--text-dim)' }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Müşteriler yükleniyor...</div>
              </div>
            </div>
          ) : customers.length === 0 ? (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 220 }}>
              <div style={{ textAlign: 'center', color: 'var(--text-dim)' }}>
                <div style={{ fontSize: 15, fontWeight:600, marginBottom: 4 }}>Müşteri bulunamadı</div>
                <div style={{ fontSize: 13 }}>Yeni müşteri ekleyin veya arama kriterlerini değiştirin.</div>
              </div>
            </div>
          ) : (
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                <thead style={{ background: 'var(--surface2)' }}>
                  <tr>
                    <th style={thStyle}>Ad / Soyad</th>
                    <th style={thStyle}>Telefon</th>
                    <th style={thStyle}>Şirket</th>
                    <th style={thStyle}>Etiketler</th>
                    <th style={thStyle}>Kara Liste</th>
                    <th style={thStyle}>Son Çağrı</th>
                    <th style={{ ...thStyle, textAlign: 'right' }}>İşlemler</th>
                  </tr>
                </thead>
                <tbody>
                  {customers.map((c, i) => (
                    <tr key={c.id}
                      style={{ background: i % 2 === 0 ? 'transparent' : 'var(--surface2)', transition: 'background .12s' }}
                      onMouseEnter={e =>e.currentTarget.style.background = 'var(--blue)10'}
                      onMouseLeave={e =>e.currentTarget.style.background = i % 2 === 0 ? 'transparent' : 'var(--surface2)'}
                    >
                      <td style={tdStyle}>
                        <span style={{ fontWeight: 600, color: 'var(--text)' }}>
                          {c.name || <span style={{ color: 'var(--text-dim)', fontStyle: 'italic' }}>(İsimsiz)</span>}
                        </span>
                      </td>
                      <td style={{ ...tdStyle, fontFamily: 'var(--mono, monospace)', color: 'var(--text-dim)' }}>
                        {c.phone}
                      </td>
                      <td style={{ ...tdStyle, color: 'var(--text-dim)' }}>
                        {c.company || '—'}
                      </td>
                      <td style={tdStyle}>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                          {(c.tags || []).length > 0
                            ? (c.tags || []).map(t => <TagBadge key={t} tag={t} />)
                            : <span style={{ color: 'var(--text-dim)' }}>—</span>
                          }
                        </div>
                      </td>
                      <td style={tdStyle}>
                        {c.is_blacklist ? <BlacklistBadge /> : <span style={{ color: 'var(--text-dim)' }}>—</span>}
                      </td>
                      <td style={{ ...tdStyle, color: 'var(--text-dim)', whiteSpace: 'nowrap' }}>
                        {c.last_call_at ? formatDate(c.last_call_at) : '—'}
                      </td>
                      <td style={{ ...tdStyle, textAlign: 'right', whiteSpace: 'nowrap' }}>
                        <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                          <button
                            title="Detay"
                            onClick={() => { setDetailCustomerId(c.id); setDetailInitialTab('info'); }}
                            style={{
                              padding: '5px 10px', borderRadius: 7, border: '1px solid var(--border)',
                              background: 'var(--surface2)', color: 'var(--text)', cursor: 'pointer',
                              fontSize: 13, transition: 'background .12s, border-color .12s',
                            }}
                            onMouseEnter={e => { e.currentTarget.style.background = 'var(--blue)20'; e.currentTarget.style.borderColor = 'var(--blue)'; }}
                            onMouseLeave={e => { e.currentTarget.style.background = 'var(--surface2)'; e.currentTarget.style.borderColor = 'var(--border)'; }}
                          >
                            
                          </button>
                          <button
                            title="Düzenle"
                            onClick={() => { setDetailCustomerId(c.id); setDetailInitialTab('info'); }}
                            style={{
                              padding: '5px 10px', borderRadius: 7, border: '1px solid var(--border)',
                              background: 'var(--surface2)', color: 'var(--text)', cursor: 'pointer',
                              fontSize: 13, transition: 'background .12s, border-color .12s',
                            }}
                            onMouseEnter={e => { e.currentTarget.style.background = 'var(--amber)20'; e.currentTarget.style.borderColor = 'var(--amber)'; }}
                            onMouseLeave={e => { e.currentTarget.style.background = 'var(--surface2)'; e.currentTarget.style.borderColor = 'var(--border)'; }}
                          >
                            
                          </button>
                          <button
                            title="Sil"
                            onClick={() =>setDeleteTarget(c)}
                            style={{
                              padding: '5px 10px', borderRadius: 7, border: '1px solid var(--border)',
                              background: 'var(--surface2)', color: 'var(--text)', cursor: 'pointer',
                              fontSize: 13, transition: 'background .12s, border-color .12s',
                            }}
                            onMouseEnter={e => { e.currentTarget.style.background = '#ef444420'; e.currentTarget.style.borderColor = 'var(--red)'; }}
                            onMouseLeave={e => { e.currentTarget.style.background = 'var(--surface2)'; e.currentTarget.style.borderColor = 'var(--border)'; }}
                          >
                            
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {/* ── Pagination ── */}
          {totalPages > 1 && (
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '12px 20px',
              borderTop: '1px solid var(--border)',
              background: 'var(--surface2)',
            }}>
              <div style={{ fontSize: 13, color: 'var(--text-dim)' }}>
                Toplam <strong style={{ color: 'var(--text)' }}>{total}</strong>müşteri
                &nbsp;·&nbsp;
                Sayfa <strong style={{ color: 'var(--text)' }}>{page}</strong> / {totalPages}
              </div>
              <div style={{ display: 'flex', gap: 6 }}>
                <button
                  className="btn outline"
                  disabled={page <= 1}
                  onClick={() =>setPage(p =>Math.max(1, p - 1))}
                  style={{ padding: '5px 14px', fontSize: 13 }}
                >
                  ← Önceki
                </button>
                {/* Page numbers (show up to 7 around current page) */}
                {Array.from({ length: totalPages }, (_, i) =>i + 1)
                  .filter(p =>p === 1 || p === totalPages || Math.abs(p - page) <= 2)
                  .reduce((acc, p, idx, arr) => {
                    if (idx > 0 && p - arr[idx - 1] > 1) acc.push('...');
                    acc.push(p);
                    return acc;
                  }, [])
                  .map((p, idx) =>
                    p === '...' ? (
                      <span key={`ellipsis-${idx}`} style={{ padding: '5px 6px', color: 'var(--text-dim)', fontSize: 13 }}>…</span>
                    ) : (
                      <button
                        key={p}
                        onClick={() =>setPage(p)}
                        style={{
                          padding: '5px 11px', fontSize: 13, borderRadius: 7, cursor: 'pointer',
                          border: page === p ? '1px solid var(--blue)' : '1px solid var(--border)',
                          background: page === p ? 'var(--blue)' : 'var(--surface)',
                          color: page === p ? '#fff' : 'var(--text)',
                          fontWeight: page === p ? 700 : 400,
                          transition: 'all .12s',
                        }}
                      >
                        {p}
                      </button>
                    )
                  )
                }
                <button
                  className="btn outline"
                  disabled={page >= totalPages}
                  onClick={() =>setPage(p =>Math.min(totalPages, p + 1))}
                  style={{ padding: '5px 14px', fontSize: 13 }}
                >
                  Sonraki →
                </button>
              </div>
            </div>
          )}
        </div>

        {/* ── Modals ── */}
        {showNewModal && (
          <NewCustomerModal
            toast={toast}
            onClose={() =>setShowNewModal(false)}
            onSaved={() => {
              setShowNewModal(false);
              setPage(1);
              loadCustomers(1);
              loadBlacklistCount();
            }}
          />
        )}

        {detailCustomerId && (
          <CustomerDetailModal
            customerId={detailCustomerId}
            initialTab={detailInitialTab}
            toast={toast}
            onClose={() =>setDetailCustomerId(null)}
            onSaved={() => {
              loadCustomers(page);
              loadBlacklistCount();
            }}
          />
        )}

        {deleteTarget && (
          <ConfirmDeleteModal
            customer={deleteTarget}
            onConfirm={() =>handleDelete(deleteTarget)}
            onCancel={() =>setDeleteTarget(null)}
          />
        )}
      </div>
    );
  }

  window.CustomersTab = CustomersTab;
})();
