// Products page — connected to API with seller assignment
const Products = () => {
  const { Icon, useToast } = window.SB_UI;
  const { fa, faMoney } = window.SB_DATA;
  const { useState, useEffect } = React;
  const toast = useToast();
  const token = localStorage.getItem(window.TOKEN_KEY);
  const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` };

  const [tab,       setTab]       = useState('sale');   // 'sale' | 'prize'
  const [items,     setItems]     = useState([]);
  const [sellers,   setSellers]   = useState([]);
  const [loading,   setLoading]   = useState(true);
  const [open,      setOpen]      = useState(false);
  const [editItem,  setEditItem]  = useState(null); // null=بستن, 'new'=جدید, object=ویرایش
  const [form,      setForm]      = useState({ name: '', desc: '', price: '', type: 'online', tags: '', color: '#6366F1', category: '', avg_value: '' });
  const [saving,    setSaving]    = useState(false);
  const [spModal,    setSpModal]    = useState(null);  // محصولی که داریم فروشنده‌هاش رو مدیریت می‌کنیم
  const [spSellers,  setSpSellers]  = useState([]);
  const [pzModal,    setPzModal]    = useState(null);  // محصول فروشی که داریم جوایزش رو مدیریت می‌کنیم
  const [allPrizes,  setAllPrizes]  = useState([]);   // همه محصولات is_prize=1
  const [linkedPrizes, setLinkedPrizes] = useState([]); // جوایز لینک‌شده به pzModal

  const COLORS = ['#6366F1','#34D399','#F59E0B','#38BDF8','#F472B6','#A78BFA','#FB923C','#F87171'];
  const isPrize = tab === 'prize';

  const load = (currentTab) => {
    const t = currentTab ?? tab;
    setLoading(true);
    const prizeParam = t === 'prize' ? '?prize=1' : '?prize=0';
    Promise.all([
      fetch(`/api/market/products${prizeParam}`, { headers }).then(r => r.json()),
      fetch('/api/market/sellers',  { headers }).then(r => r.json()),
    ]).then(([pd, sd]) => {
      if (pd.success) setItems(pd.data.products || []);
      else setItems([]);
      if (sd.success) setSellers(sd.data.sellers || []);
      setLoading(false);
    }).catch(() => {
      setItems([]);
      setLoading(false);
    });
  };
  useEffect(() => { load(tab); }, [tab]);

  const openNew = () => {
    setForm({ name: '', desc: '', price: isPrize ? '' : '', type: 'online', tags: '', color: isPrize ? '#F59E0B' : '#6366F1', category: '', avg_value: '', list_price: '' });
    setEditItem('new');
    setOpen(true);
  };

  const openEdit = (p) => {
    setForm({
      name: p.name || '', desc: p.desc || p.description || '', price: p.price != null ? String(p.price) : '',
      type: p.type || 'online', tags: Array.isArray(p.tags) ? p.tags.join('، ') : (p.tags || ''),
      color: p.color || '#6366F1', category: p.category || '', avg_value: p.avg_value != null ? String(p.avg_value) : '',
      list_price: p.list_price != null ? String(p.list_price) : '',
    });
    setEditItem(p);
    setOpen(true);
  };

  const submit = () => {
    if (!form.name) return toast('نام محصول الزامی است', 'error');
    setSaving(true);
    const body = {
      name: form.name, desc: form.desc, price: Number(form.price) || 0,
      type: form.type, color: form.color, category: form.category,
      avg_value: Number(form.avg_value) || 0,
      list_price: Number(form.list_price) || 0,
      tags: form.tags.split(/[،,]/).map(t => t.trim()).filter(Boolean),
      is_active: 1,
      is_prize: isPrize ? 1 : 0,
    };

    const isNew = editItem === 'new';
    const url   = isNew ? '/api/market/products' : `/api/market/products/${editItem.id}`;
    fetch(url, { method: isNew ? 'POST' : 'PUT', headers, body: JSON.stringify(body) })
      .then(r => r.json()).then(d => {
        setSaving(false);
        if (d.success) {
          toast(isNew ? 'محصول اضافه شد' : 'ذخیره شد', 'success');
          setOpen(false); setEditItem(null); load();
        } else {
          // اگر API وجود نداره، به‌صورت محلی ذخیره کن
          if (isNew) {
            setItems(prev => [{ id: Date.now(), ...body, tags: body.tags, active: true }, ...prev]);
            toast('محصول اضافه شد', 'success');
          } else {
            setItems(prev => prev.map(p => p.id === editItem.id ? { ...p, ...body } : p));
            toast('ذخیره شد', 'success');
          }
          setOpen(false); setEditItem(null);
        }
      })
      .catch(() => {
        setSaving(false);
        if (isNew) {
          setItems(prev => [{ id: Date.now(), ...body, tags: body.tags, active: true }, ...prev]);
          toast('محصول اضافه شد (حالت آفلاین)', 'success');
        }
        setOpen(false); setEditItem(null);
      });
  };

  const toggleActive = (p) => {
    fetch(`/api/market/products/${p.id}`, { method: 'PUT', headers, body: JSON.stringify({ is_active: p.is_active ? 0 : 1 }) })
      .then(r => r.json()).then(d => {
        if (d.success) load();
        else setItems(prev => prev.map(x => x.id === p.id ? { ...x, active: !x.active, is_active: x.is_active ? 0 : 1 } : x));
      }).catch(() => {
        setItems(prev => prev.map(x => x.id === p.id ? { ...x, active: !x.active } : x));
      });
  };

  const deleteProduct = (p) => {
    if (!confirm(`محصول "${p.name}" حذف شود؟`)) return;
    fetch(`/api/market/products/${p.id}`, { method: 'DELETE', headers })
      .then(r => r.json()).then(d => {
        if (d.success) { toast('حذف شد', 'success'); load(); }
        else toast(d.message || 'خطا', 'error');
      }).catch(() => {
        setItems(prev => prev.filter(x => x.id !== p.id));
        toast('حذف شد', 'success');
      });
  };

  const openSp = (prod) => {
    setSpModal(prod);
    setSpSellers(sellers.map(s => ({
      ...s,
      assigned: (s.products || []).some(pp => pp.id === prod.id),
      level:    (s.products || []).find(pp => pp.id === prod.id)?.sp_level || 'junior',
    })));
  };

  const PROD_LEVEL = { junior: 'مبتدی', senior: 'ارشد', expert: 'متخصص' };

  const toggleSp = (prod, seller, newLevel) => {
    const already = seller.assigned;
    const url  = already ? `/api/market/sellers/${seller.id}/products/${prod.id}` : `/api/market/sellers/${seller.id}/products`;
    const meth = already ? 'DELETE' : 'POST';
    const body = already ? undefined : JSON.stringify({ product_id: prod.id, level: newLevel || 'junior' });
    fetch(url, { method: meth, headers, body })
      .then(r => r.json()).then(d => {
        if (d.success) {
          load();
          setSpSellers(prev => prev.map(s => s.id === seller.id ? { ...s, assigned: !already, level: newLevel || 'junior' } : s));
        } else toast(d.message || 'خطا', 'error');
      });
  };

  const changeSpLevel = (prod, seller, level) => {
    fetch(`/api/market/sellers/${seller.id}/products`, { method: 'POST', headers, body: JSON.stringify({ product_id: prod.id, level }) })
      .then(r => r.json()).then(d => {
        if (d.success) {
          load();
          setSpSellers(prev => prev.map(s => s.id === seller.id ? { ...s, level } : s));
        }
      });
  };

  const openPzModal = (prod) => {
    setPzModal(prod);
    Promise.all([
      fetch('/api/market/products?prize=1', { headers }).then(r => r.json()),
      fetch(`/api/market/products/${prod.id}/prizes`, { headers }).then(r => r.json()),
    ]).then(([allD, linkedD]) => {
      setAllPrizes(allD.data?.products || allD.products || []);
      setLinkedPrizes((linkedD.data?.prizes || linkedD.prizes || []).map(p => p.id));
    }).catch(() => {});
  };

  const togglePrizeLink = (prod, prizeId, currentlyLinked) => {
    const url = currentlyLinked
      ? `/api/market/products/${prod.id}/prizes/${prizeId}`
      : `/api/market/products/${prod.id}/prizes`;
    const method = currentlyLinked ? 'DELETE' : 'POST';
    const body = currentlyLinked ? undefined : JSON.stringify({ prize_product_id: prizeId });
    fetch(url, { method, headers, body })
      .then(r => r.json()).then(d => {
        if (d.success || d.ok) {
          setLinkedPrizes(prev => currentlyLinked ? prev.filter(id => id !== prizeId) : [...prev, prizeId]);
          load();
        } else toast(d.message || 'خطا', 'error');
      });
  };

  const isActive = (p) => p.is_active !== undefined ? p.is_active : p.active;

  const tabColor = isPrize ? '#F59E0B' : '#6366F1';
  const tabBtnStyle = (t) => ({
    padding: '7px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', fontWeight: 600,
    border: tab === t ? `1.5px solid ${t === 'prize' ? '#F59E0B' : '#6366F1'}` : '1.5px solid rgba(255,255,255,.08)',
    background: tab === t ? (t === 'prize' ? 'rgba(245,158,11,.13)' : 'rgba(99,102,241,.13)') : 'transparent',
    color: tab === t ? (t === 'prize' ? '#F59E0B' : '#818CF8') : '#64748b',
    transition: 'all .15s',
  });

  return (
    <div>
      {/* ── تب‌بندی ── */}
      <div className="row gap-8" style={{ marginBottom: 18 }}>
        <button style={tabBtnStyle('sale')} onClick={() => setTab('sale')}>📦 محصولات فروش</button>
        <button style={tabBtnStyle('prize')} onClick={() => setTab('prize')}>🎁 محصولات جوایز</button>
      </div>

      {/* ── سرصفحه ── */}
      <div className="row between">
        <div className="row gap-8">
          <span className="text-2 text-sm">
            {loading ? '...' : `${fa(items.length)} ${isPrize ? 'جایزه' : 'محصول'} • ${fa(items.filter(p => isActive(p)).length)} فعال`}
          </span>
        </div>
        <div className="row gap-8">
          <button className="btn ghost" onClick={() => load(tab)} style={{ padding: '7px 14px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.1)', background: 'transparent', color: '#64748b' }}>
            <Icon name="refresh-cw" size={13} style={{ marginLeft: 4 }} /> رفرش
          </button>
          <button onClick={openNew} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 18px', borderRadius: 9, fontSize: 12, cursor: 'pointer', border: 'none', background: tabColor, color: '#fff', fontWeight: 600 }}>
            <Icon name="plus" size={13} /> {isPrize ? 'افزودن جایزه' : 'افزودن محصول'}
          </button>
        </div>
      </div>

      {/* ── گرید محصولات ── */}
      {loading ? (
        <div style={{ padding: 48, textAlign: 'center', color: '#64748b', marginTop: 24 }}>در حال بارگذاری...</div>
      ) : (
        <div className="grid grid-3 mt-16">
          {items.map(p => {
            const color    = p.color || typeColor(p.type);
            const colorD   = typeColorD(p.type);
            const active   = isActive(p);
            const specCount = sellers.filter(s => (s.products || []).some(sp => sp.id === p.id)).length;

            return (
              <div key={p.id} className="card card-hover" style={{ padding: 0, overflow: 'hidden', opacity: active ? 1 : 0.6 }}>
                {/* هدر گرادیانت */}
                <div style={{ height: 110, background: `linear-gradient(135deg, ${color}bb, ${colorD})`, display: 'grid', placeItems: 'center', position: 'relative' }}>
                  <Icon name={typeIcon(p.type)} size={38} color="#fff" strokeWidth={1.3} />
                  {/* نوع - بالا راست */}
                  <div style={{ position: 'absolute', top: 10, right: 10 }}>
                    <span style={{ fontSize: 10, padding: '3px 10px', borderRadius: 20, backdropFilter: 'blur(8px)', fontWeight: 600, background: 'rgba(255,255,255,.2)', color: '#fff' }}>
                      {typeLabel(p.type)}
                    </span>
                  </div>
                  {/* دسته‌بندی - بالا چپ */}
                  {p.category && (
                    <div style={{ position: 'absolute', top: 10, left: 10 }}>
                      <span style={{ fontSize: 9, padding: '3px 8px', borderRadius: 20, backdropFilter: 'blur(8px)', background: 'rgba(0,0,0,.3)', color: 'rgba(255,255,255,.8)' }}>
                        {p.category}
                      </span>
                    </div>
                  )}
                  {/* تعداد فروشنده - پایین راست */}
                  {specCount > 0 && (
                    <div style={{ position: 'absolute', bottom: 10, left: 10 }}>
                      <span style={{ fontSize: 9, padding: '2px 8px', borderRadius: 20, background: 'rgba(0,0,0,.35)', color: 'rgba(255,255,255,.75)' }}>
                        👥 {fa(specCount)} متخصص
                      </span>
                    </div>
                  )}
                </div>

                {/* محتوا */}
                <div style={{ padding: 16 }}>
                  <div className="row between" style={{ alignItems: 'flex-start', marginBottom: 10 }}>
                    <div style={{ flex: 1 }}>
                      <div className="semi" style={{ fontSize: 14 }}>{p.name}</div>
                      {(p.desc || p.description) && <div className="text-xs text-3 mt-4">{p.desc || p.description}</div>}
                    </div>
                    <div style={{ cursor: 'pointer', flexShrink: 0, marginRight: 8 }} onClick={() => toggleActive(p)}>
                      <div style={{ width: 34, height: 18, borderRadius: 9, background: active ? '#6366F1' : 'rgba(255,255,255,.1)', position: 'relative', transition: 'background .2s' }}>
                        <div style={{ width: 14, height: 14, borderRadius: '50%', background: '#fff', position: 'absolute', top: 2, left: active ? 18 : 2, transition: 'left .2s' }} />
                      </div>
                    </div>
                  </div>

                  {/* قیمت + تگ‌ها */}
                  <div className="row between mt-8" style={{ alignItems: 'flex-end' }}>
                    <div>
                      <div className="text-xs text-3">قیمت</div>
                      <div className="bold mono mt-4" style={{ fontSize: 15 }}>
                        {(p.price === 0 || p.price === '0')
                          ? <span style={{ color: '#34D399' }}>رایگان</span>
                          : <span>{faMoney(p.price || 0)} <span className="text-xs text-3">تومان</span></span>}
                      </div>
                      {p.avg_value > 0 && (
                        <div style={{ fontSize: 9, color: '#475569', marginTop: 2, fontFamily: 'JetBrains Mono' }}>
                          میانگین: {fa(p.avg_value)} تومان
                        </div>
                      )}
                    </div>
                    <div className="row gap-4">
                      {(Array.isArray(p.tags) ? p.tags : []).slice(0, 2).map(t => (
                        <span key={t} className="badge solid" style={{ background: 'rgba(255,255,255,.04)', color: 'var(--text-2)', border: '1px solid var(--border-soft)', fontSize: 9 }}>{t}</span>
                      ))}
                    </div>
                  </div>

                  {/* دکمه‌ها */}
                  <div style={{ display: 'flex', gap: 6, marginTop: 14 }}>
                    {!isPrize && (
                      <>
                        <button onClick={() => openSp(p)} style={{ flex: 1, padding: '6px 0', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: `1px solid ${color}50`, background: `${color}15`, color, fontWeight: 600 }}>
                          👥 فروشندگان
                        </button>
                        <button onClick={() => openPzModal(p)} style={{ flex: 1, padding: '6px 0', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(245,158,11,.3)', background: 'rgba(245,158,11,.08)', color: '#F59E0B', fontWeight: 600 }}>
                          🎁 جوایز {p.eligible_prizes?.length > 0 ? `(${fa(p.eligible_prizes.length)})` : ''}
                        </button>
                      </>
                    )}
                    <button onClick={() => openEdit(p)} style={{ flex: 1, padding: '6px 0', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(99,102,241,.3)', background: 'rgba(99,102,241,.08)', color: '#818CF8' }}>
                      ✏️ ویرایش
                    </button>
                    <button onClick={() => deleteProduct(p)} style={{ padding: '6px 10px', borderRadius: 8, fontSize: 11, cursor: 'pointer', border: '1px solid rgba(248,113,113,.2)', background: 'transparent', color: '#F87171' }}>🗑</button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* ── Modal افزودن/ویرایش محصول ── */}
      {open && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.78)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setOpen(false)}>
          <div style={{ background: '#111118', border: '1px solid rgba(255,255,255,.1)', borderRadius: 16, padding: 28, width: 440, maxHeight: '90vh', overflow: 'auto' }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#e2e8f0', marginBottom: 22 }}>
              {editItem === 'new' ? (isPrize ? '🎁 جایزه جدید' : '📦 محصول جدید') : `ویرایش — ${editItem?.name}`}
            </div>
            <div className="col gap-14">
              {/* نام */}
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>نام محصول *</div>
                <input className="input" placeholder="مثلا: دوره AIP پیشرفته" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
              </div>
              {/* توضیحات */}
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>توضیحات</div>
                <textarea className="textarea" rows={2} placeholder="یک پاراگراف کوتاه..." value={form.desc} onChange={e => setForm({ ...form, desc: e.target.value })} />
              </div>
              {/* قیمت + نوع */}
              <div className="grid grid-2 gap-12">
                <div>
                  <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>قیمت (تومان)</div>
                  <input className="input mono" placeholder="0" value={form.price} onChange={e => setForm({ ...form, price: e.target.value.replace(/\D/g, '') })} style={{ direction: 'ltr' }} />
                </div>
                <div>
                  <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>نوع</div>
                  <select className="select" value={form.type} onChange={e => setForm({ ...form, type: e.target.value })}>
                    <option value="online">آنلاین</option>
                    <option value="workshop">کارگاه</option>
                    <option value="free">رایگان</option>
                  </select>
                </div>
              </div>
              {/* دسته + میانگین ارزش */}
              <div className="grid grid-2 gap-12">
                <div>
                  <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>دسته‌بندی</div>
                  <input className="input" placeholder="مثلا: بیمه، وام" value={form.category} onChange={e => setForm({ ...form, category: e.target.value })} />
                </div>
                <div>
                  <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>میانگین ارزش (تومان)</div>
                  <input className="input mono" placeholder="0" value={form.avg_value} onChange={e => setForm({ ...form, avg_value: e.target.value.replace(/\D/g, '') })} style={{ direction: 'ltr' }} />
                </div>
              </div>
              {/* قیمت مصوب — مرجع محاسبه تخفیف فروشنده‌ها */}
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>قیمت مصوب فروش (تومان) — مرجع محاسبه تخفیف</div>
                <input className="input mono" placeholder="0" value={form.list_price} onChange={e => setForm({ ...form, list_price: e.target.value.replace(/\D/g, '') })} style={{ direction: 'ltr' }} />
              </div>
              {/* تگ‌ها */}
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 5 }}>تگ‌ها (با ، جدا کن)</div>
                <input className="input" placeholder="پایه، آنلاین، AIP" value={form.tags} onChange={e => setForm({ ...form, tags: e.target.value })} />
              </div>
              {/* رنگ */}
              <div>
                <div style={{ fontSize: 11, color: '#64748b', marginBottom: 8 }}>رنگ نمایش</div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {COLORS.map(c => (
                    <div key={c} onClick={() => setForm({ ...form, color: c })} style={{ width: 30, height: 30, borderRadius: '50%', background: c, cursor: 'pointer', transition: 'all .15s', outline: form.color === c ? `3px solid ${c}` : 'none', outlineOffset: 2, opacity: form.color === c ? 1 : .65 }} />
                  ))}
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 24 }}>
              <button onClick={() => setOpen(false)} style={{ padding: '8px 18px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: '1px solid rgba(255,255,255,.12)', background: 'transparent', color: '#64748b' }}>انصراف</button>
              <button onClick={submit} disabled={saving || !form.name} style={{ padding: '8px 22px', borderRadius: 8, fontSize: 12, cursor: 'pointer', border: 'none', background: form.name ? '#6366F1' : 'rgba(99,102,241,.3)', color: form.name ? '#fff' : '#475569', fontWeight: 600 }}>
                {saving ? 'در حال ذخیره...' : 'ذخیره محصول'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── Modal مدیریت فروشندگان محصول ── */}
      {spModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.82)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setSpModal(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(255,255,255,.1)', borderRadius: 14, padding: 24, width: 440, maxHeight: '75vh', overflow: 'auto' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: `${spModal.color || '#6366F1'}20`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>📦</div>
              <div>
                <div style={{ fontSize: 14, fontWeight: 700, color: spModal.color || '#818CF8' }}>{spModal.name}</div>
                <div style={{ fontSize: 11, color: '#64748b', marginTop: 2 }}>مدیریت فروشندگان متخصص</div>
              </div>
              <button onClick={() => setSpModal(null)} style={{ marginRight: 'auto', background: 'none', border: 'none', color: '#475569', cursor: 'pointer', fontSize: 22, lineHeight: 1 }}>×</button>
            </div>

            {sellers.length === 0 ? (
              <div style={{ padding: 24, textAlign: 'center', color: '#64748b', fontSize: 12 }}>فروشنده‌ای ثبت نشده</div>
            ) : (
              <div className="col gap-8">
                {spSellers.map(s => (
                  <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 10, transition: 'background .15s', background: s.assigned ? `${spModal.color || '#6366F1'}12` : 'rgba(255,255,255,.03)', border: `1px solid ${s.assigned ? (spModal.color || '#6366F1') + '45' : 'rgba(255,255,255,.07)'}` }}>
                    <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'rgba(99,102,241,.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, color: '#818CF8', fontWeight: 700, flexShrink: 0 }}>{s.name[0]}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: '#e2e8f0' }}>{s.name}</div>
                      {s.assigned && (
                        <select value={s.level} onChange={e => changeSpLevel(spModal, s, e.target.value)} onClick={ev => ev.stopPropagation()}
                          style={{ marginTop: 3, fontSize: 10, background: 'transparent', border: 'none', color: spModal.color || '#6366F1', cursor: 'pointer', outline: 'none', fontFamily: 'Vazirmatn' }}>
                          <option value="junior">مبتدی</option>
                          <option value="senior">ارشد</option>
                          <option value="expert">متخصص</option>
                        </select>
                      )}
                    </div>
                    <button onClick={() => toggleSp(spModal, s)} style={{ padding: '5px 14px', borderRadius: 8, fontSize: 11, cursor: 'pointer', fontWeight: 600, border: 'none', transition: 'all .15s', background: s.assigned ? 'rgba(248,113,113,.18)' : `${spModal.color || '#6366F1'}25`, color: s.assigned ? '#F87171' : (spModal.color || '#818CF8') }}>
                      {s.assigned ? 'حذف' : 'اضافه'}
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}
      {/* ── Modal مدیریت جوایز محصول ── */}
      {pzModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.82)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => e.target === e.currentTarget && setPzModal(null)}>
          <div style={{ background: '#111118', border: '1px solid rgba(255,255,255,.1)', borderRadius: 14, padding: 24, width: 460, maxHeight: '80vh', overflow: 'auto' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(245,158,11,.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>🎁</div>
              <div>
                <div style={{ fontSize: 14, fontWeight: 700, color: '#F59E0B' }}>{pzModal.name}</div>
                <div style={{ fontSize: 11, color: '#64748b', marginTop: 2 }}>جوایز مجاز هنگام فروش این محصول</div>
              </div>
              <button onClick={() => setPzModal(null)} style={{ marginRight: 'auto', background: 'none', border: 'none', color: '#475569', cursor: 'pointer', fontSize: 22, lineHeight: 1 }}>×</button>
            </div>

            {allPrizes.length === 0 ? (
              <div style={{ padding: 24, textAlign: 'center', color: '#64748b', fontSize: 12 }}>
                هیچ محصول جایزه‌ای تعریف نشده — ابتدا در تب «محصولات جوایز» محصول جایزه اضافه کنید.
              </div>
            ) : (
              <div className="col gap-8">
                {allPrizes.map(pr => {
                  const linked = linkedPrizes.includes(pr.id);
                  return (
                    <div key={pr.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 10, background: linked ? 'rgba(245,158,11,.08)' : 'rgba(255,255,255,.03)', border: `1px solid ${linked ? 'rgba(245,158,11,.4)' : 'rgba(255,255,255,.07)'}` }}>
                      <div style={{ width: 32, height: 32, borderRadius: '50%', background: `${pr.color || '#F59E0B'}20`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, flexShrink: 0 }}>🎁</div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: '#e2e8f0' }}>{pr.name}</div>
                        {pr.category && <div style={{ fontSize: 10, color: '#64748b', marginTop: 1 }}>{pr.category}</div>}
                      </div>
                      {linked && <span style={{ fontSize: 10, color: '#F59E0B', padding: '2px 8px', borderRadius: 10, background: 'rgba(245,158,11,.12)', marginLeft: 4 }}>✓ مجاز</span>}
                      <button onClick={() => togglePrizeLink(pzModal, pr.id, linked)} style={{ padding: '5px 14px', borderRadius: 8, fontSize: 11, cursor: 'pointer', fontWeight: 600, border: 'none', background: linked ? 'rgba(248,113,113,.18)' : 'rgba(245,158,11,.2)', color: linked ? '#F87171' : '#F59E0B' }}>
                        {linked ? 'حذف از مجازها' : '+ اضافه کردن'}
                      </button>
                    </div>
                  );
                })}
              </div>
            )}

            <div style={{ marginTop: 18, padding: '10px 14px', borderRadius: 9, background: 'rgba(255,255,255,.03)', border: '1px solid rgba(255,255,255,.07)', fontSize: 11, color: '#475569', lineHeight: 1.7 }}>
              💡 فروشنده‌ها فقط جوایز مجاز همین محصول رو می‌تونن انتخاب کنند.<br/>
              جایزه شناور (متن آزاد) همیشه در دسترسه بدون محدودیت.
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const typeColor  = (t) => ({ online: '#8B5CF6', workshop: '#F97316', free: '#10B981' }[t] || '#6366F1');
const typeColorD = (t) => ({ online: 'rgba(67,56,202,0.5)', workshop: 'rgba(194,65,12,0.5)', free: 'rgba(5,150,105,0.5)' }[t] || 'rgba(31,31,56,0.5)');
const typeIcon   = (t) => ({ online: 'monitor', workshop: 'users', free: 'gift' }[t] || 'package');
const typeLabel  = (t) => ({ online: 'آنلاین', workshop: 'کارگاه', free: 'رایگان' }[t] || t);

window.Products = Products;
