Files
canina/frontend/admin-panel/src/pages/Blogs.tsx
T

1825 lines
86 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
Calendar,
CheckCircle2,
Clock,
Edit2,
Eye,
FileText,
FolderTree,
Globe,
Image as ImageIcon,
Layers,
Pin,
Plus,
Search,
Share2,
ShoppingBag,
Sparkles,
Tag,
Trash2,
X,
XCircle
} from 'lucide-react';
import { useCallback,useEffect,useState } from 'react';
import { toast } from 'react-hot-toast';
import { useSearchParams } from 'react-router-dom';
import Button from '../components/ui/Button';
import ConfirmModal from '../components/ui/ConfirmModal';
import MediaSelector from '../components/ui/MediaSelector';
import Modal from '../components/ui/Modal';
import Pagination from '../components/ui/Pagination';
import RichTextEditor from '../components/ui/RichTextEditor';
import Spinner from '../components/ui/Spinner';
import api,{ BASE_DOMAIN } from '../services/api';
export interface BlogCategory {
id: string;
name: string;
slug: string;
parentId?: string | null;
children?: BlogCategory[];
parent?: BlogCategory | null;
}
export interface BlogTag {
id: string;
name: string;
slug: string;
}
export interface AuthorUser {
id: string;
firstName: string;
lastName: string;
email?: string;
role?: string;
}
export interface ProductSimple {
id: string;
nameFa: string;
slug: string;
imageUrl?: string;
priceValue?: number;
}
export interface BlogPost {
id: string;
title: string;
slug: string;
content: string;
excerpt?: string;
authorId?: string;
authorTeam?: string;
authorRole?: string;
contentUpdatedAt?: string | null;
author?: {
id?: string;
firstName?: string;
lastName?: string;
email?: string;
};
categoryId?: string | null;
category?: BlogCategory | null;
tags?: BlogTag[];
imageUrl?: string;
imageAlt?: string;
imageCaption?: string;
metaTitle?: string;
metaDescription?: string;
keywords?: string;
canonicalUrl?: string;
ogTitle?: string;
ogDescription?: string;
ogImage?: string;
status: 'DRAFT' | 'PUBLISHED' | 'SCHEDULED' | 'ARCHIVED';
isPublished: boolean;
publishedAt?: string | null;
scheduledAt?: string | null;
readingTime: number;
featured: boolean;
allowComments: boolean;
viewCount: number;
showOnHome: boolean;
relatedProductIds: string[];
relatedBlogIds: string[];
createdAt?: string;
updatedAt?: string;
_count?: {
comments: number;
};
}
export default function Blogs() {
const [searchParams, setSearchParams] = useSearchParams();
const [blogs, setBlogs] = useState<BlogPost[]>([]);
const [categories, setCategories] = useState<BlogCategory[]>([]);
const [tagsList, setTagsList] = useState<BlogTag[]>([]);
const [authors, setAuthors] = useState<AuthorUser[]>([]);
const [allProducts, setAllProducts] = useState<ProductSimple[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [search, setSearch] = useState(() => searchParams.get('search') || '');
const [statusFilter, setStatusFilter] = useState(() => searchParams.get('status') || 'ALL');
const [categoryFilter, setCategoryFilter] = useState(() => searchParams.get('categoryId') || 'ALL');
const [page, setPage] = useState(() => Number(searchParams.get('page')) || 1);
const [totalPages, setTotalPages] = useState(1);
const limit = 10;
// Active Tab inside Blog Form Modal
const [activeFormTab, setActiveFormTab] = useState<'content' | 'media' | 'seo' | 'relations' | 'publishing'>('content');
// Modals state
const [isModalOpen, setIsModalOpen] = useState(false);
const [isLivePreviewOpen, setIsLivePreviewOpen] = useState(false);
const [isMediaSelectorOpen, setIsMediaSelectorOpen] = useState(false);
const [mediaSelectTarget, setMediaSelectTarget] = useState<'featured' | 'ogImage'>('featured');
const [editingBlog, setEditingBlog] = useState<BlogPost | null>(null);
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
// Category & Tag Management Modal
const [isCatTagModalOpen, setIsCatTagModalOpen] = useState(false);
const [newCatName, setNewCatName] = useState('');
const [newCatSlug, setNewCatSlug] = useState('');
const [newCatParentId, setNewCatParentId] = useState('');
const [newTagName, setNewTagName] = useState('');
// Tag Input in Edit Form
const [currentTagInput, setCurrentTagInput] = useState('');
// Auto-slug manual override flag
const [isSlugManuallyEdited, setIsSlugManuallyEdited] = useState(false);
// Unsaved Local Draft State
const [hasSavedDraft, setHasSavedDraft] = useState(false);
const updateUrlParams = (paramsObj: Record<string, string | number | undefined | null>) => {
const current = Object.fromEntries(searchParams.entries());
const merged = { ...current, ...paramsObj };
const cleaned: Record<string, string> = {};
Object.entries(merged).forEach(([k, v]) => {
if (v !== undefined && v !== null && String(v).trim() !== '' && String(v) !== 'ALL') {
cleaned[k] = String(v);
}
});
setSearchParams(cleaned, { replace: true });
};
const [formData, setFormData] = useState({
title: '',
slug: '',
content: '',
excerpt: '',
authorId: '',
authorTeam: '',
authorRole: '',
markContentUpdated: false,
categoryId: '',
tagNames: [] as string[],
imageUrl: '',
imageAlt: '',
imageCaption: '',
metaTitle: '',
metaDescription: '',
keywords: '',
focusKeywords: '',
canonicalUrl: '',
noIndex: false,
noFollow: false,
schemaType: 'BlogPosting',
ogTitle: '',
ogDescription: '',
ogImage: '',
status: 'PUBLISHED' as 'DRAFT' | 'PUBLISHED' | 'SCHEDULED' | 'ARCHIVED',
isPublished: true,
publishedAt: '',
scheduledAt: '',
readingTime: 3,
featured: false,
allowComments: true,
showOnHome: false,
relatedProductIds: [] as string[],
relatedBlogIds: [] as string[],
});
// Calculate reading time automatically based on word count
const calculateReadingTime = (htmlContent: string) => {
const textOnly = htmlContent.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
const wordCount = textOnly ? textOnly.split(' ').length : 0;
const wordsPerMinute = 200;
const minutes = Math.max(1, Math.ceil(wordCount / wordsPerMinute));
return minutes;
};
// Auto-generate slug from title
const generateSlug = (text: string) => {
return text
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^\w\u0600-\u06FF-]+/g, '')
.substring(0, 180);
};
const handleTitleChange = (newTitle: string) => {
setFormData((prev) => {
const updated = { ...prev, title: newTitle };
if (!isSlugManuallyEdited && (!editingBlog || !prev.slug)) {
updated.slug = generateSlug(newTitle);
}
return updated;
});
};
const handleContentChange = (newContent: string) => {
setFormData((prev) => ({
...prev,
content: newContent,
readingTime: calculateReadingTime(newContent),
}));
};
const openModal = (blog: BlogPost | null = null) => {
setActiveFormTab('content');
setIsSlugManuallyEdited(false);
if (blog) {
setEditingBlog(blog);
updateUrlParams({ modal: 'edit', blogId: blog.id });
setFormData({
title: blog.title,
slug: blog.slug,
content: blog.content || '',
excerpt: blog.excerpt || '',
authorId: blog.authorId || (blog.author?.id || ''),
authorTeam: blog.authorTeam || '',
authorRole: blog.authorRole || '',
markContentUpdated: false,
categoryId: blog.categoryId || '',
tagNames: blog.tags ? blog.tags.map((t) => t.name) : [],
imageUrl: blog.imageUrl || '',
imageAlt: blog.imageAlt || '',
imageCaption: blog.imageCaption || '',
metaTitle: blog.metaTitle || '',
metaDescription: blog.metaDescription || '',
keywords: blog.keywords || '',
focusKeywords: (blog as any).focusKeywords || '',
canonicalUrl: blog.canonicalUrl || '',
noIndex: Boolean((blog as any).noIndex),
noFollow: Boolean((blog as any).noFollow),
schemaType: (blog as any).schemaType || 'BlogPosting',
ogTitle: blog.ogTitle || '',
ogDescription: blog.ogDescription || '',
ogImage: blog.ogImage || '',
status: blog.status || (blog.isPublished ? 'PUBLISHED' : 'DRAFT'),
isPublished: blog.isPublished !== false,
publishedAt: blog.publishedAt ? new Date(blog.publishedAt).toISOString().slice(0, 16) : '',
scheduledAt: blog.scheduledAt ? new Date(blog.scheduledAt).toISOString().slice(0, 16) : '',
readingTime: blog.readingTime || calculateReadingTime(blog.content || ''),
featured: Boolean(blog.featured),
allowComments: blog.allowComments !== false,
showOnHome: Boolean(blog.showOnHome),
relatedProductIds: blog.relatedProductIds || [],
relatedBlogIds: blog.relatedBlogIds || [],
});
} else {
setEditingBlog(null);
updateUrlParams({ modal: 'create', blogId: undefined });
setFormData({
title: '',
slug: '',
content: '',
excerpt: '',
authorId: authors[0]?.id || '',
authorTeam: '',
authorRole: '',
markContentUpdated: false,
categoryId: '',
tagNames: [],
imageUrl: '',
imageAlt: '',
imageCaption: '',
metaTitle: '',
metaDescription: '',
keywords: '',
focusKeywords: '',
canonicalUrl: '',
noIndex: false,
noFollow: false,
schemaType: 'BlogPosting',
ogTitle: '',
ogDescription: '',
ogImage: '',
status: 'PUBLISHED',
isPublished: true,
publishedAt: new Date().toISOString().slice(0, 16),
scheduledAt: '',
readingTime: 3,
featured: false,
allowComments: true,
showOnHome: false,
relatedProductIds: [],
relatedBlogIds: [],
});
}
setIsModalOpen(true);
};
const DRAFT_STORAGE_KEY = 'canina_admin_blog_draft_v1';
// Check for saved draft on mount
useEffect(() => {
try {
const saved = localStorage.getItem(DRAFT_STORAGE_KEY);
if (saved) {
const parsed = JSON.parse(saved);
if (parsed && (parsed.title || parsed.content)) {
setHasSavedDraft(true);
}
}
} catch {
// ignore
}
}, []);
// Auto-save unsaved blog form content
useEffect(() => {
if (!isModalOpen) return;
if (editingBlog) return; // Don't auto-save over existing published blogs
if (!formData.title && !formData.content) return;
const timer = setTimeout(() => {
try {
localStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(formData));
setHasSavedDraft(true);
} catch {
// ignore quota
}
}, 1000);
return () => clearTimeout(timer);
}, [formData, isModalOpen, editingBlog]);
const restoreDraft = () => {
try {
const saved = localStorage.getItem(DRAFT_STORAGE_KEY);
if (saved) {
const parsed = JSON.parse(saved);
setFormData((prev) => ({ ...prev, ...parsed }));
toast.success('پیش‌نویس ذخیره‌شده با موفقیت بازیابی شد');
setHasSavedDraft(false);
}
} catch {
toast.error('خطا در بازیابی پیش‌نویس');
}
};
const discardDraft = () => {
try {
localStorage.removeItem(DRAFT_STORAGE_KEY);
setHasSavedDraft(false);
toast.success('پیش‌نویس محلی پاک شد');
} catch {
// ignore
}
};
const closeModal = () => {
setIsModalOpen(false);
updateUrlParams({ modal: undefined, blogId: undefined });
};
const fetchAuxiliaryData = useCallback(async () => {
try {
const [catsRes, tagsRes, authorsRes, prodsRes] = await Promise.allSettled([
api.get('/admin/blogs/categories'),
api.get('/admin/blogs/tags'),
api.get('/admin/blogs/authors'),
api.get('/admin/products', { params: { limit: 100 } }),
]);
if (catsRes.status === 'fulfilled' && catsRes.value.data?.data) {
setCategories(catsRes.value.data.data);
}
if (tagsRes.status === 'fulfilled' && tagsRes.value.data?.data) {
setTagsList(tagsRes.value.data.data);
}
if (authorsRes.status === 'fulfilled' && authorsRes.value.data?.data) {
setAuthors(authorsRes.value.data.data);
}
if (prodsRes.status === 'fulfilled' && prodsRes.value.data?.data) {
setAllProducts(prodsRes.value.data.data);
}
} catch (error) {
console.error('Failed to load auxiliary blog data', error);
}
}, []);
const fetchBlogs = useCallback(async () => {
try {
setIsLoading(true);
const params: any = { page, limit, search };
if (statusFilter !== 'ALL') params.status = statusFilter;
if (categoryFilter !== 'ALL') params.categoryId = categoryFilter;
const res = await api.get('/admin/blogs', { params });
if (res.data?.data) {
const blogList: BlogPost[] = res.data.data;
setBlogs(blogList);
setTotalPages(res.data.meta?.lastPage || 1);
const modalParam = searchParams.get('modal');
const blogId = searchParams.get('blogId');
if (modalParam === 'create') {
openModal(null);
} else if (modalParam === 'edit' && blogId) {
const found = blogList.find((b) => b.id === blogId);
if (found) openModal(found);
}
}
} catch (err) {
console.error(err);
toast.error('خطا در دریافت لیست مقالات');
} finally {
setIsLoading(false);
}
}, [page, search, statusFilter, categoryFilter, searchParams]);
useEffect(() => {
fetchAuxiliaryData();
}, [fetchAuxiliaryData]);
useEffect(() => {
const timer = setTimeout(() => {
fetchBlogs();
}, 400);
return () => clearTimeout(timer);
}, [fetchBlogs]);
// Tag helper
const addTag = (tagText: string) => {
const trimmed = tagText.trim().replace(/^#/, '');
if (trimmed && !formData.tagNames.includes(trimmed)) {
setFormData((prev) => ({ ...prev, tagNames: [...prev.tagNames, trimmed] }));
}
setCurrentTagInput('');
};
const removeTag = (tagToRemove: string) => {
setFormData((prev) => ({
...prev,
tagNames: prev.tagNames.filter((t) => t !== tagToRemove),
}));
};
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.title.trim()) {
toast.error('عنوان مقاله نمی‌تواند خالی باشد');
return;
}
if (!formData.slug.trim()) {
toast.error('اسلاگ (Slug) مقاله الزامی است');
return;
}
if (formData.imageUrl && !formData.imageAlt?.trim()) {
setActiveFormTab('media');
toast.error('لطفاً متن جایگزین تصویر (Alt) را در تب تصویر وارد کنید (برای سئو الزامی است)');
return;
}
try {
const payload = {
...formData,
isPublished: formData.status === 'PUBLISHED',
scheduledAt: formData.scheduledAt ? new Date(formData.scheduledAt).toISOString() : null,
};
if (editingBlog) {
await api.put(`/admin/blogs/${editingBlog.id}`, payload);
toast.success('مقاله با موفقیت ویرایش و بروزرسانی شد');
} else {
await api.post('/admin/blogs', payload);
toast.success('مقاله جدید با موفقیت ذخیره شد');
try {
localStorage.removeItem(DRAFT_STORAGE_KEY);
setHasSavedDraft(false);
} catch {
// ignore
}
}
closeModal();
fetchBlogs();
fetchAuxiliaryData();
} catch (error) {
console.error('Save failed', error);
toast.error('خطا در ذخیره مقاله');
}
};
const confirmDelete = async () => {
if (!deleteTargetId) return;
try {
await api.delete(`/admin/blogs/${deleteTargetId}`);
toast.success('مقاله با موفقیت حذف شد');
fetchBlogs();
} catch (error) {
console.error('Delete failed', error);
toast.error('خطا در حذف مقاله');
} finally {
setDeleteTargetId(null);
}
};
// Quick Category creation
const handleCreateCategory = async (e: React.FormEvent) => {
e.preventDefault();
if (!newCatName.trim()) return;
try {
const slug = newCatSlug.trim() || generateSlug(newCatName);
await api.post('/admin/blogs/categories', {
name: newCatName.trim(),
slug,
...(newCatParentId ? { parent: { connect: { id: newCatParentId } } } : {}),
});
toast.success('دسته‌بندی جدید ایجاد شد');
setNewCatName('');
setNewCatSlug('');
setNewCatParentId('');
fetchAuxiliaryData();
} catch {
toast.error('خطا در ایجاد دسته‌بندی');
}
};
// Quick Tag creation
const handleCreateTag = async (e: React.FormEvent) => {
e.preventDefault();
if (!newTagName.trim()) return;
try {
await api.post('/admin/blogs/tags', { name: newTagName.trim() });
toast.success('برچسب جدید ایجاد شد');
setNewTagName('');
fetchAuxiliaryData();
} catch {
toast.error('خطا در ایجاد تگ');
}
};
// Helper status badge
const renderStatusBadge = (status: string, _isPublished: boolean, scheduledAt?: string | null) => {
switch (status) {
case 'PUBLISHED':
return (
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-emerald-50 text-emerald-700 border border-emerald-200 rounded-full text-xs font-black">
<CheckCircle2 className="w-3.5 h-3.5" />
منتشر شده
</span>
);
case 'SCHEDULED': {
const dateStr = scheduledAt ? new Date(scheduledAt).toLocaleDateString('fa-IR') : '';
return (
<span
className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-blue-50 text-blue-700 border border-blue-200 rounded-full text-xs font-black"
title={scheduledAt ? `موعد انتشار: ${new Date(scheduledAt).toLocaleString('fa-IR')}` : undefined}
>
<Clock className="w-3.5 h-3.5" />
{dateStr ? `در صف: ${dateStr}` : 'زمان‌بندی شده'}
</span>
);
}
case 'ARCHIVED':
return (
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-gray-100 text-gray-700 border border-gray-200 rounded-full text-xs font-black">
<Layers className="w-3.5 h-3.5" />
بایگانی
</span>
);
case 'DRAFT':
default:
return (
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-amber-50 text-amber-700 border border-amber-200 rounded-full text-xs font-black">
<XCircle className="w-3.5 h-3.5" />
پیش‌نویس
</span>
);
}
};
return (
<div className="space-y-6 font-vazir text-right" dir="rtl">
{/* Header Bar */}
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-white p-6 rounded-3xl border border-gray-200 shadow-xs">
<div>
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-3">
<div className="w-10 h-10 rounded-2xl bg-purple-100 text-purple-600 flex items-center justify-center">
<FileText className="w-5 h-5" />
</div>
<span>مدیریت جامع وبلاگ و دانشنامه سلامت</span>
</h2>
<p className="text-gray-500 font-medium text-xs sm:text-sm mt-1">
سیستم انتشار مقالات علمی، ادیتور پیشرفته چندرسانه‌ای، مدیریت دسته‌بندی و سئو
</p>
</div>
<div className="flex items-center gap-2 w-full sm:w-auto">
<Button
variant="outline"
size="sm"
startIcon={FolderTree}
onClick={() => setIsCatTagModalOpen(true)}
className="flex-1 sm:flex-none text-xs"
>
دسته‌ها و تگ‌ها
</Button>
<Button
variant="primary"
size="sm"
startIcon={Plus}
onClick={() => openModal()}
className="flex-1 sm:flex-none text-xs"
>
مقاله جدید
</Button>
</div>
</div>
{/* Filter Bar */}
<div className="bg-white p-4 rounded-3xl shadow-xs border border-gray-200 flex flex-col md:flex-row items-center gap-3">
<div className="relative flex-1 w-full">
<Search className="w-4 h-4 absolute right-4 top-1/2 -translate-y-1/2 text-gray-400" />
<input
type="text"
placeholder="جستجو در عنوان، چکیده و اسلاگ مقالات..."
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
className="w-full pl-4 pr-11 py-2.5 rounded-2xl border border-gray-200 focus:border-purple-500 text-xs sm:text-sm outline-none"
/>
</div>
<div className="flex items-center gap-2 w-full md:w-auto">
<select
value={statusFilter}
onChange={(e) => {
setStatusFilter(e.target.value);
setPage(1);
updateUrlParams({ status: e.target.value });
}}
className="px-3 py-2.5 rounded-2xl border border-gray-200 text-xs font-bold outline-none bg-gray-50/50"
>
<option value="ALL">همه وضعیت‌ها</option>
<option value="PUBLISHED">منتشر شده</option>
<option value="DRAFT">پیش‌نویس</option>
<option value="SCHEDULED">زمان‌بندی شده</option>
<option value="ARCHIVED">بایگانی شده</option>
</select>
<select
value={categoryFilter}
onChange={(e) => {
setCategoryFilter(e.target.value);
setPage(1);
updateUrlParams({ categoryId: e.target.value });
}}
className="px-3 py-2.5 rounded-2xl border border-gray-200 text-xs font-bold outline-none bg-gray-50/50"
>
<option value="ALL">همه دسته‌بندی‌ها</option>
{categories.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
</div>
</div>
{/* Main Table */}
<div className="bg-white rounded-3xl shadow-xs border border-gray-200 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-right">
<thead className="bg-gray-50/80 border-b border-gray-100">
<tr>
<th className="py-4 px-6 text-xs font-black text-gray-500">تصویر</th>
<th className="py-4 px-6 text-xs font-black text-gray-500">عنوان و خلاصه مقاله</th>
<th className="py-4 px-6 text-xs font-black text-gray-500">دسته‌بندی و تگ‌ها</th>
<th className="py-4 px-6 text-xs font-black text-gray-500">نویسنده</th>
<th className="py-4 px-6 text-xs font-black text-gray-500">زمان مطالعه</th>
<th className="py-4 px-6 text-xs font-black text-gray-500">وضعیت</th>
<th className="py-4 px-6 text-xs font-black text-gray-500 w-28">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{isLoading ? (
<tr>
<td colSpan={7} className="py-16 text-center">
<Spinner size="lg" className="mx-auto text-purple-600" />
</td>
</tr>
) : blogs.length === 0 ? (
<tr>
<td colSpan={7} className="py-16 text-center text-gray-500 font-bold">
هیچ مقاله‌ای یافت نشد.
</td>
</tr>
) : (
blogs.map((blog) => (
<tr key={blog.id} className="hover:bg-gray-50/60 transition-colors">
<td className="py-3 px-6">
{blog.imageUrl ? (
<img
src={blog.imageUrl.startsWith('http') ? blog.imageUrl : `${BASE_DOMAIN}${blog.imageUrl}`}
alt={blog.imageAlt || blog.title}
className="w-16 h-12 rounded-xl object-cover border border-gray-200 shadow-2xs"
/>
) : (
<div className="w-16 h-12 rounded-xl bg-gray-100 flex items-center justify-center text-gray-400">
<ImageIcon className="w-5 h-5" />
</div>
)}
</td>
<td className="py-4 px-6">
<div className="flex items-center gap-2">
{blog.featured && (
<span className="p-1 rounded-lg bg-amber-100 text-amber-700 font-black text-[10px] flex items-center gap-0.5" title="پست ویژه / پین شده">
<Pin className="w-3 h-3 fill-amber-700" />
ویژه
</span>
)}
<span className="font-black text-gray-900 text-sm line-clamp-1">{blog.title}</span>
</div>
<p className="text-gray-400 text-xs font-medium line-clamp-1 mt-0.5">
{blog.excerpt || 'بدون چکیده'}
</p>
<span className="text-[10px] font-mono text-purple-600 font-bold mt-0.5 block" dir="ltr">
/{blog.slug}
</span>
</td>
<td className="py-4 px-6">
{blog.category ? (
<span className="inline-block px-2.5 py-0.5 bg-purple-50 text-purple-700 border border-purple-200 rounded-lg text-xs font-bold mb-1">
{blog.category.name}
</span>
) : (
<span className="text-gray-400 text-xs block mb-1">دسته‌بندی نشده</span>
)}
<div className="flex flex-wrap gap-1">
{blog.tags?.slice(0, 2).map((t) => (
<span key={t.id} className="text-[10px] bg-gray-100 text-gray-600 px-1.5 py-0.5 rounded">
#{t.name}
</span>
))}
</div>
</td>
<td className="py-4 px-6 text-gray-600 text-xs font-bold">
{blog.author?.firstName ? `${blog.author.firstName} ${blog.author.lastName || ''}` : 'نامشخص'}
</td>
<td className="py-4 px-6 text-gray-500 text-xs font-medium">
<div className="flex items-center gap-1 mb-1">
<Clock className="w-3.5 h-3.5 text-gray-400" />
<span>{blog.readingTime || 3} دقیقه</span>
</div>
<div className="inline-flex items-center gap-1 px-2 py-0.5 bg-gray-100 text-gray-700 rounded-md font-mono text-[11px] font-bold">
<Eye className="w-3 h-3 text-purple-600" />
<span>{(blog.viewCount || 0).toLocaleString('fa-IR')} بازدید</span>
</div>
</td>
<td className="py-4 px-6">{renderStatusBadge(blog.status, blog.isPublished, blog.scheduledAt)}</td>
<td className="py-4 px-6">
<div className="flex items-center gap-1.5">
<Button
variant="ghost"
size="xs"
startIcon={Edit2}
onClick={() => openModal(blog)}
className="text-blue-600 hover:bg-blue-50"
title="ویرایش مقاله"
/>
<Button
variant="ghost"
size="xs"
startIcon={Trash2}
onClick={() => setDeleteTargetId(blog.id)}
className="text-red-600 hover:bg-red-50"
title="حذف مقاله"
/>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
{!isLoading && totalPages > 1 && (
<div className="p-4 border-t border-gray-100 flex justify-center bg-gray-50/50">
<Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
</div>
)}
</div>
{/* Main Blog Create/Edit Modal */}
{isModalOpen && (
<Modal
isOpen={isModalOpen}
onClose={closeModal}
title={editingBlog ? `ویرایش مقاله: ${editingBlog.title}` : 'افزودن مقاله جدید'}
icon={FileText}
maxWidth="5xl"
footer={
<div className="flex items-center justify-between w-full">
<button
type="button"
onClick={() => setIsLivePreviewOpen(true)}
className="px-4 py-2 rounded-xl text-xs font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center gap-1.5 transition-colors cursor-pointer"
>
<Eye className="w-4 h-4 text-purple-600" />
<span>پیش‌نمایش زنده مقاله</span>
</button>
<div className="flex items-center gap-2">
<Button variant="secondary" size="sm" type="button" onClick={closeModal}>
انصراف
</Button>
<Button data-testid="blog-save-btn" variant="primary" size="sm" type="submit" form="blogMainForm">
ذخیره مقاله
</Button>
</div>
</div>
}
>
<div className="space-y-6 text-right font-vazir">
{/* Draft Recovery Banner */}
{hasSavedDraft && !editingBlog && (
<div className="p-3.5 bg-amber-50 border border-amber-200 rounded-2xl flex items-center justify-between gap-3 text-xs text-amber-900 animate-in fade-in duration-200">
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-amber-500 animate-pulse" />
<span className="font-bold">یک پیش‌نویس ذخیره‌نشده از آخرین ویرایش شما در مرورگر موجود است.</span>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={restoreDraft}
className="px-3 py-1 bg-amber-600 hover:bg-amber-700 text-white rounded-xl font-black text-xs transition cursor-pointer"
>
بازیابی پیش‌نویس
</button>
<button
type="button"
onClick={discardDraft}
className="px-3 py-1 bg-white hover:bg-amber-100 text-amber-800 border border-amber-300 rounded-xl font-bold text-xs transition cursor-pointer"
>
نادیده گرفتن
</button>
</div>
</div>
)}
{/* Form Tabs */}
<div className="flex items-center gap-2 border-b border-gray-100 pb-2 overflow-x-auto">
{[
{ id: 'content', label: '۱. محتوا و متن', icon: FileText },
{ id: 'media', label: '۲. تصویر شاخص و رسانه', icon: ImageIcon },
{ id: 'publishing', label: '۳. زمان‌بندی و انتشار', icon: Calendar },
{ id: 'seo', label: '۴. سئو و سوشال', icon: Globe },
{ id: 'relations', label: '۵. آیتم‌های مرتبط', icon: ShoppingBag },
].map((tab) => {
const Icon = tab.icon;
return (
<button
key={tab.id}
type="button"
onClick={() => setActiveFormTab(tab.id as any)}
className={`px-3.5 py-2 rounded-2xl text-xs font-bold flex items-center gap-1.5 whitespace-nowrap transition-all cursor-pointer ${
activeFormTab === tab.id
? 'bg-purple-600 text-white shadow-xs'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
}`}
>
<Icon className="w-3.5 h-3.5" />
<span>{tab.label}</span>
</button>
);
})}
</div>
<form id="blogMainForm" onSubmit={handleSave} className="space-y-6">
{/* TAB 1: CONTENT */}
{activeFormTab === 'content' && (
<div className="space-y-5">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-1.5">
<label className="text-xs font-black text-gray-700">عنوان اصلی مقاله *</label>
<input
data-testid="blog-title-input"
required
type="text"
value={formData.title}
onChange={(e) => handleTitleChange(e.target.value)}
placeholder="مثال: راهنمای جامع مراقبت و تغذیه سگ‌های ژرمن شپرد"
className="w-full px-4 py-2.5 rounded-2xl border border-gray-200 focus:border-purple-500 outline-none text-sm font-bold"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-black text-gray-700">اسلاگ یکتا (URL Slug) *</label>
<input
required
type="text"
value={formData.slug}
dir="ltr"
onChange={(e) => {
setIsSlugManuallyEdited(true);
setFormData({ ...formData, slug: e.target.value });
}}
placeholder="german-shepherd-care-guide"
className="w-full px-4 py-2.5 rounded-2xl border border-gray-200 focus:border-purple-500 outline-none text-sm font-mono"
/>
</div>
</div>
{/* Excerpt */}
<div className="space-y-1.5">
<label className="text-xs font-black text-gray-700">
خلاصه و چکیده مقاله (Excerpt / Summary)
</label>
<textarea
rows={2}
value={formData.excerpt}
onChange={(e) => setFormData({ ...formData, excerpt: e.target.value })}
placeholder="متن کوتاه برای پیش‌نمایش در کارت‌های وبلاگ و نتایج جستجو..."
className="w-full px-4 py-2.5 rounded-2xl border border-gray-200 focus:border-purple-500 outline-none text-xs leading-relaxed"
/>
</div>
{/* Main Rich Text Editor with Inline Media Support */}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<label className="text-xs font-black text-gray-700">
محتوای کامل مقاله (ادیتور غنی با پشتیبانی از عکس، ویدئو، صوت و جدول) *
</label>
<span className="text-[11px] text-purple-600 font-bold">
زمان تخمینی مطالعه: {formData.readingTime} دقیقه
</span>
</div>
<RichTextEditor
value={formData.content}
onChange={handleContentChange}
placeholder="متن مقاله را بنویسید. از دکمه‌های نوار ابزار بالا برای درج تصویر بین پاراگراف‌ها، ویدئو، صوت، جدول و..."
minHeight="min-h-[350px]"
/>
</div>
{/* Category, Author, Tags selection row */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 pt-2">
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">دسته‌بندی مقاله</label>
<select
value={formData.categoryId}
onChange={(e) => setFormData({ ...formData, categoryId: e.target.value })}
className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs font-bold outline-none bg-gray-50/50"
>
<option value="">-- بدون دسته‌بندی --</option>
{categories.map((c) => (
<option key={c.id} value={c.id}>
{c.parent ? `${c.parent.name} > ` : ''}{c.name}
</option>
))}
</select>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">نویسنده مقاله</label>
<select
value={formData.authorId}
onChange={(e) => setFormData({ ...formData, authorId: e.target.value })}
className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs font-bold outline-none bg-gray-50/50"
>
<option value="">انتخاب نویسنده...</option>
{authors.map((a) => (
<option key={a.id} value={a.id}>
{a.firstName} {a.lastName} ({a.role || 'کاربر'})
</option>
))}
</select>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">زمان تقریبی مطالعه (دقیقه)</label>
<input
type="number"
min="1"
value={formData.readingTime}
onChange={(e) => setFormData({ ...formData, readingTime: Number(e.target.value) || 1 })}
className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs font-bold outline-none"
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div><label htmlFor="author-team" className="text-xs font-bold text-gray-700">تیم نویسندگی</label><input id="author-team" value={formData.authorTeam} onChange={(e)=>setFormData({...formData,authorTeam:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" /></div>
<div><label htmlFor="author-role" className="text-xs font-bold text-gray-700">نقش نویسنده</label><input id="author-role" value={formData.authorRole} onChange={(e)=>setFormData({...formData,authorRole:e.target.value})} className="w-full px-3 py-2.5 rounded-2xl border border-gray-200 text-xs" /></div>
</div>
{/* Chips Tag Input */}
<div className="space-y-2 p-3.5 bg-gray-50/70 border border-gray-200 rounded-2xl">
<label className="text-xs font-bold text-gray-700 block">برچسب‌ها و تگ‌های مقاله (Tag Input)</label>
<div className="flex items-center gap-2">
<input
type="text"
value={currentTagInput}
onChange={(e) => setCurrentTagInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
addTag(currentTagInput);
}
}}
placeholder="نام برچسب را بنویسید و اینتر بزنید..."
className="flex-1 px-3 py-2 rounded-xl border border-gray-200 text-xs outline-none bg-white"
/>
<button
type="button"
onClick={() => addTag(currentTagInput)}
className="px-3 py-2 rounded-xl bg-purple-600 text-white text-xs font-bold hover:bg-purple-700 cursor-pointer"
>
افزودن
</button>
</div>
{formData.tagNames.length > 0 && (
<div className="flex flex-wrap gap-1.5 pt-2">
{formData.tagNames.map((tag) => (
<span
key={tag}
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-xl bg-purple-100 text-purple-800 text-xs font-bold shadow-2xs"
>
<span>#{tag}</span>
<button
type="button"
onClick={() => removeTag(tag)}
className="text-purple-600 hover:text-red-600 cursor-pointer"
>
<X className="w-3 h-3" />
</button>
</span>
))}
</div>
)}
</div>
</div>
)}
{/* TAB 2: MEDIA */}
{activeFormTab === 'media' && (
<div className="space-y-6">
<div className="p-4 bg-gray-50/70 border border-gray-200 rounded-3xl space-y-4">
<h4 className="text-xs font-black text-purple-700">تصویر شاخص و اصلی مقاله (Featured Image)</h4>
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
{formData.imageUrl ? (
<img
src={formData.imageUrl.startsWith('http') ? formData.imageUrl : `${BASE_DOMAIN}${formData.imageUrl}`}
alt="preview"
className="w-40 h-28 rounded-2xl object-cover border border-gray-200 shadow-sm"
/>
) : (
<div className="w-40 h-28 rounded-2xl bg-gray-100 flex items-center justify-center text-gray-400 border border-gray-200">
<ImageIcon className="w-8 h-8" />
</div>
)}
<div className="space-y-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
setMediaSelectTarget('featured');
setIsMediaSelectorOpen(true);
}}
>
انتخاب از گالری رسانه
</Button>
{formData.imageUrl && (
<button
type="button"
onClick={() => setFormData({ ...formData, imageUrl: '' })}
className="block text-xs font-bold text-red-600 hover:underline cursor-pointer"
>
حذف تصویر شاخص
</button>
)}
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 pt-2">
<div>
<label className="text-xs font-bold text-gray-700 block mb-1">متن جایگزین تصویر شاخص (Alt Text - سئو) *</label>
<input
type="text"
value={formData.imageAlt}
onChange={(e) => setFormData({ ...formData, imageAlt: e.target.value })}
placeholder="توضیح کوتاه تصویر برای موتورهای جستجو..."
className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs focus:border-purple-500 outline-none"
/>
</div>
<div>
<label className="text-xs font-bold text-gray-700 block mb-1">کپشن / زیرنویس تصویر شاخص</label>
<input
type="text"
value={formData.imageCaption}
onChange={(e) => setFormData({ ...formData, imageCaption: e.target.value })}
placeholder="زیرنویس نمایش داده شده زیر تصویر اصلی..."
className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs focus:border-purple-500 outline-none"
/>
</div>
</div>
</div>
</div>
)}
{/* TAB 3: PUBLISHING WORKFLOW */}
{activeFormTab === 'publishing' && (
<div className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2 p-4 bg-gray-50 border border-gray-200 rounded-3xl">
<label className="text-xs font-black text-gray-700 block">وضعیت پست (Post Status) *</label>
<select
value={formData.status}
onChange={(e) => setFormData({ ...formData, status: e.target.value as any })}
className="w-full px-3.5 py-2.5 rounded-2xl border border-gray-200 text-xs font-bold outline-none bg-white"
>
<option value="PUBLISHED">منتشر شده (Published - نمایش عمومی در سایت)</option>
<option value="DRAFT">پیش‌نویس (Draft - غیرفعال در سایت)</option>
<option value="SCHEDULED">زمان‌بندی شده (Scheduled - انتشار در آینده)</option>
<option value="ARCHIVED">بایگانی شده (Archived)</option>
</select>
</div>
<div className="space-y-2 p-4 bg-gray-50 border border-gray-200 rounded-3xl">
<label className="text-xs font-black text-gray-700 block">
انتشار در تاریخ (خالی = انتشار فوری)
</label>
<input
type="datetime-local"
value={formData.scheduledAt}
onChange={(e) => {
const val = e.target.value;
setFormData((prev) => ({
...prev,
scheduledAt: val,
status: val && new Date(val).getTime() > Date.now() ? 'SCHEDULED' : prev.status,
}));
}}
className="w-full px-3.5 py-2 rounded-2xl border border-gray-200 text-xs font-bold outline-none bg-white font-sans"
dir="ltr"
/>
<p className="text-[11px] text-gray-400 font-medium">
در صورت تعیین تاریخ آینده، مقاله در صف انتشار زمان‌بندی‌شده قرار گرفته و در موعد مقرر خودکار منتشر می‌شود.
</p>
</div>
</div>
<label className="flex items-center gap-3 p-4 border border-blue-200 rounded-2xl bg-blue-50 cursor-pointer"><input type="checkbox" aria-label="ثبت به‌روزرسانی محتوایی مهم" checked={formData.markContentUpdated} onChange={(e)=>setFormData({...formData,markContentUpdated:e.target.checked})}/><span className="text-xs font-black">ثبت به‌روزرسانی محتوایی مهم</span></label>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<label className="flex items-center gap-3 p-4 border border-gray-200 rounded-2xl bg-white hover:bg-gray-50 transition-colors cursor-pointer">
<input
type="checkbox"
checked={formData.featured}
onChange={(e) => setFormData({ ...formData, featured: e.target.checked })}
className="w-5 h-5 text-purple-600 rounded focus:ring-purple-500"
/>
<div>
<span className="font-black text-xs text-gray-900 block">پست ویژه / پین شده (Featured)</span>
<span className="text-[10px] text-gray-500 block">سنجاق در بالای صفحه وبلاگ</span>
</div>
</label>
<label className="flex items-center gap-3 p-4 border border-gray-200 rounded-2xl bg-white hover:bg-gray-50 transition-colors cursor-pointer">
<input
type="checkbox"
checked={formData.allowComments}
onChange={(e) => setFormData({ ...formData, allowComments: e.target.checked })}
className="w-5 h-5 text-purple-600 rounded focus:ring-purple-500"
/>
<div>
<span className="font-black text-xs text-gray-900 block">فعال‌سازی دیدگاه‌ها (Comments)</span>
<span className="text-[10px] text-gray-500 block">امکان ارسال نظر برای کاربران</span>
</div>
</label>
<label className="flex items-center gap-3 p-4 border border-gray-200 rounded-2xl bg-white hover:bg-gray-50 transition-colors cursor-pointer">
<input
type="checkbox"
checked={formData.showOnHome}
onChange={(e) => setFormData({ ...formData, showOnHome: e.target.checked })}
className="w-5 h-5 text-purple-600 rounded focus:ring-purple-500"
/>
<div>
<span className="font-black text-xs text-gray-900 block">نمایش در صفحه اصلی</span>
<span className="text-[10px] text-gray-500 block">در بخش جدیدترین مقالات خانه</span>
</div>
</label>
</div>
</div>
)}
{/* TAB 4: ADVANCED SEO & SOCIAL */}
{activeFormTab === 'seo' && (
<div className="space-y-6">
{/* Real-time SEO Content Analyzer */}
{(() => {
const content = formData.content || '';
const title = formData.title || '';
const metaTitle = formData.metaTitle || '';
const focusKey = formData.focusKeywords ? formData.focusKeywords.toLowerCase().trim() : '';
const textOnly = content.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
const wordsCount = textOnly ? textOnly.split(' ').length : 0;
const h2Matches = (content.match(/<h2[^>]*>/gi) || []).length;
const h3Matches = (content.match(/<h3[^>]*>/gi) || []).length;
const imgTags = content.match(/<img[^>]+>/gi) || [];
const imgsCount = imgTags.length + (formData.imageUrl ? 1 : 0);
const imgsWithoutAlt = imgTags.filter(img => !/alt=["'][^"']+["']/i.test(img)).length + (!formData.imageAlt && formData.imageUrl ? 1 : 0);
const hasInternalLinks = /href=["'](\/|https?:\/\/(www\.)?canina\.ir)[^"']*["']/i.test(content);
let keyDensity = 0;
let keywordFoundInTitle = false;
if (focusKey) {
const regex = new RegExp(focusKey.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
const occurrences = (textOnly.match(regex) || []).length;
keyDensity = wordsCount > 0 ? Number(((occurrences / wordsCount) * 100).toFixed(1)) : 0;
keywordFoundInTitle = (title + ' ' + metaTitle).toLowerCase().includes(focusKey);
}
return (
<div className="p-4 bg-white border border-purple-200 rounded-3xl space-y-4 shadow-sm">
<div className="flex items-center justify-between border-b border-gray-100 pb-2">
<h5 className="text-xs font-black text-purple-800 flex items-center gap-1.5">
<Sparkles className="w-4 h-4 text-purple-600" />
تحلیلگر هوشمند سئو و محتوا (Real-time SEO Analyzer)
</h5>
<span className="text-[11px] font-bold text-gray-500">
طول کل متن: <strong className="text-purple-700">{wordsCount}</strong> کلمه
</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2.5 text-xs">
{/* Word count audit */}
<div className={`p-2.5 rounded-xl border flex items-center gap-2 ${wordsCount >= 300 ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : 'bg-amber-50 border-amber-200 text-amber-800'}`}>
{wordsCount >= 300 ? <CheckCircle2 className="w-4 h-4 shrink-0 text-emerald-600" /> : <XCircle className="w-4 h-4 shrink-0 text-amber-600" />}
<span>حجم محتوا: {wordsCount >= 300 ? 'عالی (بیش از ۳۰۰ کلمه)' : 'کوتاه (حداقل ۳۰۰ کلمه توصیه می‌شود)'}</span>
</div>
{/* Headings audit */}
<div className={`p-2.5 rounded-xl border flex items-center gap-2 ${h2Matches > 0 ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : 'bg-amber-50 border-amber-200 text-amber-800'}`}>
{h2Matches > 0 ? <CheckCircle2 className="w-4 h-4 shrink-0 text-emerald-600" /> : <XCircle className="w-4 h-4 shrink-0 text-amber-600" />}
<span>ساختار عناوین: {h2Matches} تیتر H2 و {h3Matches} تیتر H3</span>
</div>
{/* Image Alt audit */}
<div className={`p-2.5 rounded-xl border flex items-center gap-2 ${imgsCount > 0 && imgsWithoutAlt === 0 ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : 'bg-amber-50 border-amber-200 text-amber-800'}`}>
{imgsCount > 0 && imgsWithoutAlt === 0 ? <CheckCircle2 className="w-4 h-4 shrink-0 text-emerald-600" /> : <XCircle className="w-4 h-4 shrink-0 text-amber-600" />}
<span>متن جایگزین (Alt): {imgsWithoutAlt === 0 ? 'همه تصاویر دارای Alt' : `${imgsWithoutAlt} تصویر بدون Alt`}</span>
</div>
{/* Link audit */}
<div className={`p-2.5 rounded-xl border flex items-center gap-2 ${hasInternalLinks ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : 'bg-gray-50 border-gray-200 text-gray-700'}`}>
{hasInternalLinks ? <CheckCircle2 className="w-4 h-4 shrink-0 text-emerald-600" /> : <Clock className="w-4 h-4 shrink-0 text-gray-400" />}
<span>لینک‌های داخلی: {hasInternalLinks ? 'موجود' : 'یافت نشد'}</span>
</div>
{/* Focus keyword in Title & Desc */}
{focusKey ? (
<>
<div className={`p-2.5 rounded-xl border flex items-center gap-2 ${keywordFoundInTitle ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : 'bg-amber-50 border-amber-200 text-amber-800'}`}>
{keywordFoundInTitle ? <CheckCircle2 className="w-4 h-4 shrink-0 text-emerald-600" /> : <XCircle className="w-4 h-4 shrink-0 text-amber-600" />}
<span>کلمه کلیدی در عنوان: {keywordFoundInTitle ? 'تایید' : 'یافت نشد'}</span>
</div>
<div className={`p-2.5 rounded-xl border flex items-center gap-2 ${keyDensity >= 0.5 && keyDensity <= 3 ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : 'bg-blue-50 border-blue-200 text-blue-800'}`}>
<CheckCircle2 className="w-4 h-4 shrink-0 text-blue-600" />
<span>چگالی کلمه کلیدی: {keyDensity}% ({keyDensity >= 0.5 && keyDensity <= 3 ? 'مطلوب' : 'متوسط'})</span>
</div>
</>
) : (
<div className="p-2.5 rounded-xl border bg-gray-50 border-gray-200 text-gray-500 col-span-2">
<span>💡 کلمه کلیدی کانونی (Focus Keyword) را در زیر وارد کنید تا آنالیز دقیق‌تر فعال شود.</span>
</div>
)}
</div>
</div>
);
})()}
{/* Google SERP Preview Box */}
<div className="p-4 bg-white border border-gray-200 rounded-3xl space-y-2 shadow-2xs">
<span className="text-xs font-black text-gray-500 block">پیش‌نمایش در نتایج جستجوی گوگل (Google SERP Preview):</span>
<div className="p-4 bg-gray-50 rounded-2xl border border-gray-100 font-sans text-left space-y-1" dir="ltr">
<span className="text-xs text-emerald-800 font-medium block truncate">
https://canina.ir/blog/{formData.slug || 'slug'}
</span>
<h5 className="text-base text-blue-700 font-bold hover:underline cursor-pointer line-clamp-1">
{formData.metaTitle || formData.title || 'عنوان مقاله در گوگل'} | مکمل‌های کنینا آلمان
</h5>
<p className="text-xs text-gray-600 line-clamp-2">
{formData.metaDescription || formData.excerpt || 'توضیحات متای مقاله در اینجا نمایش داده خواهد شد...'}
</p>
</div>
</div>
{/* Focus Keywords and Schema Type */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">کلمه کلیدی کانونی و هدف (Focus Keywords)</label>
<input
type="text"
value={formData.focusKeywords || ''}
onChange={(e) => setFormData({ ...formData, focusKeywords: e.target.value })}
placeholder="مثال: تغذیه سگ، مکمل مفاصل، ویتامین گربه"
className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs focus:border-purple-500 outline-none font-bold"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">نوع داده ساختاریافته (JSON-LD Schema Type)</label>
<select
value={formData.schemaType || 'BlogPosting'}
onChange={(e) => setFormData({ ...formData, schemaType: e.target.value })}
className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs font-bold outline-none bg-gray-50/50"
>
<option value="BlogPosting">BlogPosting (پیش‌فرض مقاله وبلاگ)</option>
<option value="Article">Article (مقاله عمومی)</option>
<option value="MedicalWebPage">MedicalWebPage (مقاله علمی/پزشکی)</option>
<option value="NewsArticle">NewsArticle (اخبار)</option>
</select>
</div>
</div>
{/* Meta Title and Canonical */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-1.5">
<div className="flex justify-between items-center text-xs">
<label className="font-bold text-gray-700">عنوان متا (Meta Title)</label>
<span className={`font-mono text-[11px] ${((formData.metaTitle || '').length >= 50 && (formData.metaTitle || '').length <= 65) ? 'text-emerald-600 font-bold' : 'text-gray-400'}`}>
{(formData.metaTitle || '').length} / 60
</span>
</div>
<input
type="text"
value={formData.metaTitle}
onChange={(e) => setFormData({ ...formData, metaTitle: e.target.value })}
placeholder="عنوان سئو در تب مرورگر و نتایج سرچ..."
className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs focus:border-purple-500 outline-none"
/>
</div>
<div className="space-y-1.5">
<label className="text-xs font-bold text-gray-700">آدرس کانونیکال (Canonical URL - اختیاری)</label>
<input
type="text"
value={formData.canonicalUrl}
dir="ltr"
onChange={(e) => setFormData({ ...formData, canonicalUrl: e.target.value })}
placeholder="https://canina.ir/blog/custom-slug"
className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs font-mono focus:border-purple-500 outline-none"
/>
</div>
</div>
{/* Meta Description */}
<div className="space-y-1.5">
<div className="flex justify-between items-center text-xs">
<label className="font-bold text-gray-700">توضیحات متا (Meta Description)</label>
<span className={`font-mono text-[11px] ${((formData.metaDescription || '').length >= 140 && (formData.metaDescription || '').length <= 160) ? 'text-emerald-600 font-bold' : 'text-gray-400'}`}>
{(formData.metaDescription || '').length} / 160
</span>
</div>
<textarea
rows={2}
value={formData.metaDescription}
onChange={(e) => setFormData({ ...formData, metaDescription: e.target.value })}
placeholder="متن توضیحات سئو برای رتبه بهتر در گوگل (۱۴۰ تا ۱۶۰ کاراکتر توصیه می‌شود)..."
className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-xs focus:border-purple-500 outline-none"
/>
</div>
{/* Robots Switches (noIndex & noFollow) */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 p-4 bg-gray-50 border border-gray-200 rounded-2xl">
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={formData.noIndex || false}
onChange={(e) => setFormData({ ...formData, noIndex: e.target.checked })}
className="w-4 h-4 text-purple-600 rounded"
/>
<div>
<span className="text-xs font-black text-gray-800 block">عدم ایندکس در موتورهای جستجو (noindex)</span>
<span className="text-[10px] text-gray-400 block">جلوگیری از نمایش این مقاله در نتایج گوگل</span>
</div>
</label>
<label className="flex items-center gap-3 cursor-pointer">
<input
type="checkbox"
checked={formData.noFollow || false}
onChange={(e) => setFormData({ ...formData, noFollow: e.target.checked })}
className="w-4 h-4 text-purple-600 rounded"
/>
<div>
<span className="text-xs font-black text-gray-800 block">عدم دنبال کردن لینک‌ها (nofollow)</span>
<span className="text-[10px] text-gray-400 block">عدم انتقال اعتبار سئو به لینک‌های موجود در این مقاله</span>
</div>
</label>
</div>
{/* Open Graph Social Settings & Preview */}
<div className="p-4 bg-purple-50/50 border border-purple-100 rounded-3xl space-y-4">
<h5 className="text-xs font-black text-purple-800 flex items-center gap-1.5">
<Share2 className="w-4 h-4" />
تنظیمات کارت شبکه‌های اجتماعی (Open Graph / Telegram / Twitter)
</h5>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
<label className="text-xs font-bold text-gray-700 block mb-1">عنوان اختصاصی سوشال (og:title)</label>
<input
type="text"
value={formData.ogTitle}
onChange={(e) => setFormData({ ...formData, ogTitle: e.target.value })}
placeholder="پیش‌فرض: همان عنوان مقاله"
className="w-full px-3 py-2 rounded-xl border border-gray-200 text-xs bg-white focus:border-purple-500 outline-none"
/>
</div>
<div>
<label className="text-xs font-bold text-gray-700 block mb-1">تصویر اختصاصی سوشال (og:image - ۱۲۰۰×۶۳۰)</label>
<div className="flex items-center gap-2">
<input
type="text"
value={formData.ogImage}
dir="ltr"
onChange={(e) => setFormData({ ...formData, ogImage: e.target.value })}
placeholder="آدرس تصویر (پیش‌فرض: تصویر شاخص)"
className="w-full px-3 py-2 rounded-xl border border-gray-200 text-xs bg-white font-mono focus:border-purple-500 outline-none"
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
setMediaSelectTarget('ogImage');
setIsMediaSelectorOpen(true);
}}
>
انتخاب
</Button>
</div>
</div>
</div>
{/* Social Card Visual Mockup */}
<div className="pt-2 border-t border-purple-100/60">
<span className="text-[11px] font-bold text-purple-900 block mb-2">پیش‌نمایش کارت اشتراک‌گذاری سوشال (Social Card Preview):</span>
<div className="max-w-md bg-white rounded-2xl border border-gray-200 overflow-hidden shadow-xs text-left" dir="ltr">
<div className="aspect-[1.91/1] bg-gray-100 relative overflow-hidden flex items-center justify-center">
{(formData.ogImage || formData.imageUrl) ? (
<img
src={(formData.ogImage || formData.imageUrl).startsWith('http') ? (formData.ogImage || formData.imageUrl) : `${BASE_DOMAIN}${formData.ogImage || formData.imageUrl}`}
alt="Social preview"
className="w-full h-full object-cover"
/>
) : (
<div className="flex flex-col items-center text-gray-400 text-xs">
<ImageIcon className="w-8 h-8 mb-1" />
<span>تصویر سوشال انتخاب نشده</span>
</div>
)}
</div>
<div className="p-3 bg-gray-50 border-t border-gray-100">
<span className="text-[10px] text-gray-400 uppercase font-mono block">CANINA.IR</span>
<span className="text-xs font-bold text-gray-900 line-clamp-1 mt-0.5">
{formData.ogTitle || formData.metaTitle || formData.title || 'عنوان مقاله'}
</span>
<p className="text-[11px] text-gray-500 line-clamp-2 mt-0.5">
{formData.ogDescription || formData.metaDescription || formData.excerpt || 'توضیحات پیش‌نمایش در شبکه‌های اجتماعی...'}
</p>
</div>
</div>
</div>
</div>
</div>
)}
{/* TAB 5: RELATIONS */}
{activeFormTab === 'relations' && (
<div className="space-y-6">
{/* Related Products */}
<div className="p-4 bg-gray-50 border border-gray-200 rounded-3xl space-y-3">
<h4 className="text-xs font-black text-purple-700 flex items-center gap-1.5">
<ShoppingBag className="w-4 h-4" />
محصولات مرتبط با این مقاله (جهت ارتقای فروش و لینک‌سازی داخلی)
</h4>
<p className="text-xs text-gray-500">
محصولاتی که در این مقاله معرفی شده یا مکمل‌های مرتبط با موضوع مقاله را انتخاب کنید:
</p>
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2.5 max-h-56 overflow-y-auto p-2 bg-white rounded-2xl border border-gray-200">
{allProducts.map((p) => {
const isSelected = formData.relatedProductIds.includes(p.id);
return (
<div
key={p.id}
onClick={() => {
setFormData((prev) => ({
...prev,
relatedProductIds: isSelected
? prev.relatedProductIds.filter((id) => id !== p.id)
: [...prev.relatedProductIds, p.id],
}));
}}
className={`p-2 rounded-xl border flex items-center gap-2 cursor-pointer transition-all ${
isSelected
? 'border-purple-600 bg-purple-50 text-purple-900 font-bold'
: 'border-gray-200 hover:border-gray-300 text-gray-700'
}`}
>
<input type="checkbox" checked={isSelected} readOnly className="rounded text-purple-600" />
<span className="text-xs truncate">{p.nameFa}</span>
</div>
);
})}
</div>
</div>
{/* Related Blogs */}
<div className="p-4 bg-gray-50 border border-gray-200 rounded-3xl space-y-3">
<h4 className="text-xs font-black text-purple-700 flex items-center gap-1.5">
<FileText className="w-4 h-4" />
مقالات پیشنهادی و مرتبط
</h4>
<p className="text-xs text-gray-500">
در صورت خالی گذاشتن، مقالات هم‌دسته‌بندی به طور خودکار پیشنهاد می‌شوند.
</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-48 overflow-y-auto p-2 bg-white rounded-2xl border border-gray-200">
{blogs
.filter((b) => b.id !== editingBlog?.id)
.map((b) => {
const isSelected = formData.relatedBlogIds.includes(b.id);
return (
<div
key={b.id}
onClick={() => {
setFormData((prev) => ({
...prev,
relatedBlogIds: isSelected
? prev.relatedBlogIds.filter((id) => id !== b.id)
: [...prev.relatedBlogIds, b.id],
}));
}}
className={`p-2.5 rounded-xl border flex items-center gap-2 cursor-pointer transition-all ${
isSelected
? 'border-purple-600 bg-purple-50 text-purple-900 font-bold'
: 'border-gray-200 hover:border-gray-300 text-gray-700'
}`}
>
<input type="checkbox" checked={isSelected} readOnly className="rounded text-purple-600" />
<span className="text-xs truncate">{b.title}</span>
</div>
);
})}
</div>
</div>
</div>
)}
</form>
</div>
</Modal>
)}
{/* Live Preview Modal */}
{isLivePreviewOpen && (
<Modal
isOpen={isLivePreviewOpen}
onClose={() => setIsLivePreviewOpen(false)}
title="پیش‌نمایش زنده مقاله (نمای کاربر در سایت)"
icon={Eye}
maxWidth="4xl"
>
<div className="bg-medical-gray-50 p-6 rounded-3xl space-y-6 text-right font-vazir" dir="rtl">
<div className="bg-white rounded-3xl p-6 sm:p-10 border border-gray-200 shadow-lg space-y-6">
{formData.imageUrl && (
<div className="aspect-video w-full rounded-2xl overflow-hidden border border-gray-200">
<img
src={formData.imageUrl.startsWith('http') ? formData.imageUrl : `${BASE_DOMAIN}${formData.imageUrl}`}
alt={formData.imageAlt || formData.title}
className="w-full h-full object-cover"
/>
</div>
)}
<div className="flex flex-wrap items-center gap-3 text-xs font-bold text-purple-600">
<span className="bg-purple-100 px-3 py-1 rounded-full">
{categories.find((c) => c.id === formData.categoryId)?.name || 'علمی و تخصصی'}
</span>
<span className="flex items-center gap-1 text-gray-500">
<Clock className="w-3.5 h-3.5" />
{formData.readingTime} دقیقه مطالعه
</span>
<span className="flex items-center gap-1 text-gray-500">
<Calendar className="w-3.5 h-3.5" />
{new Date().toLocaleDateString('fa-IR')}
</span>
</div>
<h1 className="text-2xl sm:text-3xl font-black text-gray-900 leading-tight">{formData.title || 'عنوان مقاله'}</h1>
{formData.excerpt && (
<p className="text-sm sm:text-base font-bold text-gray-700 italic border-r-4 border-purple-600 pr-4 py-2 bg-purple-50/40 rounded-l-xl">
{formData.excerpt}
</p>
)}
<div
className="prose max-w-none text-gray-800 text-sm leading-loose space-y-4"
dangerouslySetInnerHTML={{ __html: formData.content || '<p class="text-gray-400">محتوایی وارد نشده است...</p>' }}
/>
{formData.tagNames.length > 0 && (
<div className="pt-6 border-t border-gray-100 flex flex-wrap gap-2">
{formData.tagNames.map((tag) => (
<span key={tag} className="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-xs font-bold">
#{tag}
</span>
))}
</div>
)}
</div>
</div>
</Modal>
)}
{/* Category & Tag Management Quick Modal */}
{isCatTagModalOpen && (
<Modal
isOpen={isCatTagModalOpen}
onClose={() => setIsCatTagModalOpen(false)}
title="مدیریت دسته‌بندی‌ها و برچسب‌های وبلاگ"
icon={FolderTree}
maxWidth="3xl"
>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 font-vazir text-right" dir="rtl">
{/* Categories column */}
<div className="space-y-4 p-4 bg-gray-50 rounded-3xl border border-gray-200">
<h4 className="font-black text-xs text-purple-700 flex items-center gap-1.5">
<FolderTree className="w-4 h-4" />
افزودن دسته‌بندی جدید
</h4>
<form onSubmit={handleCreateCategory} className="space-y-2.5">
<input
type="text"
placeholder="نام دسته‌بندی (مثلاً: تغذیه سگ)..."
value={newCatName}
onChange={(e) => setNewCatName(e.target.value)}
className="w-full px-3 py-2 rounded-xl border border-gray-200 text-xs outline-none bg-white font-bold"
/>
<input
type="text"
placeholder="اسلاگ اختیاری (dog-nutrition)..."
value={newCatSlug}
dir="ltr"
onChange={(e) => setNewCatSlug(e.target.value)}
className="w-full px-3 py-2 rounded-xl border border-gray-200 text-xs outline-none bg-white font-mono"
/>
<select
value={newCatParentId}
onChange={(e) => setNewCatParentId(e.target.value)}
className="w-full px-3 py-2 rounded-xl border border-gray-200 text-xs outline-none bg-white font-bold"
>
<option value="">-- دسته‌بندی والد (اختیاری) --</option>
{categories
.filter((c) => !c.parentId)
.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
<Button type="submit" variant="primary" size="xs" className="w-full">
افزودن دسته‌بندی
</Button>
</form>
<div className="pt-2 border-t border-gray-200 space-y-1.5 max-h-48 overflow-y-auto">
<span className="text-[11px] font-bold text-gray-500 block">دسته‌بندی‌های موجود:</span>
{categories.map((c) => (
<div key={c.id} className="p-2 rounded-xl bg-white border border-gray-200 flex items-center justify-between text-xs">
<div>
<span className="font-bold text-gray-800">{c.name}</span>
{c.parent && <span className="text-[10px] text-gray-400 block font-medium">والد: {c.parent.name}</span>}
</div>
<button
type="button"
onClick={async () => {
if (confirm(`آیا از حذف دسته‌بندی ${c.name} مطمئن هستید؟`)) {
await api.delete(`/admin/blogs/categories/${c.id}`);
toast.success('دسته‌بندی حذف شد');
fetchAuxiliaryData();
}
}}
className="p-1 text-gray-400 hover:text-red-600 transition-colors"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
))}
</div>
</div>
{/* Tags column */}
<div className="space-y-4 p-4 bg-gray-50 rounded-3xl border border-gray-200">
<h4 className="font-black text-xs text-purple-700 flex items-center gap-1.5">
<Tag className="w-4 h-4" />
افزودن برچسب جدید
</h4>
<form onSubmit={handleCreateTag} className="space-y-2.5">
<input
type="text"
placeholder="نام تگ (مثلاً: توله سگ)..."
value={newTagName}
onChange={(e) => setNewTagName(e.target.value)}
className="w-full px-3 py-2 rounded-xl border border-gray-200 text-xs outline-none bg-white font-bold"
/>
<Button type="submit" variant="primary" size="xs" className="w-full">
افزودن تگ
</Button>
</form>
<div className="pt-2 border-t border-gray-200 space-y-1.5 max-h-56 overflow-y-auto">
<span className="text-[11px] font-bold text-gray-500 block">برچسب‌های موجود:</span>
<div className="flex flex-wrap gap-1.5">
{tagsList.map((t) => (
<span
key={t.id}
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-xl bg-white border border-gray-200 text-xs font-bold text-gray-700"
>
<span>#{t.name}</span>
<button
type="button"
onClick={async () => {
if (confirm(`حذف تگ #${t.name}؟`)) {
await api.delete(`/admin/blogs/tags/${t.id}`);
toast.success('تگ حذف شد');
fetchAuxiliaryData();
}
}}
className="text-gray-400 hover:text-red-600"
>
<X className="w-3 h-3" />
</button>
</span>
))}
</div>
</div>
</div>
</div>
</Modal>
)}
{/* Media Selector */}
<MediaSelector
isOpen={isMediaSelectorOpen}
onClose={() => setIsMediaSelectorOpen(false)}
onSelect={(url) => {
if (mediaSelectTarget === 'featured') {
let derivedAlt = formData.imageAlt;
if (!derivedAlt || derivedAlt.trim() === '') {
try {
const filename = url.split('/').pop()?.split('?')[0] || '';
const baseName = filename.replace(/\.[^/.]+$/, '');
// Clean dashes, underscores and clean decoded name
const cleanName = decodeURIComponent(baseName).replace(/[-_]+/g, ' ').trim();
derivedAlt = cleanName || formData.title || 'تصویر مقاله';
} catch {
derivedAlt = formData.title || 'تصویر مقاله';
}
}
setFormData({ ...formData, imageUrl: url, imageAlt: derivedAlt });
} else {
setFormData({ ...formData, ogImage: url });
}
}}
/>
{/* Delete Confirmation */}
<ConfirmModal
isOpen={!!deleteTargetId}
title="حذف مقاله"
message="آیا از حذف این مقاله مطمئن هستید؟ این عملیات غیرقابل بازگشت است."
onConfirm={confirmDelete}
onCancel={() => setDeleteTargetId(null)}
/>
</div>
);
}