// ─── اپ فروشنده ──────────────────────────────────────────────
const SellerApp = ({ seller, onLogout }) => {
  const [page, setPage] = useState('dashboard');
  const [overdueCount, setOverdueCount] = useState(0);
  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };

  const { Icon } = window.SB_UI;

  // بارگذاری تعداد یادآورهای سررسیدگذشته
  const loadOverdue = () => {
    fetch('/api/seller/reminders', { headers }).then(r => r.json())
      .then(d => { if (d.success) setOverdueCount(d.data.overdue_count || 0); })
      .catch(() => {});
  };

  useEffect(() => {
    loadOverdue();
    const t = setInterval(loadOverdue, 2 * 60 * 1000); // هر ۲ دقیقه
    return () => clearInterval(t);
  }, []);

  const NAV_SELLER = [
    { id: 'dashboard',  label: 'داشبورد',   icon: 'layout-dashboard' },
    { id: 'leads',      label: 'لیدهای من', icon: 'users' },
    { id: 'reminders',  label: 'یادآورها',  icon: 'bell' },
    { id: 'badges',     label: 'نشان‌ها',   icon: 'award' },
  ];

  return (
    <div className="app">
      {/* ─── Sidebar ─── */}
      <aside className="sidebar">
        <div className="brand">
          <div className="brand-mark">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <path d="M3 7 L12 3 L21 7 L21 17 L12 21 L3 17 Z" stroke="white" strokeWidth="1.7" strokeLinejoin="round" />
              <circle cx="12" cy="12" r="3" fill="white" />
            </svg>
          </div>
          <div>
            <div className="brand-name">SalesBot</div>
            <div className="brand-sub mono">پنل فروشنده</div>
          </div>
        </div>

        {NAV_SELLER.map((n, i) => (
          <div key={n.id}
            className={`nav-item ${page === n.id ? 'active' : ''}`}
            onClick={() => setPage(n.id)}
            style={{ position: 'relative' }}>
            <span className="num">0{i + 1}</span>
            <Icon name={n.icon} size={16} />
            <span className="lab">{n.label}</span>
            {/* badge یادآور روی داشبورد */}
            {(n.id === 'dashboard' || n.id === 'reminders') && overdueCount > 0 && (
              <span style={{
                position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)',
                minWidth: 18, height: 18, borderRadius: 9, background: '#F87171',
                color: '#fff', fontSize: 10, fontWeight: 700, display: 'flex',
                alignItems: 'center', justifyContent: 'center', padding: '0 4px',
              }}>{overdueCount}</span>
            )}
          </div>
        ))}

        <div className="sidebar-footer">
          <div className="avatar" style={{ background: '#6366F1' }}>
            {(seller.name || 'ف').slice(0, 2)}
          </div>
          <div className="user-meta" style={{ flex: 1, minWidth: 0 }}>
            <div className="nm">{seller.name || 'فروشنده'}</div>
            <div className="rl">فروشنده</div>
          </div>
          <button className="icon-btn" style={{ width: 30, height: 30 }} onClick={onLogout} title="خروج">
            <Icon name="log-out" size={13} />
          </button>
        </div>
      </aside>

      {/* ─── Main ─── */}
      <main className="main">
        <header className="topbar">
          <div>
            <div className="page-title">{NAV_SELLER.find(n => n.id === page)?.label}</div>
            <div className="page-crumb mono">SalesBot &nbsp;/&nbsp; {NAV_SELLER.find(n => n.id === page)?.label}</div>
          </div>
          {/* هشدار یادآور در هدر */}
          {overdueCount > 0 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 14px', borderRadius: 8, background: 'rgba(248,113,113,0.12)', border: '1px solid rgba(248,113,113,0.25)', cursor: 'pointer' }}
              onClick={() => setPage('dashboard')}>
              <span style={{ fontSize: 13 }}>⚠️</span>
              <span style={{ fontSize: 12, color: '#F87171', fontWeight: 600 }}>{overdueCount} یادآور سررسیدگذشته</span>
            </div>
          )}
        </header>

        <div className="content">
          {page === 'dashboard'  && <SellerDashboard seller={seller} onOverdueChange={setOverdueCount} />}
          {page === 'leads'      && <SellerLeadsList seller={seller} />}
          {page === 'reminders'  && <SellerReminders onCallLead={(l) => {}} />}
          {page === 'badges'     && <SellerBadges seller={seller} />}
        </div>
      </main>

      {/* ─── Bottom Nav ─── */}
      <nav className="bottom-nav">
        {NAV_SELLER.map(n => (
          <button key={n.id} className={`bn-item ${page === n.id ? 'active' : ''}`} onClick={() => setPage(n.id)}
            style={{ position: 'relative' }}>
            <Icon name={n.icon} size={18} />
            <span>{n.label}</span>
            {(n.id === 'dashboard' || n.id === 'reminders') && overdueCount > 0 && (
              <span style={{ position: 'absolute', top: 4, right: '50%', marginRight: -18, width: 14, height: 14, borderRadius: 7, background: '#F87171', color: '#fff', fontSize: 9, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{overdueCount}</span>
            )}
          </button>
        ))}
      </nav>
    </div>
  );
};

