// ─── تب قوانین تگ — ورودی ────────────────────────────────────────────────────

const STATUS_META = [
  { key:'new',          fa:'جدید',         color:'#6366f1' },
  { key:'follow_up',    fa:'پیگیری',       color:'#f97316' },
  { key:'interested',   fa:'علاقمند',      color:'#10b981' },
  { key:'scheduled',    fa:'وقت گرفته',    color:'#0ea5e9' },
  { key:'consultation', fa:'مشاوره شده',   color:'#38bdf8' },
  { key:'buyer',        fa:'خریدار',       color:'#34d399' },
  { key:'lost',         fa:'از دست رفته',  color:'#ef4444' },
  { key:'cancelled',    fa:'کنسل',         color:'#f59e0b' },
  { key:'bad_number',   fa:'شماره اشتباه', color:'#94a3b8' },
];

const LS_SL = 'smartbot_status_labels';
const loadSL = () => { try { const v = localStorage.getItem(LS_SL); return v ? JSON.parse(v) : {}; } catch(e) { return {}; } };

const StatusLabelsSection = ({ onEditLabel, onEditCond, slOverrides, scRulesMap, onApply, applying }) => {
  const { useState } = React;
  const [open, setOpen] = useState(true);
  return (
    <div style={{ borderRadius:9, border:'1px solid rgba(255,255,255,0.07)', overflow:'hidden' }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'10px 14px', background:'rgba(255,255,255,0.03)' }}>
        <div onClick={() => setOpen(o => !o)} style={{ display:'flex', alignItems:'center', gap:8, cursor:'pointer', userSelect:'none', flex:1 }}>
          <span style={{ fontSize:12, fontWeight:600, color:'#94a3b8' }}>{'🏷️ وضعیت‌ها و قوانین خودکار'}</span>
          <span style={{ fontSize:10, color:'#475569' }}>{'— هر ۶ ساعت اجرا می‌شود'}</span>
          <span style={{ fontSize:11, color:'#475569' }}>{open ? '▲' : '▼'}</span>
        </div>
        <button onClick={onApply} disabled={applying}
          style={{ padding:'5px 14px', borderRadius:8, fontSize:11, cursor:applying?'not-allowed':'pointer', border:'1px solid rgba(99,102,241,0.3)', background: applying ? 'rgba(99,102,241,0.05)' : 'rgba(99,102,241,0.1)', color:'#818CF8', flexShrink:0 }}>
          {applying ? '⏳ در حال اجرا...' : '⚡ اجرا الان'}
        </button>
      </div>
      {open && (
        <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
          {STATUS_META.map((s, i) => {
            const label     = slOverrides[s.key]?.fa    ?? s.fa;
            const color     = slOverrides[s.key]?.color ?? s.color;
            const rule      = scRulesMap[s.key];
            const condCount = (rule?.conditions || []).length;
            const isActive  = rule?.is_active !== 0;
            return (
              <div key={s.key} style={{ display:'flex', alignItems:'center', gap:10, padding:'9px 14px', background: i%2===0 ? 'transparent' : 'rgba(255,255,255,0.012)', borderTop:'1px solid rgba(255,255,255,0.04)', opacity: condCount>0 && !isActive ? 0.5 : 1 }}>
                <div style={{ width:9, height:9, borderRadius:'50%', background:color, flexShrink:0 }} />
                <span style={{ fontSize:12, fontWeight:600, color:color, minWidth:95 }}>{label}</span>
                <span style={{ fontSize:11, color:'#374151', direction:'ltr' }}>{s.key}</span>
                <div style={{ flex:1 }} />
                {condCount > 0 ? (
                  <span style={{ fontSize:10, padding:'2px 9px', borderRadius:10,
                    background: isActive ? 'rgba(52,211,153,0.12)' : 'rgba(107,114,128,0.12)',
                    color:      isActive ? '#34D399'               : '#6b7280',
                    fontWeight:600 }}>
                    {condCount}{' شرط'}{isActive ? ' ✓ فعال' : ' — غیرفعال'}
                  </span>
                ) : (
                  <span style={{ fontSize:10, color:'#374151' }}>{'بدون قانون'}</span>
                )}
                <button onClick={() => onEditCond(s, rule)}
                  style={{ padding:'4px 11px', borderRadius:7, border:'1px solid rgba(52,211,153,0.22)', background:'rgba(52,211,153,0.07)', color:'#34D399', fontSize:11, cursor:'pointer', flexShrink:0 }}>
                  {'⚙️ قانون'}
                </button>
                <button onClick={() => onEditLabel(s)}
                  style={{ padding:'4px 11px', borderRadius:7, border:'1px solid rgba(99,102,241,0.25)', background:'rgba(99,102,241,0.08)', color:'#818CF8', fontSize:11, cursor:'pointer', flexShrink:0 }}>
                  {'✏️ نام'}
                </button>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

// ─── مودال تأیید رمز عبور ────────────────────────────────────
const PasswordConfirmModal = ({ headers, onConfirm, onCancel, toast }) => {
  const { useState } = React;
  const [pw, setPw] = useState('');
  const [checking, setChecking] = useState(false);

  const inp = { padding:'8px 12px', borderRadius:8, border:'1px solid rgba(255,255,255,0.15)', background:'rgba(255,255,255,0.06)', color:'#e2e8f0', fontSize:13, outline:'none', width:'100%', boxSizing:'border-box' };

  const confirm = () => {
    if (!pw) return;
    setChecking(true);
    fetch('/api/auth/verify-password', { method:'POST', headers, body:JSON.stringify({ password:pw }) })
      .then(r => r.json())
      .then(d => {
        setChecking(false);
        if (d.success) onConfirm();
        else toast(d.message || 'رمز اشتباه است', 'error');
      })
      .catch(() => { setChecking(false); toast('خطای شبکه','error'); });
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.85)', zIndex:10000, display:'flex', alignItems:'center', justifyContent:'center' }}
      onClick={e => e.target===e.currentTarget && onCancel()}>
      <div style={{ background:'#111118', border:'1px solid rgba(239,68,68,0.3)', borderRadius:14, padding:28, width:340, display:'flex', flexDirection:'column', gap:16 }}>
        <div style={{ fontSize:14, fontWeight:700, color:'#f87171' }}>{'🔐 تأیید هویت'}</div>
        <div style={{ fontSize:12, color:'#94a3b8', lineHeight:1.7 }}>
          {'این تغییر روی رفتار اصلی سیستم تأثیر می‌گذارد. برای ادامه رمز عبور ادمین را وارد کنید.'}
        </div>
        <input type='password' value={pw} onChange={e => setPw(e.target.value)}
          onKeyDown={e => e.key==='Enter' && confirm()}
          autoFocus placeholder={'رمز عبور'} style={inp} />
        <div style={{ display:'flex', gap:8, justifyContent:'flex-end' }}>
          <button onClick={onCancel} style={{ padding:'7px 16px', borderRadius:8, fontSize:12, cursor:'pointer', border:'1px solid rgba(255,255,255,0.12)', background:'transparent', color:'#64748b' }}>{'انصراف'}</button>
          <button onClick={confirm} disabled={!pw || checking} style={{ padding:'7px 22px', borderRadius:8, fontSize:12, cursor:'pointer', border:'none', background: pw && !checking ? '#ef4444' : 'rgba(239,68,68,0.3)', color:'#fff', fontWeight:600 }}>
            {checking ? '⏳ بررسی...' : '✅ تأیید'}
          </button>
        </div>
      </div>
    </div>
  );
};

const RulesInputTab = ({ headers, load: reloadParent, toast }) => {
  const { useState, useEffect } = React;

  const ALL_FIELDS = [
    { v:'status',      label:'وضعیت',                   type:'enum',   opts:['new','follow_up','interested','scheduled','consultation','buyer','lost','cancelled','bad_number'] },
    { v:'platform',    label:'پلتفرم',                   type:'enum',   opts:['telegram','bale','rubika','manual'] },
    { v:'unit',        label:'یونیت',                   type:'enum',   opts:['pool','sales','market'] },
    { v:'score',       label:'امتیاز',                  type:'number' },
    { v:'lead_type',   label:'نوع لید',                 type:'text'   },
    { v:'source',      label:'منبع',                    type:'text'   },
    { v:'interest',    label:'علاقه‌مندی',               type:'text'   },
    { v:'sale_amount', label:'مبلغ خرید',                type:'number' },
    { v:'seller_id',   label:'فروشنده (ID)',             type:'text'   },
    { v:'product_id',  label:'محصول (ID)',               type:'text'   },
    { v:'phone',       label:'شماره تلفن',               type:'text'   },
    { v:'email',       label:'ایمیل',                   type:'text'   },
    { v:'lost_reason', label:'دلیل از دست دادن',         type:'text'   },
    { v:'notes',       label:'یادداشت',                  type:'text'   },
    { v:'call_count',                    label:'تعداد تماس',                    type:'number' },
    { v:'no_answer_count',               label:'تماس بی‌پاسخ',                  type:'number' },
    { v:'last_call_days',                label:'روز از آخرین تماس',             type:'number' },
    { v:'lead_age_days',                 label:'سن لید (روز)',                  type:'number' },
    { v:'days_since_update',             label:'روز از آخرین تغییر',            type:'number' },
    { v:'days_since_last_status_change', label:'روز از آخرین تغییر وضعیت',     type:'number' },
    { v:'unpaid_installments_count',     label:'اقساط نپرداخته',                type:'number' },
    { v:'overdue_installments_count',    label:'اقساط معوق',                    type:'number' },
    { v:'return_count',                  label:'تعداد برگشت به استخر',           type:'number' },
    { v:'tag',                           label:'دارای تگ',                       type:'tag'    },
  ];

  const LEAD_FIELDS    = ALL_FIELDS.slice(0, 14);
  const DERIVED_FIELDS = ALL_FIELDS.slice(14);

  const OPS_BY_TYPE = {
    number: [
      { v:'eq',  l:'=' }, { v:'neq', l:'≠' },
      { v:'gte', l:'>=' }, { v:'lte', l:'<=' },
      { v:'gt',  l:'>' }, { v:'lt',  l:'<' },
      { v:'empty', l:'خالی' }, { v:'nempty', l:'پر' },
    ],
    text: [
      { v:'eq', l:'برابر' }, { v:'neq', l:'نابرابر' },
      { v:'contains', l:'شامل' }, { v:'ncontains', l:'شامل نباشد' },
      { v:'empty', l:'خالی' }, { v:'nempty', l:'پر' },
    ],
    enum: [
      { v:'eq', l:'برابر' }, { v:'neq', l:'نابرابر' }, { v:'in', l:'در لیست' },
    ],
    tag: [{ v:'has', l:'دارای تگ' }],
  };

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

  // ─── نام/رنگ وضعیت (localStorage) ─────────────────────────
  const [slOverrides, setSlOverrides] = useState(loadSL);
  const [statusLabelEdit, setStatusLabelEdit] = useState(null);

  const openStatusLabel = (s) => {
    const ov = loadSL();
    setStatusLabelEdit({ key:s.key, fa: ov[s.key]?.fa ?? s.fa, color: ov[s.key]?.color ?? s.color });
  };
  const saveStatusLabel = () => {
    const next = { ...loadSL(), [statusLabelEdit.key]: { fa:statusLabelEdit.fa, color:statusLabelEdit.color } };
    localStorage.setItem(LS_SL, JSON.stringify(next));
    setSlOverrides(next);
    setStatusLabelEdit(null);
  };

  // ─── قوانین وضعیت (DB via API) ─────────────────────────────
  const [scRulesMap, setScRulesMap]   = useState({});   // { status_key: ruleObj }
  const [scLoading,  setScLoading]    = useState(true);
  const [statusCondEdit, setStatusCondEdit] = useState(null);
  const [scSaving,   setScSaving]     = useState(false);
  const [scApplying, setScApplying]   = useState(false);

  const loadStatusRules = () => {
    setScLoading(true);
    fetch('/api/pool/status-rules', { headers })
      .then(r => r.json())
      .then(d => {
        if (d.success) {
          const map = {};
          (d.data.rules || []).forEach(r => { map[r.status_key] = r; });
          setScRulesMap(map);
        }
      })
      .finally(() => setScLoading(false));
  };
  useEffect(loadStatusRules, []);

  const openStatusCond = (s, existingRule) => {
    setStatusCondEdit({
      key:        s.key,
      fa:         slOverrides[s.key]?.fa    ?? s.fa,
      color:      slOverrides[s.key]?.color ?? s.color,
      conditions: existingRule?.conditions ? JSON.parse(JSON.stringify(existingRule.conditions)) : [],
      priority:   existingRule?.priority   ?? 0,
      is_active:  existingRule?.is_active  ?? 1,
    });
  };

  const saveStatusCond = () => {
    setScSaving(true);
    fetch(`/api/pool/status-rules/${statusCondEdit.key}`, {
      method:'PUT', headers,
      body: JSON.stringify({
        conditions: statusCondEdit.conditions,
        priority:   statusCondEdit.priority,
        is_active:  statusCondEdit.is_active,
      }),
    })
      .then(r => r.json())
      .then(d => {
        setScSaving(false);
        if (d.success) { toast('قانون ذخیره شد ✅', 'success'); setStatusCondEdit(null); loadStatusRules(); }
        else toast(d.message || 'خطا', 'error');
      })
      .catch(() => { setScSaving(false); toast('خطای شبکه', 'error'); });
  };

  const applyStatusRules = () => {
    setScApplying(true);
    fetch('/api/pool/status-rules/apply', { method:'POST', headers })
      .then(r => r.json())
      .then(d => {
        setScApplying(false);
        if (d.success) toast(`✅ ${d.data?.updated || 0} لید بروز شد (از ${d.data?.leads || 0})`, 'success');
        else toast(d.message || 'خطا', 'error');
      })
      .catch(() => { setScApplying(false); toast('خطای شبکه', 'error'); });
  };

  const setScCond = (i, k, v) => setStatusCondEdit(prev => {
    const conds = [...(prev.conditions || [])];
    conds[i] = { ...conds[i], [k]: v };
    if (k === 'field') {
      const fDef = ALL_FIELDS.find(x => x.v === v) || ALL_FIELDS[0];
      conds[i].op    = (OPS_BY_TYPE[fDef.type] || OPS_BY_TYPE.text)[0].v;
      conds[i].value = '';
    }
    return { ...prev, conditions: conds };
  });
  const addScCond    = () => setStatusCondEdit(p => ({ ...p, conditions:[...(p.conditions||[]), {field:'call_count',op:'eq',value:'0',logic:'AND'}] }));
  const removeScCond = (i) => setStatusCondEdit(p => ({ ...p, conditions:p.conditions.filter((_,idx)=>idx!==i) }));

  // ─── قوانین تگ ربات (بلادرنگ) ───────────────────────────────
  const EMPTY_BOT_RULE = { label:'', pattern:'', tag_name:'', tag_color:'#6366F1', tag_icon:'🏷️', is_active:1, sort_order:0 };

  const [botRules,    setBotRules]    = useState([]);
  const [botLoading,  setBotLoading]  = useState(true);
  const [botForm,     setBotForm]     = useState(null);
  const [botEditId,   setBotEditId]   = useState(null);
  const [botSaving,   setBotSaving]   = useState(false);

  const loadBotRules = () => {
    setBotLoading(true);
    fetch('/api/pool/auto-tag-rules', { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setBotRules(d.data.rules || []); })
      .finally(() => setBotLoading(false));
  };
  useEffect(loadBotRules, []);

  // ─── outcome → status ────────────────────────────────────
  const ALL_STATUSES = ['new','follow_up','interested','scheduled','consultation','buyer','lost','cancelled','bad_number'];
  const OUTCOME_LABELS = { answered:'جواب داد', no_answer:'جواب نداد', call_later:'بعداً زنگ بزن', follow_up:'پیگیری', scheduled:'وقت گرفت', sold:'فروش شد', not_interested:'علاقه ندارد', cancelled:'کنسل کرد', bad_number:'شماره اشتباه', re_request:'درخواست مجدد' };

  const [outcomeRules,   setOutcomeRules]   = useState([]);
  const [outcomeSaving,  setOutcomeSaving]  = useState(null);
  const [pwPending,      setPwPending]      = useState(null); // { action, payload }

  const loadOutcomeRules = () => {
    fetch('/api/pool/outcome-rules', { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setOutcomeRules(d.data.rules || []); });
  };
  useEffect(loadOutcomeRules, []);

  const saveOutcomeRule = (outcome, new_status, label) => {
    setOutcomeSaving(outcome);
    fetch(`/api/pool/outcome-rules/${outcome}`, { method:'PUT', headers, body:JSON.stringify({ new_status, label }) })
      .then(r => r.json())
      .then(d => {
        setOutcomeSaving(null);
        if (d.success) { toast('ذخیره شد ✅','success'); loadOutcomeRules(); }
        else toast(d.message||'خطا','error');
      }).catch(() => { setOutcomeSaving(null); toast('خطای شبکه','error'); });
  };

  // ─── resurrection ─────────────────────────────────────────
  const [resSetting, setResSetting] = useState(null);
  const [resForm,    setResForm]    = useState(null);
  const [resSaving,  setResSaving]  = useState(false);

  const loadResSetting = () => {
    fetch('/api/pool/resurrection-settings', { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setResSetting(d.data.settings); });
  };
  useEffect(loadResSetting, []);

  const saveResForm = () => {
    setResSaving(true);
    fetch('/api/pool/resurrection-settings', { method:'PUT', headers, body:JSON.stringify(resForm) })
      .then(r => r.json())
      .then(d => {
        setResSaving(false);
        if (d.success) { toast('ذخیره شد ✅','success'); setResForm(null); loadResSetting(); }
        else toast(d.message||'خطا','error');
      }).catch(() => { setResSaving(false); toast('خطای شبکه','error'); });
  };

  // هر عملیات حساس از اینجا رد می‌شه
  const withPassword = (action) => setPwPending(() => action);

  const toggleBotRule = (rule) => {
    fetch(`/api/pool/auto-tag-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) loadBotRules(); else toast('خطا','error'); });
  };
  const deleteBotRule = (id) => {
    if (!confirm('این قانون حذف شود؟')) return;
    fetch(`/api/pool/auto-tag-rules/${id}`, { method:'DELETE', headers })
      .then(r => r.json()).then(d => {
        if (d.success) { toast('حذف شد','success'); loadBotRules(); }
        else toast('خطا','error');
      });
  };
  const openBotCreate = () => { setBotForm({ ...EMPTY_BOT_RULE }); setBotEditId(null); };
  const openBotEdit   = (rule) => { setBotForm({ ...rule }); setBotEditId(rule.id); };
  const saveBotForm = () => {
    if (!botForm.label?.trim() || !botForm.pattern?.trim() || !botForm.tag_name?.trim())
      return toast('عنوان، الگو و نام تگ الزامی است','error');
    try { new RegExp(botForm.pattern); } catch { return toast('الگوی regex نامعتبر است','error'); }
    setBotSaving(true);
    const url = botEditId ? `/api/pool/auto-tag-rules/${botEditId}` : '/api/pool/auto-tag-rules';
    fetch(url, { method: botEditId ? 'PUT' : 'POST', headers, body: JSON.stringify(botForm) })
      .then(r => r.json()).then(d => {
        setBotSaving(false);
        if (d.success || d.id) { toast('ذخیره شد ✅','success'); setBotForm(null); loadBotRules(); }
        else toast(d.message || 'خطا','error');
      }).catch(() => { setBotSaving(false); toast('خطای شبکه','error'); });
  };

  // ─── قوانین تگ (batch 6h) ────────────────────────────────────────────
  const EMPTY_RULE = { name:'', description:'', tag_name:'', tag_color:'#6366F1', tag_icon:'🏷️', auto_apply:1, priority:0, conditions:[] };
  const EMPTY_COND = { field:'call_count', op:'eq', value:'0', logic:'AND' };

  const [rules,    setRules]    = useState([]);
  const [loading,  setLoading]  = useState(true);
  const [form,     setForm]     = useState(null);
  const [editId,   setEditId]   = useState(null);
  const [saving,   setSaving]   = useState(false);
  const [applying, setApplying] = useState(false);

  const loadRules = () => {
    setLoading(true);
    fetch('/api/pool/rules', { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setRules(d.data.rules || []); })
      .finally(() => setLoading(false));
  };
  useEffect(loadRules, []);

  const toggleActive = (rule) => {
    fetch(`/api/pool/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) loadRules(); else toast('خطا','error'); });
  };
  const deleteRule = (id) => {
    if (!confirm('این قانون حذف شود؟')) return;
    fetch(`/api/pool/rules/${id}`, { method:'DELETE', headers })
      .then(r => r.json()).then(d => {
        if (d.success) { toast('حذف شد','success'); loadRules(); }
        else toast('خطا','error');
      });
  };
  const openCreate = () => { setForm({ ...EMPTY_RULE, conditions:[{ ...EMPTY_COND }] }); setEditId(null); };
  const openEdit   = (rule) => { setForm({ ...rule, conditions: rule.conditions || [] }); setEditId(rule.id); };
  const saveForm = () => {
    if (!form.name.trim() || !form.tag_name.trim()) { toast('نام قانون و نام تگ الزامی است','error'); return; }
    setSaving(true);
    const url = editId ? `/api/pool/rules/${editId}` : '/api/pool/rules';
    fetch(url, { method: editId ? 'PUT' : 'POST', headers, body: JSON.stringify(form) })
      .then(r => r.json()).then(d => {
        setSaving(false);
        if (d.success || d.id) { toast('ذخیره شد ✅','success'); setForm(null); loadRules(); }
        else toast(d.message || 'خطا','error');
      }).catch(() => { setSaving(false); toast('خطای شبکه','error'); });
  };
  const applyAll = () => {
    setApplying(true);
    fetch('/api/pool/rules/apply-all', { method:'POST', headers })
      .then(r => r.json()).then(d => {
        setApplying(false);
        if (d.success) toast(`✅ ${d.data?.applied || 0} تگ اعمال شد`,'success');
        else toast('خطا','error');
      }).catch(() => { setApplying(false); toast('خطای شبکه','error'); });
  };

  const setC = (k, v) => setForm(f => ({ ...f, [k]:v }));
  const setCond = (i, k, v) => setForm(f => {
    const conds = [...(f.conditions || [])];
    conds[i] = { ...conds[i], [k]:v };
    if (k === 'field') {
      const fDef = ALL_FIELDS.find(x => x.v === v) || ALL_FIELDS[0];
      conds[i].op    = (OPS_BY_TYPE[fDef.type] || OPS_BY_TYPE.text)[0].v;
      conds[i].value = '';
    }
    return { ...f, conditions:conds };
  });
  const addCond    = () => setForm(f => ({ ...f, conditions:[...(f.conditions||[]), { ...EMPTY_COND }] }));
  const removeCond = (i) => setForm(f => ({ ...f, conditions:(f.conditions||[]).filter((_,idx)=>idx!==i) }));

  // ─── سازنده شرط (مشترک) ───────────────────────────────────
  const CondBuilder = ({ conditions, onSetCond, onAdd, onRemove }) => (
    <div>
      <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
        {(conditions||[]).map((cond, i) => {
          const fDef  = ALL_FIELDS.find(f => f.v === cond.field) || ALL_FIELDS[0];
          const ops   = OPS_BY_TYPE[fDef.type] || OPS_BY_TYPE.text;
          const noVal = cond.op === 'empty' || cond.op === 'nempty';
          return (
            <div key={i} style={{ display:'flex', gap:6, alignItems:'center', flexWrap:'wrap', padding:'8px 10px', borderRadius:8, background:'rgba(255,255,255,0.03)', border:'1px solid rgba(255,255,255,0.06)' }}>
              {i > 0 && (
                <select value={cond.logic} onChange={e => onSetCond(i,'logic',e.target.value)} style={{ ...inp, width:62, fontSize:11 }}>
                  <option value='AND'>AND</option>
                  <option value='OR'>OR</option>
                </select>
              )}
              <select value={cond.field} onChange={e => onSetCond(i,'field',e.target.value)} style={{ ...inp, flex:'2 1 140px' }}>
                <optgroup label='─ فیلدهای لید ─'>
                  {LEAD_FIELDS.map(f => <option key={f.v} value={f.v}>{f.label}</option>)}
                </optgroup>
                <optgroup label='─ محاسباتی ─'>
                  {DERIVED_FIELDS.map(f => <option key={f.v} value={f.v}>{f.label}</option>)}
                </optgroup>
              </select>
              <select value={cond.op} onChange={e => onSetCond(i,'op',e.target.value)} style={{ ...inp, flex:'1 1 80px' }}>
                {ops.map(o => <option key={o.v} value={o.v}>{o.l}</option>)}
              </select>
              {!noVal && (
                fDef.type === 'enum' ? (
                  cond.op === 'in' ? (
                    <input value={cond.value} onChange={e => onSetCond(i,'value',e.target.value)} style={{ ...inp, flex:'2 1 100px' }} placeholder={'با , جدا'} />
                  ) : (
                    <select value={cond.value} onChange={e => onSetCond(i,'value',e.target.value)} style={{ ...inp, flex:'2 1 100px' }}>
                      <option value=''>{'— انتخاب —'}</option>
                      {(fDef.opts||[]).map(o => <option key={o} value={o}>{o}</option>)}
                    </select>
                  )
                ) : (
                  <input value={cond.value} onChange={e => onSetCond(i,'value',e.target.value)}
                    type={fDef.type==='number' ? 'number' : 'text'}
                    style={{ ...inp, flex:'2 1 80px' }} placeholder={'مقدار'} />
                )
              )}
              <button onClick={() => onRemove(i)} style={{ padding:'4px 8px', borderRadius:6, border:'none', background:'rgba(239,68,68,0.15)', color:'#f87171', cursor:'pointer', fontSize:14, flexShrink:0, lineHeight:1 }}>{'×'}</button>
            </div>
          );
        })}
      </div>
      <button onClick={onAdd} style={{ marginTop:8, padding:'5px 14px', borderRadius:7, fontSize:11, cursor:'pointer', border:'1px dashed rgba(99,102,241,0.4)', background:'transparent', color:'#818CF8' }}>
        {'+ افزودن شرط'}
      </button>
    </div>
  );

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

      {/* ─── مودال تأیید رمز ──────────────────────────────── */}
      {pwPending && (
        <PasswordConfirmModal
          headers={headers}
          toast={toast}
          onConfirm={() => { const fn = pwPending; setPwPending(null); fn(); }}
          onCancel={() => setPwPending(null)}
        />
      )}

      {/* ─── وضعیت‌ها و قوانین خودکار ──────────────────────── */}
      {scLoading ? (
        <div style={{ padding:20, textAlign:'center', color:'#374151', fontSize:12 }}>{'در حال بارگذاری...'}</div>
      ) : (
        <StatusLabelsSection
          onEditLabel={openStatusLabel}
          onEditCond={(s, rule) => openStatusCond(s, rule)}
          slOverrides={slOverrides}
          scRulesMap={scRulesMap}
          onApply={applyStatusRules}
          applying={scApplying}
        />
      )}

      {/* ─── بخش قوانین تگ (batch 6h) ────────────────────── */}
      <div style={{ borderRadius:10, border:'1px solid rgba(99,102,241,0.2)', overflow:'hidden' }}>
        <div style={{ padding:'10px 14px', background:'rgba(99,102,241,0.07)', borderBottom:'1px solid rgba(99,102,241,0.15)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div>
            <span style={{ fontSize:12, fontWeight:700, color:'#818cf8' }}>{'🏷️ قوانین تگ استخر'}</span>
            <span style={{ fontSize:10, color:'#475569', marginRight:8 }}>{'— هر ۶ ساعت، بر اساس وضعیت لید'}</span>
          </div>
          <div style={{ display:'flex', gap:8 }}>
            <button onClick={openCreate} style={{ padding:'5px 14px', borderRadius:7, fontSize:11, cursor:'pointer', border:'none', background:'#6366F1', color:'#fff', fontWeight:600 }}>
              {'+ قانون جدید'}
            </button>
            <button onClick={applyAll} disabled={applying} style={{ padding:'5px 14px', borderRadius:7, fontSize:11, cursor:'pointer', border:'1px solid rgba(99,102,241,0.3)', background:'transparent', color:'#818CF8' }}>
              {applying ? 'در حال اجرا...' : '⚡ اجرا الان'}
            </button>
          </div>
        </div>

      {loading ? (
        <div style={{ padding:32, textAlign:'center', color:'#374151', fontSize:12 }}>{'در حال بارگذاری...'}</div>
      ) : rules.length === 0 ? (
        <div style={{ padding:40, textAlign:'center', color:'#374151', fontSize:12 }}>{'هنوز قانونی تعریف نشده'}</div>
      ) : (
        <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
          {rules.map((rule, i) => (
            <div key={rule.id} style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 14px', background: i%2===0 ? 'transparent' : 'rgba(255,255,255,0.012)', borderTop: i===0 ? 'none' : '1px solid rgba(255,255,255,0.04)', 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>
              <span style={{ fontSize:12, padding:'3px 10px', borderRadius:12, background:(rule.tag_color||'#6366F1')+'22', color:rule.tag_color||'#6366F1', fontWeight:600, flexShrink:0, whiteSpace:'nowrap' }}>
                {rule.tag_icon} {rule.tag_name}
              </span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:12, fontWeight:600, color:'#e2e8f0' }}>{rule.name}</div>
                {rule.description && <div style={{ fontSize:10, color:'#475569', marginTop:2 }}>{rule.description}</div>}
                <div style={{ fontSize:10, color:'#64748b', marginTop:3 }}>
                  {(rule.conditions||[]).length}{' شرط'} &nbsp;·&nbsp; {'استفاده: '}{rule.usage_count||0}{' لید'}
                  {rule.auto_apply ? ' · ⚡ خودکار' : ''}
                </div>
              </div>
              <button onClick={() => openEdit(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={() => deleteRule(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>
      )}
      </div>{/* end قوانین تگ استخر wrapper */}

      {/* ─── مودال ویرایش نام/رنگ ─────────────────────────── */}
      {statusLabelEdit && (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.78)', zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center' }}
          onClick={e => e.target===e.currentTarget && setStatusLabelEdit(null)}>
          <div style={{ background:'#111118', border:'1px solid rgba(255,255,255,0.1)', borderRadius:14, padding:24, width:360, display:'flex', flexDirection:'column', gap:14 }}>
            <div style={{ fontSize:14, fontWeight:700, color:'#e2e8f0' }}>{'✏️ ویرایش نام: '}<span style={{ color:statusLabelEdit.color }}>{statusLabelEdit.fa}</span></div>
            <div>
              <div style={{ fontSize:11, color:'#64748b', marginBottom:4 }}>{'نام نمایشی'}</div>
              <input value={statusLabelEdit.fa} onChange={e => setStatusLabelEdit(p => ({...p, fa:e.target.value}))}
                style={{ ...inp, width:'100%', boxSizing:'border-box' }} />
            </div>
            <div>
              <div style={{ fontSize:11, color:'#64748b', marginBottom:4 }}>{'رنگ'}</div>
              <div style={{ display:'flex', gap:8, alignItems:'center' }}>
                <input type='color' value={statusLabelEdit.color} onChange={e => setStatusLabelEdit(p => ({...p, color:e.target.value}))}
                  style={{ width:38, height:34, borderRadius:7, border:'1px solid rgba(255,255,255,0.1)', cursor:'pointer', background:'none', padding:2 }} />
                <span style={{ fontSize:12, fontWeight:600, color:statusLabelEdit.color }}>{statusLabelEdit.fa}</span>
              </div>
            </div>
            <div style={{ display:'flex', gap:8, justifyContent:'flex-end' }}>
              <button onClick={() => setStatusLabelEdit(null)} style={{ padding:'7px 16px', borderRadius:8, fontSize:12, cursor:'pointer', border:'1px solid rgba(255,255,255,0.12)', background:'transparent', color:'#64748b' }}>{'انصراف'}</button>
              <button onClick={saveStatusLabel} style={{ padding:'7px 22px', borderRadius:8, fontSize:12, cursor:'pointer', border:'none', background:'#6366F1', color:'#fff', fontWeight:600 }}>{'💾 ذخیره'}</button>
            </div>
          </div>
        </div>
      )}

      {/* ─── مودال ویرایش قانون وضعیت ─────────────────────── */}
      {statusCondEdit && (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.82)', zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}
          onClick={e => e.target===e.currentTarget && setStatusCondEdit(null)}>
          <div style={{ background:'#111118', border:'1px solid rgba(255,255,255,0.1)', borderRadius:14, padding:24, width:640, maxHeight:'88vh', overflowY:'auto', display:'flex', flexDirection:'column', gap:16 }}>
            <div style={{ display:'flex', alignItems:'center', gap:10 }}>
              <div style={{ width:12, height:12, borderRadius:'50%', background:statusCondEdit.color, flexShrink:0 }} />
              <div style={{ fontSize:14, fontWeight:700, color:'#e2e8f0' }}>{'قانون خودکار: '}<span style={{ color:statusCondEdit.color }}>{statusCondEdit.fa}</span></div>
              <div style={{ flex:1 }} />
              <span style={{ fontSize:11, color:'#374151', direction:'ltr' }}>{statusCondEdit.key}</span>
            </div>

            <div style={{ padding:'9px 13px', borderRadius:8, background:'rgba(99,102,241,0.07)', border:'1px solid rgba(99,102,241,0.15)', fontSize:11, color:'#64748b', lineHeight:1.7 }}>
              {'اگر لیدی همه شرط‌های زیر را داشته باشد، وضعیتش به '}<span style={{ color:statusCondEdit.color, fontWeight:600 }}>{statusCondEdit.fa}</span>{' تغییر می‌کند. این قانون هر ۶ ساعت خودکار اجرا می‌شود.'}
            </div>

            {/* فعال/غیرفعال */}
            <label style={{ display:'flex', alignItems:'center', gap:8, fontSize:12, cursor:'pointer', color:'#94a3b8', userSelect:'none' }}>
              <input type='checkbox' checked={statusCondEdit.is_active === 1}
                onChange={e => setStatusCondEdit(p => ({...p, is_active: e.target.checked ? 1 : 0}))} />
              {'⚡ این قانون فعال باشد'}
            </label>

            <div>
              <div style={{ fontSize:11, color:'#64748b', marginBottom:8 }}>{'شرط‌ها'}</div>
              <CondBuilder
                conditions={statusCondEdit.conditions}
                onSetCond={setScCond}
                onAdd={addScCond}
                onRemove={removeScCond}
              />
            </div>

            {statusCondEdit.conditions.length === 0 && (
              <div style={{ padding:'10px 13px', borderRadius:8, background:'rgba(239,68,68,0.06)', border:'1px solid rgba(239,68,68,0.15)', fontSize:11, color:'#f87171' }}>
                {'⚠️ بدون شرط — قانون اجرا نمی‌شود.'}
              </div>
            )}

            <div style={{ display:'flex', gap:8, justifyContent:'space-between', alignItems:'center' }}>
              <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                <span style={{ fontSize:11, color:'#64748b' }}>{'اولویت'}</span>
                <input type='number' value={statusCondEdit.priority}
                  onChange={e => setStatusCondEdit(p => ({...p, priority: Number(e.target.value)}))}
                  style={{ ...inp, width:60, textAlign:'center' }} />
                <span style={{ fontSize:10, color:'#475569' }}>{'(عدد بیشتر = اجرا اول)'}</span>
              </div>
              <div style={{ display:'flex', gap:8 }}>
                <button onClick={() => setStatusCondEdit(null)} style={{ padding:'7px 16px', borderRadius:8, fontSize:12, cursor:'pointer', border:'1px solid rgba(255,255,255,0.12)', background:'transparent', color:'#64748b' }}>{'انصراف'}</button>
                <button onClick={() => withPassword(saveStatusCond)} disabled={scSaving} style={{ padding:'7px 22px', borderRadius:8, fontSize:12, cursor:'pointer', border:'none', background:'#22c55e', color:'#fff', fontWeight:600 }}>
                  {scSaving ? 'در حال ذخیره...' : '💾 ذخیره'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ─── مودال قانون تگ ──────────────────────────────── */}
      {form && (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.78)', zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}
          onClick={e => e.target === e.currentTarget && setForm(null)}>
          <div style={{ background:'#111118', border:'1px solid rgba(255,255,255,0.1)', borderRadius:14, padding:24, width:600, maxHeight:'90vh', overflowY:'auto', display:'flex', flexDirection:'column', gap:16 }}>
            <div style={{ fontSize:14, fontWeight:700, color:'#e2e8f0' }}>{editId ? 'ویرایش قانون' : '🏷️ قانون جدید'}</div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
              <div>
                <div style={{ fontSize:11, color:'#64748b', marginBottom:4 }}>{'نام قانون *'}</div>
                <input value={form.name} onChange={e => setC('name',e.target.value)}
                  style={{ ...inp, width:'100%', boxSizing:'border-box' }} placeholder={'مثلاً: برگشتی مکرر'} />
              </div>
              <div>
                <div style={{ fontSize:11, color:'#64748b', marginBottom:4 }}>{'توضیح'}</div>
                <input value={form.description||''} onChange={e => setC('description',e.target.value)}
                  style={{ ...inp, width:'100%', boxSizing:'border-box' }} />
              </div>
            </div>
            <div>
              <div style={{ fontSize:11, color:'#64748b', marginBottom:6 }}>{'تگ خروجی *'}</div>
              <div style={{ display:'flex', gap:8, alignItems:'center' }}>
                <input value={form.tag_icon||'🏷️'} onChange={e => setC('tag_icon',e.target.value)}
                  style={{ ...inp, width:50, textAlign:'center', fontSize:18, padding:'4px' }} />
                <input value={form.tag_name} onChange={e => setC('tag_name',e.target.value)}
                  style={{ ...inp, flex:1 }} placeholder={'نام تگ'} />
                <input type='color' value={form.tag_color||'#6366F1'} onChange={e => setC('tag_color',e.target.value)}
                  style={{ width:38, height:34, borderRadius:7, border:'1px solid rgba(255,255,255,0.1)', cursor:'pointer', background:'none', padding:2 }} />
                <span style={{ fontSize:12, padding:'4px 12px', borderRadius:12, background:(form.tag_color||'#6366F1')+'28', color:form.tag_color||'#6366F1', fontWeight:600, whiteSpace:'nowrap', flexShrink:0 }}>
                  {form.tag_icon||'🏷️'} {form.tag_name||'پیش‌نمایش'}
                </span>
              </div>
            </div>
            <div>
              <div style={{ fontSize:11, color:'#64748b', marginBottom:8 }}>{'شرط‌ها'}</div>
              <CondBuilder conditions={form.conditions} onSetCond={setCond} onAdd={addCond} onRemove={removeCond} />
            </div>
            <div style={{ display:'flex', gap:20, alignItems:'center', padding:'10px 14px', borderRadius:8, background:'rgba(255,255,255,0.03)', border:'1px solid rgba(255,255,255,0.06)' }}>
              <label style={{ display:'flex', alignItems:'center', gap:7, fontSize:12, cursor:'pointer', color:'#94a3b8', userSelect:'none' }}>
                <input type='checkbox' checked={!!form.auto_apply} onChange={e => setC('auto_apply', e.target.checked ? 1 : 0)} />
                {'⚡ اعمال خودکار'}
              </label>
              <div style={{ flex:1 }} />
              <div style={{ fontSize:11, color:'#64748b' }}>{'اولویت'}</div>
              <input type='number' value={form.priority||0} onChange={e => setC('priority', Number(e.target.value))}
                style={{ ...inp, width:60, textAlign:'center' }} />
            </div>
            <div style={{ display:'flex', gap:8, justifyContent:'flex-end' }}>
              <button onClick={() => setForm(null)} style={{ padding:'7px 16px', borderRadius:8, fontSize:12, cursor:'pointer', border:'1px solid rgba(255,255,255,0.12)', background:'transparent', color:'#64748b' }}>{'انصراف'}</button>
              <button onClick={saveForm} disabled={saving} style={{ padding:'7px 22px', borderRadius:8, fontSize:12, cursor:'pointer', border:'none', background:'#6366F1', color:'#fff', fontWeight:600 }}>
                {saving ? 'در حال ذخیره...' : '💾 ذخیره'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ─── مودال ویرایش رستاخیز ────────────────────────── */}
      {resForm && (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.82)', zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}
          onClick={e => e.target===e.currentTarget && setResForm(null)}>
          <div style={{ background:'#111118', border:'1px solid rgba(52,211,153,0.2)', borderRadius:14, padding:24, width:520, display:'flex', flexDirection:'column', gap:16 }}>
            <div style={{ fontSize:14, fontWeight:700, color:'#34d399' }}>{'🪦 ویرایش تنظیمات رستاخیز'}</div>

            <label style={{ display:'flex', alignItems:'center', gap:8, fontSize:12, color:'#94a3b8', cursor:'pointer' }}>
              <input type='checkbox' checked={resForm.is_enabled===1}
                onChange={e => setResForm(p => ({...p, is_enabled: e.target.checked ? 1 : 0}))} />
              {'فعال باشد'}
            </label>

            <div>
              <div style={{ fontSize:11, color:'#64748b', marginBottom:6 }}>{'وضعیت‌هایی که رستاخیز را فعال می‌کنند'}</div>
              <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
                {ALL_STATUSES.map(s => (
                  <label key={s} style={{ display:'flex', alignItems:'center', gap:5, fontSize:11, color:'#94a3b8', cursor:'pointer' }}>
                    <input type='checkbox'
                      checked={(resForm.trigger_statuses||[]).includes(s)}
                      onChange={e => {
                        const ts = resForm.trigger_statuses||[];
                        setResForm(p => ({...p, trigger_statuses: e.target.checked ? [...ts,s] : ts.filter(x=>x!==s)}));
                      }} />
                    {s}
                  </label>
                ))}
              </div>
            </div>

            <div>
              <div style={{ fontSize:11, color:'#64748b', marginBottom:4 }}>{'وضعیت هدف پس از رستاخیز'}</div>
              <select value={resForm.target_status} onChange={e => setResForm(p => ({...p, target_status:e.target.value}))}
                style={{ padding:'6px 10px', borderRadius:7, border:'1px solid rgba(255,255,255,0.1)', background:'rgba(255,255,255,0.05)', color:'#e2e8f0', fontSize:12, outline:'none' }}>
                {ALL_STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
            </div>

            <div>
              <div style={{ fontSize:11, color:'#64748b', marginBottom:6 }}>{'تگ اعمال‌شده پس از رستاخیز'}</div>
              <div style={{ display:'flex', gap:8, alignItems:'center' }}>
                <input value={resForm.tag_icon||'🪦'} onChange={e => setResForm(p => ({...p, tag_icon:e.target.value}))}
                  style={{ padding:'4px', borderRadius:7, border:'1px solid rgba(255,255,255,0.1)', background:'rgba(255,255,255,0.05)', color:'#e2e8f0', width:46, textAlign:'center', fontSize:18, outline:'none' }} />
                <input value={resForm.tag_name} onChange={e => setResForm(p => ({...p, tag_name:e.target.value}))}
                  style={{ flex:1, padding:'6px 10px', borderRadius:7, border:'1px solid rgba(255,255,255,0.1)', background:'rgba(255,255,255,0.05)', color:'#e2e8f0', fontSize:12, outline:'none' }} />
                <input type='color' value={resForm.tag_color||'#34D399'} onChange={e => setResForm(p => ({...p, tag_color:e.target.value}))}
                  style={{ width:38, height:34, borderRadius:7, border:'1px solid rgba(255,255,255,0.1)', cursor:'pointer', background:'none', padding:2 }} />
              </div>
            </div>

            <div style={{ display:'flex', gap:8, justifyContent:'flex-end' }}>
              <button onClick={() => setResForm(null)} style={{ padding:'7px 16px', borderRadius:8, fontSize:12, cursor:'pointer', border:'1px solid rgba(255,255,255,0.12)', background:'transparent', color:'#64748b' }}>{'انصراف'}</button>
              <button onClick={saveResForm} disabled={resSaving} style={{ padding:'7px 22px', borderRadius:8, fontSize:12, cursor:'pointer', border:'none', background:'#34d399', color:'#111', fontWeight:700 }}>
                {resSaving ? '⏳ ذخیره...' : '💾 ذخیره'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ─── مودال قانون تگ ربات ──────────────────────────── */}
      {botForm && (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.82)', zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}
          onClick={e => e.target===e.currentTarget && setBotForm(null)}>
          <div style={{ background:'#111118', border:'1px solid rgba(16,185,129,0.2)', borderRadius:14, padding:24, width:540, display:'flex', flexDirection:'column', gap:16 }}>
            <div style={{ fontSize:14, fontWeight:700, color:'#34d399' }}>{botEditId ? '✏️ ویرایش قانون ربات' : '🤖 قانون جدید تگ ربات'}</div>

            <div style={{ padding:'9px 13px', borderRadius:8, background:'rgba(16,185,129,0.06)', border:'1px solid rgba(16,185,129,0.15)', fontSize:11, color:'#64748b', lineHeight:1.7 }}>
              {'اگر متن پیام لید با این الگو (regex) مطابقت داشته باشد، تگ به او زده می‌شود — بلافاصله روی هر پیام.'}
            </div>

            <div>
              <div style={{ fontSize:11, color:'#64748b', marginBottom:4 }}>{'عنوان قانون *'}</div>
              <input value={botForm.label} onChange={e => setBotForm(p => ({...p, label:e.target.value}))}
                style={{ ...inp, width:'100%', boxSizing:'border-box' }} placeholder={'مثلاً: بودجه کم'} />
            </div>

            <div>
              <div style={{ fontSize:11, color:'#64748b', marginBottom:4 }}>{'الگوی تطابق (regex) *'}</div>
              <input value={botForm.pattern} onChange={e => setBotForm(p => ({...p, pattern:e.target.value}))}
                style={{ ...inp, width:'100%', boxSizing:'border-box', fontFamily:'monospace', direction:'ltr' }}
                placeholder={'مثلاً: بیکار|کار ندارم'} dir='ltr' />
              <div style={{ fontSize:10, color:'#475569', marginTop:4 }}>{'چند الگو را با | جدا کنید. متن پیام به lowercase تبدیل می‌شود.'}</div>
            </div>

            <div>
              <div style={{ fontSize:11, color:'#64748b', marginBottom:6 }}>{'تگ خروجی *'}</div>
              <div style={{ display:'flex', gap:8, alignItems:'center' }}>
                <input value={botForm.tag_icon||'🏷️'} onChange={e => setBotForm(p => ({...p, tag_icon:e.target.value}))}
                  style={{ ...inp, width:50, textAlign:'center', fontSize:18, padding:'4px' }} />
                <input value={botForm.tag_name} onChange={e => setBotForm(p => ({...p, tag_name:e.target.value}))}
                  style={{ ...inp, flex:1 }} placeholder={'نام تگ (بدون فاصله)'} />
                <input type='color' value={botForm.tag_color||'#6366F1'} onChange={e => setBotForm(p => ({...p, tag_color:e.target.value}))}
                  style={{ width:38, height:34, borderRadius:7, border:'1px solid rgba(255,255,255,0.1)', cursor:'pointer', background:'none', padding:2 }} />
                <span style={{ fontSize:12, padding:'4px 12px', borderRadius:12, background:(botForm.tag_color||'#6366F1')+'28', color:botForm.tag_color||'#6366F1', fontWeight:600, whiteSpace:'nowrap' }}>
                  {botForm.tag_icon||'🏷️'} {botForm.tag_name||'پیش‌نمایش'}
                </span>
              </div>
            </div>

            <div style={{ display:'flex', alignItems:'center', gap:8 }}>
              <label style={{ display:'flex', alignItems:'center', gap:7, fontSize:12, cursor:'pointer', color:'#94a3b8', userSelect:'none' }}>
                <input type='checkbox' checked={botForm.is_active===1} onChange={e => setBotForm(p => ({...p, is_active: e.target.checked ? 1 : 0}))} />
                {'⚡ فعال باشد'}
              </label>
              <div style={{ flex:1 }} />
              <span style={{ fontSize:11, color:'#64748b' }}>{'ترتیب'}</span>
              <input type='number' value={botForm.sort_order||0} onChange={e => setBotForm(p => ({...p, sort_order:Number(e.target.value)}))}
                style={{ ...inp, width:60, textAlign:'center' }} />
            </div>

            <div style={{ display:'flex', gap:8, justifyContent:'flex-end' }}>
              <button onClick={() => setBotForm(null)} style={{ padding:'7px 16px', borderRadius:8, fontSize:12, cursor:'pointer', border:'1px solid rgba(255,255,255,0.12)', background:'transparent', color:'#64748b' }}>{'انصراف'}</button>
              <button onClick={saveBotForm} disabled={botSaving} style={{ padding:'7px 22px', borderRadius:8, fontSize:12, cursor:'pointer', border:'none', background:'#10b981', color:'#fff', fontWeight:600 }}>
                {botSaving ? 'در حال ذخیره...' : '💾 ذخیره'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
