// ─── ماژول فروشندگان ─────────────────────────────────────────────

const SUSP_LEVEL = {
  warning:    { label: '⚠️ کارت زرد', color: '#F59E0B' },
  restricted: { label: '🔶 محدودیت',   color: '#FB923C' },
  suspended:  { label: '🔴 توقف',      color: '#F87171' },
};
const PROD_LEVEL = { junior: 'مبتدی', senior: 'ارشد', expert: 'متخصص' };

const _sellerGrad = (sc, susp) => {
  if (susp === 'suspended')  return 'linear-gradient(135deg,rgba(248,113,113,.65),rgba(220,38,38,.35))';
  if (susp === 'restricted') return 'linear-gradient(135deg,rgba(251,146,60,.65),rgba(194,65,12,.35))';
  if (susp === 'warning')    return 'linear-gradient(135deg,rgba(245,158,11,.65),rgba(180,83,9,.35))';
  if (sc === null || sc === undefined) return 'linear-gradient(135deg,rgba(99,102,241,.55),rgba(67,56,202,.3))';
  if (sc >= 60) return 'linear-gradient(135deg,rgba(52,211,153,.65),rgba(5,150,105,.35))';
  if (sc >= 35) return 'linear-gradient(135deg,rgba(251,146,60,.65),rgba(194,65,12,.35))';
  return 'linear-gradient(135deg,rgba(248,113,113,.65),rgba(220,38,38,.35))';
};

const _sbtn = (color, extraBg) => ({
  flex: 1, padding: '6px 0', borderRadius: 8, fontSize: 11, cursor: 'pointer',
  border: `1px solid ${color}35`, background: extraBg || `${color}12`, color,
  fontWeight: 600, transition: 'opacity .15s',
});