// ─── لیست لیدهای فروشنده ──────────────────────────────────────
const SellerLeadsList = ({ seller }) => {
  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };
  const { Icon } = window.SB_UI;

  const [leads, setLeads] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [callLead, setCallLead] = useState(null);

  // ─── تاریخچه تماس ───
  const [historyLead, setHistoryLead] = useState(null);
  const [historyEvents, setHistoryEvents] = useState([]);
  const [historyLoading, setHistoryLoading] = useState(false);

  const STATUS_COLOR = { scheduled: '#A78BFA', interested: '#60A5FA', new: '#818CF8', follow_up: '#94A3B8', buyer: '#34D399', lost: '#6B7280', cancelled: '#EF4444' };
  const STATUS_LABEL = { scheduled: '📅 زمان‌بندی', interested: '👀 علاقه‌مند', new: '✨ جدید', follow_up: '🔄 پیگیری', buyer: '💰 خریدار', lost: '❌ از دست رفته', cancelled: '🚫 کنسل' };

  const OUTCOME_LABEL_SHORT = {
    answered: { icon: '✅', color: '#34D399' }, no_answer: { icon: '📵', color: '#F87171' },
    sold: { icon: '💰', color: '#34D399' }, follow_up: { icon: '🔄', color: '#818CF8' },
    scheduled: { icon: '📅', color: '#A78BFA' }, not_interested: { icon: '❌', color: '#6B7280' },
    call_later: { icon: '⏰', color: '#818CF8' }, cancelled: { icon: '🚫', color: '#EF4444' },
    bad_number: { icon: '☎️', color: '#DC2626' },
  };
  const OUTCOME_FA = {
    answered: 'جواب داد', no_answer: 'بی‌پاسخ', sold: 'فروش شد', follow_up: 'پیگیری',
    scheduled: 'زمان خرید داد', not_interested: 'علاقه نداشت', call_later: 'بعداً زنگ',
    cancelled: 'کنسل', bad_number: 'شماره اشتباه', re_request: 'درخواست مجدد',
  };
  const LOST_REASON_FA = {
    price: 'قیمت گران', budget: 'بودجه ندارد', timing: 'زمان مناسب نیست',
    competitor: 'رفت پیش رقیب', no_need: 'نیازی ندارد', already_bought: 'جای دیگری خریده', other: 'سایر',
  };

  const fa = (n) => String(n).replace(/[0-9]/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);

  const load = () => {
    setLoading(true);
    const params = new URLSearchParams({ limit: 100 });
    if (statusFilter) params.set('status', statusFilter);
    if (search) params.set('search', search);
    fetch(`/api/seller/leads?${params}`, { headers }).then(r => r.json())
      .then(d => { if (d.success) setLeads(d.data?.leads || []); })
      .finally(() => setLoading(false));
  };

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

  const openHistory = (lead) => {
    setHistoryLead(lead);
    setHistoryEvents([]);
    setHistoryLoading(true);
    fetch(`/api/seller/leads/${lead.id}/history`, { headers }).then(r => r.json())
      .then(d => { if (d.success) setHistoryEvents(d.data.events || []); })
      .finally(() => setHistoryLoading(false));
  };

  const FILTERS = [
    { id: '', label: 'همه' }, { id: 'new', label: '✨ جدید' },
    { id: 'follow_up', label: '🔄 پیگیری' }, { id: 'buyer', label: '💰 خریدار' },
  ];

  const fmtDate = (s) => {
    if (!s) return '';
    try {
      const d = new Date(s);
      return `${d.getFullYear()}/${String(d.getMonth()+1).padStart(2,'0')}/${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
    } catch { return s; }
  };

  return (
    <div>
      <div className="col gap-8" style={{ marginBottom: 16 }}>
        <div className="pills" style={{ overflowX: 'auto', flexWrap: 'nowrap', paddingBottom: 2 }}>
          {FILTERS.map(f => (
            <button key={f.id} className={`pill ${statusFilter === f.id ? 'active' : ''}`} onClick={() => setStatusFilter(f.id)} style={{ whiteSpace: 'nowrap' }}>
              {f.label}
            </button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <div style={{ position: 'relative', flex: 1 }}>
            <Icon name="search" size={13} style={{ position: 'absolute', right: 9, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)', pointerEvents: 'none' }} />
            <input value={search} onChange={e => setSearch(e.target.value)} onKeyDown={e => e.key === 'Enter' && load()}
              placeholder="جستجو..." style={{ width: '100%', background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.07)', borderRadius: 7, padding: '7px 28px 7px 10px', color: 'var(--text-1)', fontSize: 12, outline: 'none', direction: 'rtl', boxSizing: 'border-box' }} />
          </div>
        </div>
      </div>

      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-3)' }}>در حال بارگذاری...</div>
        ) : leads.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-3)' }}>لیدی یافت نشد</div>
        ) : (
          <table className="table">
            <thead>
              <tr>
                <th>نام</th>
                <th>شماره</th>
                <th>امتیاز</th>
                <th>تماس</th>
                <th>آخرین نتیجه</th>
                <th>وضعیت</th>
                <th style={{ width: 110 }}></th>
              </tr>
            </thead>
            <tbody>
              {leads.map(l => {
                let lastOutcome = null;
                try { lastOutcome = l.last_call_json ? JSON.parse(l.last_call_json).outcome : null; } catch {}
                const ol = lastOutcome && OUTCOME_LABEL_SHORT[lastOutcome];
                return (
                  <tr key={l.id}>
                    <td>
                      <div className="row gap-10">
                        <div className="avatar" style={{ width: 30, height: 30, fontSize: 11 }}>
                          {(l.full_name || l.username || '؟').slice(0, 2)}
                        </div>
                        <div>
                          <div className="semi text-sm">{l.full_name || l.username || 'ناشناس'}</div>
                          {l.username && l.full_name && <div className="text-xs text-3">@{l.username}</div>}
                        </div>
                      </div>
                    </td>
                    <td className="mono text-sm text-2">{l.phone || '—'}</td>
                    <td><span className="mono text-xs" style={{ color: (l.score || 0) >= 7 ? '#F87171' : (l.score || 0) >= 4 ? '#FB923C' : '#475569' }}>{l.score || 0}</span></td>
                    <td>
                      {l.call_count > 0
                        ? <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 6, background: 'rgba(52,211,153,0.12)', color: '#34D399' }}>📞 {fa(l.call_count)}</span>
                        : <span style={{ fontSize: 11, color: '#374151' }}>—</span>
                      }
                    </td>
                    <td>
                      {ol ? <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 6, background: ol.color + '18', color: ol.color }}>{ol.icon}</span> : <span style={{ color: '#374151', fontSize: 11 }}>—</span>}
                    </td>
                    <td>
                      <span style={{ fontSize: 11, padding: '3px 8px', borderRadius: 6, background: (STATUS_COLOR[l.status] || '#6B7280') + '20', color: STATUS_COLOR[l.status] || '#6B7280' }}>
                        {(STATUS_LABEL[l.status] || l.status || '').replace(/^\S+ /, '')}
                      </span>
                    </td>
                    <td>
                      <div style={{ display: 'flex', gap: 5 }}>
                        <button onClick={() => openHistory(l)} style={{ padding: '5px 8px', borderRadius: 7, background: 'rgba(56,189,248,0.12)', border: '1px solid rgba(56,189,248,0.25)', color: '#38BDF8', fontSize: 11, cursor: 'pointer' }}
                          title="تاریخچه تماس">
                          📋
                        </button>
                        <button onClick={() => setCallLead(l)} style={{ padding: '5px 8px', borderRadius: 7, background: 'rgba(99,102,241,0.18)', border: '1px solid rgba(99,102,241,0.3)', color: '#818CF8', fontSize: 11, cursor: 'pointer' }}>
                          📞
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

      {/* ─── مودال تاریخچه تماس ─── */}
      {historyLead && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }} onClick={e => e.target === e.currentTarget && setHistoryLead(null)}>
          <div style={{ width: '100%', maxWidth: 520, maxHeight: '85vh', background: '#111118', border: '1px solid rgba(56,189,248,0.25)', borderRadius: 16, boxShadow: '0 20px 60px rgba(0,0,0,0.7)', display: 'flex', flexDirection: 'column' }}>
            {/* هدر */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 18px', borderBottom: '1px solid rgba(255,255,255,0.07)' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0' }}>📋 تاریخچه تماس</div>
                <div style={{ fontSize: 11, color: '#64748b', marginTop: 2 }}>
                  {historyLead.full_name || historyLead.username || 'ناشناس'}
                  {historyLead.phone && <span style={{ fontFamily: 'JetBrains Mono' }}> — {historyLead.phone}</span>}
                </div>
              </div>
              {/* وضعیت فعلی */}
              <span style={{ fontSize: 11, padding: '3px 10px', borderRadius: 20, background: (STATUS_COLOR[historyLead.status] || '#6B7280') + '20', color: STATUS_COLOR[historyLead.status] || '#6B7280' }}>
                {STATUS_LABEL[historyLead.status] || historyLead.status}
              </span>
              <button onClick={() => setHistoryLead(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#64748b', fontSize: 18, padding: 4 }}>✕</button>
            </div>

            {/* محتوا */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '14px 18px' }}>
              {historyLoading ? (
                <div style={{ padding: 32, textAlign: 'center', color: '#475569' }}>در حال بارگذاری...</div>
              ) : historyEvents.filter(e => e.event_type === 'call' || e.event_type === 'refer').length === 0 ? (
                <div style={{ padding: 32, textAlign: 'center', color: '#475569' }}>
                  <div style={{ fontSize: 28, marginBottom: 8 }}>📞</div>
                  هنوز رویدادی ثبت نشده
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {historyEvents.filter(e => e.event_type === 'call' || e.event_type === 'refer').map(ev => {
                    let data = {};
                    try { data = JSON.parse(ev.new_value || '{}'); } catch {}

                    // ─── رویداد ارجاع ───
                    if (ev.event_type === 'refer') {
                      return (
                        <div key={ev.id} style={{ padding: '12px 14px', borderRadius: 10, background: 'rgba(167,139,250,0.06)', border: '1px solid rgba(167,139,250,0.2)' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <span style={{ fontSize: 11, padding: '2px 9px', borderRadius: 20, background: 'rgba(167,139,250,0.15)', color: '#A78BFA', fontWeight: 600 }}>
                              🔀 ارجاع به {data.seller_name || '—'}
                            </span>
                            {ev.seller_name && (
                              <span style={{ fontSize: 10, color: '#64748b' }}>توسط {ev.seller_name}</span>
                            )}
                            <span style={{ marginRight: 'auto', fontSize: 10, color: '#475569', fontFamily: 'JetBrains Mono' }}>{fmtDate(ev.created_at)}</span>
                          </div>
                          {data.reason && <div style={{ marginTop: 6, fontSize: 11, color: '#94a3b8' }}>دلیل: {data.reason}</div>}
                        </div>
                      );
                    }

                    // ─── رویداد تماس ───
                    const ol = OUTCOME_LABEL_SHORT[data.outcome];
                    return (
                      <div key={ev.id} style={{ padding: '12px 14px', borderRadius: 10, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.07)' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                          {ol && (
                            <span style={{ fontSize: 11, padding: '2px 9px', borderRadius: 20, background: ol.color + '18', color: ol.color, fontWeight: 600 }}>
                              {ol.icon} {OUTCOME_FA[data.outcome] || data.outcome}
                            </span>
                          )}
                          {data.outcome === 'sold' && data.sale_amount && (
                            <span style={{ fontSize: 11, padding: '2px 9px', borderRadius: 20, background: 'rgba(52,211,153,0.12)', color: '#34D399', fontWeight: 700, fontFamily: 'JetBrains Mono' }}>
                              💰 {Number(data.sale_amount).toLocaleString('fa-IR')} تومان
                            </span>
                          )}
                          {ev.seller_name && (
                            <span style={{ fontSize: 10, color: '#64748b' }}>👤 {ev.seller_name}</span>
                          )}
                          <span style={{ marginRight: 'auto', fontSize: 10, color: '#475569', fontFamily: 'JetBrains Mono' }}>{fmtDate(ev.created_at)}</span>
                        </div>
                        {data.note && <div style={{ fontSize: 12, color: '#94a3b8', lineHeight: 1.6 }}>{data.note}</div>}
                        {ev.follow_up_at && (
                          <div style={{ marginTop: 6, fontSize: 11, color: '#818CF8' }}>
                            🔔 یادآور: {fmtDate(ev.follow_up_at)}
                          </div>
                        )}
                        {data.lost_reason && (
                          <div style={{ marginTop: 4, fontSize: 11, color: '#6B7280' }}>
                            دلیل: {LOST_REASON_FA[data.lost_reason] || data.lost_reason}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>

            {/* فوتر با دکمه تماس */}
            <div style={{ padding: '12px 18px', borderTop: '1px solid rgba(255,255,255,0.07)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 11, color: '#475569' }}>
                {historyEvents.filter(e => e.event_type === 'call').length} تماس ثبت‌شده
              </span>
              <button onClick={() => { setHistoryLead(null); setCallLead(historyLead); }}
                style={{ padding: '7px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: '#6366F1', color: '#fff', fontWeight: 600 }}>
                📞 ثبت تماس جدید
              </button>
            </div>
          </div>
        </div>
      )}

      {callLead && (
        <SellerCallModal
          lead={callLead}
          token={token}
          onClose={() => setCallLead(null)}
          onDone={() => { setCallLead(null); load(); }}
        />
      )}
    </div>
  );
};

// ─── صفحه یادآورها ───────────────────────────────────────────
const SellerReminders = ({ onCallLead }) => {
  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };
  const { Icon } = window.SB_UI;
  const [reminders, setReminders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [callLead, setCallLead] = useState(null);

  const fa = (n) => String(n == null ? '' : n).replace(/[0-9]/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);

  const load = () => {
    setLoading(true);
    fetch('/api/seller/reminders', { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setReminders(d.data.reminders || []); })
      .finally(() => setLoading(false));
  };

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

  const now = new Date();

  const fmtDate = (s) => {
    if (!s) return '';
    try {
      const d = new Date(s);
      const diff = Math.floor((d - now) / 60000); // دقیقه
      if (diff < 0) {
        const absDiff = Math.abs(diff);
        if (absDiff < 60)  return fa(absDiff) + ' دقیقه پیش';
        if (absDiff < 1440) return fa(Math.floor(absDiff / 60)) + ' ساعت پیش';
        return fa(Math.floor(absDiff / 1440)) + ' روز پیش';
      }
      if (diff < 60)   return fa(diff) + ' دقیقه دیگر';
      if (diff < 1440) return fa(Math.floor(diff / 60)) + ' ساعت دیگر';
      return fa(Math.floor(diff / 1440)) + ' روز دیگر';
    } catch { return s; }
  };

  const STATUS_COLOR = { scheduled: '#A78BFA', interested: '#60A5FA', new: '#818CF8', follow_up: '#94A3B8', buyer: '#34D399', lost: '#6B7280' };
  const STATUS_LABEL = { scheduled: '📅 زمان‌بندی', interested: '👀 علاقه‌مند', new: '✨ جدید', follow_up: '🔄 پیگیری', buyer: '💰 خریدار', lost: '❌ از دست رفته' };

  const overdue = reminders.filter(r => new Date(r.follow_up_at) < now);
  const upcoming = reminders.filter(r => new Date(r.follow_up_at) >= now);

  if (loading) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200, color: '#64748b' }}>
      ⏳ در حال بارگذاری...
    </div>
  );

  const ReminderCard = ({ r }) => {
    const isOverdue = new Date(r.follow_up_at) < now;
    let note = '';
    try { note = JSON.parse(r.new_value || '{}').note || ''; } catch {}

    return (
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '12px 14px', borderRadius: 10,
        background: isOverdue ? 'rgba(248,113,113,0.07)' : 'rgba(255,255,255,0.03)',
        border: `1px solid ${isOverdue ? 'rgba(248,113,113,0.25)' : 'rgba(255,255,255,0.07)'}`,
      }}>
        {/* آیکون */}
        <div style={{ fontSize: 20, minWidth: 28, textAlign: 'center' }}>
          {isOverdue ? '🔴' : '🔔'}
        </div>

        {/* اطلاعات */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 13, fontWeight: 600, color: '#e2e8f0' }}>
              {r.full_name || r.username || 'ناشناس'}
            </span>
            {r.status && (
              <span style={{ fontSize: 10, padding: '1px 7px', borderRadius: 10, background: (STATUS_COLOR[r.status] || '#6B7280') + '20', color: STATUS_COLOR[r.status] || '#6B7280' }}>
                {STATUS_LABEL[r.status] || r.status}
              </span>
            )}
          </div>
          {r.phone && (
            <div style={{ fontSize: 11, color: '#64748b', fontFamily: 'JetBrains Mono', marginTop: 2 }}>{r.phone}</div>
          )}
          {note && (
            <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 3, fontStyle: 'italic' }}>
              {note.length > 60 ? note.slice(0, 60) + '…' : note}
            </div>
          )}
        </div>

        {/* زمان + دکمه */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
          <span style={{ fontSize: 10, color: isOverdue ? '#F87171' : '#818CF8', fontWeight: isOverdue ? 600 : 400, whiteSpace: 'nowrap' }}>
            {fmtDate(r.follow_up_at)}
          </span>
          <button
            onClick={() => setCallLead({ id: r.lead_id, full_name: r.full_name, username: r.username, phone: r.phone, status: r.status, score: r.score })}
            style={{ padding: '5px 12px', borderRadius: 7, fontSize: 11, cursor: 'pointer', border: 'none', background: '#6366F1', color: '#fff', fontWeight: 600, whiteSpace: 'nowrap' }}>
            📞 تماس
          </button>
        </div>
      </div>
    );
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

      {/* ─── آمار بالا ─── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <div style={{ background: overdue.length > 0 ? 'rgba(248,113,113,0.08)' : 'rgba(255,255,255,0.04)', border: `1px solid ${overdue.length > 0 ? 'rgba(248,113,113,0.25)' : 'rgba(255,255,255,0.08)'}`, borderRadius: 10, padding: '12px 16px' }}>
          <div style={{ fontSize: 24, fontWeight: 700, color: overdue.length > 0 ? '#F87171' : '#64748b' }}>{fa(overdue.length)}</div>
          <div style={{ fontSize: 11, color: '#64748b', marginTop: 3 }}>سررسیدگذشته</div>
        </div>
        <div style={{ background: 'rgba(129,140,248,0.07)', border: '1px solid rgba(129,140,248,0.15)', borderRadius: 10, padding: '12px 16px' }}>
          <div style={{ fontSize: 24, fontWeight: 700, color: '#818CF8' }}>{fa(upcoming.length)}</div>
          <div style={{ fontSize: 11, color: '#64748b', marginTop: 3 }}>پیش رو</div>
        </div>
      </div>

      {/* ─── سررسیدگذشته‌ها ─── */}
      {overdue.length > 0 && (
        <div>
          <div style={{ fontSize: 12, fontWeight: 600, color: '#F87171', marginBottom: 8 }}>🔴 سررسیدگذشته ({fa(overdue.length)})</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {overdue.map(r => <ReminderCard key={r.id} r={r} />)}
          </div>
        </div>
      )}

      {/* ─── یادآورهای پیش رو ─── */}
      {upcoming.length > 0 && (
        <div>
          <div style={{ fontSize: 12, fontWeight: 600, color: '#818CF8', marginBottom: 8 }}>🔔 پیش رو ({fa(upcoming.length)})</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {upcoming.map(r => <ReminderCard key={r.id} r={r} />)}
          </div>
        </div>
      )}

      {/* ─── خالی ─── */}
      {reminders.length === 0 && (
        <div style={{ textAlign: 'center', padding: 60, color: '#475569' }}>
          <div style={{ fontSize: 36, marginBottom: 12 }}>🎉</div>
          <div style={{ fontSize: 14, fontWeight: 600, color: '#64748b' }}>هیچ یادآوری ندارید</div>
          <div style={{ fontSize: 12, color: '#374151', marginTop: 6 }}>وقتی تماسی با «بعداً زنگ» ثبت کنید اینجا نمایش داده می‌شه</div>
        </div>
      )}

      {callLead && (
        <SellerCallModal
          lead={callLead}
          token={token}
          onClose={() => setCallLead(null)}
          onDone={() => { setCallLead(null); load(); }}
        />
      )}
    </div>
  );
};

window.SellerApp = SellerApp;
