// ── ورودی عدد با فرمت تومان ────────────────────────────────────
const MoneyInput = ({ value, onChange, placeholder, style, className }) => {
  const { fa } = window.SB_DATA;
  const [focused, setFocused] = React.useState(false);
  const [raw, setRaw] = React.useState('');
  const fmt = v => !v ? '' : fa(Math.round(v).toLocaleString('en').replace(/,/g, '،'));
  const onFocus = () => { setFocused(true); setRaw(value ? String(Math.round(value)) : ''); };
  const onBlur  = () => { setFocused(false); onChange(parseFloat(raw.replace(/[،,\s]/g, '')) || 0); };
  const onKey   = e => {
    if (!/^[0-9.]$/.test(e.key) && !['Backspace','Delete','ArrowLeft','ArrowRight','Tab'].includes(e.key)) e.preventDefault();
  };
  return (
    <input className={className || 'sw-inp'}
      style={{ direction:'ltr', textAlign:'left', ...style }}
      value={focused ? raw : (value ? fmt(value) : '')}
      placeholder={placeholder || '۰'}
      onFocus={onFocus} onBlur={onBlur} onKeyDown={onKey}
      onChange={e => setRaw(e.target.value.replace(/[^0-9.]/g, ''))} />
  );
};

// ── تارگت‌گذاری فروش — ویزارد ۵ مرحله‌ای ─────────────────────
const SalesTargets = () => {
  const { fa } = window.SB_DATA;
  const toast = (window.SB_UI?.useToast?.()) || { show: () => {} };

  // ─── CSS ────────────────────────────────────────────────────────
  useEffect(() => {
    const SID = 'st-wiz2-css';
    if (document.getElementById(SID)) return;
    const el = document.createElement('style');
    el.id = SID; el.textContent = `
.sw{direction:rtl;font-family:inherit;max-width:1100px}
.sw-steps{display:flex;align-items:flex-start;margin-bottom:28px;position:relative;gap:0}
.sw-steps::before{content:'';position:absolute;top:18px;right:28px;left:28px;height:2px;background:rgba(255,255,255,0.06);z-index:0}
.sw-step{display:flex;flex-direction:column;align-items:center;gap:5px;flex:1;position:relative;z-index:1;cursor:default}
.sw-step.clickable{cursor:pointer}
.sw-dot{width:36px;height:36px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:800;border:2px solid rgba(255,255,255,0.08);background:#0d1219;transition:all .2s}
.sw-dot.done{background:#122a1d;border-color:#34d399;color:#34d399}
.sw-dot.active{background:#141830;border-color:#818cf8;color:#a5b4fc;box-shadow:0 0 0 4px rgba(129,140,248,0.12)}
.sw-dot.idle{color:#334155}
.sw-step-lbl{font-size:10px;font-weight:700;white-space:nowrap;text-align:center}
.sw-step.active .sw-step-lbl{color:#a5b4fc}
.sw-step.done  .sw-step-lbl{color:#34d399}
.sw-step.idle  .sw-step-lbl{color:#334155}
.sw-card{background:#121823;border:1px solid rgba(255,255,255,0.07);border-radius:16px;padding:22px 24px;margin-bottom:14px}
.sw-title{font-size:17px;font-weight:800;margin-bottom:3px}
.sw-sub{font-size:12px;color:#64748b;margin-bottom:18px;line-height:1.6}
.sw-field{margin-bottom:14px}
.sw-lbl{font-size:11px;color:#64748b;font-weight:700;margin-bottom:5px}
.sw-inp{background:#0d1219;border:1px solid rgba(255,255,255,0.09);border-radius:9px;padding:10px 14px;color:#e6eaf2;font-size:14px;font-weight:700;font-family:inherit;outline:none;width:100%;box-sizing:border-box;transition:border-color .15s}
.sw-inp:focus{border-color:rgba(129,140,248,0.45)}
.sw-inp-sm{font-size:12px;padding:7px 10px}
.sw-inp-xs{font-size:12px;padding:5px 8px}
.sw-grid2{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.sw-grid3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px}
.sw-grid4{display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:10px}
.sw-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
/* ── سبک‌کارت ── */
.sw-model-card{border-radius:14px;padding:18px 20px;border:2px solid rgba(255,255,255,0.07);background:#0a1017;cursor:pointer;transition:all .18s;position:relative;overflow:hidden}
.sw-model-card:hover{border-color:rgba(255,255,255,0.15)}
.sw-model-card.sel-webinar{border-color:#818cf8;background:rgba(129,140,248,0.07)}
.sw-model-card.sel-linear{border-color:#34d399;background:rgba(52,211,153,0.07)}
.sw-model-card.sel-campaign{border-color:#f472b6;background:rgba(244,114,182,0.07)}
.sw-model-icon{font-size:32px;margin-bottom:10px}
.sw-model-name{font-size:15px;font-weight:800;margin-bottom:4px}
.sw-model-desc{font-size:11px;color:#64748b;line-height:1.6}
.sw-model-check{position:absolute;top:12px;left:12px;width:20px;height:20px;border-radius:50%;border:2px solid rgba(255,255,255,0.15);display:flex;align-items:center;justify-content:center;font-size:10px;transition:all .15s}
.sel-webinar  .sw-model-check{background:#818cf8;border-color:#818cf8;color:#fff}
.sel-linear   .sw-model-check{background:#34d399;border-color:#34d399;color:#fff}
.sel-campaign .sw-model-check{background:#f472b6;border-color:#f472b6;color:#fff}
/* ── نرخ‌باکس ── */
.sw-rate-box{background:#0a1017;border:1px solid rgba(255,255,255,0.07);border-radius:11px;padding:14px 16px}
.sw-rate-box-title{font-size:11px;font-weight:800;margin-bottom:10px;display:flex;align-items:center;gap:6px}
/* ── جدول ── */
.sw-tbl{width:100%;border-collapse:separate;border-spacing:0 5px}
.sw-tbl th{font-size:10px;color:#475569;font-weight:700;padding:5px 8px;text-align:center;white-space:nowrap}
.sw-tbl th:first-child{text-align:right}
.sw-tbl td{background:#0d1320;padding:9px 7px;text-align:center;vertical-align:middle;font-size:12px}
.sw-tbl tr td:first-child{border-radius:10px 0 0 10px;padding-right:12px;text-align:right}
.sw-tbl tr td:last-child{border-radius:0 10px 10px 0}
.sw-tbl tfoot td{background:#101c12;border-top:1px solid rgba(255,255,255,0.06)}
.sw-rate{background:#0a1017;border:1px solid rgba(255,255,255,0.07);border-radius:7px;padding:5px 7px;color:#e2e8f0;font-size:12px;font-weight:700;font-family:inherit;outline:none;width:68px;text-align:center;-moz-appearance:textfield}
.sw-rate::-webkit-inner-spin-button,.sw-rate::-webkit-outer-spin-button{-webkit-appearance:none}
.sw-rate:focus{border-color:rgba(129,140,248,0.4)}
/* ── nav ── */
.sw-nav{display:flex;justify-content:space-between;align-items:center;margin-top:20px;padding-top:16px;border-top:1px solid rgba(255,255,255,0.06)}
.sw-btn{display:inline-flex;align-items:center;gap:7px;border-radius:10px;padding:10px 20px;font-size:13px;font-weight:700;cursor:pointer;border:none;font-family:inherit;transition:opacity .15s;white-space:nowrap}
.sw-btn:hover{opacity:.85}.sw-btn:disabled{opacity:.4;cursor:not-allowed}
.sw-btn-p{background:rgba(129,140,248,0.18);color:#c7cdfa;border:1px solid rgba(129,140,248,0.3)}
.sw-btn-g{background:rgba(52,211,153,0.15);color:#5ee9b5;border:1px solid rgba(52,211,153,0.3)}
.sw-btn-ghost{background:transparent;color:#64748b;border:1px solid rgba(255,255,255,0.08)}
.sw-btn-sm{padding:6px 12px;font-size:11px;border-radius:8px}
/* ── kpi ── */
.sw-kpi{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px;margin-bottom:14px}
.sw-kpi-box{background:#0d1219;border:1px solid rgba(255,255,255,0.07);border-radius:11px;padding:12px 14px;text-align:center}
.sw-kpi-lbl{font-size:9px;color:#64748b;font-weight:700;margin-bottom:4px}
.sw-kpi-val{font-size:17px;font-weight:800}
.sw-bar-wrap{height:7px;border-radius:4px;background:rgba(255,255,255,0.06);overflow:hidden;margin-top:6px}
.sw-bar{height:100%;border-radius:4px;transition:width .5s}
.sw-av{width:30px;height:30px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:800;flex:none}
.sw-insight{display:flex;gap:8px;align-items:flex-start;background:rgba(129,140,248,0.07);border:1px solid rgba(129,140,248,0.16);border-radius:10px;padding:10px 13px;font-size:12px;line-height:1.7;color:#c4cbd8;margin-top:12px}
.sw-tag{display:inline-flex;align-items:center;font-size:10px;font-weight:700;border-radius:6px;padding:2px 8px}
.sw-g{color:#5ee9b5;background:rgba(52,211,153,0.12);border:1px solid rgba(52,211,153,0.22)}
.sw-b{color:#93c5fd;background:rgba(96,165,250,0.12);border:1px solid rgba(96,165,250,0.22)}
.sw-y{color:#fcd66b;background:rgba(251,191,36,0.12);border:1px solid rgba(251,191,36,0.22)}
.sw-pk{color:#f9a8d4;background:rgba(244,114,182,0.12);border:1px solid rgba(244,114,182,0.22)}
.sw-v{color:#c4b5fd;background:rgba(167,139,250,0.12);border:1px solid rgba(167,139,250,0.22)}
.sw-divider{height:1px;background:rgba(255,255,255,0.05);margin:14px 0}
.sw-prod-dot{width:8px;height:8px;border-radius:50%;display:inline-block;flex:none}
/* ── real-data badge ── */
.sw-real{display:inline-flex;align-items:center;gap:3px;font-size:9px;font-weight:700;color:#34d399;background:rgba(52,211,153,0.1);border:1px solid rgba(52,211,153,0.2);border-radius:4px;padding:1px 5px;white-space:nowrap}
.sw-nodata{font-size:9px;color:#475569;margin-top:2px}
.sw-rate-real{border-color:rgba(52,211,153,0.35)!important;color:#6ee7b7!important}
@media(max-width:700px){.sw-grid2,.sw-grid3,.sw-grid4{grid-template-columns:1fr}}
    `;
    document.head.appendChild(el);
  }, []);

  const COLORS = ['#818cf8','#34d399','#f472b6','#fb923c','#a78bfa','#38bdf8','#4ade80','#fbbf24','#f87171','#c084fc'];
  const curPeriod = new Date().toISOString().slice(0, 7);
  const hdrs = { 'Content-Type':'application/json', Authorization:`Bearer ${localStorage.getItem(window.TOKEN_KEY)}` };
  const api = (path, opts={}) => fetch('/api/market'+path, {headers:hdrs,...opts,body:opts.body?JSON.stringify(opts.body):undefined}).then(r=>r.json());

  const fnum  = v => (!v&&v!==0)?'—':fa(Math.round(v).toLocaleString('en').replace(/,/g,'،'));
  const fmoney= v => !v?'—':fnum(v)+' تومان';
  const fp    = v => fa(+(+v||0).toFixed(1))+'٪';

  // ─── State ─────────────────────────────────────────────────────
  const [step,    setStep]    = useState(1);
  const [loading, setLoading] = useState(true);
  const [saving,  setSaving]  = useState(false);
  const [prods,   setProds]   = useState([]);
  const [sellers, setSellers] = useState([]);

  // گام ۱: هدف
  const [target,  setTarget]  = useState(0);

  // گام ۲: سبک فروش — Set از 'webinar'|'linear'|'campaign'
  const [models,  setModels]  = useState(new Set(['linear']));

  // نرخ‌های پیش‌فرض هر مدل (قابل ویرایش در گام ۲)
  const [webinarRates, setWebinarRates] = useState({ attend_rate:18.8, stay_rate:46.7, conv_rate:17.8 });
  const [linearRates,  setLinearRates]  = useState({ sales_conv:25, sec_conv:80, work_days:22 });
  const [campaignCfg,  setCampaignCfg]  = useState({ budget:0, cpl:0, lead_conv:5 });

  // گام ۳: محصولات
  const [pCfg, setPCfg] = useState({});

  // گام ۴: فروشندگان
  const [sCfg,     setSCfg]     = useState({});
  // آمار واقعی هر فروشنده از تاریخچه: sellerId → { conv_rate, sec_conv, avg_deal, sample }
  const [realStats, setRealStats] = useState({});

  // ─── Load ───────────────────────────────────────────────────────
  useEffect(()=>{
    Promise.all([
      api('/products'),
      api('/sellers'),
      api(`/product-plan?period=${curPeriod}`),
      api(`/targets?period=${curPeriod}`),
      api(`/seller-real-stats?period=${curPeriod}`),
    ]).then(([pr,sr,planR,tgtR,realR])=>{
      const ap=(pr.data?.products||[]).filter(p=>!p.is_prize&&p.is_active);
      setProds(ap);
      const pm={};
      ap.forEach(p=>{
        pm[p.id]={ webinar_price:p.list_price||p.avg_value||0, avg_deal:p.avg_value||0, target_units:0,
          attend_rate:18.8, stay_rate:46.7, conv_rate:17.8, sales_conv:25, sec_conv:80, work_days:22 };
      });
      (planR.data?.plans||[]).forEach(pl=>{ if(pm[pl.product_id]) pm[pl.product_id]={...pm[pl.product_id],...pl}; });
      setPCfg(pm);

      const sl=(sr.data?.sellers||[]).filter(s=>s.is_active);
      setSellers(sl);

      // ساخت نقشه آمار واقعی
      const rm={};
      (realR.data?.stats||[]).forEach(r=>{ rm[r.seller_id]=r; });
      setRealStats(rm);

      const sm={};
      sl.forEach(s=>{
        const r=rm[s.id]||{};
        // اولویت: داده‌ی ذخیره‌شده قبلی → آمار واقعی → پیش‌فرض
        sm[s.id]={
          amount:          0,
          conv_rate:       r.conv_rate  ?? 25,
          sec_conv:        r.sec_conv   ?? 80,
          commission_rate: 10,
          avg_deal:        r.avg_deal   ?? 0,
        };
      });
      // اگه تارگت قبلی ذخیره شده، override کن
      (tgtR.data?.targets||[]).forEach(t=>{
        if(sm[t.seller_id]) sm[t.seller_id]={
          ...sm[t.seller_id],
          amount:          t.amount||0,
          commission_rate: t.commission_rate||10,
          // نرخ‌ها رو فقط اگه دستی ست شده override کن (یعنی با real فرق دارن)
          ...(t.conv_rate && t.conv_rate !== (rm[t.seller_id]?.conv_rate??25) ? {conv_rate: t.conv_rate} : {}),
          ...(t.sec_conv  && t.sec_conv  !== (rm[t.seller_id]?.sec_conv ??80) ? {sec_conv:  t.sec_conv}  : {}),
          ...(t.avg_deal  && t.avg_deal  !== (rm[t.seller_id]?.avg_deal ??0)  ? {avg_deal:  t.avg_deal}  : {}),
        };
      });
      setSCfg(sm);
      const tot=Object.values(sm).reduce((a,v)=>a+(v.amount||0),0);
      if(tot>0) setTarget(tot);
    }).finally(()=>setLoading(false));
  },[]);

  // ─── Helpers ────────────────────────────────────────────────────
  const updP = (pid,k,v) => setPCfg(m=>({...m,[pid]:{...m[pid],[k]:v}}));
  const updS = (sid,k,v) => setSCfg(m=>({...m,[sid]:{...m[sid],[k]:v}}));
  const updWR= (k,v) => setWebinarRates(r=>({...r,[k]:v}));
  const updLR= (k,v) => setLinearRates(r=>({...r,[k]:v}));
  const updCC= (k,v) => setCampaignCfg(r=>({...r,[k]:v}));

  const toggleModel = m => setModels(prev=>{
    const n=new Set(prev);
    n.has(m)?n.delete(m):n.add(m);
    return n;
  });

  // محاسبه لید از تارگت با استفاده از آمار واقعی فروشنده (+۲۰٪ بافر)
  const selLeads = sid => {
    const s  = sCfg[sid];     if (!s || !s.amount) return 0;
    const rs = realStats[sid] || {};
    // avg_deal: واقعی → ذخیره‌شده → میانگین محصولات گام ۳
    const prodAvgDeal = (() => {
      const vals = prods.map(p=>pCfg[p.id]?.avg_deal||0).filter(Boolean);
      return vals.length ? Math.round(vals.reduce((a,b)=>a+b,0)/vals.length) : 0;
    })();
    const ad  = rs.avg_deal || s.avg_deal || prodAvgDeal || 0;  if (!ad) return 0;
    const cr  = rs.conv_rate || s.conv_rate || 25;
    const sec = rs.sec_conv  || s.sec_conv  || 80;
    const sales   = s.amount / ad;
    const consult = cr  > 0 ? sales   / (cr  / 100) : 0;
    const raw     = sec > 0 ? Math.ceil(consult / (sec / 100)) : 0;
    return Math.ceil(raw * 1.2); // ۲۰٪ بافر برای لیدهای بی‌پاسخ
  };

  // توزیع هوشمند بر اساس نرخ کانورت ماه گذشته (فصلی fallback)
  const smartDistribute = (tgt) => {
    const total = tgt ?? target;
    if (!total || !sellers.length) return;
    const weights = sellers.map(s => {
      const rs = realStats[s.id] || {};
      // ترجیح: ماه گذشته → فصلی → پیش‌فرض
      return rs.last_month?.conv_rate ?? rs.seasonal?.conv_rate ?? rs.conv_rate ?? 10;
    });
    const sum = weights.reduce((a,b)=>a+b,0);
    if (!sum) return;
    const nm = {...sCfg};
    sellers.forEach((s,i) => { nm[s.id] = {...nm[s.id], amount: Math.round(total * (weights[i] / sum))}; });
    setSCfg(nm);
  };

  // خلاصه
  const totalSel  = sellers.reduce((a,s)=>a+(sCfg[s.id]?.amount||0),0);
  const totalComm = sellers.reduce((a,s)=>a+(sCfg[s.id]?.amount||0)*((sCfg[s.id]?.commission_rate||10)/100),0);
  const totalPro  = totalSel-totalComm;
  const totalLeads= sellers.reduce((a,s)=>a+selLeads(s.id),0);
  // تخمین درآمد از کمپین
  const campaignRevEst = models.has('campaign')
    ? (campaignCfg.budget&&campaignCfg.cpl>0 ? Math.round(campaignCfg.budget/campaignCfg.cpl*(campaignCfg.lead_conv/100)) : 0)
    : 0;

  // هر بار که وارد step 4 می‌شیم یا realStats لود می‌شه، خودکار توزیع کن
  useEffect(()=>{
    if (step===4 && target>0 && sellers.length>0 && Object.keys(realStats).length>0) {
      smartDistribute();
    }
  }, [step, Object.keys(realStats).length]);

  const save = async () => {
    setSaving(true);
    try {
      await Promise.all([
        ...prods.map(p=>api(`/product-plan/${p.id}`,{method:'PUT',body:{...pCfg[p.id],period:curPeriod}})),
        ...sellers.map(s=>api(`/sellers/${s.id}/target`,{method:'PUT',body:{...sCfg[s.id],period:curPeriod}})),
      ]);
      toast.show?.('تارگت‌ها با موفقیت ذخیره شد ✓','success');
    } catch { toast.show?.('خطا در ذخیره‌سازی','error'); } finally { setSaving(false); }
  };

  const STEPS = [
    {n:1, icon:'🎯', label:'هدف ماه'},
    {n:2, icon:'🧭', label:'سبک فروش'},
    {n:3, icon:'📦', label:'محصولات'},
    {n:4, icon:'👥', label:'فروشندگان'},
    {n:5, icon:'✅', label:'تایید'},
  ];

  const RateInp = ({label, val, onChange, step=1, min=0, max=100, unit='٪'}) => (
    <div className="sw-field" style={{marginBottom:0}}>
      <div className="sw-lbl">{label}</div>
      <div style={{display:'flex',alignItems:'center',gap:5}}>
        <input className="sw-rate" type="number" value={val} step={step} min={min} max={max}
          onChange={e=>onChange(parseFloat(e.target.value)||0)} style={{width:'100%'}}/>
        {unit && <span style={{fontSize:11,color:'#475569',whiteSpace:'nowrap'}}>{unit}</span>}
      </div>
    </div>
  );

  if(loading) return <div style={{padding:60,textAlign:'center',color:'#64748b'}}>در حال بارگذاری...</div>;

  const modelLabel = m => ({'webinar':'وبینار','linear':'خطی','campaign':'کمپین'}[m]||m);
  const modelColor = m => ({'webinar':'#818cf8','linear':'#34d399','campaign':'#f472b6'}[m]||'#64748b');

  // ══════════════════════════════════════════════════════════════════
  return (
    <div className="sw">
      {/* هدر */}
      <div style={{marginBottom:20}}>
        <div style={{fontSize:21,fontWeight:800}}>تعیین تارگت ماهانه فروش</div>
        <div style={{fontSize:12,color:'#64748b',marginTop:3}}>{curPeriod} · {prods.length} محصول · {sellers.length} فروشنده</div>
      </div>

      {/* استپر */}
      <div className="sw-steps">
        {STEPS.map(st=>{
          const cls=step>st.n?'done':step===st.n?'active':'idle';
          return (
            <div key={st.n} className={`sw-step ${step>st.n?'clickable':''} ${cls}`}
              onClick={()=>step>st.n&&setStep(st.n)}>
              <div className={`sw-dot ${cls}`}>{step>st.n?'✓':st.icon}</div>
              <div className="sw-step-lbl">{st.label}</div>
            </div>
          );
        })}
      </div>

      {/* ═══════ گام ۱: هدف ماه ══════════════════════════════════ */}
      {step===1 && (
        <div className="sw-card" style={{borderTop:'3px solid #818cf8'}}>
          <div className="sw-title">🎯 هدف درآمدی این ماه چقدر است؟</div>
          <div className="sw-sub">هدف کل شرکت را به تومان وارد کنید — در مراحل بعد بین فروشندگان تقسیم می‌شود</div>

          <div className="sw-field">
            <div className="sw-lbl">هدف کل درآمد (تومان)</div>
            <MoneyInput value={target} onChange={setTarget} placeholder="مثلاً ۹۰۰٬۰۰۰٬۰۰۰"
              style={{fontSize:26,fontWeight:900,padding:'13px 18px',maxWidth:340}}/>
            {target>0 && (
              <div style={{marginTop:8,display:'flex',gap:10,alignItems:'center',flexWrap:'wrap'}}>
                <span style={{fontSize:14,color:'#a5b4fc',fontWeight:800}}>{fmoney(target)}</span>
                <span style={{fontSize:11,color:'#475569'}}>≈ {fa(+(target/1e9).toFixed(2))} میلیارد</span>
              </div>
            )}
          </div>

          {target>0 && (
            <div className="sw-kpi" style={{marginTop:16}}>
              {[
                {l:'هدف ماه',v:fmoney(target),c:'#a5b4fc'},
                {l:'تعداد فروشنده',v:fa(sellers.length)+' نفر',c:'#e2e8f0'},
                {l:'میانگین هر فروشنده',v:fmoney(Math.round(target/sellers.length)),c:'#fbbf24'},
              ].map((k,i)=>(
                <div key={i} className="sw-kpi-box">
                  <div className="sw-kpi-lbl">{k.l}</div>
                  <div className="sw-kpi-val" style={{color:k.c,fontSize:15}}>{k.v}</div>
                </div>
              ))}
            </div>
          )}

          <div className="sw-nav">
            <div/>
            <button className="sw-btn sw-btn-p" disabled={!target} onClick={()=>setStep(2)}>
              مرحله بعد: سبک فروش ←
            </button>
          </div>
        </div>
      )}

      {/* ═══════ گام ۲: سبک فروش ══════════════════════════════════ */}
      {step===2 && (
        <div>
          <div className="sw-card" style={{borderTop:'3px solid #f472b6'}}>
            <div className="sw-title">🧭 سبک فروش این ماه را انتخاب کنید</div>
            <div className="sw-sub">می‌توانید یک یا چند سبک را همزمان فعال کنید</div>

            <div className="sw-grid3" style={{marginBottom:16}}>
              {/* وبینار */}
              <div className={`sw-model-card ${models.has('webinar')?'sel-webinar':''}`}
                onClick={()=>toggleModel('webinar')}>
                <div className="sw-model-check">{models.has('webinar')&&'✓'}</div>
                <div className="sw-model-icon">🎤</div>
                <div className="sw-model-name" style={{color:models.has('webinar')?'#a5b4fc':'#e2e8f0'}}>وبینار</div>
                <div className="sw-model-desc">ثبت‌نام → حضور → ماندگاری → خرید<br/>مناسب دوره‌های آنلاین و آموزشی</div>
              </div>
              {/* خطی */}
              <div className={`sw-model-card ${models.has('linear')?'sel-linear':''}`}
                onClick={()=>toggleModel('linear')}>
                <div className="sw-model-check">{models.has('linear')&&'✓'}</div>
                <div className="sw-model-icon">📞</div>
                <div className="sw-model-name" style={{color:models.has('linear')?'#6ee7b7':'#e2e8f0'}}>فروش خطی</div>
                <div className="sw-model-desc">لید → منشی → مشاوره → فروش<br/>مناسب تیم‌های تماس‌محور</div>
              </div>
              {/* کمپین */}
              <div className={`sw-model-card ${models.has('campaign')?'sel-campaign':''}`}
                onClick={()=>toggleModel('campaign')}>
                <div className="sw-model-check">{models.has('campaign')&&'✓'}</div>
                <div className="sw-model-icon">📢</div>
                <div className="sw-model-name" style={{color:models.has('campaign')?'#f9a8d4':'#e2e8f0'}}>کمپین تبلیغاتی</div>
                <div className="sw-model-desc">بودجه تبلیغات → لید → فروش<br/>مناسب کمپین‌های فصلی و ویژه</div>
              </div>
            </div>

            {models.size===0 && (
              <div style={{textAlign:'center',color:'#f87171',fontSize:12,padding:'8px 0'}}>حداقل یک سبک فروش انتخاب کنید</div>
            )}
          </div>

          {/* نرخ‌های پیش‌فرض هر سبک */}
          {models.has('webinar') && (
            <div className="sw-card" style={{borderTop:'2px solid #818cf8'}}>
              <div style={{fontSize:13,fontWeight:800,color:'#a5b4fc',marginBottom:12}}>🎤 نرخ‌های پیش‌فرض وبینار</div>
              <div className="sw-grid3">
                <RateInp label="نرخ حضور"      val={webinarRates.attend_rate} step={0.5} onChange={v=>updWR('attend_rate',v)}/>
                <RateInp label="نرخ ماندگاری"  val={webinarRates.stay_rate}   step={0.5} onChange={v=>updWR('stay_rate',v)}/>
                <RateInp label="نرخ تبدیل"     val={webinarRates.conv_rate}   step={0.5} onChange={v=>updWR('conv_rate',v)}/>
              </div>
              <div className="sw-insight" style={{marginTop:10}}>
                <span>💡</span><div>این نرخ‌ها به عنوان پیش‌فرض برای همه محصولات وبینار اعمال می‌شود — در گام بعد می‌توانید به‌ازای هر محصول تغییر دهید.</div>
              </div>
            </div>
          )}

          {models.has('linear') && (
            <div className="sw-card" style={{borderTop:'2px solid #34d399'}}>
              <div style={{fontSize:13,fontWeight:800,color:'#6ee7b7',marginBottom:12}}>📞 نرخ‌های پیش‌فرض فروش خطی</div>
              <div className="sw-grid3">
                <RateInp label="نرخ کانورت فروش" val={linearRates.sales_conv} step={1} onChange={v=>updLR('sales_conv',v)}/>
                <RateInp label="نرخ پاسخ منشی"   val={linearRates.sec_conv}   step={1} onChange={v=>updLR('sec_conv',v)}/>
                <RateInp label="روزهای کاری ماه" val={linearRates.work_days}  step={1} max={31} unit='روز' onChange={v=>updLR('work_days',v)}/>
              </div>
            </div>
          )}

          {models.has('campaign') && (
            <div className="sw-card" style={{borderTop:'2px solid #f472b6'}}>
              <div style={{fontSize:13,fontWeight:800,color:'#f9a8d4',marginBottom:12}}>📢 بودجه و تخمین کمپین</div>
              <div className="sw-grid3">
                <div className="sw-field" style={{marginBottom:0}}>
                  <div className="sw-lbl">بودجه تبلیغات (تومان)</div>
                  <MoneyInput className="sw-inp sw-inp-sm" value={campaignCfg.budget} onChange={v=>updCC('budget',v)} placeholder="بودجه"/>
                </div>
                <div className="sw-field" style={{marginBottom:0}}>
                  <div className="sw-lbl">هزینه هر لید — CPL (تومان)</div>
                  <MoneyInput className="sw-inp sw-inp-sm" value={campaignCfg.cpl} onChange={v=>updCC('cpl',v)} placeholder="CPL"/>
                </div>
                <RateInp label="نرخ تبدیل لید به فروش" val={campaignCfg.lead_conv} step={0.5} onChange={v=>updCC('lead_conv',v)}/>
              </div>
              {campaignCfg.budget>0 && campaignCfg.cpl>0 && (
                <div style={{marginTop:12,display:'flex',gap:10,flexWrap:'wrap'}}>
                  <span className="sw-tag sw-pk">لید تخمینی: {fnum(Math.round(campaignCfg.budget/campaignCfg.cpl))} نفر</span>
                  <span className="sw-tag sw-g">فروش تخمینی: {fnum(Math.round(campaignCfg.budget/campaignCfg.cpl*campaignCfg.lead_conv/100))} نفر</span>
                </div>
              )}
            </div>
          )}

          <div className="sw-nav">
            <button className="sw-btn sw-btn-ghost" onClick={()=>setStep(1)}>← برگشت</button>
            <button className="sw-btn sw-btn-p" disabled={models.size===0} onClick={()=>setStep(3)}>
              مرحله بعد: محصولات ←
            </button>
          </div>
        </div>
      )}

      {/* ═══════ گام ۳: محصولات ══════════════════════════════════ */}
      {step===3 && (
        <div className="sw-card" style={{borderTop:'3px solid #fb923c'}}>
          <div className="sw-title">📦 تنظیمات محصولات</div>
          <div style={{display:'flex',gap:8,marginBottom:14,flexWrap:'wrap'}}>
            {[...models].map(m=>(
              <span key={m} className="sw-tag" style={{fontSize:11,color:modelColor(m),background:modelColor(m)+'18',border:`1px solid ${modelColor(m)}33`}}>
                {m==='webinar'?'🎤':m==='linear'?'📞':'📢'} {modelLabel(m)} فعال
              </span>
            ))}
          </div>

          {prods.map((p,i)=>{
            const pc=pCfg[p.id]||{};
            return (
              <div key={p.id} style={{padding:'14px 0',borderBottom:'1px solid rgba(255,255,255,0.05)'}}>
                <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:12}}>
                  <span className="sw-prod-dot" style={{background:p.color||COLORS[i%COLORS.length]}}/>
                  <span style={{fontWeight:800,fontSize:14}}>{p.name}</span>
                  <span className="sw-tag sw-b" style={{marginRight:'auto'}}>{p.category}</span>
                </div>

                {/* فیلدهای وبینار */}
                {models.has('webinar') && (
                  <div style={{marginBottom:10}}>
                    <div style={{fontSize:10,color:'#818cf8',fontWeight:700,marginBottom:8}}>🎤 وبینار</div>
                    <div className="sw-grid4">
                      <div className="sw-field" style={{marginBottom:0}}>
                        <div className="sw-lbl">قیمت وبینار (تومان)</div>
                        <MoneyInput className="sw-inp sw-inp-xs" value={pc.webinar_price||0}
                          onChange={v=>updP(p.id,'webinar_price',v)} placeholder="قیمت"/>
                      </div>
                      <div className="sw-field" style={{marginBottom:0}}>
                        <div className="sw-lbl">تارگت خریدار (نفر)</div>
                        <input className="sw-inp sw-inp-xs" type="number" step={1} value={pc.target_units||0}
                          onChange={e=>updP(p.id,'target_units',parseInt(e.target.value)||0)}/>
                      </div>
                      <RateInp label="نرخ حضور ٪"    val={pc.attend_rate??webinarRates.attend_rate} step={0.5} onChange={v=>updP(p.id,'attend_rate',v)}/>
                      <RateInp label="نرخ ماندگاری ٪" val={pc.stay_rate??webinarRates.stay_rate}   step={0.5} onChange={v=>updP(p.id,'stay_rate',v)}/>
                    </div>
                    {pc.target_units>0 && pc.webinar_price>0 && (
                      <div style={{marginTop:6}}>
                        <span className="sw-tag sw-v">درآمد تخمینی وبینار: {fmoney((pc.target_units||0)*(pc.webinar_price||0))}</span>
                      </div>
                    )}
                  </div>
                )}

                {/* خط جداکننده */}
                {models.has('webinar') && models.has('linear') && <div className="sw-divider"/>}

                {/* فیلدهای خطی */}
                {models.has('linear') && (
                  <div>
                    <div style={{fontSize:10,color:'#34d399',fontWeight:700,marginBottom:8}}>📞 فروش خطی</div>
                    <div className="sw-grid4">
                      <div className="sw-field" style={{marginBottom:0}}>
                        <div className="sw-lbl">میانگین معامله (تومان)</div>
                        <MoneyInput className="sw-inp sw-inp-xs" value={pc.avg_deal||0}
                          onChange={v=>updP(p.id,'avg_deal',v)} placeholder="میانگین"/>
                      </div>
                      <div className="sw-field" style={{marginBottom:0}}>
                        <div className="sw-lbl">تارگت درآمد خطی (تومان)</div>
                        <MoneyInput className="sw-inp sw-inp-xs" value={pc.target_revenue||0}
                          onChange={v=>updP(p.id,'target_revenue',v)} placeholder="درآمد"/>
                      </div>
                      <RateInp label="نرخ کانورت ٪"  val={pc.sales_conv??linearRates.sales_conv} step={1} onChange={v=>updP(p.id,'sales_conv',v)}/>
                      <RateInp label="روزهای کاری"   val={pc.work_days??linearRates.work_days}   step={1} max={31} unit='روز' onChange={v=>updP(p.id,'work_days',v)}/>
                    </div>
                    {pc.target_revenue>0 && pc.avg_deal>0 && (
                      <div style={{marginTop:6}}>
                        <span className="sw-tag sw-g">فروش تخمینی: {fnum(Math.ceil(pc.target_revenue/pc.avg_deal))} معامله</span>
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}

          <div className="sw-nav">
            <button className="sw-btn sw-btn-ghost" onClick={()=>setStep(2)}>← برگشت</button>
            <button className="sw-btn sw-btn-p" onClick={()=>setStep(4)}>مرحله بعد: فروشندگان ←</button>
          </div>
        </div>
      )}

      {/* ═══════ گام ۴: فروشندگان — توزیع خودکار ══════════════════ */}
      {step===4 && (()=>{
        // هر بار که وارد گام ۴ می‌شیم اگه توزیع نشده، auto توزیع کن
        const anySel = sellers.some(s=>(sCfg[s.id]?.amount||0)>0);

        return (
        <div>
          {/* هدر */}
          <div className="sw-card" style={{borderTop:'3px solid #34d399',marginBottom:12}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:12}}>
              <div>
                <div className="sw-title">👥 توزیع تارگت بین فروشندگان</div>
                <div className="sw-sub" style={{marginBottom:0}}>سیستم بر اساس نرخ کانورت واقعی هر فروشنده تارگت تعیین کرده — فقط کمیسیون قابل تنظیم است</div>
              </div>
              <button className="sw-btn sw-btn-g sw-btn-sm" onClick={()=>smartDistribute()}>↺ توزیع مجدد</button>
            </div>

            {/* نوار هدف */}
            <div style={{background:'rgba(255,255,255,0.02)',borderRadius:10,padding:'10px 14px',display:'flex',gap:14,alignItems:'center'}}>
              <div style={{flex:1}}>
                <div style={{display:'flex',justifyContent:'space-between',fontSize:11,color:'#64748b',marginBottom:4}}>
                  <span>توزیع‌شده: <b style={{color:'#e2e8f0'}}>{fmoney(totalSel)}</b></span>
                  <span>هدف کل: <b style={{color:'#a5b4fc'}}>{fmoney(target)}</b></span>
                </div>
                <div className="sw-bar-wrap">
                  <div className="sw-bar" style={{width:`${Math.min(totalSel/(target||1)*100,100)}%`,background:totalSel>=target?'#34d399':'#818cf8'}}/>
                </div>
              </div>
              <span style={{fontSize:14,fontWeight:800,color:totalSel>=target?'#34d399':'#fbbf24',whiteSpace:'nowrap'}}>{fp(Math.min(totalSel/(target||1)*100,999))}</span>
            </div>

            {/* legend */}
            <div style={{display:'flex',gap:12,marginTop:10,fontSize:10,color:'#475569',flexWrap:'wrap'}}>
              <span style={{display:'flex',alignItems:'center',gap:4}}><span style={{width:8,height:8,borderRadius:'50%',background:'#34d399',display:'inline-block'}}/> ماه گذشته</span>
              <span style={{display:'flex',alignItems:'center',gap:4}}><span style={{width:8,height:8,borderRadius:'50%',background:'#fbbf24',display:'inline-block'}}/> فصلی (۳ ماه)</span>
              <span style={{display:'flex',alignItems:'center',gap:4}}><span style={{width:8,height:8,borderRadius:'50%',background:'#60a5fa',display:'inline-block'}}/> کل تاریخچه</span>
              <span style={{display:'flex',alignItems:'center',gap:4}}><span style={{width:8,height:8,borderRadius:'50%',background:'#475569',display:'inline-block'}}/> پیش‌فرض</span>
            </div>
          </div>

          {/* کارت هر فروشنده */}
          {sellers.map((s,i)=>{
            const sc  = sCfg[s.id]||{};
            const rs  = realStats[s.id]||{};
            const col = COLORS[i%COLORS.length];
            const leads = selLeads(s.id);

            // منبع نرخ کانورت
            const convSrc = rs.last_month?.conv_rate != null ? 'last_month'
                          : rs.seasonal?.conv_rate   != null ? 'seasonal'
                          : rs.all_time?.conv_rate   != null ? 'all_time'
                          : 'default';
            const convVal = rs.conv_rate ?? 25;
            const secVal  = rs.sec_conv  ?? 80;
            const dealVal = rs.avg_deal  ?? 0;

            const srcColor = convSrc==='last_month'?'#34d399':convSrc==='seasonal'?'#fbbf24':convSrc==='all_time'?'#60a5fa':'#475569';
            const srcLabel = convSrc==='last_month'?'ماه گذشته':convSrc==='seasonal'?'فصلی':convSrc==='all_time'?'کل تاریخچه':'پیش‌فرض';
            const srcLeads = convSrc==='last_month' ? rs.last_month?.leads : convSrc==='seasonal' ? rs.seasonal?.leads : rs.all_time?.leads;

            const selIncome = (sc.amount||0) * ((sc.commission_rate||10)/100);
            const coProfit  = (sc.amount||0) - selIncome;

            // میانگین معامله: واقعی → میانگین محصولات گام ۳
            const prodAvgDealVals = prods.map(p=>pCfg[p.id]?.avg_deal||0).filter(Boolean);
            const prodAvgDeal = prodAvgDealVals.length ? Math.round(prodAvgDealVals.reduce((a,b)=>a+b,0)/prodAvgDealVals.length) : 0;
            const effectiveDeal = dealVal || prodAvgDeal;

            return (
              <div key={s.id} className="sw-card" style={{marginBottom:8,padding:'14px 18px',borderRight:`3px solid ${col}55`}}>
                <div style={{display:'grid',gridTemplateColumns:'auto 1fr auto',gap:12,alignItems:'center'}}>
                  {/* نام */}
                  <div style={{display:'flex',alignItems:'center',gap:10}}>
                    <div className="sw-av" style={{background:col+'22',color:col,border:`1.5px solid ${col}55`,width:36,height:36,fontSize:14}}>{s.name?.[0]||'؟'}</div>
                    <div>
                      <div style={{fontWeight:800,fontSize:14}}>{s.name}</div>
                      <div style={{display:'flex',gap:5,marginTop:2}}>
                        <span style={{width:7,height:7,borderRadius:'50%',background:srcColor,display:'inline-block',marginTop:2}}/>
                        <span style={{fontSize:10,color:srcColor,fontWeight:700}}>{srcLabel}</span>
                        {srcLeads>0 && <span style={{fontSize:9,color:'#475569'}}>({fa(srcLeads)} لید)</span>}
                      </div>
                    </div>
                  </div>

                  {/* آمار */}
                  <div style={{display:'grid',gridTemplateColumns:'repeat(5,1fr)',gap:8}}>
                    {[
                      {l:'نرخ کانورت',     v:fp(convVal), c:srcColor,
                        note: convSrc==='seasonal'?`فصلی`:convSrc==='all_time'?'کل تاریخچه':null},
                      {l:'نرخ پاسخ',       v:fp(secVal),  c:'#94a3b8', note:null},
                      {l:'میانگین معامله', v:effectiveDeal>0?fmoney(effectiveDeal):'—',
                        c: dealVal>0?'#94a3b8':'#475569',
                        note: dealVal===0&&prodAvgDeal>0?'از محصولات':null},
                      {l:'تارگت ماه',      v:fmoney(sc.amount||0), c:'#a5b4fc', note:null},
                      {l:'لید نیاز (+۲۰٪)',v:leads>0?fnum(leads)+' لید':'—', c:'#fbbf24',
                        note: (convSrc==='seasonal'||convSrc==='all_time')&&leads>0?srcLabel:null},
                    ].map((k,j)=>(
                      <div key={j} style={{background:'rgba(255,255,255,0.025)',borderRadius:8,padding:'8px 10px',textAlign:'center'}}>
                        <div style={{fontSize:9,color:'#475569',fontWeight:700,marginBottom:3}}>{k.l}</div>
                        <div style={{fontSize:13,fontWeight:800,color:k.c}}>{k.v}</div>
                        {k.note && <div style={{fontSize:9,color:'#fbbf24',marginTop:2,lineHeight:1.3}}>{k.note}</div>}
                      </div>
                    ))}
                  </div>

                  {/* کمیسیون (تنها فیلد قابل ویرایش) */}
                  <div style={{display:'flex',flexDirection:'column',gap:6,alignItems:'center',minWidth:100}}>
                    <div style={{fontSize:10,color:'#64748b',fontWeight:700}}>کمیسیون ٪</div>
                    <div style={{display:'flex',alignItems:'center',gap:4}}>
                      <input className="sw-rate" type="number" step={0.5} min={0} max={50}
                        value={sc.commission_rate||10}
                        onChange={e=>updS(s.id,'commission_rate',parseFloat(e.target.value)||0)}/>
                      <span style={{fontSize:10,color:'#475569'}}>٪</span>
                    </div>
                    <div style={{fontSize:9,color:'#a5b4fc',textAlign:'center'}}>
                      <div>کمیسیون: {fmoney(selIncome)}</div>
                      <div style={{color:'#6ee7b7'}}>سود شرکت: {fmoney(coProfit)}</div>
                    </div>
                  </div>
                </div>

                {/* هشدار فصلی */}
                {convSrc==='seasonal' && leads>0 && (
                  <div style={{marginTop:10,padding:'6px 12px',background:'rgba(251,191,36,0.07)',border:'1px solid rgba(251,191,36,0.2)',borderRadius:8,fontSize:11,color:'#fbbf24',display:'flex',alignItems:'center',gap:6}}>
                    ⚠ با محاسبه فصلی — باید <b style={{margin:'0 4px'}}>{fnum(leads)} لید</b> دریافت کند (داده ماه گذشته کافی نبود)
                  </div>
                )}
                {convSrc==='default' && (
                  <div style={{marginTop:10,padding:'6px 12px',background:'rgba(100,116,139,0.07)',border:'1px solid rgba(100,116,139,0.15)',borderRadius:8,fontSize:11,color:'#64748b',display:'flex',alignItems:'center',gap:6}}>
                    ℹ داده تاریخی کافی نیست — از نرخ پیش‌فرض استفاده شده
                  </div>
                )}
              </div>
            );
          })}

          <div className="sw-nav" style={{marginTop:16}}>
            <button className="sw-btn sw-btn-ghost" onClick={()=>setStep(3)}>← برگشت</button>
            <button className="sw-btn sw-btn-p" onClick={()=>setStep(5)}>مرحله بعد: تایید ←</button>
          </div>
        </div>
        );
      })()}

      {/* ═══════ گام ۵: تایید نهایی ══════════════════════════════ */}
      {step===5 && (
        <div>
          <div className="sw-card" style={{borderTop:'3px solid #34d399'}}>
            <div className="sw-title">✅ مرور نهایی</div>
            <div className="sw-sub">
              سبک‌های فعال:&nbsp;
              {[...models].map(m=>(
                <span key={m} className="sw-tag" style={{marginLeft:4,color:modelColor(m),background:modelColor(m)+'18',border:`1px solid ${modelColor(m)}33`}}>
                  {m==='webinar'?'🎤':m==='linear'?'📞':'📢'} {modelLabel(m)}
                </span>
              ))}
            </div>

            <div className="sw-kpi">
              {[
                {l:'هدف کل',         v:fmoney(target),       c:'#a5b4fc'},
                {l:'تخصیص فروشندگان',v:fmoney(totalSel),     c:totalSel>=target?'#34d399':'#fbbf24'},
                {l:'جمع کمیسیون‌ها', v:fmoney(totalComm),    c:'#f9a8d4'},
                {l:'سود خالص شرکت',  v:fmoney(totalPro),     c:'#34d399'},
                {l:'لید نیاز ماه',   v:fnum(totalLeads)+' لید',c:'#fbbf24'},
                ...(models.has('campaign')&&campaignCfg.budget>0?[{l:'بودجه کمپین',v:fmoney(campaignCfg.budget),c:'#f9a8d4'}]:[]),
              ].map((k,i)=>(
                <div key={i} className="sw-kpi-box">
                  <div className="sw-kpi-lbl">{k.l}</div>
                  <div className="sw-kpi-val" style={{color:k.c,fontSize:14}}>{k.v}</div>
                </div>
              ))}
            </div>

            {target>0 && (
              <div style={{marginBottom:4}}>
                <div style={{display:'flex',justifyContent:'space-between',fontSize:11,color:'#64748b',marginBottom:4}}>
                  <span>پوشش هدف</span>
                  <span style={{color:totalSel>=target?'#34d399':'#fbbf24',fontWeight:700}}>{fp(Math.min(totalSel/target*100,999))}</span>
                </div>
                <div className="sw-bar-wrap">
                  <div className="sw-bar" style={{width:`${Math.min(totalSel/target*100,100)}%`,background:totalSel>=target?'#34d399':'#818cf8'}}/>
                </div>
                {totalSel<target && <div style={{fontSize:11,color:'#f87171',marginTop:4}}>کسری: {fmoney(target-totalSel)}</div>}
              </div>
            )}
          </div>

          {/* جدول سودآوری */}
          <div className="sw-card">
            <div style={{fontSize:13,fontWeight:800,marginBottom:12}}>📊 سودآوری فروشندگان</div>
            <div style={{overflowX:'auto'}}>
              <table className="sw-tbl">
                <thead>
                  <tr>
                    <th style={{minWidth:130}}>فروشنده</th>
                    <th>تارگت درآمد</th>
                    <th style={{color:'#fbbf24'}}>لید نیاز</th>
                    <th>کمیسیون</th>
                    <th style={{color:'#a5b4fc'}}>درآمد فروشنده</th>
                    <th style={{color:'#6ee7b7'}}>سود شرکت</th>
                  </tr>
                </thead>
                <tbody>
                  {sellers.map((s,i)=>{
                    const sc=sCfg[s.id]||{};
                    const amt=sc.amount||0;
                    const com=(sc.commission_rate||10)/100;
                    const selInc=amt*com, co=amt-selInc;
                    const leads=selLeads(s.id);
                    const col=COLORS[i%COLORS.length];
                    return (
                      <tr key={s.id}>
                        <td>
                          <div style={{display:'flex',alignItems:'center',gap:8}}>
                            <div className="sw-av" style={{background:col+'22',color:col,border:`1.5px solid ${col}44`}}>{s.name?.[0]||'؟'}</div>
                            <div>
                              <div style={{fontWeight:700,fontSize:13}}>{s.name}</div>
                              <div style={{fontSize:9,color:'#475569'}}>کانورت {fp(sc.conv_rate||25)}</div>
                            </div>
                          </div>
                        </td>
                        <td style={{fontWeight:700}}>{amt?fmoney(amt):'—'}</td>
                        <td style={{color:'#fbbf24',fontWeight:700}}>{leads>0?fnum(leads):'—'}</td>
                        <td><span className="sw-tag sw-y">{fp(sc.commission_rate||10)}</span></td>
                        <td style={{color:'#a5b4fc',fontWeight:800}}>{selInc?fmoney(selInc):'—'}</td>
                        <td style={{color:'#6ee7b7',fontWeight:800}}>{co?fmoney(co):'—'}</td>
                      </tr>
                    );
                  })}
                </tbody>
                <tfoot>
                  <tr>
                    <td style={{fontWeight:800,fontSize:12}}>جمع</td>
                    <td style={{fontWeight:800}}>{fmoney(totalSel)}</td>
                    <td style={{color:'#fbbf24',fontWeight:700}}>{fnum(totalLeads)}</td>
                    <td/>
                    <td style={{color:'#a5b4fc',fontWeight:800}}>{fmoney(totalComm)}</td>
                    <td style={{color:'#6ee7b7',fontWeight:800}}>{fmoney(totalPro)}</td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>

          <div className="sw-insight">
            <span>📢</span>
            <div>پس از ذخیره، تارگت و نرخ‌ها در <b>داشبورد هر فروشنده</b> و <b>پنل مدیر فروش</b> نمایش داده می‌شود.</div>
          </div>

          <div className="sw-nav">
            <button className="sw-btn sw-btn-ghost" onClick={()=>setStep(4)}>← ویرایش فروشندگان</button>
            <button className="sw-btn sw-btn-g" style={{fontSize:14,padding:'12px 28px'}} onClick={save} disabled={saving}>
              {saving?'در حال ذخیره...':'✓ ذخیره و اعمال تارگت‌ها'}
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
