// Lab page - 4 tabs
const Lab = () => {
  const { Icon } = window.SB_UI;
  const [tab, setTab] = useState('sim');
  const tabs = [
    { id: 'sim', name: 'شبیه‌ساز', icon: 'play-circle' },
    { id: 'persona', name: 'ساخت جامعه و تست', icon: 'users' },
    { id: 'compare', name: 'مقایسه اسکریپت', icon: 'columns' },
    { id: 'campaign', name: 'تست کمپین', icon: 'megaphone' },
  ];
  return (
    <div>
      <div className="tabs">
        {tabs.map(t => (
          <button key={t.id} className={`tab ${tab === t.id ? 'active' : ''}`} onClick={() => setTab(t.id)}>
            <Icon name={t.icon} size={13} />&nbsp;&nbsp;{t.name}
          </button>
        ))}
      </div>
      <div className="mt-24">
        {tab === 'sim' && <SimTab />}
        {tab === 'persona' && <PersonaTestTab />}
        {tab === 'compare' && <CompareTab />}
        {tab === 'campaign' && <CampaignTestTab />}
      </div>
    </div>
  );
};

const SimTab = () => {
  const { Icon, Button, useToast } = window.SB_UI;
  const toast = useToast();
  const [msgs, setMsgs] = useState([
    { from: 'bot', text: 'سلام! من ربات SalesBot هستم. این محیط شبیه‌سازه و می‌تونی هر پیامی بدی.', time: '۱۰:۰۰' },
  ]);
  const [input, setInput] = useState('');
  const [script, setScript] = useState(window.SB_DATA.SCRIPTS[0].name);
  const ref = useRef(null);

  useEffect(() => { if (ref.current) ref.current.scrollTop = ref.current.scrollHeight; }, [msgs]);

  const send = () => {
    if (!input.trim()) return;
    const t = new Date().toLocaleTimeString('fa-IR', { hour: '2-digit', minute: '2-digit' });
    setMsgs(m => [...m, { from: 'user', text: input, time: t }]);
    const userText = input;
    setInput('');
    setTimeout(() => {
      const reply = fakeReply(userText);
      setMsgs(m => [...m, { from: 'bot', text: reply, time: t }]);
    }, 700);
  };

  return (
    <div className="grid" style={{ gridTemplateColumns: '380px 1fr', gap: 24 }}>
      <div>
        <div className="phone-frame">
          <div style={{ height: 24, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <div style={{ width: 60, height: 5, background: 'rgba(255,255,255,0.1)', borderRadius: 3 }} />
          </div>
          <div className="phone-screen">
            <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border-soft)', display: 'flex', alignItems: 'center', gap: 10 }}>
              <div className="avatar" style={{ width: 30, height: 30, fontSize: 11, background: 'linear-gradient(135deg, var(--primary), #4F46E5)' }}>SB</div>
              <div>
                <div className="text-sm semi">SalesBot</div>
                <div className="text-xs text-3 mono">شبیه‌سازی • {script}</div>
              </div>
              <button className="icon-btn" style={{ width: 26, height: 26, marginRight: 'auto' }} onClick={() => setMsgs([msgs[0]])} title="ریست"><Icon name="rotate-ccw" size={12} /></button>
            </div>
            <div ref={ref} style={{ flex: 1, padding: 16, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 8 }}>
              {msgs.map((m, i) => (
                <div key={i} className={`bubble ${m.from}`} style={{ maxWidth: '85%' }}>
                  {m.text}
                  <span className="meta">{m.time}</span>
                </div>
              ))}
            </div>
            <div style={{ padding: 12, borderTop: '1px solid var(--border-soft)', display: 'flex', gap: 8, alignItems: 'center' }}>
              <input className="input" placeholder="پیامتو تایپ کن..." value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} style={{ background: 'rgba(15,15,26,0.6)', padding: '8px 12px' }} />
              <button className="icon-btn" style={{ background: 'var(--primary)', color: '#fff', border: 0 }} onClick={send}><Icon name="send" size={14} /></button>
            </div>
          </div>
        </div>
      </div>

      <div className="col gap-16">
        <div className="card">
          <div className="card-title"><Icon name="settings-2" size={15} color="var(--primary-2)" />تنظیمات شبیه‌سازی</div>
          <div className="col gap-12 mt-16">
            <div>
              <div className="label">اسکریپت فعال</div>
              <select className="select" value={script} onChange={e => setScript(e.target.value)}>
                {window.SB_DATA.SCRIPTS.map(s => <option key={s.id}>{s.name}</option>)}
              </select>
            </div>
            <div>
              <div className="label">پرسونای شبیه‌سازی شده</div>
              <select className="select" defaultValue="مدیر سختگیر">
                <option>مدیر سختگیر</option><option>فریلنسر کنجکاو</option><option>استارتاپی پرشتاب</option><option>دانشجوی مبتدی</option>
              </select>
            </div>
            <div className="row gap-8">
              <Button kind="secondary" icon="rotate-ccw" onClick={() => { setMsgs([msgs[0]]); toast('مکالمه ریست شد', 'info'); }}>ریست مکالمه</Button>
              <Button kind="ghost" icon="download">دانلود لاگ</Button>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-title"><Icon name="zap" size={15} color="#FB923C" />پیام‌های آماده برای تست</div>
          <div className="col gap-8 mt-12">
            {['سلام', 'گرونه', 'بعدا میام', 'بودجه من ۱۵ میلیونه', 'با خانواده مشورت کنم'].map(t => (
              <button key={t} className="pill" style={{ textAlign: 'right' }} onClick={() => setInput(t)}>{t}</button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

const fakeReply = (q) => {
  if (q.includes('گرونه') || q.includes('گرون')) return 'متوجه‌ام. اجازه بدید جزئیات سرمایه‌گذاری و بازگشت سرمایه رو با هم بررسی کنیم. شاگردانمون به‌طور میانگین ظرف ۳ ماه هزینه دوره رو برمی‌گردونن.';
  if (q.includes('سلام')) return 'سلام! خوش اومدی 👋\nقبل از هر چیز، هدف اصلی شما چیه؟';
  if (q.includes('بعدا')) return 'حتما. ولی توجه کنید که قیمت دوره از هفته آینده ۲۵٪ افزایش پیدا می‌کنه.';
  if (q.includes('میلیون')) return 'با این بودجه دوره کارگاه AIP بهترین گزینه برای شماست. می‌خواید جزئیات بیشتر تماس بگیریم؟';
  if (q.includes('خانواده') || q.includes('مشورت')) return 'البته. می‌تونیم یک تماس کوتاه ۱۵ دقیقه‌ای رایگان داشته باشیم تا با خانواده هم تصمیم نهایی بگیرید.';
  return 'متوجه شدم. اجازه بدید سوال دیگه‌ای بپرسم: تو چه حوزه‌ای فعالیت می‌کنید؟';
};

// ---- Population helpers ----
const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];
const weightedPersona = (weights, personas) => {
  const r = Math.random() * weights.reduce((s, w) => s + w, 0);
  let acc = 0;
  for (let i = 0; i < weights.length; i++) {
    acc += weights[i];
    if (r <= acc) return personas[i];
  }
  return personas[personas.length - 1];
};

const buildPopulation = (total, weights, personas, names1, names2, channels, cities) => {
  const people = [];
  for (let i = 0; i < total; i++) {
    const persona = weightedPersona(weights, personas);
    const [a, b] = persona.age.split('-').map(Number);
    const age = Math.floor(Math.random() * (b - a + 1)) + a;
    const budget = pick([3, 8, 12, 18, 25, 45]) * 1_000_000;
    people.push({
      id: i,
      name: pick(names1) + ' ' + pick(names2),
      persona,
      age,
      channel: pick(channels),
      city: pick(cities),
      budget,
    });
  }
  return people;
};

const PersonaTestTab = () => {
  const { Icon, Button, CategoryBadge, Modal, Field, useToast } = window.SB_UI;
  const { PERSONAS, SCRIPTS, FAKE_FIRST_NAMES, FAKE_LAST_NAMES, FAKE_CHANNELS, FAKE_CITIES, fa, faMoney } = window.SB_DATA;
  const toast = useToast();
  const [step, setStep] = useState('config'); // config | view | results
  const [total, setTotal] = useState(100);
  const [personas, setPersonas] = useState(PERSONAS);
  const [weights, setWeights] = useState(PERSONAS.map(() => 25));
  const [population, setPopulation] = useState([]);
  const [building, setBuilding] = useState(false);
  const [script, setScript] = useState(SCRIPTS[0].name);
  const [running, setRunning] = useState(false);
  const [results, setResults] = useState(null);
  const [filter, setFilter] = useState('all');
  const [addOpen, setAddOpen] = useState(false);
  const [editIdx, setEditIdx] = useState(null);

  const weightSum = weights.reduce((s, w) => s + w, 0);

  const PALETTE = ['#6C63FF', '#FF6B35', '#10B981', '#F59E0B', '#3B82F6', '#8B5CF6', '#EC4899', '#06B6D4'];
  const EMOJIS = ['👔', '🎨', '🚀', '🎓', '💼', '🧑‍💻', '🛍️', '📊', '🏢', '🎯', '🧠', '🦄', '🛠️', '📱', '💎', '🌟'];

  const upsertPersona = (data) => {
    if (editIdx !== null) {
      const nextP = [...personas]; nextP[editIdx] = { ...nextP[editIdx], ...data };
      setPersonas(nextP);
      toast('پرسونا ویرایش شد', 'success');
    } else {
      const newP = { id: Date.now(), custom: true, ...data };
      setPersonas([...personas, newP]);
      setWeights([...weights, 20]);
      toast('پرسونای جدید اضافه شد', 'success');
    }
    setAddOpen(false);
    setEditIdx(null);
  };

  const deletePersona = (i) => {
    if (personas.length <= 2) return toast('حداقل باید ۲ پرسونا داشته باشی', 'error');
    setPersonas(personas.filter((_, idx) => idx !== i));
    setWeights(weights.filter((_, idx) => idx !== i));
    toast('پرسونا حذف شد', 'info');
  };

  const build = () => {
    setBuilding(true);
    setTimeout(() => {
      const pop = buildPopulation(total, weights, personas, FAKE_FIRST_NAMES, FAKE_LAST_NAMES, FAKE_CHANNELS, FAKE_CITIES);
      setPopulation(pop);
      setBuilding(false);
      setStep('view');
      toast(`جامعه با ${fa(total)} نفر ساخته شد`, 'success');
    }, 900);
  };

  const runTest = () => {
    setRunning(true);
    setTimeout(() => {
      const enriched = population.map(p => {
        const baseConv = p.persona.custom ? 0.20 + Math.random() * 0.2 : ({ 1: 0.18, 2: 0.32, 3: 0.45, 4: 0.12 }[p.persona.id] || 0.25);
        const budgetBoost = p.budget >= 15_000_000 ? 0.15 : p.budget >= 8_000_000 ? 0.05 : -0.05;
        const channelBoost = p.channel === 'اینستاگرام' ? 0.05 : p.channel === 'دایرکت' ? 0.08 : 0;
        const score = Math.min(0.95, Math.max(0.02, baseConv + budgetBoost + channelBoost + (Math.random() - 0.5) * 0.2));
        const r = Math.random();
        let cat;
        if (r < score * 0.4) cat = 'ready';
        else if (r < score * 0.4 + score * 0.5) cat = 'warm';
        else if (r < 0.85) cat = 'cold';
        else cat = 'unfit';
        return { ...p, cat, score, messages: Math.round(6 + Math.random() * 18) };
      });
      const stats = {
        ready: enriched.filter(p => p.cat === 'ready').length,
        warm: enriched.filter(p => p.cat === 'warm').length,
        cold: enriched.filter(p => p.cat === 'cold').length,
        unfit: enriched.filter(p => p.cat === 'unfit').length,
      };
      const conv = ((stats.ready / total) * 100).toFixed(1);
      const avgMsg = (enriched.reduce((s, p) => s + p.messages, 0) / total).toFixed(1);
      setResults({ people: enriched, stats, conv, avgMsg });
      setRunning(false);
      setStep('results');
      toast(`تست روی ${fa(total)} نفر کامل شد`, 'success');
    }, 1600);
  };

  return (
    <div className="col gap-16">
      {/* Stepper */}
      <div className="row gap-12" style={{ padding: '4px 0' }}>
        <Stepper n="۱" label="ساخت جامعه" active={step === 'config'} done={step !== 'config'} />
        <StepLine done={step !== 'config'} />
        <Stepper n="۲" label="مشاهده جامعه" active={step === 'view'} done={step === 'results'} />
        <StepLine done={step === 'results'} />
        <Stepper n="۳" label="اجرا و نتایج" active={step === 'results'} done={false} />
      </div>

      {step === 'config' && (
        <div className="card">
          <div className="row between" style={{ alignItems: 'flex-start' }}>
            <div>
              <div className="bold" style={{ fontSize: 15 }}>ساخت جامعه آزمایشی</div>
              <div className="text-xs text-3 mt-4">اول تعداد نفرات و توزیع پرسوناها رو مشخص کن، بعد جامعه ساخته می‌شه.</div>
            </div>
            <div className="row gap-8">
              {[10, 50, 100, 500, 1000].map(n => (
                <button key={n} className={`pill ${total === n ? 'active' : ''}`} onClick={() => setTotal(n)}>{fa(n)}</button>
              ))}
            </div>
          </div>

          <div className="divider"></div>

          <div className="label">تعداد کل نفرات: <span className="mono bold" style={{ color: 'var(--primary-2)' }}>{fa(total)}</span> نفر</div>
          <input type="range" min={10} max={1000} step={10} value={total} onChange={e => setTotal(Number(e.target.value))}
            style={{ width: '100%', accentColor: '#6C63FF' }} />
          <div className="row between text-xs text-3 mono mt-4"><span>{fa(10)}</span><span>{fa(250)}</span><span>{fa(500)}</span><span>{fa(750)}</span><span>{fa(1000)}</span></div>

          <div className="divider"></div>

          <div className="row between">
            <div className="label" style={{ margin: 0 }}>توزیع پرسوناها</div>
            <div className="row gap-8">
              <button className="pill" onClick={() => setWeights(personas.map(() => 25))}>یکنواخت</button>
              <button className="pill" onClick={() => { const n = personas.length; const arr = [40, 30, 20, 10]; setWeights(personas.map((_, i) => arr[i] ?? 5)); }}>واقع‌گرایانه</button>
              <button className="pill" onClick={() => setWeights(personas.map(() => Math.round(Math.random() * 40 + 10)))}>تصادفی</button>
              <Button kind="primary" size="sm" icon="plus" onClick={() => { setEditIdx(null); setAddOpen(true); }}>پرسونای جدید</Button>
            </div>
          </div>

          <div className="col gap-12 mt-12">
            {personas.map((p, i) => {
              const pct = weightSum > 0 ? Math.round((weights[i] / weightSum) * 100) : 0;
              const planned = Math.round((weights[i] / weightSum) * total);
              return (
                <div key={p.id} className="row gap-16" style={{ padding: 12, background: 'rgba(15,15,26,0.4)', border: '1px solid var(--border-soft)', borderRadius: 12 }}>
                  <div style={{ width: 38, height: 38, borderRadius: 50, background: `linear-gradient(135deg, ${p.color}, ${p.color}66)`, display: 'grid', placeItems: 'center', fontSize: 18, flexShrink: 0 }}>{p.emoji}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="row between">
                      <div className="row gap-8">
                        <span className="text-sm semi">{p.name}</span>
                        {p.custom && <span className="badge sold solid" style={{ fontSize: 10, background: 'rgba(255,107,53,0.16)', color: '#FB923C' }}>سفارشی</span>}
                      </div>
                      <span className="mono text-xs"><span className="bold" style={{ color: p.color }}>{fa(pct)}%</span><span className="text-3"> • {fa(planned)} نفر</span></span>
                    </div>
                    <input type="range" min={0} max={100} step={5} value={weights[i]} onChange={e => {
                      const next = [...weights]; next[i] = Number(e.target.value); setWeights(next);
                    }} style={{ width: '100%', accentColor: p.color, marginTop: 6 }} />
                  </div>
                  <div className="col gap-4">
                    <button className="icon-btn" style={{ width: 28, height: 28 }} onClick={() => { setEditIdx(i); setAddOpen(true); }} title="ویرایش"><Icon name="edit-3" size={12} /></button>
                    <button className="icon-btn" style={{ width: 28, height: 28 }} onClick={() => deletePersona(i)} title="حذف"><Icon name="trash-2" size={12} color="#F87171" /></button>
                  </div>
                </div>
              );
            })}
          </div>

          <div className="row gap-8 mt-24" style={{ justifyContent: 'flex-end' }}>
            <Button kind="ghost" onClick={() => { setTotal(100); setWeights(personas.map(() => 25)); }}>پیش‌فرض</Button>
            <Button kind="primary" icon="sparkles" loading={building} onClick={build}>{building ? 'در حال ساخت...' : `بساز جامعه (${fa(total)} نفر)`}</Button>
          </div>

          <PersonaModal
            open={addOpen}
            onClose={() => { setAddOpen(false); setEditIdx(null); }}
            initial={editIdx !== null ? personas[editIdx] : null}
            palette={PALETTE}
            emojis={EMOJIS}
            onSave={upsertPersona}
          />
        </div>
      )}

      {step === 'view' && (
        <PopulationView population={population} script={script} setScript={setScript} runTest={runTest} running={running} back={() => setStep('config')} filter={filter} setFilter={setFilter} personas={personas} />
      )}

      {step === 'results' && results && (
        <Results results={results} total={total} back={() => setStep('view')} rerun={runTest} personas={personas} />
      )}
    </div>
  );
};

const PersonaModal = ({ open, onClose, initial, palette, emojis, onSave }) => {
  const { Modal, Field, Button, Icon } = window.SB_UI;
  const [name, setName] = useState('');
  const [emoji, setEmoji] = useState('🧑');
  const [ageMin, setAgeMin] = useState(25);
  const [ageMax, setAgeMax] = useState(40);
  const [traits, setTraits] = useState('');
  const [color, setColor] = useState(palette[0]);

  useEffect(() => {
    if (open) {
      if (initial) {
        setName(initial.name);
        setEmoji(initial.emoji);
        const [a, b] = (initial.age || '25-40').split('-').map(Number);
        setAgeMin(a); setAgeMax(b);
        setTraits(initial.traits || '');
        setColor(initial.color || palette[0]);
      } else {
        setName(''); setEmoji('🧑'); setAgeMin(25); setAgeMax(40); setTraits(''); setColor(palette[Math.floor(Math.random() * palette.length)]);
      }
    }
  }, [open]);

  const submit = () => {
    if (!name.trim()) return;
    onSave({ name, emoji, age: `${ageMin}-${ageMax}`, traits, color });
  };

  return (
    <Modal open={open} onClose={onClose} title={initial ? 'ویرایش پرسونا' : 'پرسونای جدید'} width={580} footer={
      <>
        <Button kind="primary" onClick={submit} icon={initial ? 'save' : 'plus'}>{initial ? 'ذخیره تغییرات' : 'افزودن پرسونا'}</Button>
        <Button kind="ghost" onClick={onClose}>انصراف</Button>
      </>
    }>
      <div className="col gap-16">
        {/* Preview */}
        <div className="row gap-16" style={{ padding: 16, background: 'rgba(15,15,26,0.5)', border: '1px solid var(--border-soft)', borderRadius: 12, alignItems: 'center' }}>
          <div style={{ width: 56, height: 56, borderRadius: 50, background: `linear-gradient(135deg, ${color}, ${color}66)`, display: 'grid', placeItems: 'center', fontSize: 26, flexShrink: 0, boxShadow: `0 4px 16px ${color}55` }}>{emoji}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="bold text-sm">{name || 'پرسونای بدون اسم'}</div>
            <div className="text-xs text-3 mono mt-4">سن: {ageMin}-{ageMax}</div>
            <div className="text-xs text-2 mt-4" style={{ lineHeight: 1.6 }}>{traits || 'توضیحات خصوصیات...'}</div>
          </div>
        </div>

        <Field label="نام پرسونا">
          <input className="input" placeholder="مثلا «مدیر مالی محتاط»" value={name} onChange={e => setName(e.target.value)} />
        </Field>

        <Field label="ایموجی نشانگر">
          <div className="row gap-6" style={{ flexWrap: 'wrap' }}>
            {emojis.map(e => (
              <button key={e} onClick={() => setEmoji(e)}
                style={{
                  width: 40, height: 40, borderRadius: 10,
                  border: `1px solid ${emoji === e ? 'var(--primary)' : 'var(--border-soft)'}`,
                  background: emoji === e ? 'var(--primary-soft)' : 'rgba(15,15,26,0.4)',
                  fontSize: 18, cursor: 'pointer',
                }}>{e}</button>
            ))}
            <input className="input" value={emoji} onChange={e => setEmoji(e.target.value.slice(0, 2))} style={{ width: 70, textAlign: 'center', fontSize: 18 }} placeholder="✨" />
          </div>
        </Field>

        <div className="grid grid-2 gap-12">
          <Field label={`حداقل سن: ${ageMin}`}>
            <input type="range" min={15} max={70} step={1} value={ageMin} onChange={e => setAgeMin(Math.min(ageMax - 1, Number(e.target.value)))}
              style={{ width: '100%', accentColor: color }} />
          </Field>
          <Field label={`حداکثر سن: ${ageMax}`}>
            <input type="range" min={16} max={80} step={1} value={ageMax} onChange={e => setAgeMax(Math.max(ageMin + 1, Number(e.target.value)))}
              style={{ width: '100%', accentColor: color }} />
          </Field>
        </div>

        <Field label="خصوصیات (با ، جدا کن)">
          <textarea className="textarea" rows={2} placeholder="تصمیم‌گیر، نتیجه‌محور، بدبین به تبلیغ" value={traits} onChange={e => setTraits(e.target.value)} />
        </Field>

        <Field label="رنگ نشانگر">
          <div className="row gap-8">
            {palette.map(c => (
              <button key={c} onClick={() => setColor(c)}
                style={{
                  width: 34, height: 34, borderRadius: 10,
                  background: c,
                  border: `2px solid ${color === c ? '#fff' : 'transparent'}`,
                  boxShadow: color === c ? `0 0 0 2px ${c}` : 'none',
                  cursor: 'pointer',
                }} />
            ))}
          </div>
        </Field>
      </div>
    </Modal>
  );
};

const Stepper = ({ n, label, active, done }) => (
  <div className="row gap-10">
    <div style={{
      width: 28, height: 28, borderRadius: 50,
      background: done ? 'linear-gradient(135deg, #10B981, #34D399)' : active ? 'linear-gradient(135deg, var(--primary), #4F46E5)' : 'rgba(255,255,255,0.04)',
      border: '1px solid ' + (active || done ? 'transparent' : 'var(--border-soft)'),
      display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700,
      color: active || done ? '#fff' : 'var(--text-3)',
      boxShadow: active ? '0 0 12px var(--primary-glow)' : 'none',
    }}>{done ? <window.SB_UI.Icon name="check" size={12} strokeWidth={3} /> : n}</div>
    <span className="text-sm semi" style={{ color: active || done ? 'var(--text)' : 'var(--text-3)' }}>{label}</span>
  </div>
);
const StepLine = ({ done }) => <div style={{ flex: 1, height: 1, background: done ? 'linear-gradient(90deg, #10B981, transparent)' : 'var(--border-soft)' }} />;

const PopulationView = ({ population, script, setScript, runTest, running, back, filter, setFilter, personas }) => {
  const { Icon, Button } = window.SB_UI;
  const { SCRIPTS, fa, faMoney } = window.SB_DATA;
  const visible = filter === 'all' ? population : population.filter(p => p.persona.id === filter);

  const byPersona = personas.map(p => ({ p, n: population.filter(x => x.persona.id === p.id).length }));
  const byChannel = [...new Set(population.map(p => p.channel))].map(ch => ({ ch, n: population.filter(p => p.channel === ch).length }));

  return (
    <>
      <div className="card">
        <div className="row between">
          <div>
            <div className="bold" style={{ fontSize: 15 }}>جامعه ساخته شده — {fa(population.length)} نفر</div>
            <div className="text-xs text-3 mt-4">می‌تونی روی هر نفر کلیک کنی تا جزئیاتش رو ببینی، یا مستقیم تست رو اجرا کنی.</div>
          </div>
          <Button kind="ghost" icon="arrow-right" onClick={back}>برگشت به تنظیمات</Button>
        </div>

        <div className="grid grid-2 gap-16 mt-16">
          <div style={{ padding: 14, background: 'rgba(15,15,26,0.4)', border: '1px solid var(--border-soft)', borderRadius: 12 }}>
            <div className="text-xs text-3 semi" style={{ textTransform: 'uppercase', letterSpacing: 0.04, marginBottom: 10 }}>توزیع پرسونا</div>
            <div className="col gap-10">
              {byPersona.map(({ p, n }) => {
                const pct = (n / population.length) * 100;
                return (
                  <div key={p.id}>
                    <div className="row between">
                      <div className="row gap-8">
                        <span style={{ width: 18, height: 18, borderRadius: 50, background: `linear-gradient(135deg, ${p.color}, ${p.color}66)`, display: 'grid', placeItems: 'center', fontSize: 10 }}>{p.emoji}</span>
                        <span className="text-sm">{p.name}</span>
                      </div>
                      <span className="mono text-sm semi">{fa(n)} <span className="text-3 text-xs">({pct.toFixed(0)}%)</span></span>
                    </div>
                    <div className="bar mt-4"><div style={{ width: pct + '%', height: '100%', background: p.color, borderRadius: 999 }} /></div>
                  </div>
                );
              })}
            </div>
          </div>
          <div style={{ padding: 14, background: 'rgba(15,15,26,0.4)', border: '1px solid var(--border-soft)', borderRadius: 12 }}>
            <div className="text-xs text-3 semi" style={{ textTransform: 'uppercase', letterSpacing: 0.04, marginBottom: 10 }}>توزیع کانال</div>
            <div className="col gap-10">
              {byChannel.map(({ ch, n }) => {
                const pct = (n / population.length) * 100;
                return (
                  <div key={ch}>
                    <div className="row between">
                      <span className="text-sm">{ch}</span>
                      <span className="mono text-sm semi">{fa(n)} <span className="text-3 text-xs">({pct.toFixed(0)}%)</span></span>
                    </div>
                    <div className="bar mt-4"><div className="bar-fill" style={{ width: pct + '%' }} /></div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <div className="divider"></div>

        <div className="row between">
          <div className="row gap-8" style={{ flexWrap: 'wrap' }}>
            <button className={`pill ${filter === 'all' ? 'active' : ''}`} onClick={() => setFilter('all')}>همه<span className="count mono">{fa(population.length)}</span></button>
            {personas.map(p => {
              const n = population.filter(x => x.persona.id === p.id).length;
              return <button key={p.id} className={`pill ${filter === p.id ? 'active' : ''}`} onClick={() => setFilter(p.id)}>{p.emoji} {p.name}<span className="count mono">{fa(n)}</span></button>;
            })}
          </div>
        </div>

        <div className="grid grid-3 mt-16" style={{ maxHeight: 360, overflowY: 'auto', paddingLeft: 4 }}>
          {visible.slice(0, 60).map(p => (
            <div key={p.id} className="row gap-12" style={{ padding: 12, background: 'rgba(15,15,26,0.5)', border: '1px solid var(--border-soft)', borderRadius: 10, alignItems: 'center' }}>
              <div style={{ width: 36, height: 36, borderRadius: 50, background: `linear-gradient(135deg, ${p.persona.color}, ${p.persona.color}66)`, display: 'grid', placeItems: 'center', fontSize: 16, flexShrink: 0 }}>{p.persona.emoji}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="text-sm semi" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</div>
                <div className="text-xs text-3 mono" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{fa(p.age)} • {p.city} • {p.channel}</div>
                <div className="text-xs text-3 mono mt-4">بودجه: {faMoney(p.budget / 1_000_000)}M</div>
              </div>
            </div>
          ))}
        </div>
        {visible.length > 60 && (
          <div className="text-xs text-3 mt-12" style={{ textAlign: 'center' }}>{fa(visible.length - 60)} نفر دیگه — برای دیدن همه از خروجی CSV استفاده کن</div>
        )}
      </div>

      <div className="card">
        <div className="row between gap-16" style={{ flexWrap: 'wrap' }}>
          <div style={{ flex: 1, minWidth: 200 }}>
            <div className="label">اسکریپت برای تست</div>
            <select className="select" value={script} onChange={e => setScript(e.target.value)}>
              {SCRIPTS.map(s => <option key={s.id}>{s.name}</option>)}
            </select>
          </div>
          <div className="row gap-8" style={{ alignSelf: 'flex-end' }}>
            <Button kind="ghost" icon="download">خروجی CSV جامعه</Button>
            <Button kind="primary" icon="play" loading={running} onClick={runTest}>{running ? 'در حال تست...' : `اجرای تست روی ${fa(population.length)} نفر`}</Button>
          </div>
        </div>
      </div>
    </>
  );
};

const Results = ({ results, total, back, rerun, personas }) => {
  const { Icon, Button, CategoryBadge, Donut } = window.SB_UI;
  const { fa } = window.SB_DATA;
  const segs = [
    { value: results.stats.ready, color: '#10B981', label: 'آماده' },
    { value: results.stats.warm, color: '#F59E0B', label: 'گرم' },
    { value: results.stats.cold, color: '#3B82F6', label: 'سرد' },
    { value: results.stats.unfit, color: '#6B7280', label: 'نامناسب' },
  ];

  // Per-persona breakdown
  const byPersona = personas.map(p => {
    const subset = results.people.filter(x => x.persona.id === p.id);
    const n = subset.length;
    return {
      p,
      n,
      ready: subset.filter(x => x.cat === 'ready').length,
      warm: subset.filter(x => x.cat === 'warm').length,
      cold: subset.filter(x => x.cat === 'cold').length,
      unfit: subset.filter(x => x.cat === 'unfit').length,
      readyPct: n === 0 ? 0 : Math.round((subset.filter(x => x.cat === 'ready').length / n) * 100),
    };
  });

  return (
    <>
      <div className="card" style={{ background: 'linear-gradient(135deg, rgba(108,99,255,0.12), rgba(16,185,129,0.08))', border: '1px solid rgba(108,99,255,0.3)' }}>
        <div className="row between">
          <div>
            <div className="row gap-8">
              <Icon name="check-circle-2" size={18} color="#34D399" />
              <span className="bold" style={{ fontSize: 15 }}>تست با موفقیت کامل شد</span>
            </div>
            <div className="text-xs text-3 mt-4">{fa(total)} نفر تست شدن • زمان: {fa(2)} دقیقه و {fa(14)} ثانیه</div>
          </div>
          <div className="row gap-8">
            <Button kind="ghost" icon="arrow-right" onClick={back}>برگشت</Button>
            <Button kind="secondary" icon="rotate-ccw" onClick={rerun}>اجرای مجدد</Button>
            <Button kind="primary" icon="download">دانلود گزارش کامل</Button>
          </div>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1fr 2fr', gap: 16 }}>
        <div className="card">
          <div className="card-title"><Icon name="pie-chart" size={15} color="var(--primary-2)" />نتیجه کلی</div>
          <div style={{ position: 'relative', margin: '16px auto', width: 'fit-content' }}>
            <Donut segments={segs} size={160} stroke={22} />
            <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', textAlign: 'center' }}>
              <div>
                <div className="text-xs text-3">نرخ تبدیل</div>
                <div className="bold" style={{ fontSize: 22, color: '#34D399' }}>{fa(results.conv)}%</div>
              </div>
            </div>
          </div>
          <div className="col gap-8 mt-8">
            {segs.map(s => (
              <div key={s.label} className="row between">
                <div className="row gap-8"><span style={{ width: 10, height: 10, background: s.color, borderRadius: 3 }} /><span className="text-sm">{s.label}</span></div>
                <span className="mono semi">{fa(s.value)}</span>
              </div>
            ))}
            <div className="divider" style={{ margin: '4px 0' }}></div>
            <div className="row between"><span className="text-xs text-3">میانگین تعداد پیام</span><span className="mono semi">{fa(results.avgMsg)}</span></div>
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <div className="card-title"><Icon name="bar-chart-3" size={15} color="var(--primary-2)" />تفکیک بر اساس پرسونا</div>
            <Button kind="ghost" size="sm" icon="download">CSV</Button>
          </div>
          <table className="table">
            <thead><tr><th>پرسونا</th><th>تعداد</th><th>آماده</th><th>گرم</th><th>سرد</th><th>نامناسب</th><th>نرخ آماده</th></tr></thead>
            <tbody>
              {byPersona.filter(r => r.n > 0).map(r => (
                <tr key={r.p.id}>
                  <td>
                    <div className="row gap-10">
                      <div style={{ width: 26, height: 26, borderRadius: 50, background: `linear-gradient(135deg, ${r.p.color}, ${r.p.color}66)`, display: 'grid', placeItems: 'center', fontSize: 12 }}>{r.p.emoji}</div>
                      <span className="semi text-sm">{r.p.name}</span>
                    </div>
                  </td>
                  <td className="mono">{fa(r.n)}</td>
                  <td><span className="mono" style={{ color: '#34D399' }}>{fa(r.ready)}</span></td>
                  <td><span className="mono" style={{ color: '#FBBF24' }}>{fa(r.warm)}</span></td>
                  <td><span className="mono" style={{ color: '#60A5FA' }}>{fa(r.cold)}</span></td>
                  <td><span className="mono text-3">{fa(r.unfit)}</span></td>
                  <td>
                    <div className="col gap-4" style={{ minWidth: 100 }}>
                      <span className="mono text-xs semi" style={{ color: '#34D399' }}>{fa(r.readyPct)}%</span>
                      <div className="bar"><div className="bar-fill green" style={{ width: r.readyPct + '%' }} /></div>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="card">
        <div className="card-head">
          <div className="card-title"><Icon name="list" size={15} color="var(--primary-2)" />تک‌تک نتایج (نمونه)</div>
          <span className="text-xs text-3">نمایش ۱۲ نفر اول. خروجی کامل CSV دانلود کن.</span>
        </div>
        <div className="grid grid-3 gap-12">
          {results.people.slice(0, 12).map(p => (
            <div key={p.id} className="row gap-12" style={{ padding: 12, background: 'rgba(15,15,26,0.5)', border: '1px solid var(--border-soft)', borderRadius: 10 }}>
              <div style={{ width: 32, height: 32, borderRadius: 50, background: `linear-gradient(135deg, ${p.persona.color}, ${p.persona.color}66)`, display: 'grid', placeItems: 'center', fontSize: 14, flexShrink: 0 }}>{p.persona.emoji}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="row between">
                  <span className="text-sm semi" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</span>
                  <CategoryBadge cat={p.cat} />
                </div>
                <div className="text-xs text-3 mono mt-4">{p.channel} • {fa(p.messages)} پیام</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

const CompareTab = () => {
  const { Icon, Button, BarH } = window.SB_UI;
  const { fa } = window.SB_DATA;
  const metrics = [
    { label: 'نرخ تبدیل', a: 24, b: 31, max: 40, unit: '٪' },
    { label: 'میانگین پیام', a: 12, b: 15, max: 20, unit: '' },
    { label: 'نرخ دراپ', a: 18, b: 12, max: 30, unit: '٪' },
    { label: 'مدت مکالمه', a: 9.5, b: 11.2, max: 15, unit: ' دقیقه' },
  ];

  return (
    <div className="grid grid-2 gap-16">
      {[
        { side: 'a', name: 'اسکریپت A — پیش‌فرض', color: '#6C63FF', winner: false },
        { side: 'b', name: 'اسکریپت B — جدید', color: '#FF6B35', winner: true },
      ].map(s => (
        <div key={s.side} className={`ab-col ${s.side}`} style={{ borderTopColor: s.color }}>
          <div className="row between">
            <div className="bold">{s.name}</div>
            {s.winner && <span className="badge ready">برنده ✓</span>}
          </div>
          <div className="col gap-16 mt-16">
            {metrics.map(m => (
              <BarH key={m.label} label={m.label} value={s.side === 'a' ? m.a : m.b} max={m.max} color={s.color}
                right={`${fa(s.side === 'a' ? m.a : m.b)}${m.unit}`} />
            ))}
          </div>
          <div className="divider"></div>
          <div className="text-xs text-3 mb-8">نمونه پیام:</div>
          <div className="text-sm" style={{ padding: 12, background: 'rgba(15,15,26,0.5)', borderRadius: 10, lineHeight: 1.8 }}>
            {s.side === 'a'
              ? '«بودجه‌ای که برای این موضوع در نظر گرفتید چقدره؟»'
              : '«برای رسیدن به هدفت چقدر سرمایه‌گذاری در نظر داری؟»'}
          </div>
        </div>
      ))}
      <div className="card" style={{ gridColumn: '1 / -1' }}>
        <div className="row between">
          <div>
            <div className="bold">نتیجه تست</div>
            <div className="text-xs text-3 mt-4">اسکریپت B در ۳ از ۴ معیار برتری داره</div>
          </div>
          <div className="row gap-8">
            <Button kind="secondary">دانلود گزارش</Button>
            <Button kind="primary" icon="check">انتخاب اسکریپت B</Button>
          </div>
        </div>
      </div>
    </div>
  );
};

const CampaignTestTab = () => {
  const { Icon, Button } = window.SB_UI;
  const { CAMPAIGNS, fa } = window.SB_DATA;
  const [keyword, setKeyword] = useState('تابستان');
  const matched = CAMPAIGNS.find(c => c.keyword === keyword && c.active);

  return (
    <div className="card">
      <div className="card-head">
        <div>
          <div className="card-title"><Icon name="zap" size={15} color="var(--primary-2)" />تست تشخیص کمپین</div>
          <div className="card-sub mt-4">یک کلمه کلیدی وارد کن تا ببینی کدوم کمپین فعال می‌شه.</div>
        </div>
      </div>
      <div className="row gap-12">
        <input className="input mono" placeholder="کلمه کلیدی..." value={keyword} onChange={e => setKeyword(e.target.value)} style={{ flex: 1 }} />
        <Button kind="primary" icon="search">جستجو</Button>
      </div>
      <div className="mt-24">
        {matched ? (
          <div className="card" style={{ background: 'rgba(16,185,129,0.06)', border: '1px solid rgba(16,185,129,0.3)' }}>
            <div className="row gap-12">
              <div style={{ width: 44, height: 44, borderRadius: 10, background: 'rgba(16,185,129,0.16)', display: 'grid', placeItems: 'center' }}>
                <Icon name="check-circle-2" size={22} color="#34D399" />
              </div>
              <div style={{ flex: 1 }}>
                <div className="text-xs text-3">کمپین فعال:</div>
                <div className="bold mt-4" style={{ fontSize: 16 }}>{matched.name}</div>
                <div className="row gap-16 mt-12 text-xs text-2">
                  <span><span className="text-3">کلمه: </span><span className="kbd-key">#{matched.keyword}</span></span>
                  <span><span className="text-3">تا تاریخ: </span><span className="mono">{matched.end}</span></span>
                  <span><span className="text-3">Trigger: </span><span className="mono semi">{fa(matched.triggers)}</span></span>
                </div>
              </div>
              <Button kind="ghost" size="sm" icon="arrow-left">جزئیات</Button>
            </div>
          </div>
        ) : (
          <div className="card" style={{ background: 'rgba(245,158,11,0.06)', border: '1px solid rgba(245,158,11,0.3)' }}>
            <div className="row gap-12">
              <div style={{ width: 44, height: 44, borderRadius: 10, background: 'rgba(245,158,11,0.16)', display: 'grid', placeItems: 'center' }}>
                <Icon name="alert-triangle" size={22} color="#FBBF24" />
              </div>
              <div>
                <div className="bold">کمپینی فعال نمی‌شه</div>
                <div className="text-xs text-3 mt-4">برای این کلمه کلیدی هیچ کمپین فعالی پیدا نشد. اسکریپت پیش‌فرض اجرا می‌شه.</div>
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="text-xs text-3 mt-24" style={{ marginBottom: 8 }}>کلمات کلیدی فعال:</div>
      <div className="row gap-8" style={{ flexWrap: 'wrap' }}>
        {CAMPAIGNS.filter(c => c.active).map(c => (
          <button key={c.id} className="pill" onClick={() => setKeyword(c.keyword)}>
            <span className="kbd-key">#{c.keyword}</span>&nbsp;{c.name}
          </button>
        ))}
      </div>
    </div>
  );
};

window.Lab = Lab;
