// CRM — Müşteri İlişkileri Yönetimi (satış hattı, kişiler, etkileşimler)
const CRMIcons = window.Icons;
const CRM_STAGE_LIST = window.PMStore.CRM_STAGES;
const CRM_ACT_LIST   = window.PMStore.CRM_ACTIVITY_TYPES;

const STAGE_BY_ID = Object.fromEntries(CRM_STAGE_LIST.map(s => [s.id, s]));
const ACT_BY_ID   = Object.fromEntries(CRM_ACT_LIST.map(a => [a.id, a]));
const PIPELINE_STAGES = CRM_STAGE_LIST.filter(s => s.id !== 'won' && s.id !== 'lost');

const crmMoney = (n) => new Intl.NumberFormat('tr-TR', { maximumFractionDigits: 0 }).format(n || 0) + ' ₺';
const crmMoneyShort = (n) => Math.abs(n) >= 1000
  ? new Intl.NumberFormat('tr-TR', { maximumFractionDigits: 1 }).format(n / 1000) + 'B ₺'
  : crmMoney(n);
const crmInitials = (name) => (name || '?').split(/\s+/).filter(Boolean).map(w => w[0]).join('').slice(0, 2).toUpperCase();
const crmDateLabel = (d) => d ? new Date(d + 'T00:00:00').toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' }) : '';
const onlyDigits = (s) => (s || '').replace(/[^\d+]/g, '');

