// simulation.jsx — شبیه‌سازی ۱۰۰ سناریوی فالوآپ
const { useState, useEffect, useCallback, useRef } = React;

const CAT_COLORS = {
  script_drop:   '#F59E0B',
  free_content:  '#10B981',
  consultation:  '#6366F1',
  payment:       '#EF4444',
  warm_cold:     '#64748B',
  new_offer:     '#8B5CF6',
  campaign:      '#06B6D4',
  post_purchase: '#F97316',
  cold_reactive: '#3B82F6',
  special:       '#EC4899',
};

const toman = (n) => {
  if (n >= 1e9) return (n / 1e9).toFixed(1) + ' میلیارد';
  if (n >= 1e6) return (n / 1e6).toFixed(1) + ' میلیون';
  return n.toLocaleString();
};

const pct = (n) => (n == null ? '—' : n.toFixed(1) + '%');
const fa  = window.SB_DATA?.fa || (n => String(n));

// ── Mini bar ────────────────────────────────────────────
const MiniBar = ({ base, fu, color }) => {
  const max = Math.max(fu, 0.01);
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:3, width:90 }}>
      <div style={{ display:'flex', alignItems:'center', gap:4 }}>
        <div style={{ height:6, width: `${Math.round(base / max * 70)}px`, minWidth:2, background:'rgba(255,255,255,0.18)', borderRadius:3 }} />
        <span style={{ fontSize:10, color:'var(--text-3)', fontFamily:'JetBrains Mono' }}>{pct(base * 100)}</span>
      </div>
      <div style={{ display:'flex', alignItems:'center', gap:4 }}>
        <div style={{ height:6, width:`${Math.round(70)}px`, background:color, borderRadius:3, opacity:0.85 }} />
        <span style={{ fontSize:10, color, fontFamily:'JetBrains Mono', fontWeight:700 }}>{pct(fu * 100)}</span>
      </div>
    </div>
  );
};

// ── Stat card ───────────────────────────────────────────
const StatCard = ({ label, value, sub, color = '#818CF8', big = false }) => (
  <div className="card" style={{ padding:'14px 16px', textAlign:'center' }}>
    <div style={{ fontSize: big ? 28 : 22, fontWeight:700, color, fontFamily:'JetBrains Mono', lineHeight:1.1 }}>
      {value}
    </div>
    <div style={{ fontSize:11, color:'var(--text-3)', marginTop:4 }}>{label}</div>
    {sub && <div style={{ fontSize:10, color:'var(--text-3)', marginTop:2, opacity:0.7 }}>{sub}</div>}
  </div>
);

