// ── مودال آپلود فایل ارسالی ──────────────────────────────
const SendUploadModalContent = ({ onClose, onUpload, uploading, sendCats }) => {
  const { Button, Modal } = window.SB_UI;
  const [dragOver, setSendDragOver] = React.useState(false);
  const [selCat, setSelCat] = React.useState('');
  const [pickedFile, setPickedFile] = React.useState(null);
  const inputRef = React.useRef();

  const handleFile = (f) => { if (f) setPickedFile(f); };
  const handleDrop = (e) => {
    e.preventDefault(); setSendDragOver(false);
    const f = e.dataTransfer.files[0];
    if (f) setPickedFile(f);
  };

  return (
    <Modal open onClose={onClose} title="آپلود فایل ارسالی" width={480}
      footer={<>
        <Button kind="primary" disabled={!pickedFile || uploading} onClick={() => onUpload(pickedFile, selCat)}>
          {uploading ? 'در حال آپلود...' : 'آپلود'}
        </Button>
        <Button kind="ghost" onClick={onClose}>انصراف</Button>
      </>}>
      <div className="col gap-14">
        {/* ناحیه drag & drop */}
        <div
          onDragOver={e => { e.preventDefault(); setSendDragOver(true); }}
          onDragLeave={() => setSendDragOver(false)}
          onDrop={handleDrop}
          onClick={() => inputRef.current?.click()}
          style={{ border: `2px dashed ${dragOver ? 'var(--primary)' : 'var(--border)'}`, borderRadius: 12, padding: 32, textAlign: 'center', cursor: 'pointer', background: dragOver ? 'rgba(99,102,241,.06)' : 'var(--bg-2)', transition: 'all .2s' }}>
          <div style={{ fontSize: 36, marginBottom: 8 }}>{pickedFile ? '✅' : '📁'}</div>
          {pickedFile ? (
            <div>
              <div className="semi text-sm">{pickedFile.name}</div>
              <div className="text-xs text-3" style={{ marginTop: 4 }}>{(pickedFile.size / 1024).toFixed(0)} KB</div>
              <div className="text-xs" style={{ marginTop: 8, color: 'var(--primary)' }}>برای تغییر فایل کلیک کنید</div>
            </div>
          ) : (
            <div>
              <div className="semi text-sm" style={{ marginBottom: 4 }}>فایل را اینجا رها کنید</div>
              <div className="text-xs text-3">یا برای انتخاب کلیک کنید</div>
            </div>
          )}
          <input ref={inputRef} type="file" style={{ display: 'none' }} onChange={e => handleFile(e.target.files[0])} />
        </div>

        {/* دسته‌بندی */}
        <div>
          <label className="text-xs text-3 mb-6">دسته‌بندی <span className="text-3">(اختیاری)</span></label>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {sendCats.map(c => (
              <button key={c.id}
                onClick={() => setSelCat(selCat === c.id ? '' : c.id)}
                style={{ padding: '6px 12px', borderRadius: 18, border: `2px solid ${selCat === c.id ? c.color : 'transparent'}`, background: selCat === c.id ? `${c.color}22` : 'var(--bg-2)', color: selCat === c.id ? c.color : 'var(--text-2)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12 }}>
                {c.icon} {c.label}
              </button>
            ))}
          </div>
        </div>
      </div>
    </Modal>
  );
};

// Library v3 — طراحی تمیز و روان
const Library = () => {
  const { Icon, Button, Modal, Field, useToast } = window.SB_UI;
  const { fa } = window.SB_DATA;
  const toast = useToast();

  const [tab,         setTab]         = window.useStickyState('tab_library', 'collections');
  const [collections, setCollections] = useState([]);
  const [files,       setFiles]       = useState([]);
  const [surveys,     setSurveys]     = useState([]);
  const [activeCol,   setActiveCol]   = useState(null);   // null = لیست، object = داخل دسته
  const [loading,     setLoading]     = useState(true);


  // مودال‌ها
  const [colModal,  setColModal]  = useState(false);
  const [editColId, setEditColId] = useState(null);
  const [itemModal, setItemModal] = useState(false);
  const [survModal, setSurvModal] = useState(false);
  const [aiData,    setAiData]    = useState(null);
  const [aiLoading, setAiLoading] = useState(false);
  const [applied,   setApplied]   = useState({});

  // ── تب ارسال سریع ──
  const [sendFiles,      setSendFiles]      = useState([]);
  const [sendLoading,    setSendLoading]    = useState(false);
  const [sendCatFilter,  setSendCatFilter]  = useState('');
  const [sendEditModal,  setSendEditModal]  = useState(null); // null | file object
  const [sendUploadModal,setSendUploadModal]= useState(false);
  const [sendEditForm,   setSendEditForm]   = useState({});
  const [sendUploading,  setSendUploading]  = useState(false);
  const [sendProducts,   setSendProducts]   = useState([]);

  const SEND_CATS = [
    { id: 'intro',        label: 'معرفی محصول',     icon: '📦', color: '#3B82F6' },
    { id: 'offer',        label: 'پیشنهاد ویژه',    icon: '🏷️', color: '#F59E0B' },
    { id: 'testimonial',  label: 'توصیه‌نامه',       icon: '❤️', color: '#EC4899' },
    { id: 'free_content', label: 'محتوای رایگان',    icon: '🎁', color: '#10B981' },
    { id: 'pricing',      label: 'جدول قیمت',        icon: '💰', color: '#8B5CF6' },
    { id: 'technical',    label: 'اطلاعات فنی',      icon: '⚙️', color: '#6B7280' },
    { id: 'other',        label: 'متفرقه',           icon: '📎', color: '#64748b' },
  ];

  const loadSendFiles = () => {
    setSendLoading(true);
    fetch('/api/library?sendable=1', { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setSendFiles(d.data.files || []); })
      .finally(() => setSendLoading(false));
  };

  const loadSendProducts = () => {
    fetch('/api/market/products?prize=0', { headers })
      .then(r => r.json())
      .then(d => { if (d.success) setSendProducts(d.data.products || []); })
      .catch(() => {});
  };

  useEffect(() => {
    if (tab === 'sendable') { loadSendFiles(); loadSendProducts(); }
  }, [tab]);

  const openSendEdit = (f) => {
    setSendEditForm({
      name: f.name,
      send_category: f.send_category || '',
      related_product_ids: (() => { try { return JSON.parse(f.related_product_ids || '[]'); } catch { return []; } })(),
      description: f.description || '',
    });
    setSendEditModal(f);
  };

  const saveSendEdit = () => {
    const f = sendEditModal;
    fetch(`/api/library/${f.id}`, {
      method: 'PUT', headers,
      body: JSON.stringify({
        name: sendEditForm.name,
        description: sendEditForm.description,
        send_category: sendEditForm.send_category,
        related_product_ids: sendEditForm.related_product_ids,
      }),
    }).then(r => r.json()).then(d => {
      if (d.success || d.message === 'Updated') {
        toast('ذخیره شد ✓', 'success');
        setSendEditModal(null);
        loadSendFiles();
      } else toast(d.message || 'خطا', 'error');
    });
  };

  const toggleSendable = (f) => {
    fetch(`/api/library/${f.id}`, {
      method: 'PUT', headers,
      body: JSON.stringify({ is_sendable: f.is_sendable ? 0 : 1 }),
    }).then(r => r.json()).then(d => {
      if (d.success || d.message === 'Updated') loadSendFiles();
    });
  };

  const uploadSendFile = async (file, cat) => {
    setSendUploading(true);
    const fd = new FormData();
    fd.append('file', file);
    fd.append('name', file.name.replace(/\.[^.]+$/, ''));
    fd.append('is_sendable', '1');
    fd.append('send_category', cat || '');
    try {
      const r = await fetch('/api/library/upload', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: fd });
      const d = await r.json();
      if (d.success) { toast('فایل آپلود شد ✓', 'success'); setSendUploadModal(false); loadSendFiles(); }
      else toast(d.message || 'خطا در آپلود', 'error');
    } catch { toast('خطا در آپلود', 'error'); }
    setSendUploading(false);
  };

  // ── Custom mouse drag (بدون HTML5 DnD API) ──
  const [dragState, setDragState]   = useState(null); // { title } — فقط برای نمایش ghost
  const activeColRef = useRef(null);
  const srcRef       = useRef(null); // { secId, idx, items }
  const overElRef    = useRef(null); // المنت هایلایت شده
  const ghostRef     = useRef(null); // ghost DOM element
  useEffect(() => { activeColRef.current = activeCol; }, [activeCol]);

  const startDrag = (e, secId, idx, secItems, title) => {
    if (e.button !== 0) return;
    e.preventDefault();
    srcRef.current   = { secId, idx, items: secItems };
    overElRef.current = null;
    setDragState({ title });
  };

  useEffect(() => {
    if (!dragState) return;

    const findRow = (x, y) => {
      const els = document.elementsFromPoint(x, y);
      for (const el of els) {
        if (el.dataset && el.dataset.dragIdx !== undefined) return el;
      }
      return null;
    };

    const setOver = (el) => {
      if (el === overElRef.current) return;
      if (overElRef.current) {
        overElRef.current.style.outline = '';
        overElRef.current.style.boxShadow = '';
      }
      overElRef.current = el;
      if (el) {
        el.style.outline = '2px solid #6366F1';
        el.style.boxShadow = '0 0 0 4px rgba(99,102,241,.15)';
      }
    };

    const onMove = (e) => {
      if (ghostRef.current) {
        ghostRef.current.style.left = (e.clientX + 14) + 'px';
        ghostRef.current.style.top  = (e.clientY - 14) + 'px';
      }
      setOver(findRow(e.clientX, e.clientY));
    };

    const onUp = (e) => {
      const overEl = overElRef.current;
      setOver(null);
      setDragState(null);

      const src = srcRef.current;
      srcRef.current = null;
      if (!src || !overEl) return;

      const toIdx = +overEl.dataset.dragIdx;
      const toSec = overEl.dataset.dragSec;
      if (toSec !== src.secId || toIdx === src.idx) return;

      const arr = [...src.items];
      const [moved] = arr.splice(src.idx, 1);
      arr.splice(toIdx, 0, moved);

      const ac = activeColRef.current;
      if (!ac) return;
      const tok = localStorage.getItem(window.TOKEN_KEY);
      const hdrs = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + tok };
      fetch('/api/library/collections/' + ac.collection.id + '/reorder', {
        method: 'POST', headers: hdrs,
        body: JSON.stringify({ ids: arr.map(i => i.id) }),
      }).then(r => r.json()).then(d => {
        if (d.success) {
          fetch('/api/library/collections/' + ac.collection.id, { headers: hdrs })
            .then(r => r.json()).then(d2 => { if (d2.success) setActiveCol(d2.data); });
        }
      });
    };

    const onKey = (e) => {
      if (e.key === 'Escape') { setOver(null); setDragState(null); srcRef.current = null; }
    };

    document.addEventListener('mousemove', onMove);
    document.addEventListener('mouseup',   onUp);
    document.addEventListener('keydown',   onKey);
    return () => {
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseup',   onUp);
      document.removeEventListener('keydown',   onKey);
    };
  }, [dragState]);

  // ── drag برای مرتب‌سازی دسته‌ها ──
  const [colDragState, setColDragState] = useState(null); // { name }
  const colSrcRef    = useRef(null); // { idx, collections }
  const colOverRef   = useRef(null);
  const colGhostRef  = useRef(null);

  const startColDrag = (e, idx, colName) => {
    if (e.button !== 0) return;
    e.preventDefault();
    e.stopPropagation();
    colSrcRef.current = { idx, cols: [...collections] };
    colOverRef.current = null;
    setColDragState({ name: colName });
  };

  useEffect(() => {
    if (!colDragState) return;

    const findCard = (x, y) => {
      const els = document.elementsFromPoint(x, y);
      for (const el of els) {
        if (el.dataset && el.dataset.colIdx !== undefined) return el;
      }
      return null;
    };

    const setColOver = (el) => {
      if (el === colOverRef.current) return;
      if (colOverRef.current) { colOverRef.current.style.outline = ''; colOverRef.current.style.boxShadow = ''; }
      colOverRef.current = el;
      if (el) { el.style.outline = '2px solid #6366F1'; el.style.boxShadow = '0 0 0 4px rgba(99,102,241,.15)'; }
    };

    const onMove = (e) => {
      if (colGhostRef.current) {
        colGhostRef.current.style.left = (e.clientX + 14) + 'px';
        colGhostRef.current.style.top  = (e.clientY - 14) + 'px';
      }
      setColOver(findCard(e.clientX, e.clientY));
    };

    const onUp = () => {
      const overEl = colOverRef.current;
      setColOver(null);
      setColDragState(null);
      const src = colSrcRef.current;
      colSrcRef.current = null;
      if (!src || !overEl) return;
      const toIdx = +overEl.dataset.colIdx;
      if (toIdx === src.idx) return;
      const arr = [...src.cols];
      const [moved] = arr.splice(src.idx, 1);
      arr.splice(toIdx, 0, moved);
      // optimistic update
      setCollections(arr);
      fetch('/api/library/collections/reorder', {
        method: 'POST', headers,
        body: JSON.stringify({ ids: arr.map(c => c.id) }),
      }).then(r => r.json()).then(d => { if (!d.success) loadAll(); });
    };

    const onKey = (e) => { if (e.key === 'Escape') { setColOver(null); setColDragState(null); colSrcRef.current = null; } };

    document.addEventListener('mousemove', onMove);
    document.addEventListener('mouseup',   onUp);
    document.addEventListener('keydown',   onKey);
    return () => {
      document.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseup',   onUp);
      document.removeEventListener('keydown',   onKey);
    };
  }, [colDragState]);

  // modal انتقال آیتم
  const [moveModal, setMoveModal] = useState(false);
  const [moveItem_,  setMoveItem_]  = useState(null); // آیتم در حال انتقال
  const [moveSec,   setMoveSec]   = useState('general');
  const [moveColId, setMoveColId] = useState('');

  const openMoveModal = (item) => {
    setMoveItem_(item);
    setMoveColId('');
    setMoveSec(item.section || 'general');
    setMoveModal(true);
  };

  const confirmMove = () => {
    if (!moveColId || !moveItem_ || !activeCol) return toast('دسته مقصد رو انتخاب کن', 'error');
    fetch(`/api/library/collections/${activeCol.collection.id}/items/${moveItem_.id}/move`, {
      method: 'POST', headers, body: JSON.stringify({ targetColId: moveColId, section: moveSec }),
    }).then(r => r.json()).then(d => {
      if (d.success) {
        toast('آیتم منتقل شد ✓', 'success');
        setMoveModal(false);
        setMoveItem_(null);
        refreshCol(activeCol.collection);
        loadAll();
      } else toast(d.message || 'خطا', 'error');
    });
  };

  // فرم‌های خالی
  const EMPTY_COL  = { name: '', type: 'general', description: '', color: '#6366F1', payment_link: '', discount_code: '', discount_value: '' };
  const EMPTY_ITEM = { item_type: 'file', file_id: '', title: '', url: '', content: '', section: 'general' };
  const EMPTY_SURV = { title: '', target_type: 'buyers', questions: [{ id: 1, text: '', type: 'text' }] };

  const [colForm,  setColForm]  = useState(EMPTY_COL);
  const [itemForm, setItemForm] = useState(EMPTY_ITEM);
  const [survForm, setSurvForm] = useState(EMPTY_SURV);

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

  // ─── بارگذاری ────────────────────────────────────────
  const loadAll = () => {
    setLoading(true);
    Promise.all([
      fetch('/api/library/collections', { headers }).then(r => r.json()),
      fetch('/api/library',             { headers }).then(r => r.json()),
      fetch('/api/library/surveys',     { headers }).then(r => r.json()),
    ]).then(([cd, fd, sd]) => {
      if (cd.success) setCollections(cd.data.collections || []);
      if (fd.success) setFiles(fd.data.files || []);
      if (sd.success) setSurveys(sd.data.surveys || []);
    }).finally(() => setLoading(false));
  };

  useEffect(() => { loadAll(); }, []);

  const refreshCol = (col) => {
    fetch(`/api/library/collections/${col.id}`, { headers })
      .then(r => r.json()).then(d => { if (d.success) setActiveCol(d.data); });
  };

  const goToCol = (col) => {
    fetch(`/api/library/collections/${col.id}`, { headers })
      .then(r => r.json()).then(d => { if (d.success) { setActiveCol(d.data); setTab('collections'); } });
  };

  const goBack = () => setActiveCol(null);

  // ─── CRUD دسته ──────────────────────────────────────
  const openNewCol = () => { setEditColId(null); setColForm(EMPTY_COL); setColModal(true); };

  const openEditCol = (col) => {
    setColForm({ name: col.name, type: col.type, description: col.description || '', color: col.color || '#6366F1', payment_link: col.payment_link || '', discount_code: col.discount_code || '', discount_value: col.discount_value || '' });
    setEditColId(col.id);
    setColModal(true);
  };

  const closeColModal = () => { setColModal(false); setEditColId(null); setColForm(EMPTY_COL); };

  const saveCollection = () => {
    if (!colForm.name.trim()) return toast('نام دسته الزامیه', 'error');
    const url    = editColId ? `/api/library/collections/${editColId}` : '/api/library/collections';
    const method = editColId ? 'PUT' : 'POST';
    fetch(url, { method, headers, body: JSON.stringify(colForm) })
      .then(r => r.json()).then(d => {
        if (d.success) {
          toast(editColId ? 'دسته آپدیت شد ✓' : 'دسته ساخته شد ✓', 'success');
          closeColModal();
          loadAll();
          if (editColId && activeCol?.collection?.id === editColId) refreshCol({ id: editColId });
        } else toast(d.message || 'خطا', 'error');
      });
  };

  const deleteCollection = (col) => {
    if (!confirm(`دسته «${col.name}» و همه آیتم‌هایش حذف شود؟`)) return;
    fetch(`/api/library/collections/${col.id}`, { method: 'DELETE', headers })
      .then(r => r.json()).then(d => {
        if (d.success) {
          toast('دسته حذف شد', 'success');
          loadAll();
          if (activeCol?.collection?.id === col.id) setActiveCol(null);
        }
      });
  };

  // ─── آیتم‌ها ─────────────────────────────────────────
  const [uploading, setUploading] = useState(false);

  const openAddItem = (sectionId) => {
    setItemForm({ ...EMPTY_ITEM, section: sectionId || 'general' });
    setItemModal(true);
  };

  // حذف فایل آپلودشده‌ای که ذخیره نشده (silent)
  const deleteOrphanFile = (fileId) => {
    if (!fileId) return;
    fetch(`/api/library/${fileId}`, { method: 'DELETE', headers }).catch(() => {});
  };

  // بستن مودال — اگه فایل آپلود شده ولی ذخیره نشده، حذفش کن
  const closeItemModal = () => {
    if (itemForm._pendingFileId) deleteOrphanFile(itemForm._pendingFileId);
    setItemModal(false);
    setItemForm(EMPTY_ITEM);
  };

  // آپلود فایل داخل مودال
  const uploadForItem = async (file) => {
    setUploading(true);
    const fd = new FormData();
    fd.append('file', file);
    fd.append('name', file.name.replace(/\.[^.]+$/, ''));
    try {
      const r = await fetch('/api/library/upload', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: fd });
      const d = await r.json();
      if (d.success) {
        // _pendingFileId = فایلی که آپلود شده ولی هنوز به collection وصل نشده
        setItemForm(f => ({
          ...f,
          file_id: d.data.file.id,
          _pendingFileId: d.data.file.id,
          title: f.title || d.data.file.name,
          _fileName: file.name,
        }));
        toast('فایل آپلود شد ✓', 'success');
      } else toast(d.message || 'خطا در آپلود', 'error');
    } catch { toast('خطا در آپلود', 'error'); }
    setUploading(false);
  };

  // تغییر فایل — قبلی رو حذف کن
  const changeFile = () => {
    deleteOrphanFile(itemForm._pendingFileId);
    setItemForm(f => ({ ...f, file_id: '', _pendingFileId: '', _fileName: '' }));
  };

  const addItem = () => {
    if (!activeCol) return;
    if (itemForm.item_type === 'file' && !itemForm.file_id) return toast('فایل رو آپلود کنید', 'error');
    if (itemForm.item_type === 'link' && !itemForm.url.trim()) return toast('URL الزامیه', 'error');
    if (itemForm.item_type === 'text' && !itemForm.content.trim()) return toast('متن الزامیه', 'error');
    fetch(`/api/library/collections/${activeCol.collection.id}/items`, { method: 'POST', headers, body: JSON.stringify(itemForm) })
      .then(r => r.json()).then(d => {
        if (d.success) {
          toast('آیتم اضافه شد ✓', 'success');
          // _pendingFileId رو پاک کن — فایل الان به collection وصله، نباید حذف بشه
          setItemForm(EMPTY_ITEM);
          setItemModal(false);
          refreshCol(activeCol.collection);
        } else toast(d.message || 'خطا', 'error');
      });
  };

  const removeItem = (itemId) => {
    if (!confirm('آیتم حذف شود؟')) return;
    fetch(`/api/library/collections/${activeCol.collection.id}/items/${itemId}`, { method: 'DELETE', headers })
      .then(r => r.json()).then(d => { if (d.success) { toast('حذف شد', 'success'); refreshCol(activeCol.collection); } });
  };

  // ─── نظرسنجی ────────────────────────────────────────
  const createSurvey = () => {
    if (!survForm.title.trim()) return toast('عنوان الزامیه', 'error');
    const qs = survForm.questions.filter(q => q.text.trim());
    fetch('/api/library/surveys', { method: 'POST', headers, body: JSON.stringify({ ...survForm, questions: qs }) })
      .then(r => r.json()).then(d => {
        if (d.success) { toast('نظرسنجی ساخته شد ✓', 'success'); setSurvModal(false); setSurvForm(EMPTY_SURV); loadAll(); }
        else toast(d.message || 'خطا', 'error');
      });
  };

  const sendSurvey = (surv) => {
    if (!confirm(`نظرسنجی «${surv.title}» ارسال شود؟`)) return;
    fetch(`/api/library/surveys/${surv.id}/send`, { method: 'POST', headers, body: JSON.stringify({ limit: 50 }) })
      .then(r => r.json()).then(d => { toast(d.message || (d.success ? 'ارسال شد ✓' : 'خطا'), d.success ? 'success' : 'error'); loadAll(); });
  };

  const deleteSurvey = (surv) => {
    if (!confirm(`نظرسنجی «${surv.title}» حذف شود؟`)) return;
    fetch(`/api/library/surveys/${surv.id}`, { method: 'DELETE', headers })
      .then(r => r.json()).then(d => { if (d.success) { toast('حذف شد', 'success'); loadAll(); } });
  };

  // ─── AI ─────────────────────────────────────────────
  const runAnalysis = () => {
    setAiLoading(true); setAiData(null); setApplied({});
    fetch('/api/library/ai-analyze', { method: 'POST', headers })
      .then(r => r.json()).then(d => { if (d.success) { setAiData(d.data); toast('تحلیل انجام شد ✓', 'success'); } else toast('خطا در تحلیل', 'error'); })
      .catch(() => toast('خطای شبکه', 'error')).finally(() => setAiLoading(false));
  };

  const applySug = (idx, sug) => {
    fetch('/api/library/ai-apply', { method: 'POST', headers, body: JSON.stringify({ action: sug.action, file_id: sug.file_id, target_id: sug.target_id, target_type: sug.target_type }) })
      .then(r => r.json()).then(d => { if (d.success) { setApplied(p => ({ ...p, [idx]: true })); toast(d.message, 'success'); } });
  };

  // ─── ثابت‌ها ─────────────────────────────────────────
  const FT = {
    video: { color: '#EF4444', icon: 'video',     label: 'ویدیو'  },
    audio: { color: '#8B5CF6', icon: 'mic',       label: 'صوتی'   },
    pdf:   { color: '#3B82F6', icon: 'file-text', label: 'PDF'    },
    image: { color: '#10B981', icon: 'image',     label: 'تصویر'  },
    text:  { color: '#F59E0B', icon: 'file',      label: 'متن'    },
    other: { color: '#6B7280', icon: 'file',      label: 'سایر'   },
    link:  { color: '#06B6D4', icon: 'link',      label: 'لینک'   },
  };
  const ft = (t) => FT[t] || FT.other;

  const fmtSize = (b) => !b ? '—' : b < 1048576 ? `${Math.round(b/1024)} KB` : `${(b/1048576).toFixed(1)} MB`;

  const SECTIONS = [
    { id: 'general',     label: 'عمومی',          icon: 'folder',  color: '#6B7280' },
    { id: 'intro',       label: 'معرفی محصول',     icon: 'package', color: '#3B82F6' },
    { id: 'testimonial', label: 'مشتری راضی',       icon: 'heart',   color: '#EC4899' },
    { id: 'offer',       label: 'پیشنهاد ویژه',    icon: 'tag',     color: '#F59E0B' },
    { id: 'group',       label: 'گروه / کانال',    icon: 'users',   color: '#10B981' },
  ];

  const COL_COLORS = ['#6366F1','#8B5CF6','#EC4899','#EF4444','#F59E0B','#10B981','#06B6D4','#3B82F6'];

  const TABS = [
    { id: 'collections', label: 'دسته‌ها',    icon: 'layout-grid'    },
    { id: 'sendable',    label: 'ارسال سریع', icon: 'send'           },
    { id: 'surveys',     label: 'نظرسنجی',    icon: 'clipboard-list' },
    { id: 'ai',          label: 'AI دستیار',  icon: 'cpu'            },
  ];

  // ─── رندر ────────────────────────────────────────────
  return (
    <div>

      {/* ── هدر صفحه ─────────────────────────────────── */}
      <div className="row between" style={{ marginBottom: 20 }}>

        {/* عنوان / breadcrumb */}
        {activeCol ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <button onClick={goBack} className="icon-btn" style={{ width: 30, height: 30 }}>
              <Icon name="chevron-right" size={16} color="var(--text-3)" />
            </button>
            <div style={{ width: 30, height: 30, borderRadius: 8, background: `${activeCol.collection.color}20`, display: 'grid', placeItems: 'center' }}>
              <Icon name={activeCol.collection.icon || 'folder'} size={15} color={activeCol.collection.color} />
            </div>
            <div>
              <div className="semi" style={{ fontSize: 14, lineHeight: 1.3 }}>{activeCol.collection.name}</div>
              <div className="text-xs text-3">{fa(activeCol.items?.length || 0)} آیتم</div>
            </div>
          </div>
        ) : (
          <div>
            <div className="semi" style={{ fontSize: 15 }}>کتابخانه</div>
            <div className="text-xs text-3 mt-4">
              {fa(collections.length)} دسته · {fa(surveys.length)} نظرسنجی
            </div>
          </div>
        )}

        {/* دکمه‌های اکشن */}
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {activeCol ? (
            <>
              <button className="icon-btn" style={{ width: 30, height: 30 }} title="ویرایش دسته"
                onClick={() => openEditCol(activeCol.collection)}>
                <Icon name="edit-2" size={13} color="var(--text-3)" />
              </button>
              <Button kind="primary" icon="plus" onClick={() => openAddItem()}>افزودن آیتم</Button>
            </>
          ) : tab === 'collections' ? (
            <Button kind="primary" icon="plus" onClick={openNewCol}>دسته جدید</Button>
          ) : tab === 'surveys' ? (
            <Button kind="primary" icon="plus" onClick={() => { setSurvForm(EMPTY_SURV); setSurvModal(true); }}>نظرسنجی جدید</Button>
          ) : tab === 'sendable' ? (
            <Button kind="primary" icon="upload" onClick={() => setSendUploadModal(true)}>آپلود فایل ارسالی</Button>
          ) : tab === 'ai' ? (
            <Button kind="ghost" icon={aiLoading ? 'loader' : 'refresh-cw'} onClick={runAnalysis} disabled={aiLoading}>
              {aiLoading ? 'در حال تحلیل...' : 'تحلیل مجدد'}
            </Button>
          ) : null}
        </div>
      </div>

      {/* ── تب‌ها (مخفی داخل collection) ──────────────── */}
      {!activeCol && (
        <div style={{ display: 'flex', gap: 4, marginBottom: 20, background: 'var(--bg-2)', borderRadius: 12, padding: 4 }}>
          {TABS.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              flex: 1, padding: '9px 8px', borderRadius: 9, border: 'none', cursor: 'pointer',
              background: tab === t.id ? 'var(--surface)' : 'transparent',
              boxShadow: tab === t.id ? '0 1px 6px rgba(0,0,0,.22)' : 'none',
              color: tab === t.id ? 'var(--text-1)' : 'var(--text-3)',
              fontFamily: 'inherit', transition: 'all .15s',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}>
              <Icon name={t.icon} size={13} color="currentColor" />
              <span className="text-sm semi">{t.label}</span>
            </button>
          ))}
        </div>
      )}

      {/* ══════════════════════════════════════════════════
          ویو: داخل یک دسته
      ══════════════════════════════════════════════════ */}
      {activeCol && (() => {
        const { collection: col, items } = activeCol;
        const isProduct = col.type === 'product';

        // گروه‌بندی (مرتب بر اساس position)
        const grouped = {};
        [...(items || [])].sort((a, b) => (a.position ?? 999) - (b.position ?? 999)).forEach(item => {
          const s = item.section || 'general';
          if (!grouped[s]) grouped[s] = [];
          grouped[s].push(item);
        });

        // برای محصول: همه بخش‌ها نشون داده می‌شن (پر یا خالی)
        // برای عمومی: فقط general
        const visibleSecs = isProduct ? SECTIONS : [SECTIONS[0]];

        // درصد تکمیل برای محصول — فقط ۴ بخش اصلی (بدون عمومی)
        const PROD_COMPLETION = ['intro', 'testimonial', 'offer', 'group'];
        const filledCount = isProduct ? PROD_COMPLETION.filter(id => grouped[id]?.length > 0).length : 0;
        const totalSecs   = PROD_COMPLETION.length; // = 4
        const pct         = isProduct ? Math.round(filledCount / totalSecs * 100) : 0;
        const missingSecs = isProduct
          ? SECTIONS.filter(s => PROD_COMPLETION.includes(s.id) && !(grouped[s.id]?.length > 0))
          : [];

        // ── reorder با دکمه بالا/پایین ──
        const moveItem = (secId, fromIdx, dir, secItems) => {
          const toIdx = fromIdx + dir;
          if (toIdx < 0 || toIdx >= secItems.length) return;
          const arr = [...secItems];
          const [moved] = arr.splice(fromIdx, 1);
          arr.splice(toIdx, 0, moved);
          setReordering(true);
          fetch('/api/library/collections/' + col.id + '/reorder', {
            method: 'POST', headers,
            body: JSON.stringify({ ids: arr.map(i => i.id) }),
          }).then(r => r.json()).then(d => {
            if (d.success) refreshCol(col);
          }).finally(() => setReordering(false));
        };

        return (
          <div>
            {/* ── نوار تکمیل (فقط محصول) ── */}
            {isProduct && (
              <div className="card" style={{ padding: '12px 16px', marginBottom: 16 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                  <span className="text-sm semi">تکمیل محتوا</span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: pct === 100 ? '#34D399' : 'var(--primary)' }}>{fa(pct)}٪</span>
                </div>
                {/* progress bar */}
                <div style={{ height: 6, borderRadius: 6, background: 'var(--border)', overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: `${pct}%`, borderRadius: 6, background: pct === 100 ? '#34D399' : 'var(--primary)', transition: 'width .4s ease' }} />
                </div>
                {/* بخش‌های ناقص */}
                {missingSecs.length > 0 && (
                  <div style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'wrap' }}>
                    <span className="text-xs text-3">ناقص:</span>
                    {missingSecs.map(s => (
                      <span key={s.id} onClick={() => openAddItem(s.id)} style={{
                        fontSize: 11, padding: '2px 8px', borderRadius: 20,
                        background: `${s.color}12`, color: s.color,
                        border: `1px dashed ${s.color}40`,
                        cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4,
                      }}>
                        <Icon name={s.icon} size={10} color={s.color} />
                        {s.label}
                      </span>
                    ))}
                  </div>
                )}
                {/* اطلاعات محصول */}
                {(col.payment_link || col.discount_code) && (
                  <div style={{ display: 'flex', gap: 16, marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
                    {col.payment_link && (
                      <a href={col.payment_link} target="_blank" rel="noreferrer"
                        style={{ fontSize: 12, color: '#6366F1', display: 'flex', alignItems: 'center', gap: 4, textDecoration: 'none' }}>
                        <Icon name="credit-card" size={12} />لینک پرداخت
                      </a>
                    )}
                    {col.discount_code && (
                      <span style={{ fontSize: 12, display: 'flex', alignItems: 'center', gap: 4, color: 'var(--text-2)' }}>
                        <Icon name="tag" size={12} color="#34D399" />
                        <span style={{ color: '#34D399', fontFamily: 'monospace' }}>{col.discount_code}</span>
                        {col.discount_value && <span className="text-3">({col.discount_value})</span>}
                      </span>
                    )}
                  </div>
                )}
              </div>
            )}

            {/* ── بخش‌ها ── */}
            <div className="col gap-10">
              {visibleSecs.map(sec => {
                const secItems = grouped[sec.id] || [];
                const filled   = secItems.length > 0;

                return (
                  <div key={sec.id} style={{
                    borderRadius: 14,
                    border: filled
                      ? `1px solid ${sec.color}25`
                      : '1.5px dashed rgba(255,255,255,.08)',
                    background: filled ? `${sec.color}06` : 'transparent',
                    overflow: 'hidden',
                    transition: 'all .2s',
                  }}>
                    {/* هدر بخش */}
                    <div style={{
                      display: 'flex', alignItems: 'center', gap: 10,
                      padding: '10px 14px',
                      borderBottom: filled ? `1px solid ${sec.color}15` : 'none',
                      background: filled ? `${sec.color}08` : 'transparent',
                    }}>
                      <div style={{ width: 28, height: 28, borderRadius: 8, background: filled ? `${sec.color}20` : 'var(--bg-2)', display: 'grid', placeItems: 'center' }}>
                        <Icon name={filled ? 'check-circle' : sec.icon} size={14} color={filled ? sec.color : 'var(--text-3)'} />
                      </div>
                      <span className="semi text-sm" style={{ flex: 1, color: filled ? 'var(--text-1)' : 'var(--text-3)' }}>{sec.label}</span>
                      {filled
                        ? <span style={{ fontSize: 11, color: sec.color }}>{fa(secItems.length)} آیتم</span>
                        : <span className="text-xs text-3">خالی</span>
                      }
                      <button
                        onClick={() => openAddItem(sec.id)}
                        style={{ width: 26, height: 26, borderRadius: 7, border: 'none', background: 'var(--bg-2)', cursor: 'pointer', display: 'grid', placeItems: 'center' }}>
                        <Icon name="plus" size={13} color="var(--text-3)" />
                      </button>
                    </div>

                    {/* آیتم‌ها */}
                    {filled && (
                      <div className="col gap-0">
                        {secItems.map((item, idx) => {
                          const itemFt = item.item_type === 'file' ? ft(item.file?.file_type) : ft(item.item_type);
                          const title  = item.title || item.file?.name || item.url || '(بدون عنوان)';
                          const sub    = item.item_type === 'file'
                            ? `${itemFt.label} · ${fmtSize(item.file?.size)}`
                            : item.item_type === 'link' ? item.url
                            : item.content?.slice(0, 70);
                          return (
                            <div key={item.id}
                              data-drag-idx={idx}
                              data-drag-sec={sec.id}
                              style={{
                                display: 'flex', alignItems: 'center', gap: 10,
                                padding: '9px 14px',
                                borderTop: idx > 0 ? '1px solid var(--border)' : 'none',
                                userSelect: 'none',
                                transition: 'outline .1s',
                              }}
                            >
                              {/* دستگیره drag — onMouseDown شروع drag */}
                              <div
                                onMouseDown={(e) => startDrag(e, sec.id, idx, secItems, title)}
                                style={{ flexShrink: 0, display: 'flex', alignItems: 'center', opacity: 0.4, cursor: 'grab', padding: '2px' }}>
                                <Icon name="grip-vertical" size={14} color="var(--text-3)" />
                              </div>
                              <div style={{ width: 30, height: 30, borderRadius: 8, background: `${itemFt.color}15`, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                                <Icon name={itemFt.icon} size={14} color={itemFt.color} />
                              </div>
                              <div style={{ flex: 1, minWidth: 0 }}>
                                <div className="semi text-sm" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title}</div>
                                <div className="text-xs text-3 mt-2" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sub}</div>
                              </div>
                              <span style={{ fontSize: 10, padding: '2px 7px', borderRadius: 20, background: `${itemFt.color}12`, color: itemFt.color, flexShrink: 0 }}>
                                {item.item_type === 'file' ? itemFt.label : item.item_type === 'link' ? 'لینک' : 'متن'}
                              </span>
                              <button className="icon-btn" title="انتقال به دسته دیگر" style={{ width: 24, height: 24, flexShrink: 0 }} onClick={(e) => { e.stopPropagation(); openMoveModal(item); }}>
                                <Icon name="move-right" size={11} color="#6366F1" />
                              </button>
                              <button className="icon-btn" style={{ width: 24, height: 24, flexShrink: 0 }} onClick={() => removeItem(item.id)}>
                                <Icon name="trash-2" size={11} color="#F87171" />
                              </button>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        );
      })()}

      {/* ══════════════════════════════════════════════════
          تب: دسته‌ها
      ══════════════════════════════════════════════════ */}
      {!activeCol && tab === 'collections' && (
        loading ? (
          <div style={{ textAlign: 'center', padding: 60, color: 'var(--text-3)' }}>در حال بارگذاری...</div>
        ) : !collections.length ? (
          <div className="card" style={{ textAlign: 'center', padding: 60 }}>
            <Icon name="layout-grid" size={44} color="var(--text-3)" />
            <div className="semi mt-16">هنوز دسته‌ای نساختی</div>
            <div className="text-xs text-3 mt-8 mb-20">فایل‌هات رو در دسته‌های موضوعی مرتب کن</div>
            <Button kind="primary" icon="plus" onClick={openNewCol}>اولین دسته را بساز</Button>
          </div>
        ) : (
          <div className="grid grid-3 gap-16">
            {collections.map((col, colIdx) => {
              const filled = col.filled_sections || [];
              const tc     = col.type_counts   || {};
              const isProduct = col.type === 'product';

              // بخش‌های محصول با وضعیت پر/خالی
              const PROD_SECS = [
                { id: 'intro',       label: 'معرفی',    color: '#3B82F6' },
                { id: 'testimonial', label: 'مشتری',    color: '#EC4899' },
                { id: 'offer',       label: 'پیشنهاد',  color: '#F59E0B' },
                { id: 'group',       label: 'گروه',     color: '#10B981' },
              ];

              // نوع فایل‌های موجود برای دسته عمومی
              const typeEntries = Object.entries(tc).filter(([, v]) => v > 0);

              return (
                <div key={col.id} className="card card-hover"
                  data-col-idx={colIdx}
                  style={{ padding: 0, overflow: 'hidden', cursor: 'pointer', opacity: col.is_active ? 1 : 0.5, position: 'relative' }}
                  onClick={() => goToCol(col)}>

                  {/* دستگیره drag — گوشه بالا چپ */}
                  <div
                    onMouseDown={(e) => startColDrag(e, colIdx, col.name)}
                    onClick={e => e.stopPropagation()}
                    style={{
                      position: 'absolute', top: 7, right: 8, zIndex: 2,
                      padding: '3px 4px', borderRadius: 6,
                      cursor: 'grab', opacity: 0.35,
                      background: 'transparent',
                      pointerEvents: 'all',
                    }}>
                    <Icon name="grip-vertical" size={14} color="var(--text-3)" />
                  </div>

                  {/* هدر رنگی */}
                  <div style={{
                    height: 88,
                    background: `linear-gradient(135deg, ${col.color}28 0%, ${col.color}0a 100%)`,
                    borderBottom: `1px solid ${col.color}20`,
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                    padding: '0 16px',
                  }}>
                    <div style={{ width: 44, height: 44, borderRadius: 14, background: `${col.color}22`, display: 'grid', placeItems: 'center' }}>
                      <Icon name={col.icon || 'folder'} size={22} color={col.color} />
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 5 }}>
                      {isProduct && (
                        <span style={{ fontSize: 10, padding: '2px 8px', borderRadius: 20, background: 'rgba(245,158,11,.15)', color: '#FBBF24', fontWeight: 600 }}>📦 محصول</span>
                      )}
                      <span style={{ fontSize: 11, padding: '2px 8px', borderRadius: 20, background: `${col.color}18`, color: col.color, fontWeight: 600 }}>
                        {fa(col.item_count)} آیتم
                      </span>
                    </div>
                  </div>

                  {/* بدنه */}
                  <div style={{ padding: '12px 14px 14px' }}>
                    <div className="semi text-sm" style={{ marginBottom: 3 }}>{col.name}</div>

                    {/* توضیح — اگه نبود، فضای ثابت کوتاه */}
                    <div className="text-xs text-3" style={{ marginBottom: 10, minHeight: 16, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {col.description || ' '}
                    </div>

                    {/* ── محتوای وسط کارت ── */}
                    {isProduct ? (
                      /* نوار وضعیت بخش‌های محصول */
                      <div style={{ display: 'flex', gap: 5, marginBottom: 10 }}>
                        {PROD_SECS.map(s => {
                          const hasSec = filled.includes(s.id);
                          return (
                            <div key={s.id} title={s.label} style={{
                              flex: 1, height: 4, borderRadius: 4,
                              background: hasSec ? s.color : 'var(--border)',
                              transition: 'background .2s',
                            }} />
                          );
                        })}
                      </div>
                    ) : (
                      /* چیپ نوع فایل‌ها برای دسته عمومی */
                      <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', marginBottom: 10, minHeight: 22 }}>
                        {typeEntries.length > 0
                          ? typeEntries.map(([t, cnt]) => (
                              <span key={t} style={{ fontSize: 10, padding: '2px 7px', borderRadius: 20, background: `${ft(t).color}15`, color: ft(t).color }}>
                                {ft(t).label} {fa(cnt)}
                              </span>
                            ))
                          : <span className="text-xs text-3">خالی</span>
                        }
                      </div>
                    )}

                    {/* ردیف پایین: کوپن یا لینک پرداخت + اکشن */}
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }} onClick={e => e.stopPropagation()}>
                      <div style={{ display: 'flex', gap: 6, alignItems: 'center', minWidth: 0 }}>
                        {col.payment_link && (
                          <span style={{ fontSize: 10, color: '#6366F1', display: 'flex', alignItems: 'center', gap: 3 }}>
                            <Icon name="credit-card" size={10} color="#6366F1" />پرداخت
                          </span>
                        )}
                        {col.discount_code && (
                          <span style={{ fontSize: 10, padding: '1px 7px', borderRadius: 20, background: 'rgba(52,211,153,.1)', color: '#34D399', fontFamily: 'monospace' }}>
                            {col.discount_code}
                          </span>
                        )}
                        {!col.payment_link && !col.discount_code && (
                          <span className="text-xs text-3">{col.created_at?.slice(0, 10)}</span>
                        )}
                      </div>
                      <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
                        <button className="icon-btn" style={{ width: 26, height: 26 }} onClick={() => openEditCol(col)}>
                          <Icon name="edit-2" size={11} color="var(--text-3)" />
                        </button>
                        <button className="icon-btn" style={{ width: 26, height: 26 }} onClick={() => deleteCollection(col)}>
                          <Icon name="trash-2" size={11} color="#F87171" />
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )
      )}


      {/* ══════════════════════════════════════════════════
          تب: نظرسنجی
      ══════════════════════════════════════════════════ */}
      {!activeCol && tab === 'surveys' && (
        !surveys.length ? (
          <div className="card" style={{ textAlign: 'center', padding: 60 }}>
            <Icon name="clipboard-list" size={44} color="var(--text-3)" />
            <div className="semi mt-16">هنوز نظرسنجی نساختی</div>
            <div className="text-xs text-3 mt-8 mb-20">ربات به‌صورت رندوم برای لیدهای خریدار می‌فرسته</div>
            <Button kind="primary" icon="plus" onClick={() => setSurvModal(true)}>نظرسنجی جدید</Button>
          </div>
        ) : (
          <div className="col gap-8">
            {surveys.map(surv => {
              let qs = [];
              try { qs = JSON.parse(surv.questions || '[]'); } catch {}
              return (
                <div key={surv.id} className="card" style={{ padding: '14px 18px' }}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div className="semi text-sm mb-6">{surv.title}</div>
                      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                        <span className="text-xs text-3">{{ buyers: 'خریداران', all: 'همه لیدها', tag: 'تگ‌دار' }[surv.target_type]}</span>
                        <span className="text-xs text-3">{fa(qs.length)} سوال</span>
                        <span className="text-xs" style={{ color: '#A5B4FC' }}>ارسال: {fa(surv.sent_count)}</span>
                        <span className="text-xs" style={{ color: '#34D399' }}>پاسخ: {fa(surv.response_count)}</span>
                      </div>
                      {qs.length > 0 && (
                        <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
                          {qs.slice(0, 2).map((q, i) => (
                            <div key={i} className="text-xs text-3" style={{ marginBottom: 2 }}>{i + 1}. {q.text}</div>
                          ))}
                          {qs.length > 2 && <div className="text-xs text-3">و {fa(qs.length - 2)} سوال دیگر...</div>}
                        </div>
                      )}
                    </div>
                    <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                      <Button kind="primary" size="sm" icon="send" onClick={() => sendSurvey(surv)}>ارسال</Button>
                      <button className="icon-btn" style={{ width: 28, height: 28 }} onClick={() => deleteSurvey(surv)}>
                        <Icon name="trash-2" size={12} color="#F87171" />
                      </button>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )
      )}

      {/* ══════════════════════════════════════════════════
          تب: AI دستیار
      ══════════════════════════════════════════════════ */}
      {!activeCol && tab === 'ai' && (
        !aiData ? (
          <div className="card" style={{ textAlign: 'center', padding: 64 }}>
            <div style={{ fontSize: 48, marginBottom: 12 }}>🤖</div>
            <div className="semi" style={{ fontSize: 15, marginBottom: 8 }}>تحلیل هوشمند کتابخانه</div>
            <div className="text-xs text-3" style={{ marginBottom: 28, lineHeight: 2 }}>
              بر اساس فایل‌ها، تریگرها و آمار مکالمات پیشنهاد می‌ده<br />
              چه محتوایی کجا باید باشه
            </div>
            {aiLoading
              ? <div className="text-3 text-sm">در حال تحلیل...</div>
              : <Button kind="primary" icon="cpu" onClick={runAnalysis}>شروع تحلیل</Button>}
          </div>
        ) : (
          <div className="col gap-16">
            {/* آمار */}
            <div className="card" style={{ padding: '12px 18px' }}>
              <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
                {[
                  { label: 'فایل',     val: aiData.meta?.files         },
                  { label: 'اسکریپت', val: aiData.meta?.scripts       },
                  { label: 'تریگر',   val: aiData.meta?.triggers      },
                  { label: 'لید',      val: aiData.meta?.leads         },
                  { label: 'مکالمه',  val: aiData.meta?.conversations },
                ].map(m => (
                  <div key={m.label} style={{ textAlign: 'center' }}>
                    <div className="semi" style={{ fontSize: 20 }}>{fa(m.val || 0)}</div>
                    <div className="text-xs text-3">{m.label}</div>
                  </div>
                ))}
              </div>
            </div>
            {/* پیشنهادات */}
            {aiData.suggestions?.length > 0 && (
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                  <Icon name="sparkles" size={14} color="#A5B4FC" />
                  <span className="semi text-sm">پیشنهادات ({fa(aiData.suggestions.length)})</span>
                </div>
                <div className="col gap-8">
                  {aiData.suggestions.map((sug, idx) => (
                    <div key={idx} className="card" style={{ padding: '12px 16px', borderRight: `3px solid ${{ high: '#EF4444', medium: '#F59E0B', low: '#6366F1' }[sug.priority] || '#6B7280'}` }}>
                      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
                        <div style={{ flex: 1 }}>
                          <div className="semi text-sm mb-4">{sug.file_name}</div>
                          <div style={{ fontSize: 12, marginBottom: 4 }}>
                            <span className="text-3">→ </span>
                            <span style={{ color: sug.target_type === 'trigger' ? '#34D399' : '#A5B4FC' }}>{sug.target_name}</span>
                          </div>
                          <div className="text-xs text-3">{sug.reason}</div>
                        </div>
                        {applied[idx]
                          ? <span style={{ color: '#34D399', fontSize: 12, display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
                              <Icon name="check-circle" size={14} color="#34D399" />اعمال شد
                            </span>
                          : <Button kind="primary" size="sm" onClick={() => applySug(idx, sug)}>تأیید</Button>}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
            {/* هشدارها */}
            {aiData.warnings?.length > 0 && (
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                  <Icon name="alert-triangle" size={14} color="#FBBF24" />
                  <span className="semi text-sm">هشدارها ({fa(aiData.warnings.length)})</span>
                </div>
                <div className="col gap-8">
                  {aiData.warnings.map((w, idx) => (
                    <div key={idx} className="card" style={{ padding: '12px 16px', borderRight: `3px solid ${{ critical: '#EF4444', high: '#F59E0B', medium: '#6366F1' }[w.severity] || '#6B7280'}` }}>
                      <div className="semi text-sm mb-4">{w.title}</div>
                      <div className="text-xs text-3 mb-8">{w.body}</div>
                      {w.action_hint && (
                        <div style={{ fontSize: 11, color: '#A5B4FC', padding: '6px 10px', background: 'rgba(99,102,241,.07)', borderRadius: 7 }}>
                          💡 {w.action_hint}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )
      )}

      {/* ══════════════════════════════════════════════════
          تب: ارسال سریع
      ══════════════════════════════════════════════════ */}
      {!activeCol && tab === 'sendable' && (
        <div>
          {/* فیلتر دسته‌بندی */}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 20 }}>
            <button
              onClick={() => setSendCatFilter('')}
              style={{ padding: '6px 14px', borderRadius: 20, border: `2px solid ${sendCatFilter === '' ? 'var(--primary)' : 'transparent'}`, background: sendCatFilter === '' ? 'rgba(99,102,241,.13)' : 'var(--bg-2)', color: sendCatFilter === '' ? 'var(--primary)' : 'var(--text-2)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, transition: 'all .15s' }}>
              🗂 همه
            </button>
            {SEND_CATS.map(c => (
              <button key={c.id}
                onClick={() => setSendCatFilter(sendCatFilter === c.id ? '' : c.id)}
                style={{ padding: '6px 14px', borderRadius: 20, border: `2px solid ${sendCatFilter === c.id ? c.color : 'transparent'}`, background: sendCatFilter === c.id ? `${c.color}22` : 'var(--bg-2)', color: sendCatFilter === c.id ? c.color : 'var(--text-2)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, transition: 'all .15s' }}>
                {c.icon} {c.label}
              </button>
            ))}
          </div>

          {/* گرید فایل‌ها */}
          {sendLoading ? (
            <div style={{ textAlign: 'center', padding: 60, color: 'var(--text-3)' }}>در حال بارگذاری...</div>
          ) : (() => {
            const filtered = sendFiles.filter(f => !sendCatFilter || f.send_category === sendCatFilter);
            if (!filtered.length) return (
              <div className="card" style={{ textAlign: 'center', padding: 60 }}>
                <div style={{ fontSize: 40, marginBottom: 12 }}>📤</div>
                <div className="semi" style={{ marginBottom: 8 }}>فایلی برای ارسال سریع وجود ندارد</div>
                <div className="text-xs text-3" style={{ marginBottom: 20 }}>فایل‌هایی که می‌خواهید فروشنده‌ها بتوانند با یک کلیک ارسال کنند را آپلود کنید</div>
                <Button kind="primary" icon="upload" onClick={() => setSendUploadModal(true)}>آپلود فایل</Button>
              </div>
            );
            return (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
                {filtered.map(f => {
                  const catInfo = SEND_CATS.find(c => c.id === f.send_category) || { icon: '📎', label: f.send_category || 'متفرقه', color: '#64748b' };
                  const relIds = (() => { try { return JSON.parse(f.related_product_ids || '[]'); } catch { return []; } })();
                  const relProds = relIds.map(id => sendProducts.find(p => p.id === id)).filter(Boolean);
                  const ext = (f.name || '').split('.').pop().toLowerCase();
                  const fileIcon = { pdf: '📄', mp4: '🎬', mov: '🎬', avi: '🎬', jpg: '🖼', jpeg: '🖼', png: '🖼', gif: '🖼', xlsx: '📊', xls: '📊', docx: '📝', doc: '📝', mp3: '🎵', wav: '🎵', zip: '🗜' }[ext] || '📎';
                  return (
                    <div key={f.id} className="card" style={{ padding: 0, overflow: 'hidden', opacity: f.is_sendable ? 1 : 0.55 }}>
                      {/* هدر فایل */}
                      <div style={{ background: `${catInfo.color}18`, borderBottom: `1px solid ${catInfo.color}30`, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10 }}>
                        <span style={{ fontSize: 24 }}>{fileIcon}</span>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div className="semi text-sm" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.name}</div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 3 }}>
                            <span style={{ fontSize: 10, color: catInfo.color, background: `${catInfo.color}20`, padding: '2px 8px', borderRadius: 10 }}>{catInfo.icon} {catInfo.label}</span>
                          </div>
                        </div>
                        {/* سوییچ فعال/غیرفعال */}
                        <button
                          onClick={() => toggleSendable(f)}
                          title={f.is_sendable ? 'غیرفعال کردن' : 'فعال کردن'}
                          style={{ width: 34, height: 20, borderRadius: 10, border: 'none', cursor: 'pointer', background: f.is_sendable ? '#10B981' : '#475569', position: 'relative', transition: 'background .2s', flexShrink: 0 }}>
                          <span style={{ position: 'absolute', top: 2, right: f.is_sendable ? 2 : 14, width: 16, height: 16, borderRadius: '50%', background: '#fff', transition: 'right .2s', display: 'block' }} />
                        </button>
                      </div>

                      {/* محتوا */}
                      <div style={{ padding: '10px 14px' }}>
                        {f.description && (
                          <div className="text-xs text-3" style={{ marginBottom: 8, lineHeight: 1.6 }}>{f.description}</div>
                        )}
                        {/* محصولات مرتبط */}
                        {relProds.length > 0 ? (
                          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginBottom: 8 }}>
                            {relProds.map(p => (
                              <span key={p.id} style={{ fontSize: 10, padding: '2px 8px', borderRadius: 10, background: (p.color || '#6366f1') + '22', color: p.color || '#6366f1', border: `1px solid ${p.color || '#6366f1'}33` }}>{p.name}</span>
                            ))}
                          </div>
                        ) : (
                          <div className="text-xs text-3" style={{ marginBottom: 8 }}>برای همه محصولات</div>
                        )}

                        {/* دکمه‌ها */}
                        <div style={{ display: 'flex', gap: 6 }}>
                          <Button kind="ghost" size="sm" icon="edit-2" onClick={() => openSendEdit(f)}>ویرایش</Button>
                          {f.url && (
                            <a href={f.url} target="_blank" rel="noreferrer">
                              <Button kind="ghost" size="sm" icon="external-link">مشاهده</Button>
                            </a>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            );
          })()}
        </div>
      )}

      {/* ══════════════════════════════════════════════════
          مودال: ویرایش فایل ارسالی
      ══════════════════════════════════════════════════ */}
      <Modal open={!!sendEditModal} onClose={() => setSendEditModal(null)}
        title="ویرایش فایل ارسالی" width={520}
        footer={<><Button kind="primary" onClick={saveSendEdit}>ذخیره</Button><Button kind="ghost" onClick={() => setSendEditModal(null)}>انصراف</Button></>}>
        {sendEditModal && (
          <div className="col gap-14">
            <div>
              <label className="text-xs text-3 mb-6">نام نمایشی</label>
              <input className="input" value={sendEditForm.name || ''} onChange={e => setSendEditForm(f => ({ ...f, name: e.target.value }))} placeholder="نام فایل" />
            </div>
            <div>
              <label className="text-xs text-3 mb-6">توضیحات</label>
              <textarea className="input" rows={2} value={sendEditForm.description || ''} onChange={e => setSendEditForm(f => ({ ...f, description: e.target.value }))} placeholder="توضیح کوتاه برای فروشنده..." style={{ resize: 'vertical' }} />
            </div>
            <div>
              <label className="text-xs text-3 mb-6">دسته‌بندی ارسال</label>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {SEND_CATS.map(c => (
                  <button key={c.id}
                    onClick={() => setSendEditForm(f => ({ ...f, send_category: f.send_category === c.id ? '' : c.id }))}
                    style={{ padding: '6px 12px', borderRadius: 18, border: `2px solid ${sendEditForm.send_category === c.id ? c.color : 'transparent'}`, background: sendEditForm.send_category === c.id ? `${c.color}22` : 'var(--bg-2)', color: sendEditForm.send_category === c.id ? c.color : 'var(--text-2)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12 }}>
                    {c.icon} {c.label}
                  </button>
                ))}
              </div>
            </div>
            <div>
              <label className="text-xs text-3 mb-6">محصولات مرتبط <span className="text-3">(خالی = همه)</span></label>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 180, overflowY: 'auto' }}>
                {sendProducts.map(p => {
                  const checked = sendEditForm.related_product_ids?.includes(p.id);
                  return (
                    <label key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 10px', borderRadius: 8, background: checked ? 'rgba(99,102,241,.08)' : 'var(--bg-2)', cursor: 'pointer', border: `1px solid ${checked ? 'rgba(99,102,241,.3)' : 'transparent'}` }}>
                      <input type="checkbox" checked={!!checked} onChange={() => setSendEditForm(f => {
                        const ids = [...(f.related_product_ids || [])];
                        const i = ids.indexOf(p.id);
                        if (i >= 0) ids.splice(i, 1); else ids.push(p.id);
                        return { ...f, related_product_ids: ids };
                      })} style={{ accentColor: p.color || '#6366f1' }} />
                      <span style={{ width: 10, height: 10, borderRadius: '50%', background: p.color || '#6366f1', flexShrink: 0 }} />
                      <span className="text-sm">{p.name}</span>
                    </label>
                  );
                })}
              </div>
            </div>
          </div>
        )}
      </Modal>

      {/* ══════════════════════════════════════════════════
          مودال: آپلود فایل ارسالی
      ══════════════════════════════════════════════════ */}
      {sendUploadModal && (
        <SendUploadModalContent
          onClose={() => setSendUploadModal(false)}
          onUpload={uploadSendFile}
          uploading={sendUploading}
          sendCats={SEND_CATS}
        />
      )}

      {/* ══════════════════════════════════════════════════
          مودال: دسته جدید / ویرایش
      ══════════════════════════════════════════════════ */}
      <Modal open={colModal} onClose={closeColModal}
        title={editColId ? 'ویرایش دسته' : 'دسته جدید'} width={500}
        footer={<><Button kind="primary" onClick={saveCollection}>ذخیره</Button><Button kind="ghost" onClick={closeColModal}>انصراف</Button></>}>
        <div className="col gap-14">
          {/* نوع */}
          <div style={{ display: 'flex', gap: 6, padding: 4, background: 'var(--bg-2)', borderRadius: 10 }}>
            {[{ id: 'general', label: '📁 عمومی' }, { id: 'product', label: '📦 محصول' }].map(t => (
              <button key={t.id} onClick={() => setColForm(f => ({ ...f, type: t.id }))} style={{ flex: 1, padding: '8px', borderRadius: 8, border: 'none', cursor: 'pointer', background: colForm.type === t.id ? 'var(--surface)' : 'transparent', color: colForm.type === t.id ? 'var(--text-1)' : 'var(--text-3)', fontFamily: 'inherit', fontSize: 13, transition: 'all .15s' }}>{t.label}</button>
            ))}
          </div>
          <Field label="نام دسته">
            <input className="input" value={colForm.name} onChange={e => setColForm(f => ({ ...f, name: e.target.value }))} placeholder="مثلاً: دوره فروش آنلاین" autoFocus />
          </Field>
          <Field label="توضیح (اختیاری)">
            <input className="input" value={colForm.description} onChange={e => setColForm(f => ({ ...f, description: e.target.value }))} placeholder="توضیح کوتاه" />
          </Field>
          <Field label="رنگ">
            <div style={{ display: 'flex', gap: 8 }}>
              {COL_COLORS.map(c => (
                <button key={c} onClick={() => setColForm(f => ({ ...f, color: c }))} style={{ width: 28, height: 28, borderRadius: 8, background: c, border: colForm.color === c ? '3px solid rgba(255,255,255,.8)' : '3px solid transparent', cursor: 'pointer', outline: colForm.color === c ? `2px solid ${c}` : 'none', outlineOffset: 1 }} />
              ))}
            </div>
          </Field>
          {colForm.type === 'product' && (
            <>
              <Field label="لینک پرداخت (اختیاری)">
                <input className="input" value={colForm.payment_link} onChange={e => setColForm(f => ({ ...f, payment_link: e.target.value }))} placeholder="https://..." />
              </Field>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                <Field label="کد کوپن">
                  <input className="input mono" value={colForm.discount_code} onChange={e => setColForm(f => ({ ...f, discount_code: e.target.value }))} placeholder="SALE20" />
                </Field>
                <Field label="مقدار تخفیف">
                  <input className="input" value={colForm.discount_value} onChange={e => setColForm(f => ({ ...f, discount_value: e.target.value }))} placeholder="۲۰٪ یا ۵۰،۰۰۰ تومان" />
                </Field>
              </div>
            </>
          )}
        </div>
      </Modal>

      {/* ══════════════════════════════════════════════════
          مودال: افزودن آیتم
      ══════════════════════════════════════════════════ */}
      <Modal open={itemModal} onClose={closeItemModal}
        title="افزودن آیتم" width={480}
        footer={<><Button kind="primary" onClick={addItem}>اضافه</Button><Button kind="ghost" onClick={closeItemModal}>انصراف</Button></>}>
        <div className="col gap-14">

          {/* ── انتخاب بخش (فقط محصول) ── */}
          {activeCol?.collection?.type === 'product' && (() => {
            const PROD_SECS = [
              { id: 'intro',       label: 'معرفی محصول',  icon: 'package', color: '#3B82F6' },
              { id: 'testimonial', label: 'مشتری راضی',    icon: 'heart',   color: '#EC4899' },
              { id: 'offer',       label: 'پیشنهاد ویژه', icon: 'tag',     color: '#F59E0B' },
              { id: 'group',       label: 'گروه / کانال', icon: 'users',   color: '#10B981' },
              { id: 'general',     label: 'عمومی',         icon: 'folder',  color: '#6B7280' },
            ];
            return (
              <div>
                <div className="text-xs text-3" style={{ marginBottom: 8 }}>این آیتم مربوط به کدام بخش است؟</div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {PROD_SECS.map(s => {
                    const active = itemForm.section === s.id;
                    return (
                      <button key={s.id} onClick={() => setItemForm(f => ({ ...f, section: s.id }))}
                        style={{
                          display: 'flex', alignItems: 'center', gap: 6,
                          padding: '7px 12px', borderRadius: 10, border: 'none', cursor: 'pointer',
                          background: active ? `${s.color}20` : 'var(--bg-2)',
                          color: active ? s.color : 'var(--text-3)',
                          fontFamily: 'inherit', fontSize: 12, fontWeight: active ? 600 : 400,
                          outline: active ? `1.5px solid ${s.color}50` : 'none',
                          transition: 'all .15s',
                        }}>
                        <Icon name={active ? 'check-circle' : s.icon} size={13} color={active ? s.color : 'var(--text-3)'} />
                        {s.label}
                      </button>
                    );
                  })}
                </div>
              </div>
            );
          })()}

          {/* ── نوع آیتم ── */}
          <div style={{ display: 'flex', gap: 6 }}>
            {[{ id: 'file', icon: 'file', label: 'فایل' }, { id: 'link', icon: 'link', label: 'لینک' }, { id: 'text', icon: 'type', label: 'متن' }].map(t => (
              <button key={t.id} onClick={() => setItemForm(f => ({ ...f, item_type: t.id }))}
                style={{ flex: 1, padding: '9px', borderRadius: 9, border: 'none', cursor: 'pointer', background: itemForm.item_type === t.id ? 'var(--primary)' : 'var(--bg-2)', color: itemForm.item_type === t.id ? '#fff' : 'var(--text-3)', fontFamily: 'inherit', fontSize: 13, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, transition: 'all .15s' }}>
                <Icon name={t.icon} size={13} color="currentColor" />{t.label}
              </button>
            ))}
          </div>

          {/* ── فیلدهای پویا ── */}
          {itemForm.item_type === 'file' && (
            <div>
              {itemForm.file_id ? (
                /* فایل آپلود شده */
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 10, background: 'rgba(52,211,153,.06)', border: '1px solid rgba(52,211,153,.2)' }}>
                  <Icon name="check-circle" size={16} color="#34D399" />
                  <span className="text-sm semi" style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{itemForm._fileName || 'فایل آپلود شد'}</span>
                  <button onClick={changeFile}
                    style={{ border: 'none', background: 'none', color: 'var(--text-3)', cursor: 'pointer', fontSize: 13 }}>تغییر</button>
                </div>
              ) : (
                /* ناحیه آپلود */
                <label style={{ display: 'block', cursor: uploading ? 'wait' : 'pointer' }}>
                  <input type="file" style={{ display: 'none' }} disabled={uploading}
                    onChange={e => { if (e.target.files[0]) uploadForItem(e.target.files[0]); }} />
                  <div style={{
                    border: '2px dashed rgba(99,102,241,.3)', borderRadius: 12,
                    padding: '24px 16px', textAlign: 'center',
                    background: 'rgba(99,102,241,.03)',
                    opacity: uploading ? 0.6 : 1,
                  }}>
                    <Icon name={uploading ? 'loader' : 'upload-cloud'} size={26} color="#6366F1" />
                    <div className="semi text-sm mt-8" style={{ color: 'var(--text-2)' }}>
                      {uploading ? 'در حال آپلود...' : 'کلیک کن یا فایل بکش اینجا'}
                    </div>
                    <div className="text-xs text-3 mt-4">ویدیو · صوت · PDF · تصویر · متن — تا ۲۰۰MB</div>
                  </div>
                </label>
              )}
            </div>
          )}
          {itemForm.item_type === 'link' && (
            <Field label="آدرس لینک">
              <input className="input" value={itemForm.url} onChange={e => setItemForm(f => ({ ...f, url: e.target.value }))} placeholder="https://t.me/... یا هر لینک" autoFocus />
            </Field>
          )}
          {itemForm.item_type === 'text' && (
            <Field label="متن">
              <textarea className="input" rows={4} value={itemForm.content} onChange={e => setItemForm(f => ({ ...f, content: e.target.value }))} placeholder="پیام آماده یا توضیحات..." style={{ resize: 'vertical', fontFamily: 'inherit', fontSize: 13 }} autoFocus />
            </Field>
          )}

          <Field label="عنوان (اختیاری)">
            <input className="input" value={itemForm.title} onChange={e => setItemForm(f => ({ ...f, title: e.target.value }))} placeholder="نام نمایشی — اگه خالی بمونه، نام فایل/لینک نشون داده می‌شه" />
          </Field>

        </div>
      </Modal>

      {/* ══════════════════════════════════════════════════
          مودال: نظرسنجی جدید
      ══════════════════════════════════════════════════ */}
      <Modal open={survModal} onClose={() => { setSurvModal(false); setSurvForm(EMPTY_SURV); }}
        title="نظرسنجی جدید" width={560}
        footer={<><Button kind="primary" onClick={createSurvey}>ذخیره</Button><Button kind="ghost" onClick={() => { setSurvModal(false); setSurvForm(EMPTY_SURV); }}>انصراف</Button></>}>
        <div className="col gap-14">
          <Field label="عنوان">
            <input className="input" value={survForm.title} onChange={e => setSurvForm(f => ({ ...f, title: e.target.value }))} placeholder="رضایت از دوره فروش آنلاین" autoFocus />
          </Field>
          <Field label="مخاطبان">
            <select className="select" value={survForm.target_type} onChange={e => setSurvForm(f => ({ ...f, target_type: e.target.value }))}>
              <option value="buyers">فقط خریداران</option>
              <option value="all">همه لیدها</option>
              <option value="tag">لیدهای با تگ خاص</option>
            </select>
          </Field>
          <Field label={`سوال‌ها`}>
            <div className="col gap-8">
              {survForm.questions.map((q, i) => (
                <div key={q.id} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  <span className="text-xs text-3 mono" style={{ flexShrink: 0, width: 18 }}>{i + 1}.</span>
                  <input className="input" style={{ flex: 1 }} value={q.text}
                    onChange={e => setSurvForm(f => ({ ...f, questions: f.questions.map((x, j) => j === i ? { ...x, text: e.target.value } : x) }))}
                    placeholder={`سوال ${i + 1}...`} />
                  <select className="select" style={{ width: 88, flexShrink: 0 }} value={q.type}
                    onChange={e => setSurvForm(f => ({ ...f, questions: f.questions.map((x, j) => j === i ? { ...x, type: e.target.value } : x) }))}>
                    <option value="text">متنی</option>
                    <option value="rating">امتیاز</option>
                  </select>
                  {survForm.questions.length > 1 && (
                    <button onClick={() => setSurvForm(f => ({ ...f, questions: f.questions.filter((_, j) => j !== i) }))}
                      style={{ border: 'none', background: 'none', color: '#F87171', cursor: 'pointer', flexShrink: 0, display: 'flex', padding: 4 }}>
                      <Icon name="x" size={14} />
                    </button>
                  )}
                </div>
              ))}
              <button onClick={() => setSurvForm(f => ({ ...f, questions: [...f.questions, { id: Date.now(), text: '', type: 'text' }] }))}
                style={{ padding: '8px', borderRadius: 9, border: '1.5px dashed rgba(99,102,241,.3)', background: 'transparent', color: '#A5B4FC', cursor: 'pointer', fontSize: 12, fontFamily: 'inherit' }}>
                + سوال جدید
              </button>
            </div>
          </Field>
        </div>
      </Modal>

      {/* Ghost هنگام drag آیتم */}
      {dragState && (
        <div ref={ghostRef} style={{
          position: 'fixed', top: 0, left: 0,
          pointerEvents: 'none', zIndex: 9999,
          background: 'var(--surface)', border: '1.5px solid #6366F1',
          borderRadius: 10, padding: '7px 14px',
          boxShadow: '0 8px 32px rgba(0,0,0,.5)',
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 12, fontWeight: 600, color: 'var(--text-1)',
          maxWidth: 220, overflow: 'hidden',
        }}>
          <Icon name="grip-vertical" size={13} color="#6366F1" />
          <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {dragState.title}
          </span>
        </div>
      )}

      {/* Ghost هنگام drag دسته */}
      {colDragState && (
        <div ref={colGhostRef} style={{
          position: 'fixed', top: 0, left: 0,
          pointerEvents: 'none', zIndex: 9999,
          background: 'var(--surface)', border: '1.5px solid #6366F1',
          borderRadius: 10, padding: '7px 16px',
          boxShadow: '0 8px 32px rgba(0,0,0,.5)',
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 12, fontWeight: 600, color: 'var(--text-1)',
          maxWidth: 240, overflow: 'hidden',
        }}>
          <Icon name="layout-grid" size={13} color="#6366F1" />
          <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {colDragState.name}
          </span>
        </div>
      )}

      {/* مودال انتقال آیتم به دسته دیگر */}
      {moveModal && (
        <Modal title="انتقال به دسته دیگر" onClose={() => { setMoveModal(false); setMoveItem_(null); }}>
          <div className="col gap-16">
            <div style={{ padding: '10px 14px', background: 'var(--bg)', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10 }}>
              <Icon name="file-text" size={15} color="var(--text-3)" />
              <span className="text-sm semi">{moveItem_?.title || moveItem_?.file?.original_name || 'آیتم'}</span>
            </div>

            <Field label="دسته مقصد">
              <select
                value={moveColId}
                onChange={e => setMoveColId(e.target.value)}
                style={{
                  width: '100%', padding: '9px 12px', borderRadius: 8,
                  background: 'var(--bg)', border: '1px solid var(--border)',
                  color: 'var(--text-1)', fontSize: 13,
                }}>
                <option value="">انتخاب کن...</option>
                {collections
                  .filter(c => !activeCol || c.id !== activeCol.collection.id)
                  .map(c => (
                    <option key={c.id} value={c.id}>{c.name}</option>
                  ))}
              </select>
            </Field>

            <Field label="بخش مقصد">
              <select
                value={moveSec}
                onChange={e => setMoveSec(e.target.value)}
                style={{
                  width: '100%', padding: '9px 12px', borderRadius: 8,
                  background: 'var(--bg)', border: '1px solid var(--border)',
                  color: 'var(--text-1)', fontSize: 13,
                }}>
                <option value="general">عمومی</option>
                <option value="intro">معرفی</option>
                <option value="testimonial">توصیه‌نامه</option>
                <option value="offer">پیشنهاد</option>
                <option value="group">گروه</option>
              </select>
            </Field>

            <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', paddingTop: 4 }}>
              <Button kind="ghost" onClick={() => { setMoveModal(false); setMoveItem_(null); }}>لغو</Button>
              <Button kind="primary" icon="move-right" onClick={confirmMove}>انتقال</Button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
};

window.Library = Library;