// ── Fırsat kartı (satış hattı) ───────────────────────────────
function DealCard({ deal, firm, contact, onClick, onStageChange, onDragStart }) {
  const overdue = deal.expectedClose && deal.status === 'open' &&
    new Date(deal.expectedClose + 'T00:00:00') < new Date(new Date().toDateString());
  return (
    <div className="crm-deal-card" draggable onDragStart={onDragStart} onClick={onClick}>
      <div className="crm-deal-top">
        <span className="crm-deal-title">{deal.title}</span>
        {deal.value > 0 && <span className="crm-deal-value">{crmMoneyShort(deal.value)}</span>}
      </div>
      <div className="crm-deal-meta">
        {firm
          ? <span className="crm-deal-firm"><span className="project-dot" style={{ background: firm.color }} />{firm.name}</span>
          : deal.company && <span className="crm-deal-firm"><CRMIcons.Building size={11} />{deal.company}</span>}
      </div>
      {(contact || deal.expectedClose) && (
        <div className="crm-deal-sub">
          {contact && <span className="crm-deal-contact"><CRMIcons.User size={11} />{contact.name}</span>}
          {deal.expectedClose && (
            <span className={`crm-deal-close${overdue ? ' overdue' : ''}`}>
              <CRMIcons.Clock size={11} />{crmDateLabel(deal.expectedClose)}
            </span>
          )}
        </div>
      )}
      <select className="crm-deal-stage-select" value={deal.stage}
        onClick={e => e.stopPropagation()}
        onChange={e => { e.stopPropagation(); onStageChange(deal.id, e.target.value); }}>
        {CRM_STAGE_LIST.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
      </select>
    </div>
  );
}

// ── Kişi kartı ───────────────────────────────────────────────
function ContactCard({ contact, firm, onClick, dealCount }) {
  const color = firm?.color || 'var(--accent)';
  return (
    <button className="crm-contact-card" onClick={onClick}>
      <div className="crm-contact-head">
        <span className="crm-contact-avatar" style={{ background: color }}>{crmInitials(contact.name)}</span>
        <div className="crm-contact-id">
          <span className="crm-contact-name">{contact.name}{contact.isPrimary && <CRMIcons.Star size={11} className="crm-primary-star" />}</span>
          {contact.role && <span className="crm-contact-role">{contact.role}</span>}
        </div>
      </div>
      {(firm || contact.company) && (
        <div className="crm-contact-firm">
          {firm ? <><span className="project-dot" style={{ background: firm.color }} />{firm.name}</> : <><CRMIcons.Building size={11} />{contact.company}</>}
          {dealCount > 0 && <span className="crm-contact-dealcount">{dealCount} fırsat</span>}
        </div>
      )}
      <div className="crm-contact-actions" onClick={e => e.stopPropagation()}>
        {contact.phone && <a className="crm-contact-act" href={`tel:${onlyDigits(contact.phone)}`} title="Ara"><CRMIcons.Phone size={14} /></a>}
        {contact.phone && <a className="crm-contact-act wa" href={`https://wa.me/${onlyDigits(contact.phone).replace(/^0/, '90')}`} target="_blank" rel="noreferrer" title="WhatsApp"><CRMIcons.MessageSquare size={14} /></a>}
        {contact.email && <a className="crm-contact-act" href={`mailto:${contact.email}`} title="E-posta gönder"><CRMIcons.Mail size={14} /></a>}
      </div>
    </button>
  );
}

// ── Yeni / Düzenle: Fırsat modalı ────────────────────────────
function DealModal({ state, editing, onSave, onDelete, onClose, onConvert }) {
  const isEdit = !!(editing && editing.id);
  const projects = (state.projects || []).filter(p => !p.archived);
  const [title,     setTitle]     = React.useState(editing?.title     || '');
  const [projectId, setProjectId] = React.useState(editing?.projectId || '');
  const [company,   setCompany]   = React.useState(editing?.company   || '');
  const [contactId, setContactId] = React.useState(editing?.contactId || '');
  const [value,     setValue]     = React.useState(editing?.value ? String(editing.value) : '');
  const [stage,     setStage]     = React.useState(editing?.stage     || 'lead');
  const [expClose,  setExpClose]  = React.useState(editing?.expectedClose || '');
  const [notes,     setNotes]     = React.useState(editing?.notes     || '');

  const firmContacts = (state.crmContacts || []).filter(c => projectId ? c.projectId === projectId : true);

  React.useEffect(() => {
    const fn = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', fn);
    return () => window.removeEventListener('keydown', fn);
  }, [onClose]);

  const save = () => {
    if (!title.trim()) return;
    onSave({
      title: title.trim(),
      projectId: projectId || null,
      company: projectId ? '' : company.trim(),
      contactId: contactId || null,
      value: parseFloat(String(value).replace(',', '.')) || 0,
      stage,
      expectedClose: expClose || null,
      notes: notes.trim(),
    });
  };

  return (
    <div className="confirm-overlay" onClick={onClose}>
      <div className="finance-modal" onClick={e => e.stopPropagation()}>
        <div className="finance-modal-hdr">
          <CRMIcons.Handshake size={17} style={{ color: 'var(--accent)' }} />
          <h3>{isEdit ? 'Fırsatı Düzenle' : 'Yeni Fırsat'}</h3>
          <button className="icon-btn icon-btn-sm" onClick={onClose}><CRMIcons.X size={16} /></button>
        </div>
        <div className="finance-modal-body">
          <label className="login-field">
            <span>Fırsat başlığı</span>
            <input className="input" value={title} autoFocus placeholder="örn. Web sitesi yenileme"
              onChange={e => setTitle(e.target.value)} onKeyDown={e => e.key === 'Enter' && save()} />
          </label>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="login-field">
              <span>Firma</span>
              <select className="input" value={projectId} onChange={e => { setProjectId(e.target.value); setContactId(''); }}>
                <option value="">— Aday (firma yok) —</option>
                {projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
              </select>
            </label>
            <label className="login-field">
              <span>Tutar (₺)</span>
              <input type="number" className="input" value={value} placeholder="0" min="0"
                onChange={e => setValue(e.target.value)} />
            </label>
          </div>

          {!projectId && (
            <label className="login-field">
              <span>Aday firma adı <span style={{ color: 'var(--text-faint)', fontWeight: 400 }}>(henüz müşteri değil)</span></span>
              <input className="input" value={company} placeholder="örn. Demir İnşaat"
                onChange={e => setCompany(e.target.value)} />
            </label>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="login-field">
              <span>Aşama</span>
              <select className="input" value={stage} onChange={e => setStage(e.target.value)}>
                {CRM_STAGE_LIST.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
              </select>
            </label>
            <label className="login-field">
              <span>Tahmini kapanış</span>
              <input type="date" className="input" value={expClose} onChange={e => setExpClose(e.target.value)} />
            </label>
          </div>

          {firmContacts.length > 0 && (
            <label className="login-field">
              <span>İlgili kişi <span style={{ color: 'var(--text-faint)', fontWeight: 400 }}>(opsiyonel)</span></span>
              <select className="input" value={contactId} onChange={e => setContactId(e.target.value)}>
                <option value="">— Kişi seçin —</option>
                {firmContacts.map(c => <option key={c.id} value={c.id}>{c.name}{c.role ? ` · ${c.role}` : ''}</option>)}
              </select>
            </label>
          )}

          <label className="login-field">
            <span>Not <span style={{ color: 'var(--text-faint)', fontWeight: 400 }}>(opsiyonel)</span></span>
            <textarea className="input" value={notes} rows={2} placeholder="Görüşme notları, beklentiler..."
              onChange={e => setNotes(e.target.value)} style={{ resize: 'vertical', minHeight: 56 }} />
          </label>

          {isEdit && stage === 'won' && !projectId && company.trim() && (
            <button className="btn btn-sm" style={{ background: '#22c55e', color: '#fff', justifyContent: 'center' }}
              onClick={() => onConvert(editing)}>
              <CRMIcons.Building size={14} /> Bu adayı firmaya dönüştür
            </button>
          )}
        </div>
        <div className="finance-modal-footer">
          {isEdit && <button className="btn btn-ghost btn-sm" style={{ marginRight: 'auto', color: 'var(--p-high)' }} onClick={() => onDelete(editing.id)}><CRMIcons.Trash size={14} /> Sil</button>}
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Vazgeç</button>
          <button className="btn btn-primary btn-sm" onClick={save} disabled={!title.trim()}>
            <CRMIcons.Save size={14} /> {isEdit ? 'Kaydet' : 'Fırsat Ekle'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Yeni / Düzenle: Kişi modalı ──────────────────────────────
function ContactModal({ state, editing, onSave, onDelete, onClose }) {
  const isEdit = !!(editing && editing.id);
  const projects = (state.projects || []).filter(p => !p.archived);
  const [name,    setName]    = React.useState(editing?.name    || '');
  const [role,    setRole]    = React.useState(editing?.role    || '');
  const [projectId, setProjectId] = React.useState(editing?.projectId || '');
  const [company, setCompany] = React.useState(editing?.company || '');
  const [email,   setEmail]   = React.useState(editing?.email   || '');
  const [phone,   setPhone]   = React.useState(editing?.phone   || '');
  const [notes,   setNotes]   = React.useState(editing?.notes   || '');
  const [isPrimary, setIsPrimary] = React.useState(!!editing?.isPrimary);

  React.useEffect(() => {
    const fn = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', fn);
    return () => window.removeEventListener('keydown', fn);
  }, [onClose]);

  const save = () => {
    if (!name.trim()) return;
    onSave({
      name: name.trim(), role: role.trim(),
      projectId: projectId || null,
      company: projectId ? '' : company.trim(),
      email: email.trim(), phone: phone.trim(),
      notes: notes.trim(), isPrimary,
    });
  };

  return (
    <div className="confirm-overlay" onClick={onClose}>
      <div className="finance-modal" onClick={e => e.stopPropagation()}>
        <div className="finance-modal-hdr">
          <CRMIcons.User size={17} style={{ color: 'var(--accent)' }} />
          <h3>{isEdit ? 'Kişiyi Düzenle' : 'Yeni Kişi'}</h3>
          <button className="icon-btn icon-btn-sm" onClick={onClose}><CRMIcons.X size={16} /></button>
        </div>
        <div className="finance-modal-body">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="login-field">
              <span>Ad Soyad</span>
              <input className="input" value={name} autoFocus placeholder="örn. Ahmet Yılmaz"
                onChange={e => setName(e.target.value)} onKeyDown={e => e.key === 'Enter' && save()} />
            </label>
            <label className="login-field">
              <span>Ünvan</span>
              <input className="input" value={role} placeholder="örn. Pazarlama Müdürü"
                onChange={e => setRole(e.target.value)} />
            </label>
          </div>

          <label className="login-field">
            <span>Firma</span>
            <select className="input" value={projectId} onChange={e => setProjectId(e.target.value)}>
              <option value="">— Firma seçin / aday —</option>
              {projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </label>
          {!projectId && (
            <label className="login-field">
              <span>Firma adı <span style={{ color: 'var(--text-faint)', fontWeight: 400 }}>(opsiyonel)</span></span>
              <input className="input" value={company} placeholder="Henüz müşteri olmayan firma"
                onChange={e => setCompany(e.target.value)} />
            </label>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="login-field">
              <span>Telefon</span>
              <input className="input" value={phone} placeholder="0532 000 00 00" inputMode="tel"
                onChange={e => setPhone(e.target.value)} />
            </label>
            <label className="login-field">
              <span>E-posta</span>
              <input className="input" value={email} placeholder="ad@firma.com" inputMode="email"
                onChange={e => setEmail(e.target.value)} />
            </label>
          </div>

          <label className="login-field">
            <span>Not <span style={{ color: 'var(--text-faint)', fontWeight: 400 }}>(opsiyonel)</span></span>
            <textarea className="input" value={notes} rows={2} placeholder="Ek bilgiler..."
              onChange={e => setNotes(e.target.value)} style={{ resize: 'vertical', minHeight: 56 }} />
          </label>

          <label className="fn-recur-check">
            <input type="checkbox" checked={isPrimary} onChange={e => setIsPrimary(e.target.checked)} />
            <span>Birincil iletişim kişisi</span>
          </label>
        </div>
        <div className="finance-modal-footer">
          {isEdit && <button className="btn btn-ghost btn-sm" style={{ marginRight: 'auto', color: 'var(--p-high)' }} onClick={() => onDelete(editing.id)}><CRMIcons.Trash size={14} /> Sil</button>}
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Vazgeç</button>
          <button className="btn btn-primary btn-sm" onClick={save} disabled={!name.trim()}>
            <CRMIcons.Save size={14} /> {isEdit ? 'Kaydet' : 'Kişi Ekle'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Hızlı etkileşim ekleme ───────────────────────────────────
function ActivityComposer({ state, onAdd }) {
  const [type,    setType]    = React.useState('call');
  const [summary, setSummary] = React.useState('');
  const [projectId, setProjectId] = React.useState('');
  const projects = (state.projects || []).filter(p => !p.archived);
  const submit = () => {
    if (!summary.trim()) return;
    onAdd({ type, summary: summary.trim(), projectId: projectId || null, date: new Date().toISOString().slice(0, 10) });
    setSummary('');
  };
  return (
    <div className="crm-composer">
      <select className="select-control" value={type} onChange={e => setType(e.target.value)}>
        {CRM_ACT_LIST.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
      </select>
      <select className="select-control" value={projectId} onChange={e => setProjectId(e.target.value)}>
        <option value="">Firma (ops.)</option>
        {projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
      </select>
      <input className="crm-composer-input" value={summary} placeholder="Etkileşim özeti yaz — Enter"
        onChange={e => setSummary(e.target.value)} onKeyDown={e => e.key === 'Enter' && submit()} />
      <button className="btn btn-primary btn-sm" onClick={submit} disabled={!summary.trim()}>Ekle</button>
    </div>
  );
}

// ── Ana CRM Görünümü ─────────────────────────────────────────
function CRMView({ state, onAddContact, onUpdateContact, onDeleteContact, onAddDeal, onUpdateDeal, onDeleteDeal, onAddActivity, onDeleteActivity, onConvertDeal }) {
  const [tab,          setTab]          = React.useState('pipeline');
  const [dealModal,    setDealModal]    = React.useState(null);
  const [contactModal, setContactModal] = React.useState(null);
  const [search,       setSearch]       = React.useState('');
  const [actFilter,    setActFilter]    = React.useState('all');
  const [dragStage,    setDragStage]    = React.useState(null);
  const dragDealId = React.useRef(null);

  const projects   = (state.projects || []).filter(p => !p.archived);
  const projById   = Object.fromEntries(projects.map(p => [p.id, p]));
  const contacts   = state.crmContacts   || [];
  const deals      = state.crmDeals       || [];
  const activities = state.crmActivities  || [];
  const contactById = Object.fromEntries(contacts.map(c => [c.id, c]));

  // KPI'lar
  const openDeals  = deals.filter(d => d.status === 'open');
  const pipelineValue = openDeals.reduce((s, d) => s + (d.value || 0), 0);
  const monthKey   = new Date().toISOString().slice(0, 7);
  const wonThisMonth = deals.filter(d => d.status === 'won' && (d.closedAt || '').slice(0, 7) === monthKey);
  const wonValue   = wonThisMonth.reduce((s, d) => s + (d.value || 0), 0);
  const wonCount   = deals.filter(d => d.status === 'won').length;
  const lostCount  = deals.filter(d => d.status === 'lost').length;
  const convRate   = (wonCount + lostCount) > 0 ? Math.round(wonCount / (wonCount + lostCount) * 100) : null;

  const setDealStage = (id, stage) => onUpdateDeal(id, { stage });

  // Satış hattı kolonları (won/lost ayrı özet)
  const dealsByStage = (stageId) => deals
    .filter(d => d.stage === stageId)
    .sort((a, b) => (b.value || 0) - (a.value || 0));

  const onDrop = (stageId) => {
    if (dragDealId.current) setDealStage(dragDealId.current, stageId);
    dragDealId.current = null;
    setDragStage(null);
  };

  // Kişi araması
  const filteredContacts = contacts.filter(c => {
    if (!search) return true;
    const q = search.toLowerCase();
    const firmName = projById[c.projectId]?.name || c.company || '';
    return [c.name, c.role, c.email, c.phone, firmName].filter(Boolean).join(' ').toLowerCase().includes(q);
  }).sort((a, b) => (b.isPrimary - a.isPrimary) || a.name.localeCompare(b.name, 'tr'));

  const dealCountByContact = (cid) => deals.filter(d => d.contactId === cid).length;

  // Etkileşim listesi (tarihe göre)
  const filteredActivities = activities
    .filter(a => actFilter === 'all' || a.type === actFilter)
    .sort((a, b) => (b.date || '').localeCompare(a.date || '') || (b.createdAt || '').localeCompare(a.createdAt || ''));

  const TABS = [
    { id: 'pipeline',   label: 'Satış Hattı', icon: 'Handshake' },
    { id: 'contacts',   label: 'Kişiler',     icon: 'Users' },
    { id: 'activities', label: 'Etkileşimler', icon: 'Activity' },
  ];

  return (
    <div className="content crm-content">
      {/* Header */}
      <div className="report-header">
        <h2 className="report-title">CRM</h2>
        <div className="report-filters">
          {tab === 'contacts' && (
            <div className="fn-search-wrap" style={{ minWidth: 180 }}>
              <CRMIcons.Search size={14} style={{ color: 'var(--text-faint)', flexShrink: 0 }} />
              <input className="fn-search-input" placeholder="Kişi ara..." value={search} onChange={e => setSearch(e.target.value)} />
              {search && <button className="fn-search-clear" onClick={() => setSearch('')}><CRMIcons.X size={12} /></button>}
            </div>
          )}
          <button className="btn btn-ghost btn-sm" onClick={() => setContactModal({})}>
            <CRMIcons.User size={14} /> Yeni Kişi
          </button>
          <button className="btn btn-primary btn-sm" onClick={() => setDealModal({})}>
            <CRMIcons.Plus size={14} /> Yeni Fırsat
          </button>
        </div>
      </div>

      {/* KPI şeridi */}
      <div className="crm-kpi-strip">
        <div className="crm-kpi">
          <div className="crm-kpi-icon"><CRMIcons.Handshake size={17} /></div>
          <div><div className="crm-kpi-val">{openDeals.length}</div><div className="crm-kpi-lbl">Açık Fırsat</div></div>
        </div>
        <div className="crm-kpi">
          <div className="crm-kpi-icon"><CRMIcons.TrendingUp size={17} /></div>
          <div><div className="crm-kpi-val">{crmMoneyShort(pipelineValue)}</div><div className="crm-kpi-lbl">Pipeline Değeri</div></div>
        </div>
        <div className="crm-kpi">
          <div className="crm-kpi-icon" style={{ color: '#22c55e' }}><CRMIcons.CheckCircle size={17} /></div>
          <div><div className="crm-kpi-val">{crmMoneyShort(wonValue)}</div><div className="crm-kpi-lbl">Bu Ay Kazanılan</div></div>
        </div>
        <div className="crm-kpi">
          <div className="crm-kpi-icon"><CRMIcons.Target size={17} /></div>
          <div><div className="crm-kpi-val">{convRate !== null ? `%${convRate}` : '—'}</div><div className="crm-kpi-lbl">Dönüşüm Oranı</div></div>
        </div>
      </div>

      {/* Sekmeler */}
      <div className="report-tabs">
        {TABS.map(t => (
          <button key={t.id} className={`report-tab-btn${tab === t.id ? ' active' : ''}`} onClick={() => setTab(t.id)}>
            {t.label}
          </button>
        ))}
      </div>

      {/* ── Satış Hattı ── */}
      {tab === 'pipeline' && (
        deals.length === 0 ? (
          <div className="rp-empty-state">
            <CRMIcons.Handshake size={28} />
            <div>Henüz fırsat yok</div>
            <button className="btn btn-primary btn-sm" onClick={() => setDealModal({})}><CRMIcons.Plus size={14} /> İlk fırsatı ekle</button>
          </div>
        ) : (
          <div className="crm-pipeline">
            {PIPELINE_STAGES.map(stage => {
              const list = dealsByStage(stage.id);
              const sum = list.reduce((s, d) => s + (d.value || 0), 0);
              return (
                <div key={stage.id}
                  className={`crm-pipe-col${dragStage === stage.id ? ' drag-over' : ''}`}
                  onDragOver={e => { e.preventDefault(); setDragStage(stage.id); }}
                  onDragLeave={() => setDragStage(s => s === stage.id ? null : s)}
                  onDrop={() => onDrop(stage.id)}>
                  <div className="crm-pipe-head">
                    <span className="crm-pipe-dot" style={{ background: stage.color }} />
                    <span className="crm-pipe-label">{stage.label}</span>
                    <span className="crm-pipe-count">{list.length}</span>
                    {sum > 0 && <span className="crm-pipe-sum">{crmMoneyShort(sum)}</span>}
                  </div>
                  <div className="crm-pipe-list">
                    {list.map(deal => (
                      <DealCard key={deal.id} deal={deal}
                        firm={projById[deal.projectId]} contact={contactById[deal.contactId]}
                        onClick={() => setDealModal(deal)}
                        onStageChange={setDealStage}
                        onDragStart={() => { dragDealId.current = deal.id; }} />
                    ))}
                    {list.length === 0 && <div className="crm-pipe-empty">—</div>}
                  </div>
                </div>
              );
            })}
            {/* Kazanılan / Kaybedilen özet sütunu */}
            <div className="crm-pipe-col crm-pipe-closed">
              {['won', 'lost'].map(sid => {
                const st = STAGE_BY_ID[sid];
                const list = dealsByStage(sid);
                return (
                  <div key={sid}
                    className={`crm-closed-group${dragStage === sid ? ' drag-over' : ''}`}
                    onDragOver={e => { e.preventDefault(); setDragStage(sid); }}
                    onDragLeave={() => setDragStage(s => s === sid ? null : s)}
                    onDrop={() => onDrop(sid)}>
                    <div className="crm-pipe-head">
                      <span className="crm-pipe-dot" style={{ background: st.color }} />
                      <span className="crm-pipe-label">{st.label}</span>
                      <span className="crm-pipe-count">{list.length}</span>
                    </div>
                    <div className="crm-pipe-list">
                      {list.slice(0, 6).map(deal => (
                        <DealCard key={deal.id} deal={deal}
                          firm={projById[deal.projectId]} contact={contactById[deal.contactId]}
                          onClick={() => setDealModal(deal)}
                          onStageChange={setDealStage}
                          onDragStart={() => { dragDealId.current = deal.id; }} />
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )
      )}

      {/* ── Kişiler ── */}
      {tab === 'contacts' && (
        contacts.length === 0 ? (
          <div className="rp-empty-state">
            <CRMIcons.Users size={28} />
            <div>Henüz kişi eklenmemiş</div>
            <button className="btn btn-primary btn-sm" onClick={() => setContactModal({})}><CRMIcons.Plus size={14} /> İlk kişiyi ekle</button>
          </div>
        ) : (
          <div className="crm-contact-grid">
            {filteredContacts.map(c => (
              <ContactCard key={c.id} contact={c} firm={projById[c.projectId]}
                dealCount={dealCountByContact(c.id)} onClick={() => setContactModal(c)} />
            ))}
            {filteredContacts.length === 0 && <div className="report-empty">Aramayla eşleşen kişi yok</div>}
          </div>
        )
      )}

      {/* ── Etkileşimler ── */}
      {tab === 'activities' && (
        <div className="crm-activities">
          <ActivityComposer state={state} onAdd={onAddActivity} />
          <div className="crm-act-filters">
            <button className={`fn-chip-btn${actFilter === 'all' ? ' active' : ''}`} onClick={() => setActFilter('all')}>Tümü</button>
            {CRM_ACT_LIST.map(t => (
              <button key={t.id} className={`fn-chip-btn${actFilter === t.id ? ' active' : ''}`} onClick={() => setActFilter(t.id)}>{t.label}</button>
            ))}
          </div>
          {filteredActivities.length === 0 ? (
            <div className="report-empty">Henüz etkileşim kaydı yok</div>
          ) : (
            <div className="crm-act-list">
              {filteredActivities.map(a => {
                const at = ACT_BY_ID[a.type] || ACT_BY_ID.note;
                const Icon = CRMIcons[at.icon] || CRMIcons.FileText;
                const firm = projById[a.projectId];
                const contact = contactById[a.contactId];
                return (
                  <div key={a.id} className="crm-act-row">
                    <span className={`crm-act-icon crm-act-${a.type}`}><Icon size={14} /></span>
                    <div className="crm-act-body">
                      <div className="crm-act-summary">{a.summary}</div>
                      <div className="crm-act-meta">
                        <span className="crm-act-type">{at.label}</span>
                        {contact && <><span className="fn-sep">·</span><span>{contact.name}</span></>}
                        {firm && <><span className="fn-sep">·</span><span className="project-dot" style={{ background: firm.color }} />{firm.name}</>}
                        <span className="fn-sep">·</span><span>{crmDateLabel(a.date)}</span>
                      </div>
                    </div>
                    <button className="fn-tx-action-btn danger" onClick={() => onDeleteActivity(a.id)} title="Sil"><CRMIcons.Trash size={13} /></button>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* Modallar */}
      {dealModal && (
        <DealModal state={state} editing={dealModal}
          onClose={() => setDealModal(null)}
          onSave={(data) => { if (dealModal.id) onUpdateDeal(dealModal.id, data); else onAddDeal(data); setDealModal(null); }}
          onDelete={(id) => { onDeleteDeal(id); setDealModal(null); }}
          onConvert={(deal) => { onConvertDeal(deal); setDealModal(null); }} />
      )}
      {contactModal && (
        <ContactModal state={state} editing={contactModal}
          onClose={() => setContactModal(null)}
          onSave={(data) => { if (contactModal.id) onUpdateContact(contactModal.id, data); else onAddContact(data); setContactModal(null); }}
          onDelete={(id) => { onDeleteContact(id); setContactModal(null); }} />
      )}
    </div>
  );
}

window.CRMView = CRMView;