// ═══════════════════════════════════════════════════════
const Simulation = () => {
  const { useToast } = window.SB_UI;
  const toast = useToast();
  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { 'Content-Type':'application/json', Authorization:`Bearer ${token}` };

  const [report,   setReport]   = useState(null);
  const [loading,  setLoading]  = useState(false);
  const [tab,      setTab]      = window.useStickyState('tab_simulation', 'overview');   // overview | categories | scenarios | top10
  const [config,   setConfig]   = useState({ multiplier:1, deal_value:15000000, seed:42 });
  const [filter,   setFilter]   = useState('');
  const [catFilter,setCatFilter]= useState('');
  const [sortBy,   setSortBy]   = useState('lift_rel');
  const [sortDir,  setSortDir]  = useState(-1);          // -1 = desc

  const run = async () => {
    setLoading(true);
    try {
      const r = await fetch('/api/simulation/run', {
        method: 'POST', headers,
        body: JSON.stringify({
          multiplier: config.multiplier,
          deal_value: config.deal_value,
          seed: config.seed,
        }),
      });
      const d = await r.json();
      if (d.success) {
        setReport(d.data);
        setTab('overview');
        toast('شبیه‌سازی اجرا شد ✓', 'success');
      } else toast(d.error || 'خطا', 'error');
    } catch { toast('خطای شبکه', 'error'); }
    finally { setLoading(false); }
  };

  useEffect(() => { run(); }, []);  // اجرای اولیه خودکار

  // ── sort helper ─────────────────────────────────────
  const sortedScenarios = report ? [...report.scenarios]
    .filter(s =>
      (!filter    || s.name.includes(filter))  &&
      (!catFilter || s.cat === catFilter)
    )
    .sort((a, b) => {
      const av = a[sortBy] ?? 0, bv = b[sortBy] ?? 0;
      return sortDir * (bv - av);
    }) : [];

  const toggleSort = (col) => {
    if (sortBy === col) setSortDir(d => -d);
    else { setSortBy(col); setSortDir(-1); }
  };

  const SortTh = ({ col, label }) => (
    <th style={{ cursor:'pointer', userSelect:'none', whiteSpace:'nowrap' }}
      onClick={() => toggleSort(col)}>
      {label} {sortBy === col ? (sortDir < 0 ? '↓' : '↑') : ''}
    </th>
  );

  const cats = report ? Object.values(report.by_category) : [];

  // ── اگه هنوز لود نشده ────────────────────────────────
  if (!report && loading) {
    return (
      <div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', height:320, gap:16 }}>
        <div style={{ fontSize:48, animation:'spin 1s linear infinite' }}>⚙️</div>
        <div style={{ color:'var(--text-3)', fontSize:13 }}>در حال اجرای شبیه‌سازی...</div>
      </div>
    );
  }

  return (
    <div>
      {/* ── کنترل پنل ───────────────────────────────── */}
      <div className="card" style={{ padding:'16px 20px', marginBottom:24 }}>
        <div style={{ display:'flex', flexWrap:'wrap', alignItems:'flex-end', gap:16 }}>
          <div>
            <div style={{ fontSize:11, color:'var(--text-3)', marginBottom:5 }}>ضریب لیدها (۱× = ~۲۵۰۰ لید)</div>
            <div style={{ display:'flex', gap:6 }}>
              {[0.5,1,2,5,10].map(v => (
                <button key={v} onClick={() => setConfig(c => ({ ...c, multiplier:v }))}
                  style={{ padding:'5px 12px', borderRadius:7, border:'none', cursor:'pointer', fontFamily:'JetBrains Mono', fontSize:12,
                    background: config.multiplier === v ? 'var(--primary)' : 'var(--bg-2)',
                    color: config.multiplier === v ? '#fff' : 'var(--text-3)' }}>
                  {v}×
                </button>
              ))}
            </div>
          </div>
          <div>
            <div style={{ fontSize:11, color:'var(--text-3)', marginBottom:5 }}>ارزش هر فروش (تومان)</div>
            <div style={{ display:'flex', gap:6 }}>
              {[5e6,10e6,15e6,25e6,50e6].map(v => (
                <button key={v} onClick={() => setConfig(c => ({ ...c, deal_value:v }))}
                  style={{ padding:'5px 10px', borderRadius:7, border:'none', cursor:'pointer', fontFamily:'JetBrains Mono', fontSize:11,
                    background: config.deal_value === v ? 'var(--primary)' : 'var(--bg-2)',
                    color: config.deal_value === v ? '#fff' : 'var(--text-3)' }}>
                  {toman(v)}
                </button>
              ))}
            </div>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:6 }}>
            <div>
              <div style={{ fontSize:11, color:'var(--text-3)', marginBottom:5 }}>Seed تصادفی</div>
              <input className="input" type="number" style={{ width:90, fontFamily:'JetBrains Mono', fontSize:12 }}
                value={config.seed}
                onChange={e => setConfig(c => ({ ...c, seed: +e.target.value }))} />
            </div>
            <button
              onClick={() => setConfig(c => ({ ...c, seed: Math.floor(Math.random() * 999999) }))}
              style={{ marginTop:20, padding:'5px 10px', borderRadius:7, border:'none', cursor:'pointer', background:'var(--bg-2)', color:'var(--text-3)', fontSize:13 }}
              title="seed تصادفی">🎲</button>
          </div>
          <div style={{ marginRight:'auto', display:'flex', gap:8 }}>
            <button className="btn btn-primary" onClick={run} disabled={loading}
              style={{ minWidth:100 }}>
              {loading ? '⏳ در حال اجرا...' : '▶ اجرای شبیه‌سازی'}
            </button>
          </div>
        </div>
        {report && (
          <div style={{ marginTop:10, fontSize:11, color:'var(--text-3)', fontFamily:'JetBrains Mono' }}>
            آخرین اجرا: {new Date(report.meta.run_at).toLocaleTimeString('fa-IR')} —
            {fa(report.meta.total_leads)} لید —
            {report.meta.elapsed_ms}ms
          </div>
        )}
      </div>

      {report && (
        <>
          {/* ── خلاصه اعداد بالا ─────────────────────── */}
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(150px,1fr))', gap:12, marginBottom:24 }}>
            <StatCard label="کل لیدها" value={fa(report.meta.total_leads)} color="#60A5FA" big />
            <StatCard label="تبدیل بدون فالوآپ"
              value={fa(report.summary.base_conv)}
              sub={`نرخ: ${pct(report.summary.base_rate)}`}
              color="#94A3B8" />
            <StatCard label="تبدیل با فالوآپ"
              value={fa(report.summary.fu_conv)}
              sub={`نرخ: ${pct(report.summary.fu_rate)}`}
              color="#34D399" big />
            <StatCard label="مشتری اضافه‌تر"
              value={`+${fa(report.summary.extra_conv)}`}
              sub="از فالوآپ"
              color="#FBBF24" big />
            <StatCard label="لیفت کلی"
              value={`+${report.summary.lift_rel}%`}
              sub={`+${report.summary.lift_abs} p.p`}
              color="#818CF8" big />
            <StatCard label="درآمد اضافی"
              value={toman(report.summary.extra_revenue)}
              sub={`هر فروش ${toman(config.deal_value)}`}
              color="#F97316" big />
          </div>

          {/* ── تب‌ها ─────────────────────────────────── */}
          <div style={{ display:'flex', gap:4, marginBottom:20, background:'var(--bg-2)', padding:4, borderRadius:12, width:'fit-content' }}>
            {[
              { id:'overview',   label:'📊 نمای کلی'       },
              { id:'categories', label:'📂 دسته‌بندی'       },
              { id:'scenarios',  label:'📋 ۱۰۰ سناریو'     },
              { id:'top10',      label:'🏆 برترین‌ها'       },
            ].map(t => (
              <button key={t.id} onClick={() => setTab(t.id)}
                style={{ padding:'7px 16px', borderRadius:9, border:'none', cursor:'pointer', fontFamily:'inherit', fontSize:12,
                  background: tab === t.id ? 'var(--surface)' : 'transparent',
                  color: tab === t.id ? 'var(--text-1)' : 'var(--text-3)',
                  boxShadow: tab === t.id ? '0 1px 6px rgba(0,0,0,0.25)' : 'none',
                  transition:'all .15s' }}>
                {t.label}
              </button>
            ))}
          </div>

          {/* ════════════════════════════════════════════
              TAB: نمای کلی
          ════════════════════════════════════════════ */}
          {tab === 'overview' && (
            <div className="col gap-20">
              {/* نمودار ستونی دسته‌بندی */}
              <div className="card" style={{ padding:'20px 24px' }}>
                <div className="semi" style={{ fontSize:14, marginBottom:20 }}>مقایسه نرخ تبدیل بر اساس دسته</div>
                <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
                  {cats.sort((a,b) => b.lift_rel - a.lift_rel).map(cat => {
                    const maxFu = Math.max(...cats.map(c => c.fu_rate));
                    const barW = maxFu > 0 ? Math.round(cat.fu_rate / maxFu * 100) : 0;
                    const barWBase = maxFu > 0 ? Math.round(cat.base_rate / maxFu * 100) : 0;
                    return (
                      <div key={cat.id} style={{ display:'grid', gridTemplateColumns:'160px 1fr 80px', alignItems:'center', gap:12 }}>
                        <div style={{ display:'flex', alignItems:'center', gap:6 }}>
                          <div style={{ width:8, height:8, borderRadius:'50%', background:cat.color, flexShrink:0 }} />
                          <span style={{ fontSize:11, color:'var(--text-2)', lineHeight:1.3 }}>{cat.name}</span>
                        </div>
                        <div style={{ position:'relative', height:28 }}>
                          {/* base bar */}
                          <div style={{ position:'absolute', top:4, left:0, height:8, width:`${barWBase}%`, background:'rgba(255,255,255,0.10)', borderRadius:4 }} />
                          {/* fu bar */}
                          <div style={{ position:'absolute', top:16, left:0, height:8, width:`${barW}%`, background:cat.color, borderRadius:4, opacity:0.85 }} />
                        </div>
                        <div style={{ textAlign:'left', fontFamily:'JetBrains Mono' }}>
                          <div style={{ fontSize:10, color:'var(--text-3)' }}>{cat.base_rate}%</div>
                          <div style={{ fontSize:12, color:cat.color, fontWeight:700 }}>{cat.fu_rate}%</div>
                        </div>
                      </div>
                    );
                  })}
                </div>
                <div style={{ marginTop:14, display:'flex', gap:16, fontSize:10, color:'var(--text-3)' }}>
                  <span>▪ نرخ بدون فالوآپ</span>
                  <span style={{ color:'var(--primary)' }}>▪ نرخ با فالوآپ</span>
                </div>
              </div>

              {/* جدول خلاصه دسته */}
              <div className="card" style={{ padding:0, overflow:'hidden' }}>
                <div style={{ padding:'14px 20px', borderBottom:'1px solid rgba(255,255,255,0.06)' }}>
                  <div className="semi" style={{ fontSize:14 }}>عملکرد فالوآپ به تفکیک دسته</div>
                </div>
                <table className="table">
                  <thead>
                    <tr>
                      <th>دسته</th>
                      <th>لیدها</th>
                      <th>بدون فالوآپ</th>
                      <th>با فالوآپ</th>
                      <th>لیفت</th>
                      <th>مشتری اضافه</th>
                      <th>درآمد اضافی</th>
                    </tr>
                  </thead>
                  <tbody>
                    {cats.sort((a,b) => b.lift_rel - a.lift_rel).map(cat => (
                      <tr key={cat.id}>
                        <td>
                          <div style={{ display:'flex', alignItems:'center', gap:7 }}>
                            <div style={{ width:8, height:8, borderRadius:'50%', background:cat.color, flexShrink:0 }} />
                            <span style={{ fontSize:12 }}>{cat.name}</span>
                          </div>
                        </td>
                        <td className="mono text-xs">{fa(cat.leads)}</td>
                        <td className="mono text-xs" style={{ color:'var(--text-3)' }}>{cat.base_rate}%</td>
                        <td className="mono text-xs" style={{ color:cat.color, fontWeight:700 }}>{cat.fu_rate}%</td>
                        <td>
                          <span style={{ fontSize:11, padding:'2px 8px', borderRadius:6,
                            background:`${cat.color}18`, color:cat.color, fontFamily:'JetBrains Mono', fontWeight:700 }}>
                            +{cat.lift_rel}%
                          </span>
                        </td>
                        <td className="mono text-xs" style={{ color:'#FBBF24' }}>+{fa(cat.extra_conv)}</td>
                        <td className="mono text-xs" style={{ color:'#34D399' }}>{toman(cat.extra_revenue)}</td>
                      </tr>
                    ))}
                    {/* جمع */}
                    <tr style={{ borderTop:'2px solid rgba(255,255,255,0.1)', background:'rgba(99,102,241,0.05)' }}>
                      <td><strong>جمع کل</strong></td>
                      <td className="mono text-xs"><strong>{fa(report.meta.total_leads)}</strong></td>
                      <td className="mono text-xs" style={{ color:'var(--text-3)' }}>{pct(report.summary.base_rate)}</td>
                      <td className="mono text-xs" style={{ color:'#34D399', fontWeight:700 }}>{pct(report.summary.fu_rate)}</td>
                      <td><span style={{ fontSize:11, padding:'2px 8px', borderRadius:6, background:'rgba(99,102,241,0.15)', color:'#818CF8', fontFamily:'JetBrains Mono', fontWeight:700 }}>+{report.summary.lift_rel}%</span></td>
                      <td className="mono text-xs" style={{ color:'#FBBF24', fontWeight:700 }}>+{fa(report.summary.extra_conv)}</td>
                      <td className="mono text-xs" style={{ color:'#34D399', fontWeight:700 }}>{toman(report.summary.extra_revenue)}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* ════════════════════════════════════════════
              TAB: دسته‌بندی
          ════════════════════════════════════════════ */}
          {tab === 'categories' && (
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(300px,1fr))', gap:16 }}>
              {cats.sort((a,b) => b.lift_rel - a.lift_rel).map(cat => {
                const scenariosInCat = report.scenarios.filter(s => s.cat === cat.id)
                  .sort((a,b) => b.lift_rel - a.lift_rel);
                return (
                  <div key={cat.id} className="card" style={{ padding:'16px 18px', borderColor:`${cat.color}33` }}>
                    <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
                      <div style={{ width:10, height:10, borderRadius:'50%', background:cat.color }} />
                      <div className="semi" style={{ fontSize:13, color:cat.color }}>{cat.name}</div>
                      <span style={{ fontSize:10, padding:'1px 7px', borderRadius:10, background:`${cat.color}18`, color:cat.color, marginRight:'auto' }}>
                        +{cat.lift_rel}% لیفت
                      </span>
                    </div>
                    <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8, marginBottom:12 }}>
                      {[
                        { l:'لیدها', v: fa(cat.leads) },
                        { l:'بدون فالوآپ', v: cat.base_rate + '%' },
                        { l:'با فالوآپ', v: cat.fu_rate + '%', c: cat.color },
                      ].map(s => (
                        <div key={s.l} style={{ textAlign:'center', padding:'8px 4px', borderRadius:8, background:'var(--bg-2)' }}>
                          <div style={{ fontSize:14, fontWeight:700, color: s.c || 'var(--text-1)', fontFamily:'JetBrains Mono' }}>{s.v}</div>
                          <div style={{ fontSize:10, color:'var(--text-3)', marginTop:2 }}>{s.l}</div>
                        </div>
                      ))}
                    </div>
                    <div style={{ borderTop:'1px solid rgba(255,255,255,0.06)', paddingTop:10 }}>
                      <div style={{ fontSize:10, color:'var(--text-3)', marginBottom:6 }}>بهترین سناریوها:</div>
                      {scenariosInCat.slice(0,3).map(s => (
                        <div key={s.id} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'3px 0', fontSize:11, color:'var(--text-2)' }}>
                          <span style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', maxWidth:190 }}>{s.icon} {s.name}</span>
                          <span style={{ color:cat.color, fontFamily:'JetBrains Mono', fontWeight:700, flexShrink:0 }}>+{s.lift_rel}%</span>
                        </div>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {/* ════════════════════════════════════════════
              TAB: ۱۰۰ سناریو
          ════════════════════════════════════════════ */}
          {tab === 'scenarios' && (
            <div>
              {/* فیلتر */}
              <div style={{ display:'flex', gap:10, marginBottom:16, flexWrap:'wrap' }}>
                <input className="input" value={filter}
                  onChange={e => setFilter(e.target.value)}
                  placeholder="🔍 جستجو در سناریوها..."
                  style={{ flex:1, minWidth:180 }} />
                <select className="select" value={catFilter}
                  onChange={e => setCatFilter(e.target.value)}
                  style={{ width:180 }}>
                  <option value="">همه دسته‌بندی‌ها</option>
                  {cats.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
                <button className="btn btn-ghost" style={{ fontSize:11 }}
                  onClick={() => { setFilter(''); setCatFilter(''); }}>
                  پاک کردن
                </button>
              </div>

              <div style={{ fontSize:12, color:'var(--text-3)', marginBottom:10 }}>
                {fa(sortedScenarios.length)} سناریو
              </div>

              <div className="card" style={{ padding:0, overflow:'hidden' }}>
                <table className="table">
                  <thead>
                    <tr>
                      <th>#</th>
                      <th>سناریو</th>
                      <th>دسته</th>
                      <SortTh col="n"           label="لیدها" />
                      <SortTh col="base_rate_theo" label="بدون فالوآپ" />
                      <SortTh col="fu_rate_theo"   label="با فالوآپ" />
                      <SortTh col="lift_rel"    label="لیفت ٪" />
                      <SortTh col="extra_conv"  label="اضافه" />
                    </tr>
                  </thead>
                  <tbody>
                    {sortedScenarios.map(s => {
                      const color = CAT_COLORS[s.cat] || '#6B7280';
                      return (
                        <tr key={s.id}>
                          <td className="mono text-xs" style={{ color:'var(--text-3)' }}>{fa(s.id)}</td>
                          <td>
                            <span style={{ fontSize:12 }}>{s.icon} {s.name}</span>
                          </td>
                          <td>
                            <span style={{ fontSize:10, padding:'1px 7px', borderRadius:10, background:`${color}18`, color, whiteSpace:'nowrap' }}>
                              {report.by_category[s.cat]?.name || s.cat}
                            </span>
                          </td>
                          <td className="mono text-xs">{fa(s.n)}</td>
                          <td className="mono text-xs" style={{ color:'var(--text-3)' }}>{pct(s.base_rate_theo * 100)}</td>
                          <td className="mono text-xs" style={{ color, fontWeight:700 }}>{pct(s.fu_rate_theo * 100)}</td>
                          <td>
                            <span style={{ fontSize:11, padding:'2px 8px', borderRadius:6,
                              background: s.lift_rel >= 200 ? 'rgba(52,211,153,0.15)' : s.lift_rel >= 100 ? 'rgba(99,102,241,0.12)' : 'rgba(107,114,128,0.1)',
                              color: s.lift_rel >= 200 ? '#34D399' : s.lift_rel >= 100 ? '#818CF8' : '#6B7280',
                              fontFamily:'JetBrains Mono', fontWeight:700 }}>
                              +{s.lift_rel}%
                            </span>
                          </td>
                          <td className="mono text-xs" style={{ color:'#FBBF24' }}>
                            {s.extra_conv > 0 ? `+${s.extra_conv}` : s.extra_conv}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* ════════════════════════════════════════════
              TAB: برترین‌ها
          ════════════════════════════════════════════ */}
          {tab === 'top10' && (
            <div className="col gap-20">
              {/* Top 10 */}
              <div>
                <div className="semi" style={{ fontSize:14, marginBottom:14 }}>
                  🏆 ۱۰ سناریوی برتر — بیشترین تأثیر فالوآپ
                </div>
                <div className="col gap-8">
                  {report.top10.map((s, idx) => {
                    const color = CAT_COLORS[s.cat] || '#6B7280';
                    const catName = report.by_category[s.cat]?.name || s.cat;
                    return (
                      <div key={s.id} className="card" style={{ padding:'12px 16px', borderColor:`${color}33` }}>
                        <div style={{ display:'flex', alignItems:'center', gap:12 }}>
                          <div style={{ width:28, height:28, borderRadius:'50%', background:`${color}20`, border:`2px solid ${color}50`,
                            display:'flex', alignItems:'center', justifyContent:'center', fontSize:13, fontWeight:700, color, flexShrink:0 }}>
                            {fa(idx + 1)}
                          </div>
                          <div style={{ flex:1, minWidth:0 }}>
                            <div style={{ fontSize:12, fontWeight:600, marginBottom:3 }}>{s.icon} {s.name}</div>
                            <div style={{ fontSize:10, color:'var(--text-3)' }}>{catName}</div>
                          </div>
                          <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', gap:3, flexShrink:0 }}>
                            <span style={{ fontSize:14, fontWeight:700, color, fontFamily:'JetBrains Mono' }}>+{s.lift_rel}%</span>
                            <div style={{ display:'flex', gap:10, fontSize:11, fontFamily:'JetBrains Mono' }}>
                              <span style={{ color:'var(--text-3)' }}>{pct(s.base_rate_theo * 100)}</span>
                              <span>→</span>
                              <span style={{ color }}>{pct(s.fu_rate_theo * 100)}</span>
                            </div>
                          </div>
                        </div>
                        {/* progress visual */}
                        <div style={{ marginTop:10, display:'flex', alignItems:'center', gap:8 }}>
                          <div style={{ flex:1, height:5, borderRadius:3, background:'rgba(255,255,255,0.06)', overflow:'hidden', position:'relative' }}>
                            <div style={{ position:'absolute', height:'100%', width:`${s.base_rate_theo * 100}%`, background:'rgba(255,255,255,0.18)', borderRadius:3 }} />
                          </div>
                          <div style={{ flex:1, height:5, borderRadius:3, background:'rgba(255,255,255,0.06)', overflow:'hidden', position:'relative' }}>
                            <div style={{ position:'absolute', height:'100%', width:`${Math.min(s.fu_rate_theo * 100, 100)}%`, background:color, borderRadius:3 }} />
                          </div>
                          <div style={{ fontSize:10, color:'#FBBF24', fontFamily:'JetBrains Mono', whiteSpace:'nowrap' }}>
                            +{s.extra_conv} نفر
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Bottom 10 */}
              <div>
                <div className="semi" style={{ fontSize:14, marginBottom:14 }}>
                  🧊 ۱۰ سناریوی سرد — کمترین تأثیر (نیاز به بهبود هوک)
                </div>
                <div className="col gap-8">
                  {report.bottom10.map((s, idx) => {
                    const color = CAT_COLORS[s.cat] || '#6B7280';
                    const catName = report.by_category[s.cat]?.name || s.cat;
                    return (
                      <div key={s.id} className="card" style={{ padding:'10px 14px', opacity:0.8 }}>
                        <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                          <span style={{ fontSize:11, color:'var(--text-3)', fontFamily:'JetBrains Mono', width:20, textAlign:'center' }}>
                            {fa(idx + 1)}
                          </span>
                          <div style={{ flex:1, minWidth:0 }}>
                            <div style={{ fontSize:11 }}>{s.icon} {s.name}</div>
                            <div style={{ fontSize:10, color:'var(--text-3)' }}>{catName}</div>
                          </div>
                          <div style={{ display:'flex', gap:10, fontSize:11, fontFamily:'JetBrains Mono' }}>
                            <span style={{ color:'var(--text-3)' }}>{pct(s.base_rate_theo * 100)}</span>
                            <span>→</span>
                            <span style={{ color }}>{pct(s.fu_rate_theo * 100)}</span>
                            <span style={{ color:'#64748B', fontWeight:700 }}>+{s.lift_rel}%</span>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* توصیه‌نامه */}
              <div className="card" style={{ padding:'16px 20px', borderColor:'rgba(99,102,241,0.3)', background:'rgba(99,102,241,0.04)' }}>
                <div className="semi" style={{ fontSize:13, marginBottom:12 }}>💡 توصیه‌های اولویت‌دار</div>
                <div className="col gap-8">
                  {[
                    { icon:'💳', text:'یادآور پرداخت — بیشترین نرخ تبدیل. اول اینجا هوک بساز.' },
                    { icon:'📅', text:'پیگیری بعد از مشاوره — اگه ۴۸ ساعت پاسخ نداد، پیام بده.' },
                    { icon:'📦', text:'بعد از ارسال محتوای رایگان — ۲۴ ساعت بعد پیگیری کن.' },
                    { icon:'🎯', text:'پیشنهاد دوره تکمیلی به خریدار — آسان‌ترین فروش.' },
                    { icon:'🚪', text:'Script drop — بعد از ۳ ساعت بی‌جوابی پیام خودکار بده.' },
                  ].map((t, i) => (
                    <div key={i} style={{ display:'flex', gap:10, fontSize:12, color:'var(--text-2)', lineHeight:1.5 }}>
                      <span style={{ flexShrink:0 }}>{t.icon}</span>
                      <span>{t.text}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
};

window.Simulation = Simulation;