// ─────────────────────────────────────────────────────────────────
const Sellers = () => {
  const { useToast } = window.SB_UI;
  const { fa } = window.SB_DATA;
  const { useState } = React;
  const toast = useToast();
  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };
  const api = (url, opts = {}) => fetch(url, { headers, ...opts }).then(r => r.json());
  const [tab, setTab] = window.useStickyState('tab_sellers', 'sellers');

  const TABS = [
    { id: 'sellers',     label: '👥 فروشندگان' },
    { id: 'performance', label: '📊 ارزیابی عملکرد' },
    { id: 'commission',  label: '💰 پورسانت' },
    { id: 'activities',  label: '🎯 فعالیت‌ها' },
    { id: 'sales',       label: '📊 کارنامه فروش' },
    { id: 'badges',      label: '🏅 نشان‌ها' },
  ];

  return (
    <div style={{ padding: 24, height: '100%', display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* ─── تب‌ها ─── */}
      <div style={{ display: 'flex', gap: 6, borderBottom: '1px solid rgba(255,255,255,.07)' }}>
        {TABS.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 18px', borderRadius: '8px 8px 0 0', fontSize: 12, cursor: 'pointer',
            border: 'none', borderBottom: tab === t.id ? '2px solid #6366F1' : '2px solid transparent',
            background: tab === t.id ? 'rgba(99,102,241,.1)' : 'transparent',
            color: tab === t.id ? '#818CF8' : '#64748b', fontWeight: tab === t.id ? 600 : 400,
            transition: 'all .15s',
          }}>{t.label}</button>
        ))}
      </div>

      {/* ─── محتوا ─── */}
      <div style={{ flex: 1, overflow: 'auto' }}>
        {tab === 'sellers'     && <SellersTab     api={api} headers={headers} toast={toast} fa={fa} />}
        {tab === 'performance' && <PerformanceTab headers={headers} toast={toast} fa={fa} />}
        {tab === 'commission'  && <CommissionTab  headers={headers} toast={toast} fa={fa} />}
        {tab === 'activities'  && <ActivitiesTab  headers={headers} fa={fa} />}
        {tab === 'sales'       && <Sales />}
        {tab === 'badges'      && <BadgesAdminTab headers={headers} toast={toast} />}
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────
// کامپوننت محتوای کارتابل (جداگانه تا از IIFE در JSX جلوگیری شود)
// ─────────────────────────────────────────────────────────────────
const DashboardContent = ({ dashboard, scores, fa, setDashboard }) => {
  const d  = dashboard;
  const sl = d.seller;
  const sc = scores[sl && sl.id];
  const scoreVal = (sc && sc.finalScore) || 0;
  const monthMax = (sl && sl.max_active_leads) || 50;

  const metricLabel = { score: 'امتیاز کلی', expire_rate: 'نرخ expire', contact_rate: 'نرخ تماس' };

  return (
    <>
      {/* هدر کارتابل */}
      <div style={{ padding: '20px 24px 16px', borderBottom: '1px solid rgba(255,255,255,.07)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 44, height: 44, borderRadius: '50%', background: 'rgba(99,102,241,.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, color: '#818CF8', fontWeight: 700, flexShrink: 0 }}>
            {sl && sl.name && sl.name[0]}
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#e2e8f0' }}>{sl && sl.name}</div>
            <div style={{ fontSize: 11, color: '#64748b', marginTop: 3, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {(d.products || []).map(p => (
                <span key={p.id} style={{ padding: '1px 8px', borderRadius: 20, background: (p.color || '#6366F1') + '20', color: p.color || '#6366F1', fontSize: 10 }}>
                  {p.name} · {PROD_LEVEL[p.sp_level] || p.sp_level}
                </span>
              ))}
              {(d.products || []).length === 0 && <span>بدون تخصص</span>}
            </div>
          </div>
          <button onClick={() => setDashboard(null)} style={{ background: 'none', border: 'none', color: '#475569', cursor: 'pointer', fontSize: 22, lineHeight: 1, padding: '0 4px' }}>×</button>
        </div>
      </div>

      {d.suspension && (
        <div style={{ margin: '16px 24px 0', padding: '12px 16px', borderRadius: 10, background: ((SUSP_LEVEL[d.suspension.level] && SUSP_LEVEL[d.suspension.level].color) || '#F87171') + '15', border: '1px solid ' + ((SUSP_LEVEL[d.suspension.level] && SUSP_LEVEL[d.suspension.level].color) || '#F87171') + '40' }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: (SUSP_LEVEL[d.suspension.level] && SUSP_LEVEL[d.suspension.level].color) || '#F87171' }}>
            {(SUSP_LEVEL[d.suspension.level] && SUSP_LEVEL[d.suspension.level].label) || d.suspension.level} — فعال
          </div>
          <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 3 }}>{d.suspension.reason}</div>
          {d.suspension.ends_at && <div style={{ fontSize: 10, color: '#64748b', marginTop: 2 }}>پایان: {d.suspension.ends_at.slice(0, 10)}</div>}
        </div>
      )}
      {sl && sl.on_leave && (
        <div style={{ margin: '12px 24px 0', padding: '10px 14px', borderRadius: 10, background: 'rgba(251,146,60,.1)', border: '1px solid rgba(251,146,60,.25)' }}>
          <span style={{ fontSize: 12, color: '#FB923C' }}>🏖 در مرخصی — لید جدید دریافت نمی‌کند</span>
        </div>
      )}

      {/* آمار */}
      <div style={{ padding: '20px 24px' }}>
        <div style={{ fontSize: 11, color: '#64748b', marginBottom: 14, fontWeight: 600 }}>وضعیت جاری</div>
        {[
          { label: 'امتیاز ارزیابی', val: Math.round(scoreVal),                    max: 100,      color: '#818CF8', note: 'از ۱۰۰' },
          { label: 'لید این ماه',    val: d.monthAssigned || 0,                     max: monthMax, color: '#34D399', note: 'از ' + fa(monthMax) + ' ظرفیت' },
          { label: 'نرخ تماس',       val: Math.round((d.metrics && d.metrics.contact_rate) || 0), max: 100, color: '#38BDF8', note: 'درصد' },
        ].map(bar => (
          <div key={bar.label} style={{ marginBottom: 14 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#94a3b8', marginBottom: 5 }}>
              <span>{bar.label}</span>
              <span style={{ color: '#e2e8f0', fontWeight: 600 }}>{fa(bar.val)} <span style={{ color: '#475569', fontWeight: 400 }}>{bar.note}</span></span>
            </div>
            <div style={{ height: 8, borderRadius: 4, background: 'rgba(255,255,255,.07)', overflow: 'hidden' }}>
              <div style={{ height: '100%', borderRadius: 4, width: (bar.max > 0 ? Math.min(100, Math.round(bar.val / bar.max * 100)) : 0) + '%', background: bar.color, transition: 'width .4s' }} />
            </div>
          </div>
        ))}
      </div>

      {/* قوانین */}
      {(d.ruleStatuses || []).length > 0 && (
        <div style={{ padding: '0 24px 20px' }}>
          <div style={{ fontSize: 11, color: '#64748b', marginBottom: 10, fontWeight: 600 }}>📋 وضعیت قوانین</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {(d.ruleStatuses || []).map(rule => {
              const safe  = !rule.violated;
              const near  = safe && rule.distance < rule.threshold * 0.2;
              const icon  = safe ? (near ? '⚠️' : '✅') : '🚫';
              const color = safe ? (near ? '#FB923C' : '#34D399') : '#F87171';
              return (
                <div key={rule.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', borderRadius: 8, background: 'rgba(255,255,255,.03)', border: '1px solid rgba(255,255,255,.07)' }}>
                  <span style={{ fontSize: 14, flexShrink: 0 }}>{icon}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 11, color: '#e2e8f0', fontWeight: 600 }}>{rule.name}</div>
                    <div style={{ fontSize: 10, color: '#475569', marginTop: 1 }}>
                      {metricLabel[rule.metric] || rule.metric} — {rule.operator === 'lt' ? 'زیر' : 'بالای'} {rule.threshold}
                    </div>
                  </div>
                  <div style={{ textAlign: 'left', flexShrink: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color }}>{fa(rule.current)}</div>
                    {near && !rule.violated && <div style={{ fontSize: 9, color: '#FB923C' }}>فقط {fa(Math.abs(rule.distance))} تا آستانه</div>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* پیش‌بینی */}
      {d.predictedScore !== null && d.predictedScore !== undefined && (
        <div style={{ margin: '0 24px 20px', padding: '14px 16px', borderRadius: 10, background: 'rgba(99,102,241,.06)', border: '1px solid rgba(99,102,241,.15)' }}>
          <div style={{ fontSize: 11, color: '#64748b', marginBottom: 8 }}>🔮 پیش‌بینی امتیاز</div>
          <div style={{ display: 'flex', gap: 20, alignItems: 'flex-end' }}>
            <div>
              <div style={{ fontSize: 22, fontWeight: 800, color: d.predictedScore >= 60 ? '#34D399' : d.predictedScore >= 30 ? '#FB923C' : '#F87171', fontFamily: 'JetBrains Mono' }}>
                {fa(d.predictedScore)}
                {d.snapshots && d.snapshots.length >= 2 && (
                  <span style={{ fontSize: 12, color: d.predictedScore > ((d.snapshots[0] && d.snapshots[0].final_score) || 0) ? '#34D399' : '#F87171', marginRight: 6 }}>
                    {d.predictedScore > ((d.snapshots[0] && d.snapshots[0].final_score) || 0) ? '▲' : '▼'}
                  </span>
                )}
              </div>
              <div style={{ fontSize: 10, color: d.predictedScore >= 30 && !(d.ruleStatuses || []).some(r => r.violated) ? '#34D399' : '#FB923C', marginTop: 2 }}>
                {(d.ruleStatuses || []).some(r => r.violated) ? '⚠️ نیاز به توجه' : '✅ روند عادی'}
              </div>
            </div>
            {(d.snapshots || []).length > 0 && (
              <div style={{ flex: 1, display: 'flex', alignItems: 'flex-end', gap: 3, height: 40 }}>
                {d.snapshots.slice(0, 6).reverse().map((snap, i) => (
                  <div key={i} style={{ flex: 1, borderRadius: '3px 3px 0 0', background: 'rgba(99,102,241,.35)', minHeight: 4, height: Math.max(4, Math.round(((snap.final_score) || 0) / 100 * 40)) }} />
                ))}
              </div>
            )}
          </div>
        </div>
      )}
    </>
  );
};

// ─────────────────────────────────────────────────────────────────
// بخش توزیع خودکار لید
// ─────────────────────────────────────────────────────────────────
const AutoDistributeSection = ({ headers, toast, fa }) => {
  const { useState, useEffect } = React;
  const [poolCount,    setPoolCount]    = useState(null);
  const [autoOn,       setAutoOn]       = useState(false);
  const [minPct,       setMinPct]       = useState(10);
  const [editMinPct,   setEditMinPct]   = useState(false);
  const [minPctDraft,  setMinPctDraft]  = useState('10');
  const [distributing, setDistributing] = useState(false);
  const [preview,      setPreview]      = useState(null);
  const [lastResult,   setLastResult]   = useState(null);

  const load = () => {
    Promise.all([
      fetch('/api/market/pool', { headers }).then(r => r.json()),
      fetch('/api/distrules/evaluation/rules', { headers }).then(r => r.json()),
    ]).then(([pool, ev]) => {
      if (pool.success) setPoolCount(pool.data.total ?? pool.data.leads?.length ?? 0);
      if (ev.success) {
        const rules = ev.data.rules || [];
        const ad  = rules.find(r => r.rule_key === 'auto_distribute');
        const mp  = rules.find(r => r.rule_key === 'min_allocation_pct');
        if (ad) setAutoOn(ad.value === 'true' || ad.value === true);
        if (mp) { setMinPct(parseFloat(mp.value) || 10); setMinPctDraft(mp.value); }
      }
    });
  };
  useEffect(load, []);

  const toggleAuto = () => {
    const newVal = !autoOn;
    fetch('/api/distrules/evaluation/rules/auto_distribute', {
      method: 'PUT', headers, body: JSON.stringify({ value: String(newVal), enabled: 1 }),
    }).then(r => r.json()).then(d => {
      if (d.success) { setAutoOn(newVal); toast(newVal ? 'توزیع خودکار فعال شد' : 'توزیع خودکار غیرفعال شد', 'success'); }
      else toast(d.message || 'خطا', 'error');
    });
  };

  const saveMinPct = () => {
    const v = parseFloat(minPctDraft);
    if (isNaN(v) || v < 0 || v > 30) { toast('مقدار باید بین ۰ تا ۳۰ باشد', 'error'); return; }
    fetch('/api/distrules/evaluation/rules/min_allocation_pct', {
      method: 'PUT', headers, body: JSON.stringify({ value: String(v), enabled: 1 }),
    }).then(r => r.json()).then(d => {
      if (d.success) { setMinPct(v); setEditMinPct(false); toast('ذخیره شد', 'success'); }
      else toast(d.message || 'خطا', 'error');
    });
  };

  const doPreview = () => {
    setDistributing(true); setPreview(null); setLastResult(null);
    fetch('/api/distrules/auto-distribute?dry_run=true', { method: 'POST', headers })
      .then(r => r.json()).then(d => {
        setDistributing(false);
        if (d.success) setPreview(d.data);
        else toast(d.message || 'خطا', 'error');
      }).catch(() => { setDistributing(false); toast('خطای شبکه', 'error'); });
  };

  const doDistribute = () => {
    setDistributing(true); setPreview(null);
    fetch('/api/distrules/auto-distribute', { method: 'POST', headers })
      .then(r => r.json()).then(d => {
        setDistributing(false);
        if (d.success) { setLastResult(d.data); load(); toast(d.data.message || 'توزیع انجام شد', 'success'); }
        else toast(d.message || 'خطا', 'error');
      }).catch(() => { setDistributing(false); toast('خطای شبکه', 'error'); });
  };

  return (
    <div style={{ padding: '16px 20px', borderRadius: 14, background: 'rgba(99,102,241,.06)', border: '1px solid rgba(99,102,241,.18)', marginBottom: 8 }}>
      {/* ─── هدر ─── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
        <span style={{ fontSize: 16 }}>🎯</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: '#e2e8f0' }}>توزیع خودکار لید</div>
          <div style={{ fontSize: 11, color: '#64748b', marginTop: 1 }}>
            {poolCount === null ? 'در حال بارگذاری...' : `${fa(poolCount)} لید در استخر منتظر ارجاع`}
          </div>
        </div>
        {/* toggle روشن/خاموش */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 11, color: autoOn ? '#34D399' : '#64748b' }}>{autoOn ? 'خودکار فعال' : 'خودکار خاموش'}</span>
          <button onClick={toggleAuto} style={{
            width: 40, height: 22, borderRadius: 11, border: 'none', cursor: 'pointer', position: 'relative',
            background: autoOn ? 'rgba(52,211,153,.35)' : 'rgba(107,114,128,.2)', transition: 'background .2s',
          }}>
            <div style={{
              width: 16, height: 16, borderRadius: '50%', position: 'absolute', top: 3,
              left: autoOn ? 21 : 3, background: autoOn ? '#34D399' : '#6B7280', transition: 'left .2s',
            }} />
          </button>
        </div>
      </div>

      {/* ─── تنظیم حداقل سهم ─── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14, padding: '10px 14px', borderRadius: 10, background: 'rgba(255,255,255,.03)', border: '1px solid rgba(255,255,255,.07)' }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: '#94a3b8' }}>حداقل سهم فروشنده جدید</div>
          <div style={{ fontSize: 10, color: '#475569', marginTop: 2 }}>فروشنده‌ای که داده کافی ندارد حداقل این درصد از لیدها را می‌گیرد</div>
        </div>
        {editMinPct ? (
          <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <input type="number" value={minPctDraft} onChange={e => setMinPctDraft(e.target.value)}
              style={{ width: 64, padding: '4px 8px', borderRadius: 7, background: 'rgba(255,255,255,.08)', border: '1px solid rgba(99,102,241,.4)', color: '#e2e8f0', fontSize: 13, outline: 'none', direction: 'ltr', fontFamily: 'JetBrains Mono', textAlign: 'center' }} />
            <span style={{ fontSize: 11, color: '#64748b' }}>٪</span>
            <button onClick={saveMinPct} style={{ padding: '4px 12px', borderRadius: 7, fontSize: 11, cursor: 'pointer', border: 'none', background: '#6366F1', color: '#fff', fontWeight: 600 }}>ذخیره</button>
            <button onClick={() => setEditMinPct(false)} style={{ padding: '4px 8px', borderRadius: 7, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(255,255,255,.1)', background: 'transparent', color: '#64748b' }}>×</button>
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: '#818CF8', fontFamily: 'JetBrains Mono' }}>{fa(minPct)}٪</span>
            <button onClick={() => setEditMinPct(true)} style={{ padding: '3px 10px', borderRadius: 7, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(99,102,241,.25)', background: 'rgba(99,102,241,.08)', color: '#818CF8' }}>تغییر</button>
          </div>
        )}
      </div>

      {/* ─── دکمه‌های اجرا ─── */}
      <div style={{ display: 'flex', gap: 8 }}>
        <button onClick={doPreview} disabled={distributing || poolCount === 0}
          style={{ flex: 1, padding: '9px 0', borderRadius: 9, fontSize: 12, fontWeight: 600, cursor: poolCount === 0 ? 'not-allowed' : 'pointer', border: '1px solid rgba(99,102,241,.3)', background: 'rgba(99,102,241,.1)', color: '#818CF8', opacity: poolCount === 0 ? 0.4 : 1 }}>
          {distributing ? '⏳ در حال بررسی...' : '🔍 پیش‌نمایش توزیع'}
        </button>
        <button onClick={doDistribute} disabled={distributing || poolCount === 0}
          style={{ flex: 1, padding: '9px 0', borderRadius: 9, fontSize: 12, fontWeight: 600, cursor: poolCount === 0 ? 'not-allowed' : 'pointer', border: 'none', background: poolCount === 0 ? 'rgba(99,102,241,.25)' : '#6366F1', color: '#fff', opacity: poolCount === 0 ? 0.4 : 1 }}>
          🎯 توزیع همین الان
        </button>
      </div>

      {/* ─── نتیجه آخرین توزیع ─── */}
      {lastResult && lastResult.assigned > 0 && (
        <div style={{ marginTop: 12, padding: '10px 14px', borderRadius: 10, background: 'rgba(52,211,153,.07)', border: '1px solid rgba(52,211,153,.2)' }}>
          <div style={{ fontSize: 12, color: '#34D399', fontWeight: 600, marginBottom: 6 }}>✅ {fa(lastResult.assigned)} لید توزیع شد</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {(lastResult.breakdown || []).map((b, i) => (
              <span key={i} style={{ fontSize: 10, padding: '2px 10px', borderRadius: 20, background: 'rgba(52,211,153,.12)', color: '#34D399', border: '1px solid rgba(52,211,153,.2)' }}>
                {b.name} · {fa(b.count)} لید
              </span>
            ))}
          </div>
          {lastResult.skipped > 0 && <div style={{ fontSize: 10, color: '#FB923C', marginTop: 6 }}>⚠️ {fa(lastResult.skipped)} لید بدون ظرفیت/متخصص ماند</div>}
        </div>
      )}

      {/* ─── Modal پیش‌نمایش ─── */}
      {preview && (
        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,.8)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
          onClick={e => e.target === e.currentTarget && setPreview(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(99,102,241,.3)', borderRadius: 16, padding: 28, width: 440, maxHeight: '80vh', overflow: 'auto' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
              <span style={{ fontSize: 22 }}>🎯</span>
              <div>
                <div style={{ fontSize: 15, fontWeight: 700, color: '#e2e8f0' }}>پیش‌نمایش توزیع هوشمند</div>
                <div style={{ fontSize: 11, color: '#475569', marginTop: 2 }}>قبل از اجرا بررسی کنید</div>
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 18 }}>
              <div style={{ padding: '12px 14px', borderRadius: 10, background: 'rgba(52,211,153,.08)', border: '1px solid rgba(52,211,153,.2)', textAlign: 'center' }}>
                <div style={{ fontSize: 24, fontWeight: 800, color: '#34D399' }}>{fa(preview.planned)}</div>
                <div style={{ fontSize: 10, color: '#475569', marginTop: 2 }}>لید توزیع می‌شود</div>
              </div>
              <div style={{ padding: '12px 14px', borderRadius: 10, background: 'rgba(255,255,255,.04)', border: '1px solid rgba(255,255,255,.08)', textAlign: 'center' }}>
                <div style={{ fontSize: 24, fontWeight: 800, color: '#64748b' }}>{fa(preview.skipped)}</div>
                <div style={{ fontSize: 10, color: '#475569', marginTop: 2 }}>بدون متخصص/ظرفیت</div>
              </div>
            </div>
            {(preview.breakdown || []).length > 0 && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 20 }}>
                {preview.breakdown.map((b, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', borderRadius: 8, background: 'rgba(255,255,255,.03)', border: '1px solid rgba(255,255,255,.07)' }}>
                    <div style={{ flex: 1, fontSize: 12, color: '#e2e8f0' }}>{b.name}</div>
                    <span style={{ fontSize: 10, color: '#64748b' }}>امتیاز {fa(b.score)}</span>
                    <span style={{ fontSize: 13, fontWeight: 700, color: '#818CF8', fontFamily: 'JetBrains Mono' }}>{fa(b.count)} لید</span>
                  </div>
                ))}
              </div>
            )}
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => setPreview(null)} style={{ flex: 1, padding: '9px 0', borderRadius: 9, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#64748b' }}>انصراف</button>
              <button onClick={() => { setPreview(null); doDistribute(); }} style={{ flex: 1, padding: '9px 0', borderRadius: 9, fontSize: 12, cursor: 'pointer', border: 'none', background: '#6366F1', color: '#fff', fontWeight: 600 }}>✅ تأیید و توزیع</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ─────────────────────────────────────────────────────────────────
// تب فروشندگان — کارت‌های گرادیانت
// ─────────────────────────────────────────────────────────────────
const SellersTab = ({ api, headers, toast, fa }) => {
  const { useState, useEffect } = React;
  const { Icon } = window.SB_UI;
  const [sellers,      setSellers]      = useState([]);
  const [scores,       setScores]       = useState({});
  const [loading,      setLoading]      = useState(true);
  const [editModal,    setEditModal]    = useState(null);
  const [form,         setForm]         = useState({ name: '', phone: '', max_active_leads: 50 });
  const [saving,       setSaving]       = useState(false);
  const [detailSeller, setDetailSeller] = useState(null);
  const [sellerLeads,  setSellerLeads]  = useState([]);
  const [dashboard,    setDashboard]    = useState(null);
  const [suspModal,    setSuspModal]    = useState(null);
  const [suspForm,     setSuspForm]     = useState({ level: 'warning', reason: '', days: 30 });
  const [plans,        setPlans]        = useState(null); // null = هنوز لود نشده
  const [planModal,    setPlanModal]    = useState(null); // { seller, current }
  const [planForm,     setPlanForm]     = useState({ plan_id: '', start_date: '' });
  const [planSaving,   setPlanSaving]   = useState(false);

  const load = () => {
    setLoading(true);
    Promise.all([
      fetch('/api/market/sellers',           { headers }).then(r => r.json()),
      fetch('/api/distrules/evaluation/scores', { headers }).then(r => r.json()),
    ]).then(([sd, sc]) => {
      if (sd.success) setSellers(sd.data.sellers || []);
      if (sc.success) {
        const map = {};
        (sc.data.scores || []).forEach(s => { map[s.sellerId] = s; });
        setScores(map);
      }
      setLoading(false);
    }).catch(() => setLoading(false));
  };
  useEffect(load, []);

  const openNew  = () => { setForm({ name: '', phone: '', max_active_leads: 50 }); setEditModal('new'); };
  const openEdit = (s) => { setForm({ name: s.name, phone: s.phone || '', max_active_leads: s.max_active_leads || 50 }); setEditModal(s); };

  const save = () => {
    if (!form.name.trim()) return;
    setSaving(true);
    const isNew = editModal === 'new';
    fetch(isNew ? '/api/market/sellers' : `/api/market/sellers/${editModal.id}`, {
      method: isNew ? 'POST' : 'PUT', headers, body: JSON.stringify(form),
    }).then(r => r.json()).then(d => {
      setSaving(false);
      if (d.success) { toast(isNew ? 'فروشنده اضافه شد' : 'ذخیره شد', 'success'); setEditModal(null); load(); }
      else toast(d.message || 'خطا', 'error');
    }).catch(() => { setSaving(false); toast('خطای شبکه', 'error'); });
  };

  const toggleActive = (s) => {
    fetch(`/api/market/sellers/${s.id}`, { method: 'PUT', headers, body: JSON.stringify({ is_active: s.is_active ? 0 : 1 }) })
      .then(r => r.json()).then(d => { if (d.success) load(); else toast(d.message || 'خطا', 'error'); });
  };

  const deleteSeller = (s) => {
    if (!confirm(`فروشنده "${s.name}" حذف شود؟`)) return;
    fetch(`/api/market/sellers/${s.id}`, { method: 'DELETE', headers })
      .then(r => r.json()).then(d => {
        if (d.success) { toast('حذف شد', 'success'); load(); }
        else toast(d.message || 'خطا', 'error');
      });
  };

  const openDetail = (s) => {
    setDetailSeller(s);
    fetch(`/api/market/sellers/${s.id}/leads`, { headers }).then(r => r.json()).then(d => {
      if (d.success) setSellerLeads(d.data.leads || []);
    });
  };

  const openDashboard = (s) => {
    setDashboard({ seller: s, loading: true });
    fetch(`/api/market/sellers/${s.id}/dashboard`, { headers }).then(r => r.json()).then(d => {
      if (d.success) setDashboard(d.data);
      else { setDashboard(null); toast(d.message || 'خطا', 'error'); }
    }).catch(() => { setDashboard(null); toast('خطای شبکه', 'error'); });
  };

  const toggleLeave = (s) => {
    fetch(`/api/market/sellers/${s.id}`, { method: 'PUT', headers, body: JSON.stringify({ on_leave: s.on_leave ? 0 : 1 }) })
      .then(r => r.json()).then(d => {
        if (d.success) { toast(s.on_leave ? 'مرخصی پایان یافت' : 'مرخصی ثبت شد', 'success'); load(); }
        else toast(d.message || 'خطا', 'error');
      });
  };

  const openPlanModal = (s) => {
    setPlanModal({ seller: s, current: null });
    setPlanForm({ plan_id: '', start_date: new Date().toISOString().slice(0, 10) });
    if (plans === null) {
      fetch('/api/commission/plans', { headers }).then(r => r.json())
        .then(d => setPlans(d.success ? (d.data.plans || []) : [])).catch(() => setPlans([]));
    }
    // طرح فعلی فروشنده
    const period = new Date().toISOString().slice(0, 7);
    fetch(`/api/commission/sellers/${s.id}/summary?period=${period}`, { headers }).then(r => r.json())
      .then(d => { if (d.success) setPlanModal(m => m && m.seller.id === s.id ? { ...m, current: d.data.plan_name || null } : m); })
      .catch(() => {});
  };

  const saveSellerPlan = () => {
    if (!planModal || !planForm.plan_id) return;
    setPlanSaving(true);
    fetch(`/api/commission/sellers/${planModal.seller.id}/assign-plan`, {
      method: 'POST', headers, body: JSON.stringify({ plan_id: planForm.plan_id, start_date: planForm.start_date || new Date().toISOString().slice(0, 10) })
    }).then(r => r.json()).then(d => {
      setPlanSaving(false);
      if (d.success) { setPlanModal(null); toast('طرح فروشنده تغییر کرد ✅', 'success'); }
      else toast(d.message || 'خطا', 'error');
    }).catch(() => setPlanSaving(false));
  };

  const doSuspend = () => {
    if (!suspModal) return;
    fetch(`/api/distrules/sellers/${suspModal.id}/suspend`, { method: 'POST', headers, body: JSON.stringify(suspForm) })
      .then(r => r.json()).then(d => {
        if (d.success) { toast('توقف اعمال شد', 'success'); setSuspModal(null); load(); }
        else toast(d.message || 'خطا', 'error');
      });
  };

  const doUnsuspend = (s) => {
    fetch(`/api/distrules/sellers/${s.id}/unsuspend`, { method: 'POST', headers })
      .then(r => r.json()).then(d => {
        if (d.success) { toast('توقف برداشته شد', 'success'); load(); }
        else toast(d.message || 'خطا', 'error');
      });
  };

  return (
    <div className="col gap-16">
      {/* ── دسترسی مدیر فروش (ادمین پنل مادر) ── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 10, background: 'rgba(99,102,241,.08)', border: '1px solid rgba(99,102,241,.18)' }}>
        <span style={{ fontSize: 11, color: '#818CF8', fontWeight: 600 }}>🛡 مدیر فروش (ادمین پنل):</span>
        <span style={{ fontSize: 12, color: '#e2e8f0', fontFamily: 'JetBrains Mono', direction: 'ltr' }}>admin / admin123</span>
      </div>

      {/* ── توزیع خودکار ── */}
      <AutoDistributeSection headers={headers} toast={toast} fa={fa} />

      {/* ── سرصفحه ── */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ fontSize: 12, color: '#64748b' }}>
          {!loading && `${fa(sellers.length)} فروشنده • ${fa(sellers.filter(s => s.is_active).length)} فعال`}
        </span>
        <button onClick={openNew} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 18px', borderRadius: 9, fontSize: 12, cursor: 'pointer', border: 'none', background: '#6366F1', color: '#fff', fontWeight: 600 }}>
          <Icon name="plus" size={13} /> فروشنده جدید
        </button>
      </div>

      {loading ? (
        <div style={{ padding: 48, textAlign: 'center', color: '#64748b' }}>در حال بارگذاری...</div>
      ) : sellers.length === 0 ? (
        <div style={{ padding: 48, textAlign: 'center', color: '#64748b' }}>
          <div style={{ fontSize: 32, marginBottom: 10 }}>👥</div>
          هنوز فروشنده‌ای ثبت نشده
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16 }}>
          {sellers.map(s => {
            const sc         = scores[s.id];
            const scoreVal   = sc?.totalLeads > 0 ? sc.finalScore : null;
            const grad       = _sellerGrad(scoreVal, s.suspension_level);
            const pct        = s.max_active_leads > 0 ? Math.min(100, Math.round((s.active_leads || 0) / s.max_active_leads * 100)) : 0;
            const capColor   = pct > 80 ? '#F87171' : pct > 50 ? '#FB923C' : '#34D399';
            const scoreColor = scoreVal !== null ? (scoreVal >= 60 ? '#34D399' : scoreVal >= 35 ? '#FB923C' : '#F87171') : '#818CF8';

            return (
              <div key={s.id}
                style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 14, overflow: 'hidden', opacity: s.is_active ? 1 : 0.55, transition: 'box-shadow 0.2s' }}
                onMouseEnter={e => e.currentTarget.style.boxShadow = '0 6px 28px rgba(99,102,241,.18)'}
                onMouseLeave={e => e.currentTarget.style.boxShadow = 'none'}
              >
                {/* ── هدر گرادیانت ── */}
                <div style={{ height: 110, background: grad, display: 'grid', placeItems: 'center', position: 'relative' }}>
                  <div style={{ width: 54, height: 54, borderRadius: '50%', background: 'rgba(255,255,255,.18)', backdropFilter: 'blur(12px)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24, color: '#fff', fontWeight: 800 }}>
                    {s.name[0]}
                  </div>
                  {/* وضعیت — بالا راست */}
                  <div style={{ position: 'absolute', top: 10, right: 10 }}>
                    <span style={{ fontSize: 10, padding: '3px 10px', borderRadius: 20, backdropFilter: 'blur(8px)', fontWeight: 600, background: s.is_active ? 'rgba(52,211,153,.25)' : 'rgba(107,114,128,.25)', color: s.is_active ? '#34D399' : '#94A3B8' }}>
                      {s.is_active ? '● فعال' : '○ غیرفعال'}
                    </span>
                  </div>
                  {/* مرخصی/توقف — بالا چپ */}
                  {(s.on_leave || s.suspension_level) && (
                    <div style={{ position: 'absolute', top: 10, left: 10 }}>
                      {s.on_leave
                        ? <span style={{ fontSize: 10, padding: '3px 10px', borderRadius: 20, backdropFilter: 'blur(8px)', background: 'rgba(251,146,60,.28)', color: '#FB923C', fontWeight: 600 }}>🏖 مرخصی</span>
                        : <span style={{ fontSize: 10, padding: '3px 10px', borderRadius: 20, backdropFilter: 'blur(8px)', background: `${SUSP_LEVEL[s.suspension_level]?.color || '#F87171'}30`, color: SUSP_LEVEL[s.suspension_level]?.color || '#F87171', fontWeight: 600 }}>
                            {SUSP_LEVEL[s.suspension_level]?.label || s.suspension_level}
                          </span>
                      }
                    </div>
                  )}
                </div>

                {/* ── محتوا ── */}
                <div style={{ padding: '14px 16px 16px' }}>
                  {/* نام + تلفن */}
                  <div style={{ marginBottom: 10 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0' }}>{s.name}</div>
                    {s.phone && <div style={{ fontSize: 11, color: '#475569', fontFamily: 'JetBrains Mono', marginTop: 2 }}>{s.phone}</div>}
                    {s.login_username && (
                      <div style={{ fontSize: 11, color: '#818CF8', fontFamily: 'JetBrains Mono', marginTop: 4, direction: 'ltr', textAlign: 'right' }}>
                        🔑 {s.login_username}
                      </div>
                    )}
                  </div>

                  {/* چیپ محصولات */}
                  {(s.products || []).length > 0 && (
                    <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginBottom: 10 }}>
                      {s.products.map(p => (
                        <span key={p.id} style={{ fontSize: 9, padding: '2px 8px', borderRadius: 20, background: `${p.color || '#6366F1'}20`, color: p.color || '#6366F1', border: `1px solid ${p.color || '#6366F1'}40` }}>
                          {p.name} · {PROD_LEVEL[p.sp_level] || p.sp_level}
                        </span>
                      ))}
                    </div>
                  )}

                  {/* نوار امتیاز */}
                  {scoreVal !== null ? (
                    <div style={{ marginBottom: 10, padding: '8px 12px', borderRadius: 9, background: 'rgba(255,255,255,.03)', border: '1px solid rgba(255,255,255,.06)' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 5 }}>
                        <span style={{ fontSize: 10, color: '#64748b' }}>امتیاز ارزیابی</span>
                        <span style={{ fontSize: 14, fontWeight: 700, color: scoreColor, fontFamily: 'JetBrains Mono' }}>{fa(Math.round(scoreVal))}</span>
                      </div>
                      <div style={{ height: 4, borderRadius: 4, background: 'rgba(255,255,255,.07)' }}>
                        <div style={{ height: '100%', borderRadius: 4, width: scoreVal + '%', background: scoreColor, transition: 'width .4s' }} />
                      </div>
                    </div>
                  ) : (
                    <div style={{ marginBottom: 10, padding: '6px 12px', borderRadius: 9, fontSize: 10, color: '#475569', background: 'rgba(255,255,255,.02)', textAlign: 'center' }}>
                      داده کافی برای ارزیابی نیست
                    </div>
                  )}

                  {/* نوار ظرفیت */}
                  <div style={{ marginBottom: 14 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: '#64748b', marginBottom: 4 }}>
                      <span>ظرفیت لید</span>
                      <span style={{ fontFamily: 'JetBrains Mono', color: pct > 80 ? '#F87171' : '#94a3b8' }}>{fa(s.active_leads || 0)} / {fa(s.max_active_leads || 50)}</span>
                    </div>
                    <div style={{ height: 5, borderRadius: 5, background: 'rgba(255,255,255,.07)' }}>
                      <div style={{ height: '100%', borderRadius: 5, width: pct + '%', background: capColor, transition: 'width .3s' }} />
                    </div>
                  </div>

                  {/* دکمه‌ها — ردیف ۱ */}
                  <div style={{ display: 'flex', gap: 6, marginBottom: 6 }}>
                    <button onClick={() => openDashboard(s)} style={_sbtn('#A78BFA')}>📊 کارتابل</button>
                    <button onClick={() => openDetail(s)}    style={_sbtn('#38BDF8')}>👁 لیدها</button>
                    <button onClick={() => openEdit(s)}      style={_sbtn('#818CF8')}>✏️ ویرایش</button>
                  </div>
                  {/* دکمه‌ها — ردیف ۲ */}
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button onClick={() => openPlanModal(s)} style={_sbtn('#F59E0B')}>💰 طرح</button>
                    <button onClick={() => toggleLeave(s)} style={{ ..._sbtn('#FB923C'), background: s.on_leave ? 'rgba(251,146,60,.18)' : 'rgba(251,146,60,.08)' }}>
                      {s.on_leave ? '🏖 در مرخصی' : '🏖 مرخصی'}
                    </button>
                    {s.suspension_level
                      ? <button onClick={() => doUnsuspend(s)} style={_sbtn('#34D399')}>✅ رفع توقف</button>
                      : <button onClick={() => { setSuspModal(s); setSuspForm({ level: 'warning', reason: '', days: 30 }); }} style={_sbtn('#F87171')}>⛔ توقف</button>
                    }
                    <button onClick={() => toggleActive(s)} title={s.is_active ? 'غیرفعال' : 'فعال'} style={{ padding: '6px 10px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.1)', background: 'transparent', color: '#64748b' }}>
                      {s.is_active ? '⏸' : '▶'}
                    </button>
                    <button onClick={() => deleteSeller(s)} style={{ padding: '6px 10px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(248,113,113,.2)', background: 'transparent', color: '#F87171' }}>🗑</button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* ─── Modal ویرایش فروشنده ─── */}
      {editModal !== null && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.75)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setEditModal(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(255,255,255,.1)', borderRadius: 14, padding: 28, width: 380 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0', marginBottom: 20 }}>
              {editModal === 'new' ? '👤 فروشنده جدید' : `ویرایش — ${editModal.name}`}
            </div>
            <div className="col gap-14">
              {[
                { key: 'name',             label: 'نام فروشنده',        placeholder: 'مثلا: علی رضایی', type: 'text'   },
                { key: 'phone',            label: 'شماره تلفن',          placeholder: '09xxxxxxxxx',     type: 'text'   },
                { key: 'max_active_leads', label: 'حداکثر لید همزمان',  placeholder: '50',              type: 'number' },
              ].map(f => (
                <div key={f.key}>
                  <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>{f.label}</div>
                  <input type={f.type} value={form[f.key]} onChange={e => setForm(p => ({ ...p, [f.key]: e.target.value }))} placeholder={f.placeholder}
                    style={{ width: '100%', padding: '8px 12px', borderRadius: 8, background: 'rgba(255,255,255,.06)', border: '1px solid rgba(255,255,255,.12)', color: '#e2e8f0', fontSize: 13, outline: 'none', boxSizing: 'border-box', direction: f.type === 'number' ? 'ltr' : 'rtl', fontFamily: f.type === 'number' ? 'JetBrains Mono' : 'inherit' }} />
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 22 }}>
              <button onClick={() => setEditModal(null)} style={{ padding: '8px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#64748b' }}>انصراف</button>
              <button onClick={save} disabled={saving || !form.name.trim()} style={{ padding: '8px 22px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: form.name.trim() ? '#6366F1' : 'rgba(99,102,241,.3)', color: form.name.trim() ? '#fff' : '#475569', fontWeight: 600 }}>
                {saving ? 'در حال ذخیره...' : 'ذخیره'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ─── Modal لیدهای فروشنده ─── */}
      {detailSeller && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.75)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setDetailSeller(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(255,255,255,.1)', borderRadius: 14, padding: 24, width: 480, maxHeight: '72vh', overflow: 'auto' }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0', marginBottom: 16 }}>لیدهای {detailSeller.name}</div>
            {sellerLeads.length === 0 ? (
              <div style={{ padding: 24, textAlign: 'center', color: '#64748b', fontSize: 12 }}>لیدی ندارد</div>
            ) : (
              <div className="col gap-6">
                {sellerLeads.map(l => (
                  <div key={l.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', borderRadius: 8, background: 'rgba(255,255,255,.03)', border: '1px solid rgba(255,255,255,.06)' }}>
                    <div style={{ flex: 1, fontSize: 12, color: '#e2e8f0' }}>{l.full_name || l.username || 'ناشناس'}</div>
                    {l.phone && <div style={{ fontSize: 11, color: '#475569', fontFamily: 'JetBrains Mono' }}>{l.phone}</div>}
                    <span style={{ fontSize: 10, color: '#64748b' }}>{l.status}</span>
                  </div>
                ))}
              </div>
            )}
            <div style={{ marginTop: 16, textAlign: 'left' }}>
              <button onClick={() => setDetailSeller(null)} style={{ padding: '7px 20px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#94a3b8' }}>بستن</button>
            </div>
          </div>
        </div>
      )}

      {/* ─── Modal طرح پورسانت فروشنده ─── */}
      {planModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.8)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setPlanModal(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(245,158,11,.3)', borderRadius: 14, padding: 28, width: 360 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0', marginBottom: 6 }}>💰 طرح پورسانت فروشنده</div>
            <div style={{ fontSize: 12, color: '#64748b', marginBottom: 16 }}>{planModal.seller.name}</div>
            {planModal.current
              ? <div style={{ fontSize: 12, color: '#F59E0B', marginBottom: 16, padding: '8px 12px', borderRadius: 8, background: 'rgba(245,158,11,.08)', border: '1px solid rgba(245,158,11,.18)' }}>طرح فعلی: <strong>{planModal.current}</strong></div>
              : <div style={{ fontSize: 12, color: '#64748b', marginBottom: 16, padding: '8px 12px', borderRadius: 8, background: 'rgba(255,255,255,.03)', border: '1px dashed rgba(255,255,255,.1)' }}>هنوز طرحی ندارد</div>}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>طرح جدید</div>
                <select value={planForm.plan_id} onChange={e => setPlanForm(p => ({ ...p, plan_id: e.target.value }))}
                  style={{ background: 'rgba(255,255,255,.06)', border: '1px solid rgba(255,255,255,.12)', borderRadius: 8, padding: '8px 12px', color: '#e2e8f0', fontSize: 13, outline: 'none', width: '100%', boxSizing: 'border-box', appearance: 'none' }}>
                  <option value="">{plans === null ? 'در حال بارگذاری...' : 'انتخاب طرح...'}</option>
                  {(plans || []).filter(p => p.is_active).map(p => (
                    <option key={p.id} value={p.id}>
                      {p.name}{p.base_salary > 0 ? ` — حقوق ${_toM(p.base_salary, fa)}` : ''}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>از تاریخ</div>
                <input type="date" value={planForm.start_date} onChange={e => setPlanForm(p => ({ ...p, start_date: e.target.value }))}
                  style={{ background: 'rgba(255,255,255,.06)', border: '1px solid rgba(255,255,255,.12)', borderRadius: 8, padding: '8px 12px', color: '#e2e8f0', fontSize: 13, outline: 'none', width: '100%', boxSizing: 'border-box', direction: 'ltr', colorScheme: 'dark' }} />
              </div>
              <div style={{ fontSize: 11, color: '#475569', lineHeight: 1.7 }}>
                با تخصیص طرح جدید، طرح قبلی از همین تاریخ بسته می‌شود. حقوق، پورسانت و جایزه از این به بعد با طرح جدید محاسبه می‌شود.
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 22 }}>
              <button onClick={() => setPlanModal(null)} style={{ padding: '8px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#64748b' }}>انصراف</button>
              <button onClick={saveSellerPlan} disabled={planSaving || !planForm.plan_id}
                style={{ padding: '8px 22px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: planForm.plan_id ? '#F59E0B' : 'rgba(245,158,11,.3)', color: '#111', fontWeight: 600 }}>
                {planSaving ? 'در حال ذخیره...' : 'تخصیص طرح'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ─── Modal توقف ─── */}
      {suspModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.82)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setSuspModal(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(248,113,113,.3)', borderRadius: 14, padding: 26, width: 400 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#F87171', marginBottom: 4 }}>⛔ توقف فروشنده</div>
            <div style={{ fontSize: 12, color: '#64748b', marginBottom: 20 }}>{suspModal.name}</div>
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 11, color: '#64748b', marginBottom: 8 }}>سطح توقف</div>
              <div style={{ display: 'flex', gap: 8 }}>
                {Object.entries(SUSP_LEVEL).map(([k, v]) => (
                  <button key={k} onClick={() => setSuspForm(p => ({ ...p, level: k }))} style={{ flex: 1, padding: '8px 0', borderRadius: 9, fontSize: 11, cursor: 'pointer', border: 'none', fontWeight: 600, transition: 'all .15s', background: suspForm.level === k ? v.color + '28' : 'rgba(255,255,255,.05)', color: suspForm.level === k ? v.color : '#64748b' }}>
                    {v.label}
                  </button>
                ))}
              </div>
            </div>
            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>مدت (روز)</div>
              <input type="number" value={suspForm.days} onChange={e => setSuspForm(p => ({ ...p, days: e.target.value }))} style={{ width: '100%', padding: '8px 12px', borderRadius: 8, background: 'rgba(255,255,255,.06)', border: '1px solid rgba(255,255,255,.12)', color: '#e2e8f0', fontSize: 14, outline: 'none', boxSizing: 'border-box', direction: 'ltr', fontFamily: 'JetBrains Mono' }} />
            </div>
            <div style={{ marginBottom: 20 }}>
              <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>دلیل</div>
              <textarea value={suspForm.reason} onChange={e => setSuspForm(p => ({ ...p, reason: e.target.value }))} rows={2} style={{ width: '100%', padding: '8px 12px', borderRadius: 8, background: 'rgba(255,255,255,.06)', border: '1px solid rgba(255,255,255,.12)', color: '#e2e8f0', fontSize: 12, outline: 'none', resize: 'none', fontFamily: 'inherit', boxSizing: 'border-box' }} />
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <button onClick={() => setSuspModal(null)} style={{ padding: '8px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#64748b' }}>انصراف</button>
              <button onClick={doSuspend} style={{ padding: '8px 22px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: '#EF4444', color: '#fff', fontWeight: 600 }}>اعمال توقف</button>
            </div>
          </div>
        </div>
      )}

      {/* ─── Modal کارتابل ─── */}
      {dashboard && (
        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,.87)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={function(e){ if(e.target === e.currentTarget) setDashboard(null); }}>
          <div style={{ background: '#111118', border: '1px solid rgba(99,102,241,.3)', borderRadius: 16, width: 520, maxHeight: '90vh', overflow: 'auto' }}>
            {dashboard.loading ? (
              <div style={{ padding: 48, textAlign: 'center', color: '#64748b' }}>در حال بارگذاری کارتابل...</div>
            ) : (
              <DashboardContent dashboard={dashboard} scores={scores} fa={fa} setDashboard={setDashboard} />
            )}
          </div>
        </div>
      )}

    </div>
  );
};

// ─────────────────────────────────────────────────────────────────
// تب ارزیابی عملکرد فروشندگان
// ─────────────────────────────────────────────────────────────────
const PerformanceTab = ({ headers, toast, fa }) => {
  const { useState, useEffect } = React;
  const [scores,      setScores]      = useState([]);
  const [loading,     setLoading]     = useState(true);
  const [snapping,    setSnapping]    = useState(false);
  const [detail,      setDetail]      = useState(null);
  const [rules,       setRules]       = useState([]);
  const [history,     setHistory]     = useState([]);
  const [showHistory, setShowHistory] = useState(false);

  const load = () => {
    setLoading(true);
    Promise.all([
      fetch('/api/distrules/evaluation/scores',        { headers }).then(r => r.json()),
      fetch('/api/distrules/evaluation/rules',          { headers }).then(r => r.json()),
      fetch('/api/distrules/evaluation/history?limit=30', { headers }).then(r => r.json()),
    ]).then(([s, r, h]) => {
      if (s.success) setScores(s.data.scores   || []);
      if (r.success) setRules(r.data.rules     || []);
      if (h.success) setHistory(h.data.history || []);
      setLoading(false);
    }).catch(() => setLoading(false));
  };
  useEffect(load, []);

  const takeSnapshot = () => {
    setSnapping(true);
    fetch('/api/distrules/evaluation/snapshot', { method: 'POST', headers })
      .then(r => r.json()).then(d => {
        setSnapping(false);
        if (d.success) { load(); toast(`امتیازات ثبت شد — ${d.data.count} فروشنده`, 'success'); }
        else toast(d.message || 'خطا', 'error');
      }).catch(() => { setSnapping(false); toast('خطای شبکه', 'error'); });
  };

  const weightRules   = rules.filter(r => r.group_name === 'weights' && r.enabled);
  const totalRawW     = weightRules.reduce((s, r) => s + parseFloat(r.value), 0) || 1;
  const METRIC_LABEL  = { conversion:'نرخ تبدیل', revenue:'مبلغ فروش', speed:'سرعت تماس', contact_rate:'نرخ تماس', consistency:'ثبات', activity:'فعالیت روزانه' };
  const METRIC_COLOR  = { conversion:'#34D399', revenue:'#F59E0B', speed:'#38BDF8', contact_rate:'#A78BFA', consistency:'#F472B6', activity:'#6EE7B7' };
  const METRIC_KEY_MAP= { conversion:'conversion_weight', revenue:'revenue_weight', speed:'speed_weight', contact_rate:'contact_weight', consistency:'consistency_weight', activity:'activity_weight' };

  const ScoreBar = ({ score, color, showLabel, label, weight }) => (
    <div style={{ marginBottom: showLabel ? 8 : 4 }}>
      {showLabel && (
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: '#64748b', marginBottom: 3 }}>
          <span style={{ color }}>{label}</span>
          <span>{Math.round(score * 100)}% <span style={{ color: '#374151' }}>× {Math.round(weight * 100)}%</span></span>
        </div>
      )}
      <div style={{ height: showLabel ? 5 : 3, borderRadius: 4, background: 'rgba(255,255,255,.07)', overflow: 'hidden' }}>
        <div style={{ height: '100%', borderRadius: 4, width: Math.round(score * 100) + '%', background: color, transition: 'width .4s' }} />
      </div>
    </div>
  );

  return (
    <div className="col gap-16">
      {/* ─── هدر ─── */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, fontSize: 13, color: '#64748b' }}>
          امتیاز واقعی — بر اساس {fa(weightRules.length)} معیار فعال
        </div>
        <button onClick={load} style={{ padding: '6px 14px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(255,255,255,.1)', background: 'rgba(255,255,255,.04)', color: '#64748b' }}>🔄 رفرش</button>
        <button onClick={takeSnapshot} disabled={snapping} style={{ padding: '6px 14px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: 'none', background: snapping ? 'rgba(99,102,241,.3)' : '#6366F1', color: snapping ? '#475569' : '#fff', fontWeight: 600 }}>
          {snapping ? 'در حال ذخیره...' : '📌 snapshot'}
        </button>
        <button onClick={() => {
          if (!scores.length) return;
          const header = ['رتبه','نام','امتیاز','لید','فروش'].join(',');
          const rows = scores.map((s, i) => [`"${i+1}"`,`"${s.sellerName}"`,`"${Math.round(s.finalScore)}"`,`"${s.totalLeads}"`,`"${s.sold}"`].join(','));
          const csv = '﻿' + header + '\n' + rows.join('\n');
          const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
          const a = document.createElement('a'); a.href = URL.createObjectURL(blob);
          a.download = `performance_${new Date().toISOString().slice(0,10)}.csv`; a.click();
          toast('CSV دانلود شد', 'success');
        }} style={{ padding: '6px 14px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(52,211,153,.3)', background: 'rgba(52,211,153,.07)', color: '#34D399' }}>
          📥 خروجی CSV
        </button>
      </div>

      {/* ─── legend وزن‌ها ─── */}
      {weightRules.length > 0 && (
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', padding: '10px 14px', borderRadius: 10, background: 'rgba(255,255,255,.03)', border: '1px solid rgba(255,255,255,.07)' }}>
          {weightRules.map(r => {
            const mk = Object.keys(METRIC_KEY_MAP).find(k => METRIC_KEY_MAP[k] === r.rule_key);
            const pct = Math.round(parseFloat(r.value) / totalRawW * 100);
            return (
              <div key={r.rule_key} style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11 }}>
                <div style={{ width: 8, height: 8, borderRadius: '50%', background: METRIC_COLOR[mk] || '#94A3B8' }} />
                <span style={{ color: '#94A3B8' }}>{METRIC_LABEL[mk] || r.name}</span>
                <span style={{ color: METRIC_COLOR[mk] || '#94A3B8' }}>{pct}%</span>
              </div>
            );
          })}
        </div>
      )}

      {/* ─── تاریخچه ─── */}
      {history.length > 0 && (
        <button onClick={() => setShowHistory(v => !v)} style={{ display: 'flex', alignItems: 'center', gap: 6, alignSelf: 'flex-start', padding: '6px 14px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(99,102,241,.3)', background: showHistory ? 'rgba(99,102,241,.15)' : 'rgba(99,102,241,.07)', color: showHistory ? '#818CF8' : '#64748b' }}>
          📈 تاریخچه امتیاز {showHistory ? '▲' : '▼'}
        </button>
      )}
      {showHistory && history.length > 0 && (() => {
        const bySellerMap = {};
        history.forEach(row => {
          if (!bySellerMap[row.seller_id]) bySellerMap[row.seller_id] = { name: row.seller_name || row.seller_id, points: [] };
          bySellerMap[row.seller_id].points.push({ date: row.snapshot_at, score: row.final_score });
        });
        Object.values(bySellerMap).forEach(s => s.points.sort((a, b) => a.date.localeCompare(b.date)));
        const sellers  = Object.values(bySellerMap).filter(s => s.points.length > 0);
        const allDates = [...new Set(history.map(r => r.snapshot_at.slice(0, 16)))].sort();
        const W = 600, H = 140, PAD = { top: 14, right: 12, bottom: 28, left: 36 };
        const chartW = W - PAD.left - PAD.right, chartH = H - PAD.top - PAD.bottom;
        const COLORS = ['#34D399','#818CF8','#F59E0B','#38BDF8','#F472B6','#A78BFA','#FB923C','#6EE7B7'];
        const toX = i => PAD.left + (allDates.length > 1 ? (i / (allDates.length - 1)) * chartW : chartW / 2);
        const toY = v => PAD.top + chartH - (v / 100) * chartH;
        return (
          <div style={{ padding: '14px 16px', borderRadius: 12, background: 'rgba(255,255,255,.03)', border: '1px solid rgba(255,255,255,.08)' }}>
            <div style={{ fontSize: 11, color: '#64748b', marginBottom: 10 }}>روند امتیاز فروشندگان ({fa(history.length)} نقطه ثبت‌شده)</div>
            <div style={{ overflowX: 'auto' }}>
              <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', minWidth: 320, height: H, display: 'block' }}>
                {[0,25,50,75,100].map(v => (
                  <g key={v}>
                    <line x1={PAD.left} y1={toY(v)} x2={W-PAD.right} y2={toY(v)} stroke="rgba(255,255,255,.05)" strokeWidth="1" />
                    <text x={PAD.left-4} y={toY(v)+4} textAnchor="end" fill="#374151" fontSize="8">{fa(v)}</text>
                  </g>
                ))}
                {sellers.map((s, si) => {
                  const color = COLORS[si % COLORS.length];
                  const pts = s.points.map(p => { const xi = allDates.indexOf(p.date.slice(0,16)); return xi < 0 ? null : `${toX(xi)},${toY(p.score)}`; }).filter(Boolean).join(' ');
                  if (!pts) return null;
                  const last = s.points[s.points.length-1];
                  const lxi  = allDates.indexOf(last.date.slice(0,16));
                  return (
                    <g key={s.name}>
                      <polyline points={pts} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" opacity=".9" />
                      {s.points.map(p => { const xi = allDates.indexOf(p.date.slice(0,16)); return xi<0?null:<circle key={p.date} cx={toX(xi)} cy={toY(p.score)} r="3" fill={color} opacity=".85"/>; })}
                      <text x={Math.min(toX(lxi>=0?lxi:allDates.length-1)+4, W-4)} y={toY(last.score)+4} fill={color} fontSize="9" fontWeight="600">{s.name.length>8?s.name.slice(0,7)+'…':s.name}</text>
                    </g>
                  );
                })}
              </svg>
            </div>
          </div>
        );
      })()}

      {/* ─── لیست امتیازات ─── */}
      {loading ? (
        <div style={{ padding: 40, textAlign: 'center', color: '#374151' }}>در حال محاسبه امتیازات...</div>
      ) : scores.length === 0 ? (
        <div style={{ padding: 40, textAlign: 'center', color: '#374151' }}>
          <div style={{ fontSize: 28, marginBottom: 8 }}>📊</div>
          هنوز فروشنده فعالی ندارید
        </div>
      ) : (
        <div className="col gap-8">
          {scores.map((s, idx) => {
            const medalColor = idx===0?'#F59E0B':idx===1?'#94A3B8':idx===2?'#CD7F32':'#475569';
            const isNew = s.bootstrapFactor < 100;
            return (
              <div key={s.sellerId} onClick={() => setDetail(detail?.sellerId === s.sellerId ? null : s)}
                style={{ padding: '12px 16px', borderRadius: 12, cursor: 'pointer', background: detail?.sellerId===s.sellerId?'rgba(99,102,241,.1)':'rgba(255,255,255,.03)', border: `1px solid ${detail?.sellerId===s.sellerId?'rgba(99,102,241,.3)':'rgba(255,255,255,.07)'}`, transition: 'all .15s' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
                  <div style={{ width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, background: medalColor+'20', color: medalColor, flexShrink: 0 }}>{idx+1}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <span style={{ fontSize: 13, fontWeight: 600, color: '#e2e8f0' }}>{s.sellerName}</span>
                      {isNew && <span style={{ fontSize: 9, padding: '1px 6px', borderRadius: 10, background: 'rgba(251,146,60,.15)', color: '#FB923C' }}>جدید</span>}
                    </div>
                    <div style={{ fontSize: 10, color: '#475569', marginTop: 2 }}>
                      {fa(s.totalLeads)} لید — {fa(s.sold)} فروش{isNew && <span style={{ color: '#FB923C' }}> — ضریب {s.bootstrapFactor}%</span>}
                      {s.returnCount > 0 && <span style={{ color: '#F87171', marginRight: 6 }}> — ↩️ {fa(s.returnCount)} برگشتی</span>}
                    </div>
                  </div>
                  <div style={{ textAlign: 'left', flexShrink: 0 }}>
                    {s.totalLeads===0 ? (
                      <div style={{ fontSize: 10, color: '#374151', textAlign: 'center', padding: '4px 8px', borderRadius: 6, background: 'rgba(255,255,255,.04)' }}>داده<br/>کافی<br/>نیست</div>
                    ) : (
                      <>
                        <div style={{ fontSize: 22, fontWeight: 800, color: s.finalScore>=60?'#34D399':s.finalScore>=30?'#FB923C':'#F87171' }}>{fa(Math.round(s.finalScore))}</div>
                        <div style={{ fontSize: 9, color: '#374151', textAlign: 'center' }}>از ۱۰۰</div>
                      </>
                    )}
                  </div>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6,1fr)', gap: 4 }}>
                  {Object.entries(s.breakdown).map(([key, m]) => (
                    <div key={key} title={`${METRIC_LABEL[key]||key}: ${Math.round(m.score*100)}%`}>
                      <ScoreBar score={m.score} color={METRIC_COLOR[key]||'#94A3B8'} weight={m.weight} />
                      <div style={{ fontSize: 9, color: '#374151', textAlign: 'center', marginTop: 2 }}>{Math.round(m.score*100)}</div>
                    </div>
                  ))}
                </div>
                {detail?.sellerId === s.sellerId && (
                  <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid rgba(255,255,255,.07)' }}>
                    {/* ─── برگشتی‌های ماه جاری ─── */}
                    <div style={{ marginBottom: 12, padding: '10px 14px', borderRadius: 10, background: s.returnCount>0?'rgba(248,113,113,0.08)':'rgba(52,211,153,0.06)', border: `1px solid ${s.returnCount>0?'rgba(248,113,113,0.25)':'rgba(52,211,153,0.2)'}`, display:'flex', alignItems:'center', gap:12 }}>
                      <span style={{ fontSize:20 }}>{s.returnCount > 0 ? '↩️' : '✅'}</span>
                      <div style={{ flex:1 }}>
                        <div style={{ fontSize:12, fontWeight:600, color: s.returnCount>0?'#F87171':'#34D399' }}>
                          {s.returnCount > 0 ? `${fa(s.returnCount)} لید برگشتی این ماه` : 'بدون برگشتی این ماه'}
                        </div>
                        <div style={{ fontSize:10, color:'#475569', marginTop:2 }}>
                          {s.returnCount > 0
                            ? 'این فروشنده لیدهایی را بدون پیگیری کافی از دست داده است'
                            : 'همه لیدهای این ماه توسط این فروشنده پیگیری شده‌اند'}
                        </div>
                      </div>
                      {s.returnCount > 0 && s.totalLeads > 0 && (
                        <div style={{ textAlign:'center', flexShrink:0 }}>
                          <div style={{ fontSize:18, fontWeight:700, color:'#F87171' }}>{fa(Math.round(s.returnCount/s.totalLeads*100))}%</div>
                          <div style={{ fontSize:9, color:'#374151' }}>نرخ برگشت</div>
                        </div>
                      )}
                    </div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                      {Object.entries(s.breakdown).map(([key, m]) => (
                        <div key={key} style={{ padding: '10px 12px', borderRadius: 8, background: 'rgba(255,255,255,.04)' }}>
                          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                            <span style={{ fontSize: 11, fontWeight: 600, color: METRIC_COLOR[key]||'#94A3B8' }}>{METRIC_LABEL[key]||key}</span>
                            <span style={{ fontSize: 11, color: '#64748b' }}>وزن: {Math.round(m.weight*100)}%</span>
                          </div>
                          <ScoreBar score={m.score} color={METRIC_COLOR[key]||'#94A3B8'} showLabel label={METRIC_LABEL[key]} weight={m.weight} />
                          <div style={{ fontSize: 10, color: '#475569', marginTop: 4 }}>
                            {key==='conversion'   && `${fa(m.sold||0)} فروش از ${fa(s.totalLeads)} لید`}
                            {key==='revenue'      && `${fa(Math.round((m.totalRevenue||0)/1000))} هزار تومان`}
                            {key==='speed'        && (m.medianHours!=null?`میانه: ${fa(Math.round(m.medianHours))} ساعت`:'داده ندارد')}
                            {key==='contact_rate' && `${fa(Math.round(m.score*100))}% تماس گرفته شده`}
                            {key==='consistency'  && (m.weeklyRates&&m.weeklyRates.filter(r=>r!==null).length>=2?`${fa(m.weeklyRates.filter(r=>r!==null).length)} هفته داده`:'داده هفتگی کافی نیست')}
                            {key==='activity'     && `${fa(Math.round(m.score*100))}% روزهای فعال`}
                          </div>
                        </div>
                      ))}
                    </div>
                    {s.breakdown.consistency?.weeklyRates && (
                      <div style={{ marginTop: 12 }}>
                        <div style={{ fontSize: 10, color: '#64748b', marginBottom: 6 }}>نرخ تبدیل هفتگی (قدیم → جدید)</div>
                        <div style={{ display: 'flex', gap: 4, alignItems: 'flex-end', height: 40 }}>
                          {s.breakdown.consistency.weeklyRates.map((r, i) => (
                            <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
                              <div style={{ width: '100%', borderRadius: '2px 2px 0 0', height: r!==null?Math.max(4,Math.round(r*36)):2, background: r!==null?`rgba(52,211,153,${0.3+r*0.7})`:'rgba(255,255,255,.08)' }} />
                              <div style={{ fontSize: 8, color: '#374151' }}>ه{fa(i+1)}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};


// ════════════════════════════════════════════════════════════
//   تب پورسانت
// ════════════════════════════════════════════════════════════
const _JALALI_M = ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'];
const _pLabel  = (p) => { const [y,m]=p.split('-').map(Number); return `${_JALALI_M[m-1]} ${y-621}`; };
const _pShort  = (p) => { const m=parseInt(p.split('-')[1]); return _JALALI_M[m-1]?.slice(0,4)||p; };
const _toM     = (n,fa) => { if(!n&&n!==0) return '—'; if(n===0) return '۰'; const f=fa||String; if(Math.abs(n)<1000000) return f(Math.round(n/1000))+' K'; const m=Math.round(n/100000)/10; return f(m%1===0?Math.round(m):m)+' M'; };

const CommissionTab = ({ headers, toast, fa }) => {
  const [sec, setSec] = useState('plans');
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
      <div style={{ display:'flex', gap:6 }}>
        {[{id:'plans',label:'📋 طرح‌های پورسانت'},{id:'targets',label:'🎯 تارگت فروشندگان'}].map(s=>(
          <button key={s.id} onClick={()=>setSec(s.id)} style={{
            padding:'7px 18px', borderRadius:8, fontSize:12, cursor:'pointer',
            border:`1px solid ${sec===s.id?'rgba(99,102,241,.4)':'rgba(255,255,255,.07)'}`,
            background:sec===s.id?'rgba(99,102,241,.15)':'rgba(255,255,255,.03)',
            color:sec===s.id?'#818CF8':'#64748b', fontWeight:sec===s.id?600:400, transition:'all .12s',
          }}>{s.label}</button>
        ))}
      </div>
      {sec==='plans'   && <PlansSection   headers={headers} toast={toast} fa={fa} />}
      {sec==='targets' && <TargetsSection headers={headers} toast={toast} fa={fa} />}
    </div>
  );
};

// ════════════════════════════════════════════════════════════
//   PlanSalaryEditor — حقوق ثابت ماهانه طرح
// ════════════════════════════════════════════════════════════
const PlanSalaryEditor = ({ plan, headers, toast, fa, onSaved }) => {
  const { useState } = React;
  const [val, setVal] = useState(plan.base_salary ? String(plan.base_salary) : '');
  const [saving, setSaving] = useState(false);
  const num = parseFloat(String(val).replace(/,/g, '')) || 0;
  const dirty = num !== (plan.base_salary || 0);

  const save = () => {
    setSaving(true);
    fetch(`/api/commission/plans/${plan.id}`, { method: 'PUT', headers, body: JSON.stringify({ base_salary: num }) })
      .then(r => r.json()).then(d => {
        if (d.success) { toast('حقوق ثابت ذخیره شد', 'success'); onSaved(); }
        else toast(d.message || 'خطا', 'error');
      }).finally(() => setSaving(false));
  };

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 8, background: 'rgba(56,189,248,.04)', border: '1px dashed rgba(56,189,248,.25)' }}>
      <div style={{ fontSize: 12, fontWeight: 700, color: '#38BDF8', flexShrink: 0 }}>💵 حقوق ثابت ماهانه</div>
      <input type="number" value={val} onChange={e => setVal(e.target.value)} placeholder="۰ = بدون حقوق ثابت"
        style={{ flex: 1, background: 'rgba(255,255,255,.05)', border: '1px solid rgba(255,255,255,.1)', borderRadius: 7, padding: '7px 10px', color: '#e2e8f0', fontSize: 12, outline: 'none', direction: 'ltr', fontFamily: 'JetBrains Mono' }} />
      {num > 0 && <span style={{ fontSize: 11, color: '#38BDF8', fontFamily: 'JetBrains Mono', flexShrink: 0 }}>= {_toM(num, fa)} تومان</span>}
      <button onClick={save} disabled={saving || !dirty}
        style={{ padding: '6px 14px', borderRadius: 7, fontSize: 11, cursor: dirty ? 'pointer' : 'default', border: '1px solid rgba(56,189,248,.3)', background: dirty ? 'rgba(56,189,248,.15)' : 'rgba(255,255,255,.04)', color: dirty ? '#38BDF8' : '#475569', fontWeight: 600, flexShrink: 0 }}>
        {saving ? '...' : 'ذخیره'}
      </button>
    </div>
  );
};

// ════════════════════════════════════════════════════════════
//   PlansSection — مدیریت طرح‌های پورسانت
// ════════════════════════════════════════════════════════════
const PlansSection = ({ headers, toast, fa }) => {
  const { useState, useEffect } = React;
  const [plans, setPlans] = useState([]);
  const [sellers, setSellers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState(null);
  const [newPlanName, setNewPlanName] = useState('');
  const [creating, setCreating] = useState(false);

  // modal تیر
  const [tierModal, setTierModal] = useState(null); // { planId, tier? }
  const [tierForm, setTierForm] = useState({ from_amount: '', to_amount: '', type: 'percentage', rate: '' });

  // modal جایزه
  const [bonusModal, setBonusModal] = useState(null); // { planId }
  const [bonusForm, setBonusForm] = useState({ name: '', condition_type: 'single_period_amount', threshold: '', bonus_amount: '', description: '' });

  // modal تخصیص طرح به فروشنده
  const [assignModal, setAssignModal] = useState(null); // { planId, planName }
  const [assignForm, setAssignForm] = useState({ seller_id: '', start_date: new Date().toISOString().slice(0, 10) });

  const load = () => {
    setLoading(true);
    Promise.all([
      fetch('/api/commission/plans', { headers }).then(r => r.json()),
      fetch('/api/market/sellers',   { headers }).then(r => r.json()),
    ]).then(([p, s]) => {
      if (p.success) setPlans(p.data.plans || []);
      if (s.success) setSellers(s.data.sellers || []);
    }).finally(() => setLoading(false));
  };
  useEffect(load, []);

  const createPlan = () => {
    if (!newPlanName.trim()) return;
    setCreating(true);
    fetch('/api/commission/plans', { method: 'POST', headers, body: JSON.stringify({ name: newPlanName.trim() }) })
      .then(r => r.json()).then(d => {
        if (d.success) { setNewPlanName(''); load(); toast('طرح ساخته شد', 'success'); }
        else toast(d.message || 'خطا', 'error');
      }).finally(() => setCreating(false));
  };

  const deletePlan = (id) => {
    if (!confirm('حذف این طرح؟')) return;
    fetch(`/api/commission/plans/${id}`, { method: 'DELETE', headers })
      .then(r => r.json()).then(d => { if (d.success) load(); else toast(d.message || 'خطا', 'error'); });
  };

  const saveTier = () => {
    if (!tierModal) return;
    const body = {
      from_amount: parseFloat(tierForm.from_amount) || 0,
      to_amount:   tierForm.to_amount ? parseFloat(tierForm.to_amount) : null,
      type: tierForm.type,
      rate: parseFloat(tierForm.rate) || 0,
    };
    const url = tierModal.tier
      ? `/api/commission/tiers/${tierModal.tier.id}`
      : `/api/commission/plans/${tierModal.planId}/tiers`;
    const method = tierModal.tier ? 'PUT' : 'POST';
    fetch(url, { method, headers, body: JSON.stringify(body) })
      .then(r => r.json()).then(d => {
        if (d.success) { setTierModal(null); load(); toast('تیر ذخیره شد', 'success'); }
        else toast(d.message || 'خطا', 'error');
      });
  };

  const deleteTier = (id) => {
    fetch(`/api/commission/tiers/${id}`, { method: 'DELETE', headers })
      .then(r => r.json()).then(d => { if (d.success) load(); });
  };

  const saveBonus = () => {
    if (!bonusModal) return;
    fetch(`/api/commission/plans/${bonusModal.planId}/bonuses`, {
      method: 'POST', headers, body: JSON.stringify({ ...bonusForm, threshold: parseFloat(bonusForm.threshold), bonus_amount: parseFloat(bonusForm.bonus_amount) })
    }).then(r => r.json()).then(d => {
      if (d.success) { setBonusModal(null); load(); toast('جایزه ذخیره شد', 'success'); }
      else toast(d.message || 'خطا', 'error');
    });
  };

  const deleteBonus = (id) => {
    fetch(`/api/commission/bonuses/${id}`, { method: 'DELETE', headers })
      .then(r => r.json()).then(d => { if (d.success) load(); });
  };

  const assignPlan = () => {
    if (!assignModal || !assignForm.seller_id) return;
    fetch(`/api/commission/sellers/${assignForm.seller_id}/assign-plan`, {
      method: 'POST', headers, body: JSON.stringify({ plan_id: assignModal.planId, start_date: assignForm.start_date })
    }).then(r => r.json()).then(d => {
      if (d.success) { setAssignModal(null); toast('طرح تخصیص یافت', 'success'); }
      else toast(d.message || 'خطا', 'error');
    });
  };

  const inp = { background: 'rgba(255,255,255,.06)', border: '1px solid rgba(255,255,255,.12)', borderRadius: 8, padding: '8px 12px', color: '#e2e8f0', fontSize: 13, outline: 'none', width: '100%', boxSizing: 'border-box' };
  const COND_LABEL = { consecutive_periods: 'دوره‌های متوالی', single_period_amount: 'فروش ماهانه', total_year_amount: 'فروش سالانه' };

  if (loading) return <div style={{ padding: 40, textAlign: 'center', color: '#475569' }}>در حال بارگذاری...</div>;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

      {/* ─── ساخت طرح جدید ─── */}
      <div style={{ display: 'flex', gap: 8 }}>
        <input value={newPlanName} onChange={e => setNewPlanName(e.target.value)} onKeyDown={e => e.key === 'Enter' && createPlan()}
          placeholder="نام طرح جدید..."
          style={{ ...inp, flex: 1 }} />
        <button onClick={createPlan} disabled={creating || !newPlanName.trim()} style={{ padding: '8px 20px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: '#6366F1', color: '#fff', fontWeight: 600 }}>
          + ساخت طرح
        </button>
      </div>

      {plans.length === 0 ? (
        <div style={{ padding: 40, textAlign: 'center', color: '#475569' }}>
          <div style={{ fontSize: 28, marginBottom: 8 }}>💰</div>
          هنوز طرح پورسانتی ندارید
        </div>
      ) : plans.map(plan => (
        <div key={plan.id} style={{ borderRadius: 12, border: '1px solid rgba(255,255,255,.08)', background: 'rgba(255,255,255,.02)', overflow: 'hidden' }}>
          {/* هدر طرح */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', cursor: 'pointer', borderBottom: expanded === plan.id ? '1px solid rgba(255,255,255,.07)' : 'none' }}
            onClick={() => setExpanded(expanded === plan.id ? null : plan.id)}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0' }}>{plan.name}</div>
              {plan.description && <div style={{ fontSize: 11, color: '#64748b', marginTop: 2 }}>{plan.description}</div>}
            </div>
            {(plan.base_salary > 0) && (
              <span style={{ fontSize: 11, padding: '2px 9px', borderRadius: 20, background: 'rgba(56,189,248,.1)', color: '#38BDF8', fontFamily: 'JetBrains Mono' }}>
                💵 حقوق: {_toM(plan.base_salary, fa)}
              </span>
            )}
            <span style={{ fontSize: 11, padding: '2px 9px', borderRadius: 20, background: 'rgba(52,211,153,.1)', color: '#34D399' }}>
              {(plan.tiers || []).length} لایه — {(plan.bonuses || []).length} جایزه
            </span>
            <button onClick={e => { e.stopPropagation(); setAssignModal({ planId: plan.id, planName: plan.name }); setAssignForm({ seller_id: '', start_date: new Date().toISOString().slice(0, 10) }); }}
              style={{ padding: '5px 12px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(99,102,241,.3)', background: 'rgba(99,102,241,.12)', color: '#818CF8' }}>
              👤 تخصیص
            </button>
            <button onClick={e => { e.stopPropagation(); deletePlan(plan.id); }}
              style={{ padding: '5px 10px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(248,113,113,.2)', background: 'transparent', color: '#F87171' }}>
              🗑
            </button>
            <span style={{ fontSize: 13, color: '#475569' }}>{expanded === plan.id ? '▲' : '▼'}</span>
          </div>

          {expanded === plan.id && (
            <div style={{ padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 16 }}>
              {/* ─── حقوق ثابت ماهانه ─── */}
              <PlanSalaryEditor plan={plan} headers={headers} toast={toast} fa={fa} onSaved={load} />

              {/* ─── تیرها ─── */}
              <div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: '#94a3b8' }}>📊 لایه‌های پورسانت</div>
                  <button onClick={() => { setTierModal({ planId: plan.id, tier: null }); setTierForm({ from_amount: '', to_amount: '', type: 'percentage', rate: '' }); }}
                    style={{ padding: '4px 12px', borderRadius: 7, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(99,102,241,.3)', background: 'rgba(99,102,241,.1)', color: '#818CF8' }}>
                    + تیر جدید
                  </button>
                </div>
                {(plan.tiers || []).length === 0 ? (
                  <div style={{ fontSize: 12, color: '#374151', padding: '10px 0', textAlign: 'center' }}>تیری تعریف نشده</div>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                    {[...plan.tiers].sort((a, b) => (a.from_amount || 0) - (b.from_amount || 0)).map(t => (
                      <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', borderRadius: 8, background: 'rgba(255,255,255,.03)' }}>
                        <span style={{ fontFamily: 'JetBrains Mono', fontSize: 12, color: '#818CF8' }}>
                          {_toM(t.from_amount, fa)} — {t.to_amount ? _toM(t.to_amount, fa) : '∞'}
                        </span>
                        <span style={{ flex: 1 }} />
                        <span style={{ fontSize: 13, fontWeight: 700, color: '#34D399', fontFamily: 'JetBrains Mono' }}>
                          {t.type === 'percentage' ? `${fa(t.rate)}٪` : `${_toM(t.rate, fa)} / فروش`}
                        </span>
                        <button onClick={() => { setTierModal({ planId: plan.id, tier: t }); setTierForm({ from_amount: t.from_amount || '', to_amount: t.to_amount || '', type: t.type, rate: t.rate || '' }); }}
                          style={{ padding: '3px 9px', borderRadius: 6, fontSize: 10, cursor: 'pointer', border: '1px solid rgba(255,255,255,.1)', background: 'transparent', color: '#64748b' }}>✏️</button>
                        <button onClick={() => deleteTier(t.id)}
                          style={{ padding: '3px 9px', borderRadius: 6, fontSize: 10, cursor: 'pointer', border: '1px solid rgba(248,113,113,.2)', background: 'transparent', color: '#F87171' }}>🗑</button>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {/* ─── جوایز ─── */}
              <div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: '#94a3b8' }}>🎯 جوایز</div>
                  <button onClick={() => { setBonusModal({ planId: plan.id }); setBonusForm({ name: '', condition_type: 'single_period_amount', threshold: '', bonus_amount: '', description: '' }); }}
                    style={{ padding: '4px 12px', borderRadius: 7, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(245,158,11,.3)', background: 'rgba(245,158,11,.1)', color: '#F59E0B' }}>
                    + جایزه جدید
                  </button>
                </div>
                {(plan.bonuses || []).length === 0 ? (
                  <div style={{ fontSize: 12, color: '#374151', padding: '10px 0', textAlign: 'center' }}>جایزه‌ای تعریف نشده</div>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                    {plan.bonuses.map(b => (
                      <div key={b.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', borderRadius: 8, background: 'rgba(245,158,11,.05)', border: '1px solid rgba(245,158,11,.15)' }}>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: 12, fontWeight: 600, color: '#e2e8f0' }}>{b.name}</div>
                          <div style={{ fontSize: 10, color: '#64748b', marginTop: 2 }}>{COND_LABEL[b.condition_type]} ≥ {_toM(b.threshold, fa)}</div>
                        </div>
                        <span style={{ fontSize: 13, fontWeight: 700, color: '#F59E0B', fontFamily: 'JetBrains Mono' }}>{_toM(b.bonus_amount, fa)}</span>
                        <button onClick={() => deleteBonus(b.id)}
                          style={{ padding: '3px 9px', borderRadius: 6, fontSize: 10, cursor: 'pointer', border: '1px solid rgba(248,113,113,.2)', background: 'transparent', color: '#F87171' }}>🗑</button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      ))}

      {/* ─── Modal تیر ─── */}
      {tierModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.8)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setTierModal(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(99,102,241,.3)', borderRadius: 14, padding: 28, width: 360 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0', marginBottom: 20 }}>
              {tierModal.tier ? 'ویرایش لایه' : 'لایه جدید'}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>از مبلغ (تومان)</div>
                <input type="number" value={tierForm.from_amount} onChange={e => setTierForm(p => ({ ...p, from_amount: e.target.value }))} placeholder="0" style={{ ...inp, direction: 'ltr', fontFamily: 'JetBrains Mono' }} />
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>تا مبلغ (تومان — خالی = بی‌نهایت)</div>
                <input type="number" value={tierForm.to_amount} onChange={e => setTierForm(p => ({ ...p, to_amount: e.target.value }))} placeholder="بی‌نهایت" style={{ ...inp, direction: 'ltr', fontFamily: 'JetBrains Mono' }} />
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>نوع پورسانت</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  {[['percentage','درصد فروش'],['fixed_per_deal','ثابت / فروش']].map(([v, l]) => (
                    <button key={v} onClick={() => setTierForm(p => ({ ...p, type: v }))} style={{ flex: 1, padding: '7px 0', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: 'none', background: tierForm.type === v ? 'rgba(99,102,241,.25)' : 'rgba(255,255,255,.05)', color: tierForm.type === v ? '#818CF8' : '#64748b', fontWeight: tierForm.type === v ? 600 : 400 }}>
                      {l}
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>
                  {tierForm.type === 'percentage' ? 'نرخ درصد (مثلا: 8)' : 'مبلغ ثابت هر فروش'}
                </div>
                <input type="number" value={tierForm.rate} onChange={e => setTierForm(p => ({ ...p, rate: e.target.value }))} placeholder={tierForm.type === 'percentage' ? '8' : '500000'} style={{ ...inp, direction: 'ltr', fontFamily: 'JetBrains Mono' }} />
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 22 }}>
              <button onClick={() => setTierModal(null)} style={{ padding: '8px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#64748b' }}>انصراف</button>
              <button onClick={saveTier} style={{ padding: '8px 22px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: '#6366F1', color: '#fff', fontWeight: 600 }}>ذخیره</button>
            </div>
          </div>
        </div>
      )}

      {/* ─── Modal جایزه ─── */}
      {bonusModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.8)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setBonusModal(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(245,158,11,.3)', borderRadius: 14, padding: 28, width: 380 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0', marginBottom: 20 }}>🎯 جایزه جدید</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>نام جایزه</div>
                <input value={bonusForm.name} onChange={e => setBonusForm(p => ({ ...p, name: e.target.value }))} placeholder="مثلا: جایزه دوماهه" style={inp} />
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>شرط</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {Object.entries(COND_LABEL).map(([v, l]) => (
                    <button key={v} onClick={() => setBonusForm(p => ({ ...p, condition_type: v }))} style={{ padding: '6px 12px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: 'none', background: bonusForm.condition_type === v ? 'rgba(245,158,11,.25)' : 'rgba(255,255,255,.05)', color: bonusForm.condition_type === v ? '#F59E0B' : '#64748b', fontWeight: bonusForm.condition_type === v ? 600 : 400 }}>
                      {l}
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>
                  {bonusForm.condition_type === 'consecutive_periods' ? 'تعداد ماه متوالی' : 'مبلغ آستانه (تومان)'}
                </div>
                <input type="number" value={bonusForm.threshold} onChange={e => setBonusForm(p => ({ ...p, threshold: e.target.value }))} style={{ ...inp, direction: 'ltr', fontFamily: 'JetBrains Mono' }} />
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>مبلغ جایزه (تومان)</div>
                <input type="number" value={bonusForm.bonus_amount} onChange={e => setBonusForm(p => ({ ...p, bonus_amount: e.target.value }))} style={{ ...inp, direction: 'ltr', fontFamily: 'JetBrains Mono' }} />
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>توضیح (اختیاری)</div>
                <input value={bonusForm.description} onChange={e => setBonusForm(p => ({ ...p, description: e.target.value }))} placeholder="" style={inp} />
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 22 }}>
              <button onClick={() => setBonusModal(null)} style={{ padding: '8px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#64748b' }}>انصراف</button>
              <button onClick={saveBonus} style={{ padding: '8px 22px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: '#F59E0B', color: '#111', fontWeight: 600 }}>ذخیره</button>
            </div>
          </div>
        </div>
      )}

      {/* ─── Modal تخصیص طرح ─── */}
      {assignModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.8)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setAssignModal(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(99,102,241,.3)', borderRadius: 14, padding: 28, width: 360 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0', marginBottom: 6 }}>👤 تخصیص طرح</div>
            <div style={{ fontSize: 12, color: '#64748b', marginBottom: 20 }}>طرح: {assignModal.planName}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>فروشنده</div>
                <select value={assignForm.seller_id} onChange={e => setAssignForm(p => ({ ...p, seller_id: e.target.value }))}
                  style={{ ...inp, appearance: 'none' }}>
                  <option value="">انتخاب فروشنده...</option>
                  {sellers.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                </select>
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>از تاریخ</div>
                <input type="date" value={assignForm.start_date} onChange={e => setAssignForm(p => ({ ...p, start_date: e.target.value }))}
                  style={{ ...inp, direction: 'ltr', colorScheme: 'dark' }} />
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 22 }}>
              <button onClick={() => setAssignModal(null)} style={{ padding: '8px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#64748b' }}>انصراف</button>
              <button onClick={assignPlan} disabled={!assignForm.seller_id} style={{ padding: '8px 22px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: assignForm.seller_id ? '#6366F1' : 'rgba(99,102,241,.3)', color: '#fff', fontWeight: 600 }}>تخصیص</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ════════════════════════════════════════════════════════════
//   TargetsSection — تارگت ماهانه فروشندگان
// ════════════════════════════════════════════════════════════
const TargetsSection = ({ headers, toast, fa }) => {
  const { useState, useEffect } = React;
  const [sellers, setSellers] = useState([]);
  const [summaries, setSummaries] = useState({});
  const [period, setPeriod] = useState(() => new Date().toISOString().slice(0, 7));
  const [loading, setLoading] = useState(true);
  const [editTarget, setEditTarget] = useState(null); // { seller }
  const [targetVal, setTargetVal] = useState('');
  const [saving, setSaving] = useState(false);
  const [pwModal, setPwModal] = useState(null); // { seller }
  const [pwForm, setPwForm] = useState({ login_username: '', password: '' });
  const [pwSaving, setPwSaving] = useState(false);
  const [payModal, setPayModal] = useState(null); // { seller, commission }
  const [payForm, setPayForm] = useState({ amount: '', note: '' });
  const [payHistory, setPayHistory] = useState([]);
  const [paySaving, setPaySaving] = useState(false);

  const periodOptions = () => {
    const opts = []; const now = new Date();
    for (let i = -1; i < 5; i++) {
      const d = new Date(now.getFullYear(), now.getMonth() + i, 1);
      opts.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`);
    }
    return opts;
  };

  const load = () => {
    setLoading(true);
    fetch('/api/market/sellers', { headers }).then(r => r.json()).then(d => {
      if (!d.success) { setLoading(false); return; }
      const sels = d.data.sellers || [];
      setSellers(sels);
      // لود خلاصه همه فروشندگان
      Promise.all(sels.map(s =>
        fetch(`/api/commission/sellers/${s.id}/summary?period=${period}`, { headers }).then(r => r.json())
      )).then(results => {
        const map = {};
        results.forEach((r, i) => { if (r.success) map[sels[i].id] = r.data; });
        setSummaries(map);
      }).finally(() => setLoading(false));
    }).catch(() => setLoading(false));
  };
  useEffect(load, [period]);

  const saveTarget = () => {
    if (!editTarget) return;
    setSaving(true);
    fetch(`/api/commission/sellers/${editTarget.seller.id}/target`, {
      method: 'POST', headers, body: JSON.stringify({ period, amount: parseFloat(targetVal) || 0 })
    }).then(r => r.json()).then(d => {
      setSaving(false);
      if (d.success) { setEditTarget(null); load(); toast('تارگت ذخیره شد', 'success'); }
      else toast(d.message || 'خطا', 'error');
    }).catch(() => setSaving(false));
  };

  const savePassword = () => {
    if (!pwModal || !pwForm.login_username.trim() || !pwForm.password) return;
    setPwSaving(true);
    fetch(`/api/commission/sellers/${pwModal.seller.id}/password`, {
      method: 'POST', headers, body: JSON.stringify(pwForm)
    }).then(r => r.json()).then(d => {
      setPwSaving(false);
      if (d.success) { setPwModal(null); toast('رمز ورود ذخیره شد ✅', 'success'); }
      else toast(d.message || 'خطا', 'error');
    }).catch(() => setPwSaving(false));
  };

  const openPayModal = (seller, commission, baseSalary, bonusTotal) => {
    setPayModal({ seller, commission, base_salary: baseSalary || 0, bonus_total: bonusTotal || 0 });
    setPayForm({ amount: String(Math.round((commission || 0) + (baseSalary || 0) + (bonusTotal || 0))), note: '' });
    setPayHistory([]);
    fetch(`/api/commission/sellers/${seller.id}/payouts`, { headers }).then(r => r.json())
      .then(d => { if (d.success) setPayHistory(d.data.payouts || []); });
  };

  const savePayout = () => {
    if (!payModal || !payForm.amount) return;
    setPaySaving(true);
    fetch(`/api/commission/sellers/${payModal.seller.id}/payout`, {
      method: 'POST', headers, body: JSON.stringify({ period, amount: parseFloat(payForm.amount), note: payForm.note })
    }).then(r => r.json()).then(d => {
      setPaySaving(false);
      if (d.success) {
        toast('پرداخت ثبت شد ✅', 'success');
        // reload history
        fetch(`/api/commission/sellers/${payModal.seller.id}/payouts`, { headers }).then(r => r.json())
          .then(dd => { if (dd.success) setPayHistory(dd.data.payouts || []); });
        setPayForm(p => ({ ...p, amount: '' }));
      } else toast(d.message || 'خطا', 'error');
    }).catch(() => setPaySaving(false));
  };

  const inp = { background: 'rgba(255,255,255,.06)', border: '1px solid rgba(255,255,255,.12)', borderRadius: 8, padding: '8px 12px', color: '#e2e8f0', fontSize: 13, outline: 'none', width: '100%', boxSizing: 'border-box' };
  const JALALI_M = ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'];

  if (loading) return <div style={{ padding: 40, textAlign: 'center', color: '#475569' }}>در حال بارگذاری...</div>;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

      {/* انتخاب ماه */}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {periodOptions().map(p => {
          const [y, m] = p.split('-').map(Number);
          const label = `${JALALI_M[m - 1]} ${y - 621}`;
          return (
            <button key={p} onClick={() => setPeriod(p)} style={{
              padding: '6px 14px', borderRadius: 8, fontSize: 12, cursor: 'pointer',
              border: `1px solid ${period === p ? 'rgba(99,102,241,.4)' : 'rgba(255,255,255,.07)'}`,
              background: period === p ? 'rgba(99,102,241,.15)' : 'rgba(255,255,255,.03)',
              color: period === p ? '#818CF8' : '#64748b', fontWeight: period === p ? 600 : 400,
            }}>{label}</button>
          );
        })}
      </div>

      {sellers.length === 0 ? (
        <div style={{ padding: 40, textAlign: 'center', color: '#475569' }}>
          <div style={{ fontSize: 28, marginBottom: 8 }}>👥</div>
          هنوز فروشنده‌ای ندارید
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {sellers.map(s => {
            const sum = summaries[s.id] || {};
            const target = sum.target || 0;
            const gross = sum.gross_sales || 0;
            const commission = sum.commission || 0;
            const baseSalary = sum.base_salary || 0;
            const bonusTotal = sum.bonus_total || 0;
            const totalPay = sum.total_pay != null ? sum.total_pay : baseSalary + commission + bonusTotal;
            const progress = target > 0 ? Math.min(gross / target, 1) : null;

            return (
              <div key={s.id} style={{ padding: '14px 16px', borderRadius: 12, background: 'rgba(255,255,255,.03)', border: '1px solid rgba(255,255,255,.08)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: progress !== null ? 12 : 0 }}>
                  <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'rgba(99,102,241,.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 700, color: '#818CF8', flexShrink: 0 }}>
                    {(s.name || 'ف')[0]}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: '#e2e8f0' }}>{s.name}</div>
                    <div style={{ fontSize: 11, color: '#64748b', marginTop: 2, display: 'flex', gap: 10 }}>
                      {sum.plan_name && <span style={{ padding: '1px 8px', borderRadius: 20, background: 'rgba(99,102,241,.12)', color: '#818CF8' }}>طرح: {sum.plan_name}</span>}
                      <span>فروش: <strong style={{ color: '#34D399', fontFamily: 'JetBrains Mono' }}>{_toM(gross, fa)}</strong></span>
                      <span>پورسانت: <strong style={{ color: '#F59E0B', fontFamily: 'JetBrains Mono' }}>{_toM(commission, fa)}</strong></span>
                      {baseSalary > 0 && <span>حقوق: <strong style={{ color: '#38BDF8', fontFamily: 'JetBrains Mono' }}>{_toM(baseSalary, fa)}</strong></span>}
                      {bonusTotal > 0 && <span>جایزه: <strong style={{ color: '#A78BFA', fontFamily: 'JetBrains Mono' }}>{_toM(bonusTotal, fa)}</strong></span>}
                      {(baseSalary > 0 || bonusTotal > 0) && <span>جمع: <strong style={{ color: '#e2e8f0', fontFamily: 'JetBrains Mono' }}>{_toM(totalPay, fa)}</strong></span>}
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    <button onClick={() => { setEditTarget({ seller: s }); setTargetVal(String(target || '')); }}
                      style={{ padding: '5px 12px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(52,211,153,.3)', background: 'rgba(52,211,153,.08)', color: '#34D399' }}>
                      🎯 تارگت
                    </button>
                    <button onClick={() => openPayModal(s, commission, baseSalary, bonusTotal)}
                      style={{ padding: '5px 12px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(245,158,11,.3)', background: 'rgba(245,158,11,.08)', color: '#F59E0B' }}>
                      💳 پرداخت
                    </button>
                    <button onClick={() => { setPwModal({ seller: s }); setPwForm({ login_username: s.login_username || '', password: '' }); }}
                      style={{ padding: '5px 12px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(99,102,241,.3)', background: 'rgba(99,102,241,.08)', color: '#818CF8' }}>
                      🔑 رمز ورود
                    </button>
                  </div>
                </div>

                {progress !== null && (
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: '#64748b', marginBottom: 5 }}>
                      <span>پیشرفت تارگت</span>
                      <span style={{ fontFamily: 'JetBrains Mono' }}>{_toM(gross, fa)} / {_toM(target, fa)} ({fa(Math.round(progress * 100))}٪)</span>
                    </div>
                    <div style={{ height: 6, borderRadius: 4, background: 'rgba(255,255,255,.08)', overflow: 'hidden' }}>
                      <div style={{ height: '100%', borderRadius: 4, width: `${Math.round(progress * 100)}%`, background: progress >= 1 ? '#34D399' : progress >= 0.7 ? '#FB923C' : '#6366F1', transition: 'width .4s' }} />
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* ─── Modal پرداخت پورسانت ─── */}
      {payModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.82)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setPayModal(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(245,158,11,.3)', borderRadius: 14, padding: 28, width: 420, maxHeight: '80vh', overflow: 'auto' }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0', marginBottom: 4 }}>💳 ثبت پرداخت پورسانت</div>
            <div style={{ fontSize: 12, color: '#64748b', marginBottom: 20 }}>
              {payModal.seller.name} — {period}
              {payModal.commission > 0 && (
                <span style={{ marginRight: 8, padding: '1px 8px', borderRadius: 20, background: 'rgba(245,158,11,.15)', color: '#F59E0B', fontSize: 11 }}>
                  پورسانت محاسبه‌شده: {_toM(payModal.commission, fa)}
                </span>
              )}
              {payModal.base_salary > 0 && (
                <span style={{ marginRight: 8, padding: '1px 8px', borderRadius: 20, background: 'rgba(56,189,248,.15)', color: '#38BDF8', fontSize: 11 }}>
                  حقوق ثابت: {_toM(payModal.base_salary, fa)}
                </span>
              )}
              {payModal.bonus_total > 0 && (
                <span style={{ marginRight: 8, padding: '1px 8px', borderRadius: 20, background: 'rgba(167,139,250,.15)', color: '#A78BFA', fontSize: 11 }}>
                  جایزه: {_toM(payModal.bonus_total, fa)}
                </span>
              )}
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 20 }}>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>مبلغ پرداختی (تومان)</div>
                <input type="number" value={payForm.amount} onChange={e => setPayForm(p => ({ ...p, amount: e.target.value }))}
                  placeholder="مبلغ را وارد کنید"
                  style={{ ...inp, direction: 'ltr', fontFamily: 'JetBrains Mono' }} />
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>یادداشت (اختیاری)</div>
                <input value={payForm.note} onChange={e => setPayForm(p => ({ ...p, note: e.target.value }))}
                  placeholder="مثلا: واریز به حساب..."
                  style={inp} />
              </div>
            </div>

            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginBottom: payHistory.length > 0 ? 20 : 0 }}>
              <button onClick={() => setPayModal(null)} style={{ padding: '8px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#64748b' }}>انصراف</button>
              <button onClick={savePayout} disabled={paySaving || !payForm.amount}
                style={{ padding: '8px 22px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: payForm.amount ? '#F59E0B' : 'rgba(245,158,11,.3)', color: '#111', fontWeight: 600 }}>
                {paySaving ? 'در حال ذخیره...' : '💳 ثبت پرداخت'}
              </button>
            </div>

            {/* تاریخچه پرداخت‌ها */}
            {payHistory.length > 0 && (
              <div style={{ borderTop: '1px solid rgba(255,255,255,.07)', paddingTop: 16 }}>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 10, fontWeight: 600 }}>📜 تاریخچه پرداخت‌ها</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {payHistory.map(p => (
                    <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', borderRadius: 8, background: 'rgba(255,255,255,.03)' }}>
                      <span style={{ fontSize: 11, color: '#64748b', fontFamily: 'JetBrains Mono' }}>{(p.paid_at || '').slice(0, 10)}</span>
                      <span style={{ fontSize: 11, color: '#94a3b8' }}>{p.period}</span>
                      <span style={{ flex: 1 }} />
                      <span style={{ fontSize: 13, fontWeight: 700, color: '#34D399', fontFamily: 'JetBrains Mono' }}>{_toM(p.amount, fa)}</span>
                      {p.note && <span style={{ fontSize: 10, color: '#475569' }}>{p.note}</span>}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* ─── Modal تارگت ─── */}
      {editTarget && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.8)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setEditTarget(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(52,211,153,.3)', borderRadius: 14, padding: 28, width: 340 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0', marginBottom: 6 }}>🎯 تارگت ماهانه</div>
            <div style={{ fontSize: 12, color: '#64748b', marginBottom: 20 }}>{editTarget.seller.name} — {period}</div>
            <div>
              <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>مبلغ تارگت (تومان)</div>
              <input type="number" value={targetVal} onChange={e => setTargetVal(e.target.value)} placeholder="مثلا: 50000000"
                style={{ ...inp, direction: 'ltr', fontFamily: 'JetBrains Mono' }} />
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 22 }}>
              <button onClick={() => setEditTarget(null)} style={{ padding: '8px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#64748b' }}>انصراف</button>
              <button onClick={saveTarget} disabled={saving} style={{ padding: '8px 22px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: '#34D399', color: '#111', fontWeight: 600 }}>
                {saving ? 'در حال ذخیره...' : 'ذخیره'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ─── Modal رمز ورود ─── */}
      {pwModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.8)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setPwModal(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(99,102,241,.3)', borderRadius: 14, padding: 28, width: 340 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0', marginBottom: 6 }}>🔑 رمز ورود فروشنده</div>
            <div style={{ fontSize: 12, color: '#64748b', marginBottom: 20 }}>{pwModal.seller.name}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>نام کاربری</div>
                <input value={pwForm.login_username} onChange={e => setPwForm(p => ({ ...p, login_username: e.target.value }))}
                  placeholder="مثلا: ali.r" style={{ ...inp, direction: 'ltr', fontFamily: 'JetBrains Mono' }} />
              </div>
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>رمز عبور جدید</div>
                <input type="password" value={pwForm.password} onChange={e => setPwForm(p => ({ ...p, password: e.target.value }))}
                  placeholder="حداقل ۶ کاراکتر" style={{ ...inp, direction: 'ltr', fontFamily: 'JetBrains Mono' }} />
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 22 }}>
              <button onClick={() => setPwModal(null)} style={{ padding: '8px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#64748b' }}>انصراف</button>
              <button onClick={savePassword} disabled={pwSaving || !pwForm.login_username.trim() || !pwForm.password}
                style={{ padding: '8px 22px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: (pwForm.login_username.trim() && pwForm.password) ? '#6366F1' : 'rgba(99,102,241,.3)', color: '#fff', fontWeight: 600 }}>
                {pwSaving ? 'در حال ذخیره...' : 'ذخیره'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const _cInp = { background:'rgba(255,255,255,.05)', border:'1px solid rgba(255,255,255,.1)', borderRadius:7, padding:'7px 10px', color:'#e2e8f0', fontSize:12, outline:'none', direction:'ltr', fontFamily:'JetBrains Mono', minWidth:80 };

const PlanCard = ({ plan, headers, toast, fa, onDelete, onToggle, onReload }) => {
  const [open, setOpen]   = useState(true);
  const [tiers, setTiers] = useState(plan.tiers||[]);
  const [bons, setBons]   = useState(plan.bonuses||[]);
  const [tf, setTf] = useState({from_amount:'',to_amount:'',type:'percentage',rate:''});
  const [bf, setBf] = useState({name:'',condition_type:'consecutive_periods',threshold:'',bonus_amount:''});

  const reload = () => {
    fetch('/api/commission/plans',{headers}).then(r=>r.json()).then(d=>{
      const p=(d.data?.plans||[]).find(x=>x.id===plan.id);
      if(p){setTiers(p.tiers||[]);setBons(p.bonuses||[]);}
    });
  };

  const addTier = () => {
    if(!tf.rate) return;
    fetch(`/api/commission/plans/${plan.id}/tiers`,{method:'POST',headers,body:JSON.stringify({
      from_amount:parseFloat(tf.from_amount)||0, to_amount:tf.to_amount?parseFloat(tf.to_amount):null,
      type:tf.type, rate:parseFloat(tf.rate),
    })}).then(r=>r.json()).then(d=>{ if(d.success){setTf({from_amount:'',to_amount:'',type:'percentage',rate:''});reload();} });
  };

  const addBonus = () => {
    if(!bf.name||!bf.threshold||!bf.bonus_amount) return;
    fetch(`/api/commission/plans/${plan.id}/bonuses`,{method:'POST',headers,body:JSON.stringify({
      name:bf.name, condition_type:bf.condition_type, threshold:parseFloat(bf.threshold), bonus_amount:parseFloat(bf.bonus_amount),
    })}).then(r=>r.json()).then(d=>{ if(d.success){setBf({name:'',condition_type:'consecutive_periods',threshold:'',bonus_amount:''});reload();} });
  };

  const COND = [
    {id:'consecutive_periods',label:'X ماه متوالی هدف',hint:'تعداد ماه'},
    {id:'single_period_amount',label:'فروش بالای X در یک ماه',hint:'مبلغ (تومان)'},
    {id:'total_year_amount',label:'فروش سالانه بالای X',hint:'مبلغ (تومان)'},
  ];

  return (
    <div style={{ borderRadius:12, border:`1px solid ${plan.is_active?'rgba(99,102,241,.22)':'rgba(255,255,255,.06)'}`, background:'rgba(255,255,255,.02)', overflow:'hidden' }}>
      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'12px 16px', cursor:'pointer', background:plan.is_active?'rgba(99,102,241,.06)':'rgba(255,255,255,.02)' }} onClick={()=>setOpen(p=>!p)}>
        <span style={{ fontSize:13, color:'#475569' }}>{open?'▼':'▶'}</span>
        <div style={{ flex:1 }}>
          <span style={{ fontSize:14, fontWeight:700, color:plan.is_active?'#e2e8f0':'#64748b' }}>{plan.name}</span>
          {plan.description&&<span style={{ fontSize:11, color:'#475569', marginRight:8 }}>{plan.description}</span>}
        </div>
        <span style={{ fontSize:11, color:'#475569' }}>{fa(tiers.length)} لایه · {fa(bons.length)} جایزه</span>
        <button onClick={e=>{e.stopPropagation();onToggle();}} style={{ padding:'3px 10px', borderRadius:6, fontSize:11, cursor:'pointer', border:'none', background:plan.is_active?'rgba(52,211,153,.15)':'rgba(255,255,255,.07)', color:plan.is_active?'#34D399':'#64748b' }}>{plan.is_active?'فعال':'غیرفعال'}</button>
        <button onClick={e=>{e.stopPropagation();onDelete();}} style={{ padding:'3px 8px', borderRadius:6, fontSize:11, cursor:'pointer', border:'none', background:'rgba(248,113,113,.12)', color:'#F87171' }}>حذف</button>
      </div>

      {open&&(
        <div style={{ padding:'14px 16px', display:'flex', flexDirection:'column', gap:20 }}>
          {/* لایه‌ها */}
          <div>
            <div style={{ fontSize:11, fontWeight:700, color:'#64748b', marginBottom:8, letterSpacing:.5 }}>TIERS — لایه‌های پورسانت</div>
            <div style={{ display:'flex', flexDirection:'column', gap:5, marginBottom:10 }}>
              {tiers.length===0&&<div style={{ fontSize:12, color:'#374151', padding:10, textAlign:'center', borderRadius:8, border:'1px dashed rgba(255,255,255,.07)' }}>لایه‌ای تعریف نشده</div>}
              {[...tiers].sort((a,b)=>(a.from_amount||0)-(b.from_amount||0)).map(t=>(
                <div key={t.id} style={{ display:'flex', alignItems:'center', gap:8, padding:'9px 12px', borderRadius:8, background:'rgba(255,255,255,.04)', border:'1px solid rgba(255,255,255,.07)' }}>
                  <span style={{ fontSize:12, color:'#94a3b8', fontFamily:'JetBrains Mono' }}>{_toM(t.from_amount,fa)}</span>
                  <span style={{ color:'#374151', fontSize:12 }}>→</span>
                  <span style={{ fontSize:12, color:'#94a3b8', fontFamily:'JetBrains Mono' }}>{t.to_amount?_toM(t.to_amount,fa):'∞'}</span>
                  <div style={{ flex:1 }}/>
                  <span style={{ fontSize:13, fontWeight:700, padding:'3px 10px', borderRadius:6, background:t.type==='percentage'?'rgba(99,102,241,.18)':'rgba(52,211,153,.18)', color:t.type==='percentage'?'#818CF8':'#34D399', fontFamily:'JetBrains Mono' }}>
                    {t.type==='percentage'?`${fa(t.rate)}٪`:`${_toM(t.rate,fa)} / فروش`}
                  </span>
                  <button onClick={()=>fetch(`/api/commission/tiers/${t.id}`,{method:'DELETE',headers}).then(()=>reload())} style={{ background:'none', border:'none', cursor:'pointer', color:'#F87171', fontSize:16, padding:'0 4px', opacity:.7 }}>×</button>
                </div>
              ))}
            </div>
            <div style={{ display:'flex', gap:6, flexWrap:'wrap', padding:'10px 12px', borderRadius:8, background:'rgba(99,102,241,.04)', border:'1px dashed rgba(99,102,241,.2)' }}>
              <div style={{ fontSize:11, color:'#6366F1', width:'100%', marginBottom:4, fontWeight:600 }}>+ لایه جدید</div>
              <input value={tf.from_amount} onChange={e=>setTf(p=>({...p,from_amount:e.target.value}))} placeholder="از (تومان)" style={_cInp} />
              <span style={{ alignSelf:'center', color:'#374151' }}>→</span>
              <input value={tf.to_amount} onChange={e=>setTf(p=>({...p,to_amount:e.target.value}))} placeholder="تا (خالی=∞)" style={_cInp} />
              <select value={tf.type} onChange={e=>setTf(p=>({...p,type:e.target.value}))} style={{..._cInp,direction:'rtl',fontFamily:'inherit',minWidth:130}}>
                <option value="percentage">درصد از فروش</option>
                <option value="fixed_per_deal">مبلغ ثابت هر فروش</option>
              </select>
              <input value={tf.rate} onChange={e=>setTf(p=>({...p,rate:e.target.value}))} placeholder={tf.type==='percentage'?'درصد (مثلاً ۵)':'مبلغ (تومان)'} style={{..._cInp,width:120}} />
              <button onClick={addTier} style={{ padding:'6px 14px', borderRadius:7, background:'rgba(99,102,241,.2)', border:'1px solid rgba(99,102,241,.35)', color:'#818CF8', fontSize:12, cursor:'pointer', fontWeight:600 }}>اضافه</button>
            </div>
          </div>

          {/* جوایز */}
          <div>
            <div style={{ fontSize:11, fontWeight:700, color:'#64748b', marginBottom:8, letterSpacing:.5 }}>BONUSES — جوایز</div>
            <div style={{ display:'flex', flexDirection:'column', gap:5, marginBottom:10 }}>
              {bons.length===0&&<div style={{ fontSize:12, color:'#374151', padding:10, textAlign:'center', borderRadius:8, border:'1px dashed rgba(255,255,255,.07)' }}>جایزه‌ای تعریف نشده</div>}
              {bons.map(b=>(
                <div key={b.id} style={{ display:'flex', alignItems:'center', gap:8, padding:'10px 12px', borderRadius:8, background:'rgba(255,255,255,.04)', border:'1px solid rgba(255,255,255,.07)' }}>
                  <span style={{ fontSize:16 }}>🎯</span>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:12, fontWeight:600, color:'#e2e8f0' }}>{b.name}</div>
                    <div style={{ fontSize:11, color:'#64748b', marginTop:2 }}>
                      {b.condition_type==='consecutive_periods'&&`${fa(b.threshold)} ماه متوالی هدف رو بزن`}
                      {b.condition_type==='single_period_amount'&&`فروش بالای ${_toM(b.threshold,fa)} در یک ماه`}
                      {b.condition_type==='total_year_amount'&&`فروش سالانه بالای ${_toM(b.threshold,fa)}`}
                    </div>
                  </div>
                  <span style={{ fontSize:13, fontWeight:700, color:'#34D399', fontFamily:'JetBrains Mono', flexShrink:0 }}>{_toM(b.bonus_amount,fa)} جایزه</span>
                  <button onClick={()=>fetch(`/api/commission/bonuses/${b.id}`,{method:'DELETE',headers}).then(()=>reload())} style={{ background:'none', border:'none', cursor:'pointer', color:'#F87171', fontSize:16, padding:'0 4px', opacity:.7 }}>×</button>
                </div>
              ))}
            </div>
            <div style={{ display:'flex', gap:6, flexWrap:'wrap', padding:'10px 12px', borderRadius:8, background:'rgba(52,211,153,.03)', border:'1px dashed rgba(52,211,153,.2)' }}>
              <div style={{ fontSize:11, color:'#34D399', width:'100%', marginBottom:4, fontWeight:600 }}>+ جایزه جدید</div>
              <input value={bf.name} onChange={e=>setBf(p=>({...p,name:e.target.value}))} placeholder="نام جایزه" style={{..._cInp,direction:'rtl',fontFamily:'inherit',minWidth:140}} />
              <select value={bf.condition_type} onChange={e=>setBf(p=>({...p,condition_type:e.target.value}))} style={{..._cInp,direction:'rtl',fontFamily:'inherit',minWidth:160}}>
                {COND.map(o=><option key={o.id} value={o.id}>{o.label}</option>)}
              </select>
              <input value={bf.threshold} onChange={e=>setBf(p=>({...p,threshold:e.target.value}))} placeholder={COND.find(o=>o.id===bf.condition_type)?.hint||'عدد'} style={_cInp} />
              <input value={bf.bonus_amount} onChange={e=>setBf(p=>({...p,bonus_amount:e.target.value}))} placeholder="مبلغ جایزه (تومان)" style={_cInp} />
              <button onClick={addBonus} style={{ padding:'6px 14px', borderRadius:7, background:'rgba(52,211,153,.15)', border:'1px solid rgba(52,211,153,.3)', color:'#34D399', fontSize:12, cursor:'pointer', fontWeight:600 }}>اضافه</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ─── مودال ویرایش فروشنده ─────────────────────────────────────
const SellerSetupModal = ({ seller, period, sm, plans, headers, toast, fa, onClose, onSaved }) => {
  const [target,   setTarget]   = useState(sm?.target||'');
  const [planId,   setPlanId]   = useState('');
  const [uname,    setUname]    = useState(seller.login_username||'');
  const [pass,     setPass]     = useState('');
  const [saving,   setSaving]   = useState(false);
  const [tab,      setTab]      = useState('target');

  const saveTarget = () => {
    if(!target) return;
    setSaving(true);
    const amount = parseFloat(String(target).replace(/,/g,''))||0;
    const ps=[fetch(`/api/commission/sellers/${seller.id}/target`,{method:'POST',headers,body:JSON.stringify({period,amount})})];
    if(planId) ps.push(fetch(`/api/commission/sellers/${seller.id}/assign-plan`,{method:'POST',headers,body:JSON.stringify({plan_id:planId,start_date:period+'-01'})}));
    Promise.all(ps).then(()=>{toast?.('ذخیره شد','success');onSaved();}).finally(()=>setSaving(false));
  };

  const savePass = () => {
    if(!uname||!pass) return;
    setSaving(true);
    fetch(`/api/commission/sellers/${seller.id}/password`,{method:'POST',headers,body:JSON.stringify({login_username:uname,password:pass})})
      .then(r=>r.json()).then(d=>{
        if(d.success){toast?.('رمز تنظیم شد','success');onSaved();}
        else toast?.(d.message||'خطا','error');
      }).finally(()=>setSaving(false));
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,.65)', zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }} onClick={onClose}>
      <div style={{ width:'100%', maxWidth:460, background:'#13131f', border:'1px solid #2a2a3d', borderRadius:14, boxShadow:'0 20px 60px rgba(0,0,0,.7)' }} onClick={e=>e.stopPropagation()}>
        <div style={{ display:'flex', alignItems:'center', gap:10, padding:'14px 18px', borderBottom:'1px solid #2a2a3d' }}>
          <div style={{ width:36, height:36, borderRadius:'50%', background:'rgba(99,102,241,.2)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:13, fontWeight:700, color:'#818CF8', flexShrink:0 }}>{(seller.name||'').slice(0,2)}</div>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:14, fontWeight:700, color:'#e2e8f0' }}>{seller.name}</div>
            <div style={{ fontSize:11, color:'#64748b' }}>{_pLabel(period)}</div>
          </div>
          <button onClick={onClose} style={{ background:'none', border:'none', cursor:'pointer', color:'#64748b', fontSize:20 }}>✕</button>
        </div>

        <div style={{ display:'flex', borderBottom:'1px solid #2a2a3d' }}>
          {[{id:'target',label:'🎯 تارگت و طرح'},{id:'password',label:'🔑 دسترسی'}].map(t=>(
            <button key={t.id} onClick={()=>setTab(t.id)} style={{
              flex:1, padding:10, fontSize:12, cursor:'pointer', border:'none',
              borderBottom:`2px solid ${tab===t.id?'#6366F1':'transparent'}`,
              background:tab===t.id?'rgba(99,102,241,.08)':'transparent',
              color:tab===t.id?'#818CF8':'#64748b', fontWeight:tab===t.id?600:400,
            }}>{t.label}</button>
          ))}
        </div>

        <div style={{ padding:18 }}>
          {tab==='target'&&(
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <div>
                <div style={{ fontSize:12, color:'#64748b', marginBottom:6, fontWeight:600 }}>تارگت فروش — {_pLabel(period)}</div>
                <input value={target} onChange={e=>setTarget(e.target.value)} placeholder="مبلغ به تومان — مثلاً: 50000000"
                  style={{ width:'100%', background:'rgba(255,255,255,.05)', border:'1px solid rgba(255,255,255,.1)', borderRadius:8, padding:'10px 12px', color:'#e2e8f0', fontSize:14, outline:'none', direction:'ltr', fontFamily:'JetBrains Mono', boxSizing:'border-box' }} />
                {target&&!isNaN(parseFloat(target))&&<div style={{ fontSize:11, color:'#818CF8', marginTop:4 }}>= {_toM(parseFloat(target),fa)}</div>}
              </div>
              <div>
                <div style={{ fontSize:12, color:'#64748b', marginBottom:6, fontWeight:600 }}>طرح پورسانت</div>
                {sm?.plan_name&&<div style={{ fontSize:11, color:'#818CF8', marginBottom:6 }}>طرح فعلی: {sm.plan_name}</div>}
                <select value={planId} onChange={e=>setPlanId(e.target.value)}
                  style={{ width:'100%', background:'rgba(255,255,255,.05)', border:'1px solid rgba(255,255,255,.1)', borderRadius:8, padding:'10px 12px', color:planId?'#e2e8f0':'#64748b', fontSize:13, outline:'none', direction:'rtl', boxSizing:'border-box' }}>
                  <option value="">— بدون تغییر طرح —</option>
                  {plans.filter(p=>p.is_active).map(p=><option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
              </div>
              <button onClick={saveTarget} disabled={saving||!target} style={{ padding:'10px', borderRadius:8, fontSize:13, fontWeight:600, cursor:'pointer', border:'none', background:saving||!target?'rgba(99,102,241,.3)':'#6366F1', color:'white' }}>
                {saving?'⏳ در حال ذخیره...':'💾 ذخیره'}
              </button>
            </div>
          )}
          {tab==='password'&&(
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <div style={{ padding:'10px 14px', borderRadius:8, background:'rgba(99,102,241,.08)', border:'1px solid rgba(99,102,241,.2)', fontSize:12, color:'#94a3b8', lineHeight:1.6 }}>
                با این اطلاعات فروشنده وارد پنل اختصاصی خودش می‌شه.
              </div>
              <div>
                <div style={{ fontSize:12, color:'#64748b', marginBottom:6 }}>نام کاربری</div>
                <input value={uname} onChange={e=>setUname(e.target.value)} placeholder="مثلاً: ali"
                  style={{ width:'100%', background:'rgba(255,255,255,.05)', border:'1px solid rgba(255,255,255,.1)', borderRadius:8, padding:'10px 12px', color:'#e2e8f0', fontSize:13, outline:'none', direction:'ltr', fontFamily:'JetBrains Mono', boxSizing:'border-box' }} />
              </div>
              <div>
                <div style={{ fontSize:12, color:'#64748b', marginBottom:6 }}>رمز عبور جدید</div>
                <input type="password" value={pass} onChange={e=>setPass(e.target.value)} placeholder="حداقل ۶ کاراکتر"
                  style={{ width:'100%', background:'rgba(255,255,255,.05)', border:'1px solid rgba(255,255,255,.1)', borderRadius:8, padding:'10px 12px', color:'#e2e8f0', fontSize:13, outline:'none', boxSizing:'border-box' }} />
              </div>
              <button onClick={savePass} disabled={saving||!uname||!pass} style={{ padding:'10px', borderRadius:8, fontSize:13, fontWeight:600, cursor:'pointer', border:'none', background:saving||!uname||!pass?'rgba(99,102,241,.3)':'#6366F1', color:'white' }}>
                {saving?'⏳ در حال ذخیره...':'🔑 تنظیم رمز ورود'}
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
// ═══════════════════════════════════════════════════════════════
// تب فعالیت‌های فروشندگان
// ═══════════════════════════════════════════════════════════════
const ActivitiesTab = ({ headers, fa }) => {
  const { useState, useEffect, useRef } = React;
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [period, setPeriod] = useState('today');
  const [sellerFilter, setSellerFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const timerRef = useRef(null);

  const load = () => {
    const p = new URLSearchParams({ limit: 80, period });
    if (sellerFilter) p.set('seller_id', sellerFilter);
    if (typeFilter)   p.set('event_type', typeFilter);
    fetch('/api/market/activities?' + p.toString(), { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setData(d.data); })
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    setLoading(true);
    load();
    // رفرش خودکار هر ۳۰ ثانیه
    timerRef.current = setInterval(load, 30000);
    return () => clearInterval(timerRef.current);
  }, [period, sellerFilter, typeFilter]);

  const OUTCOME = {
    answered:      { label: 'جواب داد',   color: '#34D399', icon: '✅' },
    no_answer:     { label: 'بی‌پاسخ',    color: '#F87171', icon: '📵' },
    call_later:    { label: 'بعداً زنگ',  color: '#818CF8', icon: '⏰' },
    follow_up:     { label: 'پیگیری',     color: '#818CF8', icon: '🔄' },
    scheduled:     { label: 'زمان خرید',  color: '#A78BFA', icon: '📅' },
    sold:          { label: 'فروش شد',    color: '#34D399', icon: '💰' },
    not_interested:{ label: 'علاقه نداشت',color: '#6B7280', icon: '❌' },
    cancelled:     { label: 'کنسل',       color: '#EF4444', icon: '🚫' },
    bad_number:    { label: 'شماره اشتباه',color: '#DC2626', icon: '☎️' },
  };

  const PERIOD_OPTS = [
    { id: 'today', label: 'امروز' },
    { id: 'week',  label: '۷ روز' },
    { id: 'month', label: 'این ماه' },
    { id: '',      label: 'همه' },
  ];

  const toShamsi = (iso) => {
    if (!iso) return '';
    const d = new Date(iso);
    const now = new Date();
    const diff = Math.floor((now - d) / 60000);
    if (diff < 1) return 'همین الان';
    if (diff < 60) return fa(diff) + ' دقیقه پیش';
    if (diff < 1440) return fa(Math.floor(diff / 60)) + ' ساعت پیش';
    return fa(Math.floor(diff / 1440)) + ' روز پیش';
  };

  if (loading && !data) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200, color: '#64748b' }}>
      ⏳ در حال بارگذاری...
    </div>
  );

  const sum = data?.summary || {};
  const bySeller = data?.by_seller || [];
  const activities = data?.activities || [];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

      {/* ─── فیلترها ─── */}
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
        {/* فیلتر زمان */}
        <div style={{ display: 'flex', gap: 4, background: 'rgba(255,255,255,.04)', borderRadius: 8, padding: 4 }}>
          {PERIOD_OPTS.map(p => (
            <button key={p.id} onClick={() => setPeriod(p.id)} style={{
              padding: '5px 12px', borderRadius: 6, fontSize: 11, cursor: 'pointer',
              border: 'none',
              background: period === p.id ? 'rgba(99,102,241,.25)' : 'transparent',
              color: period === p.id ? '#818CF8' : '#64748b', fontWeight: period === p.id ? 600 : 400,
            }}>{p.label}</button>
          ))}
        </div>

        {/* فیلتر نوع */}
        <select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} style={{
          padding: '6px 10px', borderRadius: 8, fontSize: 12, border: '1px solid rgba(255,255,255,.1)',
          background: 'rgba(255,255,255,.05)', color: '#cbd5e1', outline: 'none',
        }}>
          <option value=''>همه رویدادها</option>
          <option value='call'>📞 تماس</option>
          <option value='refer'>🔀 ارجاع</option>
        </select>

        {/* فیلتر فروشنده */}
        <select value={sellerFilter} onChange={e => setSellerFilter(e.target.value)} style={{
          padding: '6px 10px', borderRadius: 8, fontSize: 12, border: '1px solid rgba(255,255,255,.1)',
          background: 'rgba(255,255,255,.05)', color: '#cbd5e1', outline: 'none',
        }}>
          <option value=''>همه فروشندگان</option>
          {bySeller.map(s => (
            <option key={s.id} value={s.id}>{s.name}</option>
          ))}
        </select>

        <div style={{ marginRight: 'auto', fontSize: 11, color: '#475569' }}>
          🔄 رفرش خودکار هر ۳۰ ثانیه
        </div>
      </div>

      {/* ─── کارت‌های خلاصه (امروز) ─── */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px,1fr))', gap: 10 }}>
        {[
          { label: 'تماس‌های امروز',  val: fa(sum.calls_today  || 0), color: '#60A5FA', icon: '📞' },
          { label: 'فروش‌های امروز',  val: fa(sum.deals_today  || 0), color: '#34D399', icon: '💰' },
          { label: 'ارجاع‌های امروز', val: fa(sum.refers_today || 0), color: '#A78BFA', icon: '🔀' },
          { label: 'درآمد امروز',     val: sum.revenue_today > 0 ? fa(Math.round(sum.revenue_today / 1000000)) + ' M' : '—', color: '#FB923C', icon: '📈' },
        ].map(s => (
          <div key={s.label} style={{ background: 'rgba(255,255,255,.04)', border: `1px solid ${s.color}22`, borderRadius: 10, padding: '12px 14px' }}>
            <div style={{ fontSize: 20, fontWeight: 700, color: s.color }}>{s.icon} {s.val}</div>
            <div style={{ fontSize: 11, color: '#64748b', marginTop: 3 }}>{s.label}</div>
          </div>
        ))}
      </div>

      {/* ─── آمار هر فروشنده (امروز) ─── */}
      {bySeller.length > 0 && (
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {bySeller.map(s => (
            <div key={s.id} onClick={() => setSellerFilter(sellerFilter === s.id ? '' : s.id)}
              style={{
                background: sellerFilter === s.id ? 'rgba(99,102,241,.15)' : 'rgba(255,255,255,.04)',
                border: `1px solid ${sellerFilter === s.id ? '#6366F1' : 'rgba(255,255,255,.08)'}`,
                borderRadius: 10, padding: '10px 14px', cursor: 'pointer', minWidth: 130,
                transition: 'all .15s',
              }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: '#e2e8f0', marginBottom: 6 }}>👤 {s.name}</div>
              <div style={{ display: 'flex', gap: 10, fontSize: 11 }}>
                <span style={{ color: '#60A5FA' }}>📞 {fa(s.calls)}</span>
                <span style={{ color: '#34D399' }}>💰 {fa(s.deals)}</span>
                <span style={{ color: '#94A3B8' }}>لید: {fa(s.active_leads)}</span>
              </div>
              {s.revenue > 0 && (
                <div style={{ fontSize: 10, color: '#FB923C', marginTop: 4 }}>
                  {fa(Math.round(s.revenue / 1000000))} M تومان
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* ─── فید فعالیت‌ها ─── */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {activities.length === 0 && (
          <div style={{ textAlign: 'center', padding: 40, color: '#475569' }}>هیچ فعالیتی در این بازه ثبت نشده</div>
        )}
        {activities.map(a => {
          const oc = a.outcome ? (OUTCOME[a.outcome] || { label: a.outcome, color: '#64748b', icon: '📌' }) : null;
          const isRefer = a.event_type === 'refer';
          const isSold  = a.outcome === 'sold';

          return (
            <div key={a.id} style={{
              display: 'flex', alignItems: 'flex-start', gap: 12,
              background: isSold ? 'rgba(52,211,153,.07)' : isRefer ? 'rgba(167,139,250,.07)' : 'rgba(255,255,255,.03)',
              border: `1px solid ${isSold ? '#34D39920' : isRefer ? '#A78BFA20' : 'rgba(255,255,255,.06)'}`,
              borderRadius: 10, padding: '10px 14px',
            }}>
              {/* آیکون */}
              <div style={{ fontSize: 18, minWidth: 28, textAlign: 'center', marginTop: 1 }}>
                {isRefer ? '🔀' : (oc ? oc.icon : '📞')}
              </div>

              {/* محتوا */}
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                  {/* فروشنده */}
                  <span style={{ fontSize: 12, fontWeight: 600, color: '#818CF8' }}>
                    {a.seller_name}
                  </span>
                  {/* نوع */}
                  {isRefer ? (
                    <span style={{ fontSize: 11, color: '#A78BFA', background: 'rgba(167,139,250,.15)', padding: '2px 8px', borderRadius: 12 }}>
                      ارجاع به {a.refer_to}
                    </span>
                  ) : oc && (
                    <span style={{ fontSize: 11, color: oc.color, background: oc.color + '18', padding: '2px 8px', borderRadius: 12 }}>
                      {oc.label}
                    </span>
                  )}
                  {/* مبلغ فروش */}
                  {isSold && a.sale_amount > 0 && (
                    <span style={{ fontSize: 12, color: '#34D399', fontWeight: 700 }}>
                      💰 {fa(Math.round(a.sale_amount).toLocaleString())} تومان
                    </span>
                  )}
                </div>

                {/* نام لید */}
                <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 3 }}>
                  لید: <span style={{ color: '#cbd5e1' }}>{a.lead_name}</span>
                  {a.lead_phone && <span style={{ marginRight: 8, color: '#64748b' }}>{a.lead_phone}</span>}
                </div>

                {/* یادداشت */}
                {a.note && (
                  <div style={{ fontSize: 11, color: '#64748b', marginTop: 3, fontStyle: 'italic' }}>
                    {a.note.length > 80 ? a.note.slice(0, 80) + '…' : a.note}
                  </div>
                )}

                {/* دلیل ارجاع */}
                {isRefer && a.refer_reason && (
                  <div style={{ fontSize: 11, color: '#64748b', marginTop: 3, fontStyle: 'italic' }}>
                    دلیل: {a.refer_reason}
                  </div>
                )}
              </div>

              {/* زمان */}
              <div style={{ fontSize: 10, color: '#475569', whiteSpace: 'nowrap', marginTop: 2 }}>
                {toShamsi(a.created_at)}
              </div>
            </div>
          );
        })}
      </div>

    </div>
  );
};


// ─── از sales.jsx ─────────────────────────────────────────────────────────────

// ─── کارنامه فروش ─────────────────────────────────────────────────

const STATUS_MAP = {
  buyer:      { label: 'خریدار',          color: '#22c55e' },
  follow_up:  { label: 'پیگیری',          color: '#60A5FA' },
  new:        { label: 'جدید',             color: '#94a3b8' },
  interested: { label: 'علاقمند',         color: '#FB923C' },
  lost:       { label: 'از دست رفته',     color: '#F87171' },
  expired:    { label: 'منقضی',           color: '#ef4444' },
  scheduled:  { label: 'زمان‌بندی شده',   color: '#A78BFA' },
  active:     { label: 'فعال',            color: '#34D399' },
};

const SORT_OPTIONS = [
  { id: 'revenue',    label: 'درآمد' },
  { id: 'buyers',     label: 'خریداران' },
  { id: 'conv',       label: 'نرخ تبدیل' },
  { id: 'totalLeads', label: 'کل لیدها' },
  { id: 'score',      label: 'امتیاز' },
];

const CUR_PERIOD = new Date().toISOString().slice(0, 7); // YYYY-MM

const cleanName = (n) => (!n || /^[\s?]+$/.test(n)) ? 'نام نامشخص' : n;

// ─── نمودار خطی SVG ──────────────────────────────────────────────
const SalesLineChart = ({ data, valueKey, color, height = 120, label = '' }) => {
  if (!data || data.length < 2) return null;
  const vals  = data.map(d => d[valueKey] || 0);
  const maxV  = Math.max(...vals, 1);
  const W = 100, H = height;
  const pts   = vals.map((v, i) => [i / (vals.length - 1) * W, H - (v / maxV) * (H - 10) - 5]);
  const path  = pts.map((p, i) => (i === 0 ? `M` : `L`) + `${p[0].toFixed(2)},${p[1].toFixed(2)}`).join(' ');
  const area  = `${path} L${W},${H} L0,${H} Z`;
  return (
    <svg viewBox={`0 0 100 ${H}`} preserveAspectRatio="none" style={{width:'100%',height:H,overflow:'visible'}}>
      <defs>
        <linearGradient id={`lg_${valueKey}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.35"/>
          <stop offset="100%" stopColor={color} stopOpacity="0.02"/>
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#lg_${valueKey})`}/>
      <path d={path} fill="none" stroke={color} strokeWidth="1.5" vectorEffect="non-scaling-stroke"/>
      {pts.map((p, i) => (
        <circle key={i} cx={p[0]} cy={p[1]} r="2.5" fill={color} vectorEffect="non-scaling-stroke"
          style={{cursor:'default'}}>
          <title>{label}: {vals[i].toLocaleString()}</title>
        </circle>
      ))}
    </svg>
  );
};

// ─── نمودار میله‌ای SVG ──────────────────────────────────────────
const BarChart = ({ data, valueKey, color, height = 120 }) => {
  if (!data || data.length === 0) return null;
  const vals = data.map(d => d[valueKey] || 0);
  const maxV = Math.max(...vals, 1);
  const gap  = 4;
  const total = data.length;
  return (
    <svg viewBox={`0 0 ${total * (100/total)} ${height}`} preserveAspectRatio="none"
      style={{width:'100%',height,overflow:'visible'}}>
      {data.map((d, i) => {
        const barW = (100 / total) - gap;
        const barH = Math.max(2, (vals[i] / maxV) * (height - 16));
        const x    = i * (100 / total) + gap / 2;
        const y    = height - barH - 10;
        return (
          <rect key={i} x={x} y={y} width={barW} height={barH}
            rx="2" fill={color} opacity={vals[i] === maxV ? 1 : 0.55}>
            <title>{d.label || d.period}: {vals[i].toLocaleString()}</title>
          </rect>
        );
      })}
    </svg>
  );
};

const Sales = () => {
  const { Icon, SlidePanel, Modal, useToast } = window.SB_UI;
  const { fa, faMoney } = window.SB_DATA;
  const { useState, useEffect, useMemo } = React;
  const toast = useToast();

  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };
  const api = (url, opts = {}) => fetch('/api' + url, { headers, ...opts }).then(r => r.json());

  const [report,  setReport]  = useState(null);
  const [loading, setLoading] = useState(true);
  const [sortBy,  setSortBy]  = window.useStickyState('sales_sort', 'revenue');
  const [panel,   setPanel]   = useState(null);
  const [leads,   setLeads]   = useState([]);
  const [lLoad,   setLLoad]   = useState(false);
  const [lStatus, setLStatus] = useState('all');
  // نمودار رشد
  const [growth,   setGrowth]  = useState(null);
  const [chartTab, setChartTab] = useState('revenue'); // revenue | buyers | leads
  const [chartView, setChartView] = useState('monthly'); // monthly | weekly
  // تارگت
  const [targetModal, setTargetModal] = useState(null); // { seller }
  const [targetForm,  setTargetForm]  = useState({ year: parseInt(CUR_PERIOD.slice(0,4)), month: parseInt(CUR_PERIOD.slice(5,7)), amount: '' });
  const [tSaving,     setTSaving]     = useState(false);

  const load = () => {
    setLoading(true);
    Promise.all([
      api('/market/sales-report'),
      api('/market/growth-stats'),
    ]).then(([d, g]) => {
      if (d.success) setReport(d.data);
      if (g.success) setGrowth(g.data);
      setLoading(false);
    }).catch(() => setLoading(false));
  };

  useEffect(() => { load(); }, []);

  const openPanel = async (seller) => {
    setPanel({ seller }); setLeads([]); setLStatus('all'); setLLoad(true);
    const r = await api(`/market/sellers/${seller.id}/leads`);
    setLLoad(false);
    if (r.success) setLeads(r.data.leads || []);
  };

  // آپدیت تارگت روی panel بدون reload کامل
  const refreshPanelSeller = (sellerId, newTarget) => {
    if (panel?.seller?.id === sellerId) {
      setPanel(p => ({ ...p, seller: { ...p.seller, target: newTarget } }));
    }
    setReport(r => {
      if (!r) return r;
      return { ...r, sellers: r.sellers.map(s => s.id === sellerId ? { ...s, target: newTarget } : s) };
    });
  };

  const saveTarget = async () => {
    const amt = parseInt(String(targetForm.amount).replace(/[,\s]/g, ''));
    if (!amt || isNaN(amt) || amt <= 0) { toast.error('مبلغ معتبر وارد کنید'); return; }
    const yr  = parseInt(targetForm.year);
    const mo  = parseInt(targetForm.month);
    if (!yr || yr < 2020 || yr > 2100) { toast.error('سال معتبر وارد کنید'); return; }
    if (!mo || mo < 1 || mo > 12)      { toast.error('ماه معتبر وارد کنید (۱ تا ۱۲)'); return; }
    const period = `${yr}-${String(mo).padStart(2,'0')}`;
    setTSaving(true);
    const r = await api(`/commission/sellers/${targetModal.seller.id}/target`, {
      method: 'POST',
      body: JSON.stringify({ period, amount: amt }),
    });
    setTSaving(false);
    if (r.success) {
      toast.success('هدف ذخیره شد');
      if (period === CUR_PERIOD) refreshPanelSeller(targetModal.seller.id, amt);
      setTargetModal(null);
    } else {
      toast.error(r.message || 'خطا');
    }
  };

  const FA_MONTHS = ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'];

  const sorted = useMemo(() => {
    if (!report) return [];
    return [...report.sellers].sort((a, b) => {
      if (sortBy === 'revenue')    return b.totalRevenue - a.totalRevenue;
      if (sortBy === 'buyers')     return b.buyers - a.buyers;
      if (sortBy === 'conv')       return b.conversionRate - a.conversionRate;
      if (sortBy === 'totalLeads') return b.totalLeads - a.totalLeads;
      if (sortBy === 'score')      return (b.score ?? 0) - (a.score ?? 0);
      return 0;
    });
  }, [report, sortBy]);

  const filteredLeads = lStatus === 'all' ? leads : leads.filter(l => l.status === lStatus);
  const buyerLeads = leads.filter(l => l.status === 'buyer');

  const fmtMon = (n) => {
    if (!n || n === 0) return '—';
    if (n >= 1_000_000_000) return fa((n / 1_000_000_000).toFixed(1)) + ' میلیارد';
    if (n >= 1_000_000)     return fa((n / 1_000_000).toFixed(1)) + ' میلیون';
    return fa(n.toLocaleString('en-US')) + ' ت';
  };

  const ScoreBadge = ({ score }) => {
    if (score === null || score === undefined) return <span style={{color:'#475569',fontSize:12}}>—</span>;
    const color = score >= 70 ? '#22c55e' : score >= 50 ? '#FB923C' : '#F87171';
    return <span style={{fontSize:12,fontWeight:700,padding:'2px 9px',borderRadius:12,background:color+'22',color}}>{fa(score)}</span>;
  };

  const TargetBar = ({ revenue, target }) => {
    if (!target) return (
      <span style={{fontSize:11,color:'#475569',fontStyle:'italic'}}>هدف ندارد</span>
    );
    const pct = Math.min(100, Math.round(revenue / target * 100));
    const color = pct >= 100 ? '#22c55e' : pct >= 60 ? '#FB923C' : '#F87171';
    return (
      <div style={{width:110}}>
        <div style={{display:'flex',justifyContent:'space-between',marginBottom:3}}>
          <span style={{fontSize:10,color,fontWeight:700}}>{fa(pct)}٪</span>
          <span style={{fontSize:10,color:'#475569'}}>{fmtMon(target)}</span>
        </div>
        <div style={{height:4,borderRadius:2,background:'rgba(255,255,255,0.1)',overflow:'hidden'}}>
          <div style={{height:'100%',width:pct+'%',borderRadius:2,background:color,transition:'width .4s'}}/>
        </div>
      </div>
    );
  };

  const StatusBreakdown = ({ byStatus, totalLeads }) => {
    if (!totalLeads) return <div style={{fontSize:12,color:'var(--text-3)'}}>لید ندارد</div>;
    const order = ['buyer','follow_up','active','new','lost','expired'];
    return (
      <div style={{display:'flex',flexDirection:'column',gap:7}}>
        {order.filter(k => byStatus[k]).map(k => {
          const cnt = byStatus[k];
          const pct = Math.round(cnt / totalLeads * 100);
          const st  = STATUS_MAP[k] || { label: k, color: '#94a3b8' };
          return (
            <div key={k}>
              <div style={{display:'flex',justifyContent:'space-between',marginBottom:3}}>
                <span style={{fontSize:12,color:'var(--text-2)'}}>{st.label}</span>
                <span style={{fontSize:12,color:st.color,fontWeight:700}}>{fa(cnt)} <span style={{fontSize:10,color:'var(--text-3)'}}>({fa(pct)}٪)</span></span>
              </div>
              <div style={{height:5,borderRadius:3,background:'rgba(255,255,255,0.07)',overflow:'hidden'}}>
                <div style={{height:'100%',width:pct+'%',borderRadius:3,background:st.color,opacity:.85}}/>
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  if (loading) return (
    <div style={{padding:40,textAlign:'center',color:'var(--text-3)'}}>
      <span className="spinner"/><br/>در حال بارگذاری...
    </div>
  );
  if (!report) return <div style={{padding:40,textAlign:'center',color:'#F87171'}}>خطا در بارگذاری گزارش</div>;

  const { overall } = report;
  const avgConv = overall.totalLeads > 0 ? Math.round(overall.totalBuyers / overall.totalLeads * 1000) / 10 : 0;

  return (
    <div style={{padding:24}}>

      {/* هدر */}
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:20}}>
        <div>
          <div style={{fontSize:18,fontWeight:700,color:'var(--text-1)'}}>کارنامه فروش</div>
          <div style={{fontSize:12,color:'var(--text-3)',marginTop:3}}>آمار و پرونده فروش فروشندگان</div>
        </div>
        <button className="icon-btn" onClick={load} title="بارگذاری مجدد" style={{width:34,height:34}}>
          <Icon name="refresh-cw" size={14}/>
        </button>
      </div>

      {/* کارت‌های خلاصه */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:12,marginBottom:24}}>
        {[
          {label:'فروشندگان فعال', value:fa(overall.activeSellers)+'/'+fa(overall.totalSellers), color:'#34D399'},
          {label:'کل لیدها',       value:fa(overall.totalLeads),       color:'#60A5FA'},
          {label:'خریداران',        value:fa(overall.totalBuyers),      color:'#22c55e', sub:fa(avgConv)+'٪ نرخ تبدیل'},
          {label:'درآمد کل',        value:fmtMon(overall.totalRevenue), color:'#FB923C'},
        ].map(m=>(
          <div key={m.label} style={{flex:1,padding:'14px 16px',borderRadius:10,background:'rgba(255,255,255,0.04)',border:'1px solid rgba(255,255,255,0.07)'}}>
            <div style={{fontSize:11,color:'var(--text-3)',marginBottom:6}}>{m.label}</div>
            <div style={{fontSize:20,fontWeight:800,color:m.color}}>{m.value}</div>
            {m.sub&&<div style={{fontSize:11,color:'var(--text-3)',marginTop:3}}>{m.sub}</div>}
          </div>
        ))}
      </div>

      {/* ─── نمودار رشد ─── */}
      {growth && (() => {
        const chartData = chartView === 'monthly' ? growth.monthly : growth.weekly;
        const TABS = [
          { id:'revenue', label:'درآمد',    color:'#FB923C' },
          { id:'buyers',  label:'خریداران', color:'#22c55e' },
          { id:'leads',   label:'لیدها',    color:'#60A5FA' },
        ];
        const activeTab = TABS.find(t => t.id === chartTab);
        const vals = chartData.map(d => d[chartTab] || 0);
        const maxV = Math.max(...vals, 1);
        const totalVal = vals.reduce((a, b) => a + b, 0);
        const avgVal   = vals.length ? Math.round(totalVal / vals.length) : 0;
        const lastVal  = vals[vals.length - 1] || 0;
        const prevVal  = vals[vals.length - 2] || 0;
        const growthPct = prevVal > 0 ? Math.round((lastVal - prevVal) / prevVal * 100) : null;

        const fmtV = (v) => {
          if (chartTab === 'revenue') {
            if (v >= 1_000_000_000) return (v/1_000_000_000).toFixed(1) + 'B';
            if (v >= 1_000_000)     return (v/1_000_000).toFixed(1) + 'M';
            return v.toLocaleString();
          }
          return fa(v);
        };

        return (
          <div className="card" style={{marginBottom:20,padding:'16px 20px'}}>
            {/* header */}
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14,flexWrap:'wrap',gap:8}}>
              <div style={{display:'flex',alignItems:'center',gap:10}}>
                <span style={{fontSize:13,fontWeight:700,color:'var(--text-1)'}}>نمودار رشد</span>
                {growthPct !== null && (
                  <span style={{fontSize:11,padding:'2px 8px',borderRadius:12,fontWeight:700,
                    background: growthPct >= 0 ? 'rgba(34,197,94,0.15)' : 'rgba(248,113,113,0.15)',
                    color: growthPct >= 0 ? '#22c55e' : '#F87171'}}>
                    {growthPct >= 0 ? '+' : ''}{fa(growthPct)}٪
                  </span>
                )}
              </div>
              <div style={{display:'flex',gap:6}}>
                {/* monthly / weekly toggle */}
                {['monthly','weekly'].map(v => (
                  <button key={v} onClick={()=>setChartView(v)} style={{
                    padding:'3px 10px',borderRadius:20,fontSize:11,cursor:'pointer',fontFamily:'inherit',border:'none',
                    background:chartView===v?'rgba(99,102,241,0.2)':'rgba(255,255,255,0.05)',
                    color:chartView===v?'#818cf8':'var(--text-3)',
                    outline:chartView===v?'1px solid rgba(99,102,241,0.35)':'1px solid rgba(255,255,255,0.07)',
                  }}>{v==='monthly'?'ماهانه':'هفتگی'}</button>
                ))}
              </div>
            </div>

            {/* metric tabs */}
            <div style={{display:'flex',gap:8,marginBottom:14}}>
              {TABS.map(t => (
                <button key={t.id} onClick={()=>setChartTab(t.id)} style={{
                  flex:1,padding:'8px 6px',borderRadius:8,fontSize:11,cursor:'pointer',fontFamily:'inherit',border:'none',textAlign:'center',
                  background:chartTab===t.id?(t.color+'18'):'rgba(255,255,255,0.04)',
                  outline:chartTab===t.id?(`1px solid ${t.color}44`):'1px solid rgba(255,255,255,0.06)',
                  color:chartTab===t.id?t.color:'var(--text-3)',transition:'all .15s',
                }}>
                  <div style={{fontWeight:700,fontSize:13}}>{fmtV(lastVal)}</div>
                  <div style={{marginTop:2}}>{t.label}</div>
                </button>
              ))}
            </div>

            {/* chart area */}
            <div style={{position:'relative',padding:'0 0 24px 0'}}>
              {/* y-axis labels */}
              <div style={{position:'absolute',left:0,top:0,height:'calc(100% - 24px)',display:'flex',flexDirection:'column',justifyContent:'space-between',pointerEvents:'none'}}>
                {[maxV, Math.round(maxV/2), 0].map(v => (
                  <span key={v} style={{fontSize:9,color:'var(--text-3)',lineHeight:1}}>{fmtV(v)}</span>
                ))}
              </div>
              {/* grid lines */}
              <div style={{marginRight:28,position:'relative'}}>
                {[0,1,2].map(i=>(
                  <div key={i} style={{position:'absolute',left:0,right:0,top:`${i*50}%`,borderTop:'1px dashed rgba(255,255,255,0.06)',pointerEvents:'none'}}/>
                ))}
                {/* line chart روی bar chart */}
                <div style={{height:130}}>
                  <BarChart data={chartData} valueKey={chartTab} color={activeTab.color+'44'} height={130}/>
                </div>
                <div style={{position:'absolute',top:0,left:0,right:0,height:130}}>
                  <SalesLineChart data={chartData} valueKey={chartTab} color={activeTab.color} height={130}/>
                </div>
              </div>
              {/* x-axis labels */}
              <div style={{marginRight:28,display:'flex',justifyContent:'space-between',marginTop:6}}>
                {chartData.map((d, i) => {
                  const lbl = d.label || (d.period ? d.period.slice(5) : '');
                  const show = chartData.length <= 8 || i % Math.ceil(chartData.length / 8) === 0 || i === chartData.length - 1;
                  return (
                    <span key={i} style={{fontSize:9,color:'var(--text-3)',flex:1,textAlign:'center',overflow:'hidden'}}>
                      {show ? lbl : ''}
                    </span>
                  );
                })}
              </div>
            </div>

            {/* خلاصه آماری */}
            <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:8,marginTop:4,paddingTop:12,borderTop:'1px solid rgba(255,255,255,0.06)'}}>
              {[
                {label:'کل دوره',   value:fmtV(totalVal)},
                {label:'میانگین',   value:fmtV(avgVal)},
                {label: chartView==='monthly'?'ماه جاری':'هفته جاری', value:fmtV(lastVal), accent:activeTab.color},
              ].map(m=>(
                <div key={m.label} style={{textAlign:'center'}}>
                  <div style={{fontSize:13,fontWeight:700,color:m.accent||'var(--text-1)'}}>{m.value}</div>
                  <div style={{fontSize:10,color:'var(--text-3)',marginTop:2}}>{m.label}</div>
                </div>
              ))}
            </div>
          </div>
        );
      })()}

      {/* مرتب‌سازی */}
      <div style={{display:'flex',gap:6,marginBottom:14,alignItems:'center',flexWrap:'wrap'}}>
        <span style={{fontSize:11,color:'var(--text-3)',marginLeft:4}}>مرتب بر اساس:</span>
        {SORT_OPTIONS.map(o=>(
          <button key={o.id} onClick={()=>setSortBy(o.id)} style={{
            padding:'4px 12px',borderRadius:20,fontSize:12,cursor:'pointer',border:'none',transition:'all .15s',fontFamily:'inherit',
            background:sortBy===o.id?'rgba(99,102,241,0.25)':'rgba(255,255,255,0.05)',
            color:sortBy===o.id?'#818cf8':'var(--text-3)',
            outline:sortBy===o.id?'1px solid rgba(99,102,241,0.4)':'1px solid rgba(255,255,255,0.07)',
          }}>{o.label}</button>
        ))}
      </div>

      {/* جدول */}
      <div className="card" style={{overflow:'hidden',marginBottom:20}}>
        <table style={{width:'100%',borderCollapse:'collapse'}}>
          <thead>
            <tr style={{borderBottom:'1px solid var(--border-soft)'}}>
              {['رتبه','فروشنده','لیدهای فعال','خریداران','نرخ تبدیل','درآمد','هدف ماه','امتیاز',''].map((h,i)=>(
                <th key={i} style={{padding:'10px 14px',textAlign:'right',fontSize:11,fontWeight:700,color:'var(--text-3)',whiteSpace:'nowrap'}}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {sorted.map((s, idx) => (
              <tr key={s.id} style={{borderBottom:'1px solid rgba(255,255,255,0.04)',opacity:s.is_active?1:0.45,cursor:'pointer'}}
                onClick={()=>openPanel(s)}
                onMouseEnter={e=>e.currentTarget.style.background='rgba(255,255,255,0.025)'}
                onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                <td style={{padding:'12px 14px'}}>
                  <span style={{fontSize:13,fontWeight:800,color:idx===0?'#FBBF24':idx===1?'#94a3b8':idx===2?'#b87333':'var(--text-3)'}}>{fa(idx+1)}</span>
                </td>
                <td style={{padding:'12px 14px'}}>
                  <div style={{display:'flex',alignItems:'center',gap:10}}>
                    <div style={{width:32,height:32,borderRadius:8,flexShrink:0,background:'rgba(52,211,153,0.15)',color:'#34D399',display:'grid',placeItems:'center',fontSize:12,fontWeight:700}}>
                      {(s.name||'?').slice(0,2)}
                    </div>
                    <div>
                      <div style={{fontSize:13,fontWeight:600,color:'var(--text-1)'}}>{s.name}</div>
                      <div className="mono" style={{fontSize:10,color:'var(--text-3)'}}>{s.login_username||'—'}</div>
                    </div>
                  </div>
                </td>
                <td style={{padding:'12px 14px',fontSize:13,fontWeight:600,color:'#60A5FA'}}>{fa(s.activeCnt)}</td>
                <td style={{padding:'12px 14px',fontSize:13,fontWeight:700,color:'#22c55e'}}>{fa(s.buyers)}</td>
                <td style={{padding:'12px 14px',fontSize:13,color:s.conversionRate>20?'#22c55e':s.conversionRate>10?'#FB923C':'var(--text-3)'}}>{fa(s.conversionRate)}٪</td>
                <td style={{padding:'12px 14px',fontSize:13,fontWeight:600,color:'var(--text-1)'}}>{fmtMon(s.totalRevenue)}</td>
                <td style={{padding:'12px 14px'}}>
                  <div style={{display:'flex',alignItems:'center',gap:8}}>
                    <TargetBar revenue={s.totalRevenue} target={s.target}/>
                    <button className="icon-btn" onClick={e=>{e.stopPropagation();setTargetModal({seller:s});setTargetForm({year:parseInt(CUR_PERIOD.slice(0,4)),month:parseInt(CUR_PERIOD.slice(5,7)),amount:s.target?String(s.target):''});}} title="تعریف هدف" style={{width:24,height:24,flexShrink:0}}>
                      <Icon name="pencil" size={11}/>
                    </button>
                  </div>
                </td>
                <td style={{padding:'12px 14px'}}><ScoreBadge score={s.score}/></td>
                <td style={{padding:'12px 14px'}}>
                  <button className="icon-btn" onClick={e=>{e.stopPropagation();openPanel(s);}} title="پرونده فروش">
                    <Icon name="folder-open" size={13}/>
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* ─── Modal تعریف هدف ─── */}
      {targetModal&&(
        <Modal open={true} title={`هدف فروش — ${targetModal.seller.name}`} width={400} onClose={()=>setTargetModal(null)}
          footer={
            <div style={{display:'flex',gap:8,justifyContent:'flex-end'}}>
              <button onClick={()=>setTargetModal(null)} className="btn btn-ghost">انصراف</button>
              <button onClick={saveTarget} disabled={tSaving} className="btn btn-primary">
                {tSaving?<span className="spinner"/>:'ذخیره'}
              </button>
            </div>
          }>
          <div style={{display:'flex',flexDirection:'column',gap:14}}>
            {/* سال و ماه */}
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10}}>
              <div>
                <label className="label">سال میلادی</label>
                <input className="input" type="number" min="2020" max="2100"
                  value={targetForm.year}
                  onChange={e=>setTargetForm(f=>({...f,year:parseInt(e.target.value)||f.year}))}/>
              </div>
              <div>
                <label className="label">ماه (۱–۱۲)</label>
                <input className="input" type="number" min="1" max="12"
                  value={targetForm.month}
                  onChange={e=>setTargetForm(f=>({...f,month:parseInt(e.target.value)||f.month}))}/>
              </div>
            </div>
            {/* نمایش نام ماه */}
            {targetForm.year && targetForm.month >= 1 && targetForm.month <= 12 && (
              <div style={{padding:'6px 12px',borderRadius:7,background:'rgba(255,255,255,0.05)',fontSize:12,color:'var(--text-2)',textAlign:'center'}}>
                {(() => {
                  const d = new Date(targetForm.year, targetForm.month - 1, 1);
                  return d.toLocaleDateString('fa-IR', { year: 'numeric', month: 'long' });
                })()}
                {' '}
                <span className="mono" style={{color:'var(--text-3)',fontSize:11}}>({targetForm.year}-{String(targetForm.month).padStart(2,'0')})</span>
              </div>
            )}
            {/* مبلغ */}
            <div>
              <label className="label">مبلغ هدف (تومان)</label>
              <input className="input" type="text" value={targetForm.amount}
                onChange={e=>setTargetForm(f=>({...f,amount:e.target.value}))}
                placeholder="مثلاً: 50000000"
                autoFocus/>
              {targetForm.amount&&!isNaN(parseInt(String(targetForm.amount).replace(/[,\s]/g,'')))&&(
                <div style={{fontSize:11,color:'#FB923C',marginTop:5}}>{fmtMon(parseInt(String(targetForm.amount).replace(/[,\s]/g,'')))}</div>
              )}
            </div>
          </div>
        </Modal>
      )}

      {/* ─── SlidePanel پرونده ─── */}
      <SlidePanel open={!!panel} onClose={()=>setPanel(null)} width={500}>
        {panel && (() => {
          const s = panel.seller;
          const statusKeys = Object.keys(s.byStatus||{}).filter(k=>STATUS_MAP[k]&&s.byStatus[k]>0);
          return (
            <div style={{display:'flex',flexDirection:'column',height:'100%'}}>
              {/* هدر */}
              <div style={{padding:'20px 24px 16px',borderBottom:'1px solid rgba(255,255,255,0.07)'}}>
                <div style={{display:'flex',alignItems:'center',gap:12,marginBottom:14}}>
                  <div style={{width:42,height:42,borderRadius:11,background:'rgba(52,211,153,0.15)',color:'#34D399',display:'grid',placeItems:'center',fontSize:15,fontWeight:700}}>
                    {(s.name||'?').slice(0,2)}
                  </div>
                  <div style={{flex:1}}>
                    <div style={{fontSize:16,fontWeight:700,color:'var(--text-1)'}}>{s.name}</div>
                    <div className="mono" style={{fontSize:11,color:'var(--text-3)'}}>{s.login_username||'—'}</div>
                  </div>
                  <ScoreBadge score={s.score}/>
                  <button className="icon-btn" onClick={()=>{setTargetModal({seller:s});setTargetForm({year:parseInt(CUR_PERIOD.slice(0,4)),month:parseInt(CUR_PERIOD.slice(5,7)),amount:s.target?String(s.target):''});}} title="تعریف هدف ماهانه" style={{width:30,height:30}}>
                    <Icon name="target" size={13}/>
                  </button>
                </div>
                {/* متریک‌ها */}
                <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:8,marginBottom:12}}>
                  {[
                    {label:'لیدهای فعال', value:fa(s.activeCnt),           color:'#60A5FA'},
                    {label:'خریداران',     value:fa(s.buyers),              color:'#22c55e'},
                    {label:'نرخ تبدیل',   value:fa(s.conversionRate)+'٪',  color:s.conversionRate>20?'#22c55e':s.conversionRate>10?'#FB923C':'#F87171'},
                  ].map(m=>(
                    <div key={m.label} style={{padding:'10px 12px',borderRadius:8,background:'rgba(255,255,255,0.04)',textAlign:'center'}}>
                      <div style={{fontSize:18,fontWeight:800,color:m.color}}>{m.value}</div>
                      <div style={{fontSize:10,color:'var(--text-3)',marginTop:2}}>{m.label}</div>
                    </div>
                  ))}
                </div>
                {/* درآمد */}
                {s.totalRevenue > 0 && (
                  <div style={{padding:'10px 14px',borderRadius:8,background:'rgba(251,146,60,0.08)',border:'1px solid rgba(251,146,60,0.2)',display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:10}}>
                    <span style={{fontSize:12,color:'var(--text-3)'}}>درآمد کل</span>
                    <span style={{fontSize:15,fontWeight:800,color:'#FB923C'}}>{fmtMon(s.totalRevenue)}</span>
                  </div>
                )}
                {/* هدف ماه */}
                <div style={{display:'flex',alignItems:'center',gap:8}}>
                  <div style={{flex:1}}>
                    {s.target ? (
                      <>
                        <div style={{display:'flex',justifyContent:'space-between',fontSize:11,color:'var(--text-3)',marginBottom:5}}>
                          <span>هدف ماه جاری</span>
                          <span>{fmtMon(s.totalRevenue)} از {fmtMon(s.target)}</span>
                        </div>
                        <div style={{height:6,borderRadius:3,background:'rgba(255,255,255,0.1)',overflow:'hidden'}}>
                          <div style={{height:'100%',borderRadius:3,transition:'width .4s',
                            width:Math.min(100,Math.round(s.totalRevenue/s.target*100))+'%',
                            background:s.totalRevenue>=s.target?'#22c55e':'#FB923C',
                          }}/>
                        </div>
                      </>
                    ) : (
                      <div style={{fontSize:11,color:'#475569',fontStyle:'italic'}}>هدف ماهانه تعریف نشده</div>
                    )}
                  </div>
                  <button onClick={()=>{setTargetModal({seller:s});setTargetForm({year:parseInt(CUR_PERIOD.slice(0,4)),month:parseInt(CUR_PERIOD.slice(5,7)),amount:s.target?String(s.target):''});}}
                    style={{padding:'4px 12px',borderRadius:8,fontSize:11,cursor:'pointer',fontFamily:'inherit',fontWeight:600,border:'1px solid rgba(251,146,60,0.3)',background:'rgba(251,146,60,0.1)',color:'#FB923C',flexShrink:0}}>
                    {s.target?'ویرایش هدف':'+ تعریف هدف'}
                  </button>
                </div>
              </div>

              {/* خریدهای ثبت شده */}
              {buyerLeads.length > 0 && (
                <div style={{padding:'14px 24px',borderBottom:'1px solid rgba(255,255,255,0.06)'}}>
                  <div style={{fontSize:12,fontWeight:700,color:'var(--text-2)',marginBottom:10,display:'flex',alignItems:'center',gap:6}}>
                    <Icon name="shopping-cart" size={13} color="#22c55e"/>
                    فروش‌های ثبت شده ({fa(buyerLeads.length)})
                  </div>
                  <div style={{display:'flex',flexDirection:'column',gap:6}}>
                    {buyerLeads.map(l=>(
                      <div key={l.id} style={{display:'flex',alignItems:'center',gap:10,padding:'8px 12px',borderRadius:8,background:'rgba(34,197,94,0.06)',border:'1px solid rgba(34,197,94,0.15)'}}>
                        <div style={{flex:1,minWidth:0}}>
                          <div style={{fontSize:12,fontWeight:600,color:'var(--text-1)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
                            {cleanName(l.full_name)}
                          </div>
                          <div style={{display:'flex',gap:8,marginTop:2,flexWrap:'wrap'}}>
                            {l.phone&&<span className="mono" style={{fontSize:10,color:'var(--text-3)'}}>{l.phone}</span>}
                            {l.product_name&&(
                              <span style={{fontSize:10,padding:'1px 7px',borderRadius:10,fontWeight:600,
                                background:(l.product_color||'#6366F1')+'22',color:l.product_color||'#818cf8'}}>
                                {l.product_name}
                              </span>
                            )}
                          </div>
                        </div>
                        <div style={{textAlign:'left',flexShrink:0}}>
                          {l.sale_amount > 0 ? (
                            <div style={{fontSize:13,fontWeight:800,color:'#22c55e'}}>{fmtMon(l.sale_amount)}</div>
                          ) : (
                            <div style={{fontSize:11,color:'#475569',fontStyle:'italic'}}>قیمت ثبت نشده</div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* توزیع وضعیت */}
              <div style={{padding:'14px 24px',borderBottom:'1px solid rgba(255,255,255,0.06)'}}>
                <div style={{fontSize:12,fontWeight:700,color:'var(--text-2)',marginBottom:10}}>توزیع لیدها</div>
                <StatusBreakdown byStatus={s.byStatus||{}} totalLeads={s.totalLeads}/>
              </div>

              {/* فیلتر وضعیت */}
              <div style={{padding:'10px 24px 8px',borderBottom:'1px solid rgba(255,255,255,0.05)'}}>
                <div style={{display:'flex',gap:6,flexWrap:'wrap'}}>
                  <button onClick={()=>setLStatus('all')} style={{padding:'3px 10px',borderRadius:20,fontSize:11,cursor:'pointer',fontFamily:'inherit',border:'none',background:lStatus==='all'?'rgba(99,102,241,0.25)':'rgba(255,255,255,0.05)',color:lStatus==='all'?'#818cf8':'var(--text-3)'}}>
                    همه ({fa(leads.length)})
                  </button>
                  {statusKeys.map(k=>(
                    <button key={k} onClick={()=>setLStatus(k)} style={{padding:'3px 10px',borderRadius:20,fontSize:11,cursor:'pointer',fontFamily:'inherit',border:'none',
                      background:lStatus===k?(STATUS_MAP[k].color+'22'):'rgba(255,255,255,0.05)',
                      color:lStatus===k?STATUS_MAP[k].color:'var(--text-3)',
                    }}>
                      {STATUS_MAP[k].label} ({fa(s.byStatus[k])})
                    </button>
                  ))}
                </div>
              </div>

              {/* لیست لیدها */}
              <div style={{flex:1,overflowY:'auto'}}>
                {lLoad ? (
                  <div style={{padding:24,textAlign:'center',color:'var(--text-3)'}}><span className="spinner"/></div>
                ) : filteredLeads.length === 0 ? (
                  <div style={{padding:32,textAlign:'center',color:'var(--text-3)',fontSize:12}}>
                    <Icon name="inbox" size={24}/><br/>لیدی یافت نشد
                  </div>
                ) : filteredLeads.map(l => {
                  const st = STATUS_MAP[l.status] || { label: l.status, color: '#94a3b8' };
                  return (
                    <div key={l.id} style={{padding:'10px 24px',borderBottom:'1px solid rgba(255,255,255,0.04)',display:'flex',alignItems:'center',gap:12}}>
                      <div style={{width:6,height:6,borderRadius:'50%',flexShrink:0,background:st.color}}/>
                      <div style={{flex:1,minWidth:0}}>
                        <div style={{fontSize:12,fontWeight:600,color:'var(--text-1)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
                          {cleanName(l.full_name)}
                        </div>
                        <div style={{display:'flex',gap:8,marginTop:2,flexWrap:'wrap',alignItems:'center'}}>
                          {l.phone&&<span className="mono" style={{fontSize:10,color:'var(--text-3)'}}>{l.phone}</span>}
                          {l.product_name&&(
                            <span style={{fontSize:10,padding:'1px 7px',borderRadius:10,fontWeight:600,
                              background:(l.product_color||'#6366F1')+'22',color:l.product_color||'#818cf8'}}>
                              {l.product_name}
                            </span>
                          )}
                        </div>
                      </div>
                      <div style={{textAlign:'left',flexShrink:0}}>
                        <span style={{fontSize:11,padding:'2px 8px',borderRadius:12,background:st.color+'18',color:st.color,display:'block',marginBottom:2}}>{st.label}</span>
                        {l.sale_amount>0&&<span style={{fontSize:11,color:'#22c55e',fontWeight:700}}>{fmtMon(l.sale_amount)}</span>}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })()}
      </SlidePanel>
    </div>
  );
};

// ─── پنل ادمین نشان‌ها ────────────────────────────────────────
const BADGE_DEFS_ADMIN = [
  { key: 'record_breaker',  title: 'رکوردشکن',       icon: '🏆', color: '#F59E0B' },
  { key: 'month_top',       title: 'نفر اول ماه',     icon: '👑', color: '#EAB308' },
  { key: 'premium_sale',    title: 'فروش گران‌قیمت',  icon: '💎', color: '#8B5CF6' },
  { key: 'high_avg',        title: 'میانگین بالا',     icon: '📈', color: '#10B981' },
  { key: 'high_conv',       title: 'نرخ تبدیل بالا',  icon: '🎯', color: '#3B82F6' },
  { key: 'cheap_lead',      title: 'لید گران‌خرج',     icon: '🧲', color: '#06B6D4' },
  { key: 'target_bust',     title: 'رد کردن تارگت',   icon: '🚀', color: '#F97316' },
  { key: 'stable_3m',       title: 'ثبات ۳ ماهه',      icon: '📅', color: '#6366F1' },
  { key: 'puzzle_complete', title: 'کامل‌کننده پازل', icon: '🧩', color: '#EC4899' },
];

const BadgesAdminTab = ({ headers, toast }) => {
  const [sellers, setSellers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [saving,  setSaving]  = React.useState(null);

  const load = () => {
    setLoading(true);
    fetch('/api/seller/all-badges', { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setSellers(d.data.sellers); setLoading(false); })
      .catch(() => setLoading(false));
  };

  React.useEffect(load, []);

  const toggle = async (sellerId, key, isUnlocked) => {
    setSaving(sellerId + key);
    const method = isUnlocked ? 'DELETE' : 'POST';
    const r = await fetch(`/api/seller/${sellerId}/badges/${key}`, { method, headers });
    const d = await r.json();
    if (d.success) {
      toast?.(isUnlocked ? '🔒 نشان بسته شد' : '✅ نشان باز شد', 'success');
      await load();
    }
    setSaving(null);
  };

  if (loading) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200, color: 'var(--text-3)' }}>
      <span className="spinner" />
    </div>
  );

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 20, display: 'flex', alignItems: 'center', gap: 10 }}>
        <span style={{ fontSize: 18 }}>🏅</span>
        <span style={{ fontSize: 15, fontWeight: 700, color: 'var(--text-1)' }}>مدیریت نشان‌های فروشندگان</span>
        <span style={{ fontSize: 11, color: 'var(--text-3)' }}>— روی هر نشان کلیک کن تا باز یا بسته بشه</span>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {sellers.map(s => {
          const unlockedSet = new Set(s.badges.map(b => b.key));
          const pct = Math.round(unlockedSet.size / BADGE_DEFS_ADMIN.length * 100);
          return (
            <div key={s.id} style={{
              background: 'rgba(255,255,255,.03)', border: '1px solid rgba(255,255,255,.07)',
              borderRadius: 14, padding: '14px 18px',
            }}>
              {/* ردیف نام + progress */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
                <div style={{
                  width: 34, height: 34, borderRadius: '50%',
                  background: 'rgba(99,102,241,.15)', color: '#818CF8',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 13, fontWeight: 700,
                }}>
                  {(s.name || '؟').slice(0, 2)}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-1)', marginBottom: 4 }}>{s.name}</div>
                  <div style={{ height: 4, background: 'rgba(255,255,255,.06)', borderRadius: 99, overflow: 'hidden' }}>
                    <div style={{
                      height: '100%', borderRadius: 99, background: '#22C55E',
                      width: pct + '%', transition: 'width .4s',
                    }} />
                  </div>
                </div>
                <div style={{ fontSize: 12, color: 'var(--text-3)', minWidth: 48, textAlign: 'left' }}>
                  {unlockedSet.size}/{BADGE_DEFS_ADMIN.length}
                </div>
              </div>

              {/* نشان‌ها */}
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
                {BADGE_DEFS_ADMIN.map(b => {
                  const active = unlockedSet.has(b.key);
                  const isSaving = saving === (s.id + b.key);
                  return (
                    <button key={b.key}
                      onClick={() => !saving && toggle(s.id, b.key, active)}
                      title={b.title}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 5,
                        padding: '4px 10px', borderRadius: 999, cursor: saving ? 'wait' : 'pointer',
                        fontFamily: 'inherit', fontSize: 11, fontWeight: active ? 700 : 400,
                        background: active ? b.color + '18' : 'rgba(255,255,255,.04)',
                        border: `1.5px solid ${active ? b.color + '66' : 'rgba(255,255,255,.08)'}`,
                        color: active ? b.color : 'rgba(255,255,255,.3)',
                        transition: 'all .15s', opacity: isSaving ? 0.5 : 1,
                      }}>
                      <span style={{ filter: active ? 'none' : 'grayscale(1) opacity(.4)', fontSize: 13 }}>{b.icon}</span>
                      {b.title}
                      {active && <span style={{ fontSize: 9 }}>✓</span>}
                    </button>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

window.Sellers = Sellers;
