// ─── هشدار لیدهای بی‌تماس ────────────────────────────────────────────────────
const DistAgingPanel = ({ headers }) => {
  const { useState, useEffect } = React;
  const [data,    setData]    = useState(null);
  const [open,    setOpen]    = useState(false);

  useEffect(() => {
    fetch('/api/distrules/aging-alerts', { headers }).then(r => r.json()).then(d => {
      if (d.success) setData(d.data);
    });
  }, []);

  if (!data || data.leads.length === 0) return null;

  return (
    <div style={{ borderRadius: 10, border: '1px solid rgba(239,68,68,0.3)', background: 'rgba(239,68,68,0.06)', overflow: 'hidden' }}>
      <button onClick={() => setOpen(p => !p)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'right' }}>
        <span style={{ fontSize: 16 }}>⏰</span>
        <span style={{ fontSize: 13, fontWeight: 700, color: '#f87171', flex: 1 }}>
          {data.leads.length} لید بدون تماس بعد از {data.threshold_hours} ساعت
        </span>
        <span style={{ fontSize: 11, color: '#64748b' }}>{open ? '▲' : '▼'}</span>
      </button>
      {open && (
        <div style={{ padding: '0 14px 12px', display: 'flex', flexDirection: 'column', gap: 4 }}>
          {data.leads.map(l => (
            <div key={l.id} style={{ display: 'grid', gridTemplateColumns: '1fr 120px 80px', gap: 8, padding: '6px 8px', borderRadius: 7, background: 'rgba(255,255,255,0.03)', fontSize: 11 }}>
              <div>
                <span style={{ color: '#e2e8f0', fontWeight: 600 }}>{l.full_name || l.username || l.phone}</span>
                <span style={{ color: '#64748b', marginRight: 8 }}>score: {l.score || '–'}</span>
              </div>
              <div style={{ color: '#94a3b8' }}>{l.seller_name}</div>
              <div style={{ color: '#f87171', textAlign: 'left', direction: 'ltr' }}>{l.hours_waiting}h بی‌تماس</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// ─── مسیریابی هوشمند ─────────────────────────────────────────────────────────
const DIST_ROUTE_FIELDS = [
  { v: 'score',     l: 'امتیاز',    ops: ['gte','lte','gt','lt'] },
  { v: 'status',    l: 'وضعیت',    ops: ['eq','neq'] },
  { v: 'platform',  l: 'پلتفرم',   ops: ['eq','neq'] },
  { v: 'source',    l: 'منبع',      ops: ['eq','neq'] },
  { v: 'lead_type', l: 'نوع لید',  ops: ['eq','neq'] },
  { v: 'tag',       l: 'دارای تگ', ops: ['has','nhas'] },
];
const DIST_ROUTE_OPS = { gte:'≥', lte:'≤', gt:'>', lt:'<', eq:'=', neq:'≠', has:'دارد', nhas:'ندارد' };
const DIST_FILTER_TYPES = [
  { v: 'all',       l: 'همه فروشندگان واجد شرایط' },
  { v: 'min_score', l: 'فروشندگان با امتیاز ≥' },
  { v: 'specific',  l: 'فروشندگان خاص' },
];

const DistRoutingModal = ({ rule, sellers, headers, onClose, onSaved }) => {
  const { useState } = React;
  const initFilter = rule ? JSON.parse(rule.seller_filter || '{"type":"all"}') : { type: 'all', value: 50, ids: [] };
  const initConds  = rule ? JSON.parse(rule.conditions  || '[]') : [{ field: 'score', op: 'gte', value: '7' }];

  const [name,     setName]     = useState(rule?.name || '');
  const [desc,     setDesc]     = useState(rule?.description || '');
  const [priority, setPriority] = useState(rule?.priority ?? 0);
  const [conds,    setConds]    = useState(initConds);
  const [filter,   setFilter]   = useState(initFilter);
  const [saving,   setSaving]   = useState(false);

  const addCond  = () => setConds(p => [...p, { field: 'score', op: 'gte', value: '7' }]);
  const remCond  = i  => setConds(p => p.filter((_, j) => j !== i));
  const setCond  = (i, k, v) => setConds(p => p.map((c, j) => j === i ? { ...c, [k]: v } : c));

  const save = () => {
    if (!name.trim()) return;
    setSaving(true);
    const body = { name, description: desc, priority: parseInt(priority) || 0, conditions: conds, seller_filter: filter };
    const url    = rule ? `/api/distrules/routing-rules/${rule.id}` : '/api/distrules/routing-rules';
    const method = rule ? 'PUT' : 'POST';
    fetch(url, { method, headers, body: JSON.stringify(body) }).then(r => r.json()).then(d => {
      setSaving(false);
      if (d.success) onSaved();
    }).catch(() => setSaving(false));
  };

  const inp = { padding: '6px 10px', borderRadius: 7, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)', color: '#e2e8f0', fontSize: 12, outline: 'none' };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
      onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{ background: '#111118', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 14, padding: 24, width: 460, maxHeight: '85vh', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: '#e2e8f0' }}>{rule ? 'ویرایش قانون مسیریابی' : 'قانون مسیریابی جدید'}</div>

        <div style={{ display: 'flex', gap: 8 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, color: '#64748b', marginBottom: 4 }}>نام</div>
            <input value={name} onChange={e => setName(e.target.value)} style={{ ...inp, width: '100%' }} placeholder="مثلاً: لیدهای داغ — ارشد" />
          </div>
          <div style={{ width: 70 }}>
            <div style={{ fontSize: 11, color: '#64748b', marginBottom: 4 }}>اولویت</div>
            <input type="number" value={priority} onChange={e => setPriority(e.target.value)} style={{ ...inp, width: '100%', textAlign: 'center' }} />
          </div>
        </div>

        <div>
          <div style={{ fontSize: 11, color: '#64748b', marginBottom: 4 }}>توضیح (اختیاری)</div>
          <input value={desc} onChange={e => setDesc(e.target.value)} style={{ ...inp, width: '100%' }} placeholder="توضیح کوتاه" />
        </div>

        <div>
          <div style={{ fontSize: 11, color: '#818cf8', fontWeight: 600, marginBottom: 8 }}>شرط‌های تطبیق لید</div>
          {conds.map((c, i) => (
            <div key={i} style={{ display: 'flex', gap: 6, marginBottom: 6, alignItems: 'center' }}>
              <select value={c.field} onChange={e => setCond(i, 'field', e.target.value)} style={{ ...inp, flex: 1 }}>
                {DIST_ROUTE_FIELDS.map(f => <option key={f.v} value={f.v}>{f.l}</option>)}
              </select>
              <select value={c.op} onChange={e => setCond(i, 'op', e.target.value)} style={{ ...inp, width: 70 }}>
                {(DIST_ROUTE_FIELDS.find(f => f.v === c.field)?.ops || ['eq']).map(op => <option key={op} value={op}>{DIST_ROUTE_OPS[op]}</option>)}
              </select>
              <input value={c.value} onChange={e => setCond(i, 'value', e.target.value)} style={{ ...inp, width: 90 }} placeholder="مقدار" />
              <button onClick={() => remCond(i)} style={{ padding: '4px 8px', borderRadius: 6, border: 'none', background: 'rgba(239,68,68,0.15)', color: '#f87171', cursor: 'pointer', fontSize: 12 }}>✕</button>
            </div>
          ))}
          <button onClick={addCond} style={{ fontSize: 11, color: '#818cf8', background: 'none', border: '1px dashed rgba(99,102,241,0.3)', borderRadius: 6, padding: '4px 12px', cursor: 'pointer' }}>+ شرط</button>
        </div>

        <div>
          <div style={{ fontSize: 11, color: '#818cf8', fontWeight: 600, marginBottom: 8 }}>فیلتر فروشنده</div>
          {DIST_FILTER_TYPES.map(ft => (
            <label key={ft.v} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, cursor: 'pointer' }}>
              <input type="radio" checked={filter.type === ft.v} onChange={() => setFilter(p => ({ ...p, type: ft.v }))} />
              <span style={{ fontSize: 12, color: '#e2e8f0' }}>{ft.l}</span>
              {ft.v === 'min_score' && filter.type === 'min_score' && (
                <input type="number" value={filter.value || 50} onChange={e => setFilter(p => ({ ...p, value: parseInt(e.target.value) }))} style={{ ...inp, width: 60, marginRight: 4 }} />
              )}
              {ft.v === 'specific' && filter.type === 'specific' && (
                <select multiple value={filter.ids || []} onChange={e => setFilter(p => ({ ...p, ids: Array.from(e.target.selectedOptions, o => o.value) }))} style={{ ...inp, height: 80, marginRight: 4 }}>
                  {sellers.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                </select>
              )}
            </label>
          ))}
        </div>

        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button onClick={onClose} style={{ padding: '8px 16px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,0.1)', background: 'transparent', color: '#64748b' }}>انصراف</button>
          <button onClick={save} disabled={saving || !name.trim()} style={{ padding: '8px 20px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: '#6366F1', color: '#fff', fontWeight: 600 }}>
            {saving ? 'ذخیره...' : 'ذخیره'}
          </button>
        </div>
      </div>
    </div>
  );
};

const DistRoutingSection = ({ headers }) => {
  const { useState, useEffect } = React;
  const [rules,   setRules]   = useState([]);
  const [sellers, setSellers] = useState([]);
  const [modal,   setModal]   = useState(null); // null | 'new' | rule object

  const load = () => {
    fetch('/api/distrules/routing-rules', { headers }).then(r => r.json()).then(d => { if (d.success) setRules(d.data.rules); });
    fetch('/api/pool/sellers', { headers }).then(r => r.json()).then(d => { if (d.success) setSellers(d.data.sellers || []); }).catch(() => {});
  };
  useEffect(load, []);

  const toggleActive = rule => {
    fetch(`/api/distrules/routing-rules/${rule.id}`, { method: 'PUT', headers, body: JSON.stringify({ is_active: rule.is_active ? 0 : 1 }) })
      .then(r => r.json()).then(d => { if (d.success) load(); });
  };

  const del = id => {
    if (!confirm('حذف شود؟')) return;
    fetch(`/api/distrules/routing-rules/${id}`, { method: 'DELETE', headers }).then(r => r.json()).then(d => { if (d.success) load(); });
  };

  const filterLabel = sf => {
    try {
      const f = typeof sf === 'string' ? JSON.parse(sf) : sf;
      if (f.type === 'all') return 'همه';
      if (f.type === 'min_score') return `امتیاز ≥ ${f.value}`;
      if (f.type === 'specific') return `${(f.ids || []).length} فروشنده`;
    } catch {}
    return '–';
  };

  const condLabel = conds => {
    try {
      const cs = typeof conds === 'string' ? JSON.parse(conds) : conds;
      return cs.map(c => `${DIST_ROUTE_FIELDS.find(f => f.v === c.field)?.l || c.field} ${DIST_ROUTE_OPS[c.op] || c.op} ${c.value}`).join(' و ');
    } catch { return '–'; }
  };

  return (
    <div>
      <div style={{ fontSize: 12, fontWeight: 700, color: '#818CF8', marginBottom: 8, padding: '6px 0', borderBottom: '1px solid rgba(99,102,241,0.2)', display: 'flex', alignItems: 'center', gap: 8 }}>
        {'🗺️ مسیریابی هوشمند توزیع'}
        <span style={{ fontSize: 10, color: '#374151', fontWeight: 400 }}>{'— لیدهای خاص به فروشندگان مناسب می‌رسن'}</span>
        <button onClick={() => setModal('new')} style={{ marginRight: 'auto', padding: '3px 12px', borderRadius: 6, fontSize: 11, cursor: 'pointer', border: 'none', background: '#6366F1', color: '#fff', fontWeight: 600 }}>+ قانون</button>
      </div>
      {rules.length === 0 ? (
        <div style={{ padding: '16px 0', textAlign: 'center', color: '#374151', fontSize: 11 }}>هنوز قانون مسیریابی تعریف نشده</div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {rules.map(rule => (
            <div key={rule.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 9, background: 'rgba(255,255,255,0.03)', border: `1px solid ${rule.is_active ? 'rgba(99,102,241,0.2)' : 'rgba(255,255,255,0.06)'}`, opacity: rule.is_active ? 1 : 0.5 }}>
              <button onClick={() => toggleActive(rule)} style={{ width: 30, height: 17, borderRadius: 9, padding: 0, border: 'none', cursor: 'pointer', flexShrink: 0, background: rule.is_active ? 'rgba(52,211,153,0.3)' : 'rgba(107,114,128,0.2)', position: 'relative' }}>
                <div style={{ width: 11, height: 11, borderRadius: '50%', position: 'absolute', top: 3, left: rule.is_active ? 16 : 3, background: rule.is_active ? '#34D399' : '#6B7280', transition: 'left 0.2s' }} />
              </button>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: '#e2e8f0', display: 'flex', alignItems: 'center', gap: 6 }}>
                  {rule.name}
                  <span style={{ fontSize: 10, color: '#475569', fontWeight: 400 }}>اولویت {rule.priority}</span>
                </div>
                <div style={{ fontSize: 10, color: '#64748b', marginTop: 3 }}>
                  اگر: <span style={{ color: '#94a3b8' }}>{condLabel(rule.conditions)}</span>
                  {' → '}
                  <span style={{ color: '#818cf8' }}>{filterLabel(rule.seller_filter)}</span>
                </div>
              </div>
              <button onClick={() => setModal(rule)} style={{ padding: '4px 10px', borderRadius: 7, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(99,102,241,0.25)', background: 'rgba(99,102,241,0.08)', color: '#818CF8', flexShrink: 0 }}>ویرایش</button>
              <button onClick={() => del(rule.id)} style={{ padding: '4px 10px', borderRadius: 7, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(239,68,68,0.2)', background: 'rgba(239,68,68,0.07)', color: '#f87171', flexShrink: 0 }}>حذف</button>
            </div>
          ))}
        </div>
      )}
      {modal && (
        <DistRoutingModal
          rule={modal === 'new' ? null : modal}
          sellers={sellers}
          headers={headers}
          onClose={() => setModal(null)}
          onSaved={() => { setModal(null); load(); }}
        />
      )}
    </div>
  );
};

// ─── تب قوانین توزیع ────────────────────────────────────────────────────────

// ── سوئیچ حالت توزیع ──────────────────────────────────────
const DistModePanel = ({ headers }) => {
  const { useState, useEffect } = React;

  const [mode,    setMode]    = useState('auto');
  const [hours,   setHours]   = useState(4);
  const [editing, setEditing] = useState(false);
  const [saving,  setSaving]  = useState(false);
  const [draft,   setDraft]   = useState(4);

  useEffect(() => {
    fetch('/api/distrules/mode', { headers }).then(r => r.json()).then(d => {
      if (d.success) { setMode(d.data.mode); setHours(d.data.fallback_hours); setDraft(d.data.fallback_hours); }
    });
  }, []);

  const save = (newMode, newHours) => {
    setSaving(true);
    fetch('/api/distrules/mode', { method:'PUT', headers, body: JSON.stringify({ mode: newMode, fallback_hours: newHours }) })
      .then(r => r.json()).then(d => {
        if (d.success) { setMode(d.data.mode); setHours(d.data.fallback_hours); setDraft(d.data.fallback_hours); setEditing(false); }
        setSaving(false);
      }).catch(() => setSaving(false));
  };

  const toggleMode = () => save(mode === 'auto' ? 'manual' : 'auto', hours);

  return (
    <div style={{ padding:'14px 16px', borderRadius:10, background: mode==='manual' ? 'rgba(251,146,60,0.07)' : 'rgba(99,102,241,0.07)', border:`1px solid ${mode==='manual' ? 'rgba(251,146,60,0.25)' : 'rgba(99,102,241,0.2)'}` }}>
      <div style={{ display:'flex', alignItems:'center', gap:14, flexWrap:'wrap' }}>
        {/* سوئیچ */}
        <div style={{ display:'flex', alignItems:'center', gap:10, flex:1 }}>
          <button onClick={toggleMode} disabled={saving} style={{
            width:44, height:24, borderRadius:12, padding:0, border:'none', cursor:'pointer', flexShrink:0, position:'relative',
            background: mode==='auto' ? '#6366F1' : 'rgba(251,146,60,0.5)', transition:'background 0.2s',
          }}>
            <div style={{ width:18, height:18, borderRadius:'50%', position:'absolute', top:3, left: mode==='auto' ? 22 : 4, background:'#fff', transition:'left 0.2s', boxShadow:'0 1px 3px rgba(0,0,0,0.3)' }} />
          </button>
          <div>
            <div style={{ fontSize:13, fontWeight:700, color: mode==='auto' ? '#818CF8' : '#FB923C' }}>
              {mode==='auto' ? '🤖 توزیع خودکار' : '👨‍💼 توزیع دستی (مدیر)'}
            </div>
            <div style={{ fontSize:11, color:'#475569', marginTop:2 }}>
              {mode==='auto' ? 'سیستم لیدها را بر اساس امتیاز فروشندگان توزیع می‌کند' : 'لیدهای جدید در صف می‌مانند تا مدیر فروش تخصیص دهد'}
            </div>
          </div>
        </div>

        {/* fallback */}
        <div style={{ display:'flex', alignItems:'center', gap:8, flexShrink:0 }}>
          <span style={{ fontSize:11, color:'#475569' }}>
            {mode==='manual' ? '⏱ توزیع خودکار بعد از' : '⏱ fallback بعد از'}
          </span>
          {editing ? (
            <input type="number" min="0.5" max="168" step="0.5" value={draft}
              onChange={e => setDraft(e.target.value)}
              style={{ width:54, padding:'4px 8px', borderRadius:6, background:'rgba(255,255,255,0.08)', border:'1px solid rgba(255,255,255,0.15)', color:'#e2e8f0', fontSize:12, outline:'none', direction:'ltr', textAlign:'center' }} />
          ) : (
            <span style={{ fontSize:13, fontWeight:700, color:'#38BDF8', cursor:'pointer' }} onClick={() => setEditing(true)}>{hours}</span>
          )}
          <span style={{ fontSize:11, color:'#475569' }}>ساعت</span>
          {editing && (
            <>
              <button onClick={() => save(mode, parseFloat(draft))} disabled={saving} style={{ padding:'3px 10px', borderRadius:6, fontSize:11, cursor:'pointer', border:'none', background:'#6366F1', color:'#fff', fontWeight:600 }}>ذخیره</button>
              <button onClick={() => { setEditing(false); setDraft(hours); }} style={{ padding:'3px 8px', borderRadius:6, fontSize:11, cursor:'pointer', border:'1px solid rgba(255,255,255,0.12)', background:'transparent', color:'#64748b' }}>انصراف</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
};


const RULES_EVAL_GRP        = { weights:'⚖️ وزن معیارها', params:'🔧 پارامترها' };
const RULES_SUSP_METRIC_LBL = { score:'امتیاز کل', expire_rate:'نرخ انقضا', contact_rate:'نرخ تماس' };
const RULES_SUSP_LVL_COLOR  = { warning:'#F59E0B', restricted:'#FB923C', suspended:'#F87171' };
const RULES_SUSP_LVL_LABEL  = { warning:'⚠️ کارت زرد', restricted:'🔶 محدودیت', suspended:'🔴 توقف' };

const RulesDistTab = ({ opsGrouped, evalGrouped, evalRules, suspRules, headers, load, toast, setEditing }) => {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <DistAgingPanel headers={headers} />
      <DistModePanel />

      {/* ─── ① قوانین عمومی سیستم ────────────────────── */}
      {(() => {
        const genRules = [
          ...(opsGrouped['lead_lifecycle'] || []),
          ...(opsGrouped['access'] || []),
        ];
        if (!genRules.length) return null;
        return (
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, color: '#818CF8', marginBottom: 8, padding: '6px 0', borderBottom: '1px solid rgba(99,102,241,0.2)', display:'flex', alignItems:'center', gap:8 }}>
              {'⚙️ قوانین عمومی سیستم'}
              <span style={{ fontSize:10, color:'#374151', fontWeight:400 }}>{'— روی همه فروشندگان اعمال می‌شود'}</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {genRules.map(r => <RulesRow key={r.id} rule={r} type="ops" headers={headers} load={load} toast={toast} setEditing={setEditing} />)}
            </div>
          </div>
        );
      })()}

      {/* ─── ② محدودیت‌های هر فروشنده ───────────────── */}
      {(() => {
        const perSellerRules = [
          ...(opsGrouped['seller'] || []),
          ...(opsGrouped['freeze'] || []),
        ];
        if (!perSellerRules.length) return null;
        return (
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, color: '#818CF8', marginBottom: 4, padding: '6px 0', borderBottom: '1px solid rgba(99,102,241,0.2)', display:'flex', alignItems:'center', gap:8 }}>
              {'👤 محدودیت‌های هر فروشنده'}
              <span style={{ fontSize:10, color:'#374151', fontWeight:400 }}>{'— پیش‌فرض‌ها (قابل تغییر به ازای هر فروشنده)'}</span>
            </div>
            <div style={{ padding: '7px 12px', borderRadius: 7, background: 'rgba(56,189,248,0.05)', border: '1px solid rgba(56,189,248,0.12)', fontSize: 11, color: '#64748b', marginBottom: 6 }}>
              {'❄️ لید فریزشده از استخر توزیع خارج می‌شود و در اختیار فروشندگان دیگر قرار نمی‌گیرد تا پایان مدت فریز.'}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {perSellerRules.map(r => <RulesRow key={r.id} rule={r} type="ops" headers={headers} load={load} toast={toast} setEditing={setEditing} />)}
            </div>
          </div>
        );
      })()}

      {/* ─── ③ امتیاز و توزیع ────────────────────────── */}
      {(() => {
        const wRules = evalRules.filter(r => r.group_name === 'weights' && r.enabled);
        const sum    = wRules.reduce((s, r) => s + parseFloat(r.value), 0);
        return (
          <React.Fragment>
            {wRules.length > 0 && Math.abs(sum - 100) > 0.1 && (
              <div style={{ display:'flex', alignItems:'center', gap:10, padding: '8px 14px', borderRadius: 8, background: 'rgba(251,146,60,0.1)', border: '1px solid rgba(251,146,60,0.25)' }}>
                <span style={{ fontSize: 11, color: '#FB923C', flex: 1 }}>{'⚠️ جمع وزن‌های فعال = '}{Math.round(sum)}{'٪ (باید ۱۰۰٪ باشد)'}</span>
                <button onClick={() => {
                  const factor = 100 / sum;
                  Promise.all(wRules.map(r => {
                    const newVal = Math.round(parseFloat(r.value) * factor);
                    return fetch('/api/distrules/evaluation/rules/' + r.rule_key, { method: 'PUT', headers, body: JSON.stringify({ value: String(newVal) }) });
                  })).then(() => { load(); toast('وزن‌ها normalize شدند', 'success'); });
                }} style={{ padding:'4px 12px', borderRadius:7, fontSize:11, cursor:'pointer', border:'none', background:'rgba(251,146,60,0.2)', color:'#FB923C', fontWeight:600, whiteSpace:'nowrap' }}>{'🔧 تنظیم خودکار'}</button>
              </div>
            )}
            {Object.entries(RULES_EVAL_GRP).map(([grp, grpLabel]) => (
              <div key={grp}>
                <div style={{ fontSize: 12, fontWeight: 700, color: '#818CF8', marginBottom: 8, padding: '6px 0', borderBottom: '1px solid rgba(99,102,241,0.2)', display: 'flex', alignItems: 'center', gap: 8 }}>
                  {'📊 '}{grpLabel}
                  {grp === 'weights' && <span style={{ fontSize: 10, color: '#374151', fontWeight: 400 }}>{'— وزن‌های غیرفعال در محاسبه لحاظ نمی‌شوند'}</span>}
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {(evalGrouped[grp] || []).map(r => <RulesRow key={r.rule_key} rule={r} type="eval" headers={headers} load={load} toast={toast} setEditing={setEditing} />)}
                </div>
              </div>
            ))}
          </React.Fragment>
        );
      })()}

      {/* ─── ④ مسیریابی هوشمند ───────────────────────── */}
      <DistRoutingSection headers={headers} />

      {/* ─── ⑤ توقف خودکار فروشنده ───────────────────── */}
      <div>
        <div style={{ fontSize: 12, fontWeight: 700, color: '#818CF8', marginBottom: 8, padding: '6px 0', borderBottom: '1px solid rgba(99,102,241,0.2)' }}>
          {'🚦 توقف خودکار فروشنده'}
        </div>
        <div style={{ padding: '8px 14px', borderRadius: 8, background: 'rgba(245,158,11,0.06)', border: '1px solid rgba(245,158,11,0.15)', fontSize: 11, color: '#94a3b8', marginBottom: 8 }}>
          {'سیستم هر ۱ ساعت بررسی می‌کند. فروشندگان با سابقه امتیاز خوب (میانه بالای ۵۰) یک درجه تخفیف می‌گیرند.'}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {suspRules.length === 0 ? (
            <div style={{ padding: 24, textAlign: 'center', color: '#374151', fontSize: 12 }}>{'هنوز قانون توقف خودکار تعریف نشده'}</div>
          ) : suspRules.map(r => {
            const lColor  = RULES_SUSP_LVL_COLOR[r.level]  || '#94a3b8';
            const lLabel  = RULES_SUSP_LVL_LABEL[r.level]  || r.level;
            const mLabel  = RULES_SUSP_METRIC_LBL[r.metric] || r.metric;
            const opLabel = r.operator === 'lt' ? 'کمتر از' : 'بیشتر از';
            return (
              <div key={r.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', borderRadius: 10, background: 'rgba(255,255,255,0.03)', border: '1px solid ' + (r.is_active ? lColor+'30' : 'rgba(255,255,255,0.07)'), opacity: r.is_active ? 1 : 0.45 }}>
                <button onClick={() => fetch('/api/distrules/suspension-rules/' + r.id, { method: 'PUT', headers, body: JSON.stringify({ is_active: r.is_active ? 0 : 1 }) }).then(d => d.json()).then(d => { if (d.success) load(); else toast('خطا', 'error'); })}
                  style={{ width: 28, height: 16, borderRadius: 8, padding: 0, border: 'none', cursor: 'pointer', flexShrink: 0, background: r.is_active ? 'rgba(52,211,153,0.3)' : 'rgba(107,114,128,0.2)', position: 'relative' }}>
                  <div style={{ width: 10, height: 10, borderRadius: '50%', position: 'absolute', top: 3, left: r.is_active ? 14 : 4, background: r.is_active ? '#34D399' : '#6B7280', transition: 'left 0.2s' }} />
                </button>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: '#e2e8f0' }}>{r.name}</div>
                  <div style={{ fontSize: 11, color: '#475569', marginTop: 3 }}>
                    {'اگر '}<span style={{ color: '#94a3b8' }}>{mLabel}</span>{' فروشنده '}<span style={{ color: '#94a3b8' }}>{opLabel}</span>{' '}
                    <span style={{ color: '#38BDF8', fontWeight: 700 }}>{r.threshold}</span>{' باشد'}{r.description ? ' — ' + r.description : ''}
                  </div>
                  {r.recovery_min_score > 0 && (
                    <div style={{ fontSize: 10, color: '#34d399', marginTop: 4 }}>
                      {'🎯 مسیر بازگشت: رسیدن به امتیاز '}{r.recovery_min_score}
                      {r.recovery_target ? ' — ' + r.recovery_target : ''}
                    </div>
                  )}
                </div>
                <div style={{ textAlign: 'left', flexShrink: 0 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: lColor }}>{lLabel}</div>
                  <div style={{ fontSize: 10, color: '#475569', marginTop: 2 }}>{r.duration}{' روز'}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};
