'use client';

import { useState } from 'react';
import Link from 'next/link';
import { Plus, Search, Filter, Download, Trash2, Eye, EyeOff, Edit2, ChevronDown, CheckSquare, Square, AlertTriangle, X, FileText, Calendar, BarChart2 } from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

type TFn = (key: string, fallback?: string, vars?: Record<string, string | number>) => string;

interface BlogPost {
  id: string;
  title: string;
  slug: string;
  author: string;
  category: string;
  status: 'draft' | 'published' | 'scheduled';
  publishDate: string;
  views: number;
  tags: string[];
}

const getInitialPosts = (t: TFn): BlogPost[] => [
  { id: '1', title: t('admin.blog.post1.title', 'How AI Voice Ordering Helped 2,400+ Restaurants Capture Every Call'), slug: 'ai-voice-ordering-restaurants', author: t('admin.blog.post1.author', 'Alex Rivera'), category: t('admin.blog.cat.aiFeatures', 'AI Features'), status: 'published', publishDate: 'Mar 12, 2026', views: 4821, tags: [t('admin.blog.tag.ai', 'AI'), t('admin.blog.tag.voice', 'Voice'), t('admin.blog.tag.revenue', 'Revenue')] },
  { id: '2', title: t('admin.blog.post2.title', 'How Bella Napoli Reduced Missed Orders by 100% with AI Voice'), slug: 'bella-napoli-case-study', author: t('admin.blog.post2.author', 'Yuki Tanaka'), category: t('admin.blog.cat.caseStudies', 'Case Studies'), status: 'published', publishDate: 'Mar 10, 2026', views: 3204, tags: [t('admin.blog.tag.caseStudy', 'Case Study'), t('admin.blog.tag.voice', 'Voice')] },
  { id: '3', title: t('admin.blog.post3.title', 'The Real Cost of a Missed Phone Order'), slug: 'cost-missed-phone-order', author: t('admin.blog.post3.author', 'Carlos Vega'), category: t('admin.blog.cat.operations', 'Restaurant Operations'), status: 'published', publishDate: 'Mar 5, 2026', views: 2987, tags: [t('admin.blog.tag.research', 'Research'), t('admin.blog.tag.revenue', 'Revenue')] },
  { id: '4', title: t('admin.blog.post4.title', 'Why Multilingual AI is Non-Negotiable for Modern Restaurants'), slug: 'multilingual-ai-restaurant', author: t('admin.blog.post4.author', 'Amara Osei'), category: t('admin.blog.cat.customerExp', 'Customer Experience'), status: 'published', publishDate: 'Feb 28, 2026', views: 1854, tags: [t('admin.blog.tag.ai', 'AI'), t('admin.blog.tag.multilingual', 'Multilingual')] },
  { id: '5', title: t('admin.blog.post5.title', 'RestroAgent 3.0: Introducing Real-Time Sentiment Analysis'), slug: 'restroagent-3-sentiment-analysis', author: t('admin.blog.post5.author', 'Lena Fischer'), category: t('admin.blog.cat.productUpdates', 'Product Updates'), status: 'published', publishDate: 'Feb 20, 2026', views: 2341, tags: [t('admin.blog.tag.product', 'Product'), t('admin.blog.tag.sentiment', 'Sentiment')] },
  { id: '6', title: t('admin.blog.post6.title', 'How to Train Your AI Agent to Sound Like Your Restaurant'), slug: 'train-ai-agent-brand-voice', author: t('admin.blog.post6.author', 'Sophie Laurent'), category: t('admin.blog.cat.aiTech', 'AI & Technology'), status: 'draft', publishDate: '—', views: 0, tags: [t('admin.blog.tag.guide', 'Guide'), t('admin.blog.tag.ai', 'AI')] },
  { id: '7', title: t('admin.blog.post7.title', 'The Future of Restaurant Ordering: Voice, Chat, or Both?'), slug: 'future-restaurant-ordering', author: t('admin.blog.post7.author', 'Arjun Mehta'), category: t('admin.blog.cat.aiTech', 'AI & Technology'), status: 'scheduled', publishDate: 'Mar 20, 2026', views: 0, tags: [t('admin.blog.tag.research', 'Research'), t('admin.blog.tag.ai', 'AI')] },
  { id: '8', title: t('admin.blog.post8.title', 'Table Booking Abandonment: Why 60% of Reservations Never Complete'), slug: 'table-booking-abandonment', author: t('admin.blog.post8.author', 'Carlos Vega'), category: t('admin.blog.cat.customerExp', 'Customer Experience'), status: 'draft', publishDate: '—', views: 0, tags: [t('admin.blog.tag.bookings', 'Bookings'), t('admin.blog.tag.insights', 'Insights')] },
];

const getCategories = (t: (key: string, fallback?: string) => string) => [
  { key: 'All', label: t('common.all', 'All') },
  { key: 'AI Features', label: t('admin.blog.cat.aiFeatures', 'AI Features') },
  { key: 'AI & Technology', label: t('admin.blog.cat.aiTech', 'AI & Technology') },
  { key: 'Case Studies', label: t('admin.blog.cat.caseStudies', 'Case Studies') },
  { key: 'Restaurant Operations', label: t('admin.blog.cat.operations', 'Restaurant Operations') },
  { key: 'Customer Experience', label: t('admin.blog.cat.customerExp', 'Customer Experience') },
  { key: 'Product Updates', label: t('admin.blog.cat.productUpdates', 'Product Updates') },
];
const statuses = ['All', 'published', 'draft', 'scheduled'];

const getStatusConfig = (t: TFn) => ({
  published: { label: t('admin.blog.status.published', 'Published'), class: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-400' },
  draft: { label: t('admin.blog.status.draft', 'Draft'), class: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400' },
  scheduled: { label: t('admin.blog.status.scheduled', 'Scheduled'), class: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-400' },
});

type BulkAction = 'publish' | 'unpublish' | 'delete' | null;

export default function AdminBlogListPage() {
  const { t, currentLang } = useLanguage();
    const statusConfig = getStatusConfig(t);
    const categories = getCategories(t);
  usePageHeader(t('admin.blog.title', 'Blog Management'), t('admin.blog.subtitle', 'Create, edit, and manage blog posts'));
  const [posts, setPosts] = useState<BlogPost[]>(() => getInitialPosts(t));
  const [search, setSearch] = useState('');
  const [filterStatus, setFilterStatus] = useState('All');
  const [filterCategory, setFilterCategory] = useState('All');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [pendingAction, setPendingAction] = useState<BulkAction>(null);
  const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
  const [showFilters, setShowFilters] = useState(false);

  const filtered = posts.filter(p => {
    const matchSearch = p.title.toLowerCase().includes(search.toLowerCase()) ||
      p.author.toLowerCase().includes(search.toLowerCase());
    const matchStatus = filterStatus === 'All' || p.status === filterStatus;
    const matchCategory = filterCategory === 'All' || p.category === filterCategory;
    return matchSearch && matchStatus && matchCategory;
  });

  const allSelected = filtered.length > 0 && filtered.every(p => selectedIds.has(p.id));
  const someSelected = selectedIds.size > 0;

  const toggleAll = () => {
    if (allSelected) setSelectedIds(new Set());
    else setSelectedIds(new Set(filtered.map(p => p.id)));
  };

  const toggleOne = (id: string) => {
    const next = new Set(selectedIds);
    if (next.has(id)) next.delete(id); else next.add(id);
    setSelectedIds(next);
  };

  const confirmBulkAction = () => {
    if (!pendingAction) return;
    if (pendingAction === 'delete') {
      setPosts(prev => prev.filter(p => !selectedIds.has(p.id)));
    } else if (pendingAction === 'publish') {
      setPosts(prev => prev.map(p => selectedIds.has(p.id) ? { ...p, status: 'published' as const, publishDate: new Date().toLocaleDateString(currentLang, { month: 'short', day: 'numeric', year: 'numeric' }) } : p));
    } else if (pendingAction === 'unpublish') {
      setPosts(prev => prev.map(p => selectedIds.has(p.id) ? { ...p, status: 'draft' as const, publishDate: '—' } : p));
    }
    setSelectedIds(new Set());
    setPendingAction(null);
  };

  const confirmDelete = () => {
    if (!deleteTargetId) return;
    setPosts(prev => prev.filter(p => p.id !== deleteTargetId));
    setDeleteTargetId(null);
  };

  const exportCSV = () => {
    const rows = [
      [t('admin.blog.csv.title', 'Title'), t('admin.blog.csv.author', 'Author'), t('admin.blog.csv.category', 'Category'), t('admin.blog.csv.status', 'Status'), t('admin.blog.csv.publishDate', 'Publish Date'), t('admin.blog.csv.views', 'Views')],
      ...filtered.map(p => [p.title, p.author, p.category, p.status, p.publishDate, String(p.views)]),
    ];
    const csv = rows.map(r => r.map(c => `"${c}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = 'blog-posts.csv'; a.click();
    URL.revokeObjectURL(url);
  };

  const stats = [
    { label: t('admin.blog.statTotalPosts', 'Total Posts'), value: posts.length, icon: <FileText size={16} />, color: 'text-orange-500' },
    { label: t('admin.blog.statPublished', 'Published'), value: posts.filter(p => p.status === 'published').length, icon: <Eye size={16} />, color: 'text-emerald-500' },
    { label: t('admin.blog.statDrafts', 'Drafts'), value: posts.filter(p => p.status === 'draft').length, icon: <Edit2 size={16} />, color: 'text-slate-500' },
    { label: t('admin.blog.statTotalViews', 'Total Views'), value: posts.reduce((a, p) => a + p.views, 0).toLocaleString(), icon: <BarChart2 size={16} />, color: 'text-blue-500' },
  ];

  return (
    <>
      {/* Admin Banner */}
      <div className="flex items-center gap-3 px-4 py-3 rounded-xl mb-6" style={{ backgroundColor: 'hsl(231, 40%, 14%)', color: 'white' }}>
        <div className="w-2 h-2 rounded-full bg-orange-400 animate-pulse" />
        <span className="text-sm font-semibold">{t('admin.blog.adminPanel', 'Admin Panel')}</span>
        <span className="text-xs opacity-60">— {t('admin.blog.adminBannerSub', 'Blog posts published here appear on the public /blog page')}</span>
      </div>

      {/* Stats Row */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        {stats.map((s, i) => (
          <div key={i} className="card p-4 flex items-center gap-3">
            <div className={`w-9 h-9 rounded-xl flex items-center justify-center ${s.color}`} style={{ backgroundColor: 'hsl(var(--muted))' }}>
              {s.icon}
            </div>
            <div>
              <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{s.label}</p>
              <p className="text-lg font-bold" style={{ color: 'hsl(var(--foreground))' }}>{s.value}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Toolbar */}
      <div className="card p-4 mb-4">
        <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between">
          <div className="flex flex-1 gap-2 w-full sm:w-auto">
            {/* Search */}
            <div className="relative flex-1 max-w-xs">
              <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
              <input
                className="input-base pl-8 py-2 text-sm w-full"
                placeholder={t('admin.blog.searchPlaceholder', 'Search posts...')}
                value={search}
                onChange={e => setSearch(e.target.value)}
              />
            </div>
            {/* Filter toggle */}
            <button
              onClick={() => setShowFilters(!showFilters)}
              className="flex items-center gap-1.5 px-3 py-2 rounded-lg border text-sm font-medium transition-all"
              style={{ borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground-secondary))' }}
            >
              <Filter size={14} />
              <span className="hidden sm:inline">{t('admin.blog.filters', 'Filters')}</span>
              <ChevronDown size={12} className={`transition-transform ${showFilters ? 'rotate-180' : ''}`} />
            </button>
          </div>
          <div className="flex gap-2">
            <button onClick={exportCSV} className="flex items-center gap-1.5 px-3 py-2 rounded-lg border text-sm font-medium transition-all hover:-translate-y-0.5" style={{ borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground-secondary))' }}>
              <Download size={14} /> <span className="hidden sm:inline">{t('admin.blog.exportCsv', 'Export CSV')}</span>
            </button>
            <Link href="/admin/blog/new" className="btn-primary flex items-center gap-1.5 text-sm px-4 py-2">
              <Plus size={15} /> {t('admin.blog.newPost', 'New Post')}
            </Link>
          </div>
        </div>

        {/* Filters */}
        {showFilters && (
          <div className="flex flex-wrap gap-3 mt-3 pt-3" style={{ borderTop: '1px solid hsl(var(--border))' }}>
            <div className="flex items-center gap-2">
              <label className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.filterStatus', 'Status')}:</label>
              <select className="input-base py-1.5 text-xs" value={filterStatus} onChange={e => setFilterStatus(e.target.value)}>
                {statuses.map(s => <option key={s} value={s}>{s === 'All' ? t('admin.blog.allStatuses', 'All Statuses') : statusConfig[s as keyof typeof statusConfig]?.label ?? s}</option>)}
              </select>
            </div>
            <div className="flex items-center gap-2">
              <label className="text-xs font-semibold" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.filterCategory', 'Category')}:</label>
              <select className="input-base py-1.5 text-xs" value={filterCategory} onChange={e => setFilterCategory(e.target.value)}>
                {categories.map(c => <option key={c.key} value={c.key}>{c.label}</option>)}
              </select>
            </div>
            {(filterStatus !== 'All' || filterCategory !== 'All') && (
              <button onClick={() => { setFilterStatus('All'); setFilterCategory('All'); }} className="flex items-center gap-1 text-xs text-orange-500 hover:text-orange-600 font-medium">
                <X size={12} /> {t('admin.blog.clearFilters', 'Clear filters')}
              </button>
            )}
          </div>
        )}
      </div>

      {/* Bulk Actions Bar */}
      {someSelected && (
        <div className="flex items-center gap-3 px-4 py-2.5 rounded-xl mb-3 text-sm" style={{ backgroundColor: 'hsl(var(--primary-light))', border: '1px solid hsl(var(--primary) / 0.2)' }}>
          <span className="font-semibold" style={{ color: 'hsl(var(--primary))' }}>{selectedIds.size} {t('admin.blog.selected', 'selected')}</span>
          <div className="flex gap-2 ml-2">
            <button onClick={() => setPendingAction('publish')} className="flex items-center gap-1 px-3 py-1 rounded-lg bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-400 text-xs font-semibold hover:bg-emerald-200 transition-colors">
              <Eye size={12} /> {t('admin.blog.publish', 'Publish')}
            </button>
            <button onClick={() => setPendingAction('unpublish')} className="flex items-center gap-1 px-3 py-1 rounded-lg bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400 text-xs font-semibold hover:bg-slate-200 transition-colors">
              <EyeOff size={12} /> {t('admin.blog.unpublish', 'Unpublish')}
            </button>
            <button onClick={() => setPendingAction('delete')} className="flex items-center gap-1 px-3 py-1 rounded-lg bg-red-100 text-red-600 dark:bg-red-900/40 dark:text-red-400 text-xs font-semibold hover:bg-red-200 transition-colors">
              <Trash2 size={12} /> {t('admin.blog.delete', 'Delete')}
            </button>
          </div>
          <button onClick={() => setSelectedIds(new Set())} className="ml-auto" style={{ color: 'hsl(var(--muted-foreground))' }}>
            <X size={14} />
          </button>
        </div>
      )}

      {/* Table */}
      <div className="card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr style={{ borderBottom: '1px solid hsl(var(--border))', backgroundColor: 'hsl(var(--muted))' }}>
                <th className="px-4 py-3 text-left w-10">
                  <button onClick={toggleAll}>
                    {allSelected ? <CheckSquare size={16} style={{ color: 'hsl(var(--primary))' }} /> : <Square size={16} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                  </button>
                </th>
                <th className="px-4 py-3 text-left font-semibold text-xs uppercase tracking-wide" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.colTitle', 'Title')}</th>
                <th className="px-4 py-3 text-left font-semibold text-xs uppercase tracking-wide hidden md:table-cell" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.colAuthor', 'Author')}</th>
                <th className="px-4 py-3 text-left font-semibold text-xs uppercase tracking-wide hidden lg:table-cell" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.colCategory', 'Category')}</th>
                <th className="px-4 py-3 text-left font-semibold text-xs uppercase tracking-wide" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.colStatus', 'Status')}</th>
                <th className="px-4 py-3 text-left font-semibold text-xs uppercase tracking-wide hidden lg:table-cell" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.colPublished', 'Published')}</th>
                <th className="px-4 py-3 text-right font-semibold text-xs uppercase tracking-wide hidden md:table-cell" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.colViews', 'Views')}</th>
                <th className="px-4 py-3 text-right font-semibold text-xs uppercase tracking-wide" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('admin.blog.colActions', 'Actions')}</th>
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 ? (
                <tr>
                  <td colSpan={8} className="px-4 py-12 text-center text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {t('admin.blog.noPostsFound', 'No posts found matching your filters.')}
                  </td>
                </tr>
              ) : filtered.map((post) => (
                <tr
                  key={post.id}
                  className="transition-colors"
                  style={{ borderBottom: '1px solid hsl(var(--border))', backgroundColor: selectedIds.has(post.id) ? 'hsl(var(--primary-light))' : undefined }}
                >
                  <td className="px-4 py-3">
                    <button onClick={() => toggleOne(post.id)}>
                      {selectedIds.has(post.id)
                        ? <CheckSquare size={16} style={{ color: 'hsl(var(--primary))' }} />
                        : <Square size={16} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                    </button>
                  </td>
                  <td className="px-4 py-3 max-w-xs">
                    <p className="font-semibold line-clamp-2 leading-snug" style={{ color: 'hsl(var(--foreground))' }}>{post.title}</p>
                    <p className="text-xs mt-0.5 truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>/{post.slug}</p>
                  </td>
                  <td className="px-4 py-3 hidden md:table-cell">
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 rounded-full bg-gradient-to-br from-orange-400 to-orange-600 flex items-center justify-center text-white text-[10px] font-bold flex-shrink-0">
                        {post.author.split(' ').map(n => n[0]).join('')}
                      </div>
                      <span className="text-sm truncate" style={{ color: 'hsl(var(--foreground-secondary))' }}>{post.author}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 hidden lg:table-cell">
                    <span className="text-xs px-2 py-1 rounded-full" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))' }}>{post.category}</span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs px-2.5 py-1 rounded-full font-semibold ${statusConfig[post.status].class}`}>
                      {statusConfig[post.status].label}
                    </span>
                  </td>
                  <td className="px-4 py-3 hidden lg:table-cell">
                    <div className="flex items-center gap-1.5 text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                      <Calendar size={11} />
                      {post.publishDate}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-right hidden md:table-cell">
                    <span className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{post.views > 0 ? post.views.toLocaleString() : '—'}</span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center justify-end gap-1">
                      <Link
                        href={`/admin/blog/${post.id}/edit`}
                        className="p-1.5 rounded-lg transition-colors hover:bg-orange-100 dark:hover:bg-orange-900/30"
                        title={t('admin.blog.edit', 'Edit')}
                      >
                        <Edit2 size={14} style={{ color: 'hsl(var(--primary))' }} />
                      </Link>
                      <button
                        onClick={() => setDeleteTargetId(post.id)}
                        className="p-1.5 rounded-lg transition-colors hover:bg-red-100 dark:hover:bg-red-900/30"
                        title={t('admin.blog.delete', 'Delete')}
                      >
                        <Trash2 size={14} className="text-red-500" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {filtered.length > 0 && (
          <div className="px-4 py-3 flex items-center justify-between text-xs" style={{ borderTop: '1px solid hsl(var(--border))', color: 'hsl(var(--muted-foreground))' }}>
            <span>{t('admin.blog.showing', 'Showing')} {filtered.length} {t('admin.blog.of', 'of')} {posts.length} {t('admin.blog.posts', 'posts')}</span>
            <span>{posts.filter(p => p.status === 'published').length} {t('admin.blog.statPublished', 'Published')} · {posts.filter(p => p.status === 'draft').length} {t('admin.blog.statDrafts', 'Drafts')}</span>
          </div>
        )}
      </div>

      {/* Bulk Action Confirmation Modal */}
      {pendingAction && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="card p-6 max-w-sm w-full shadow-2xl">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-xl bg-orange-100 dark:bg-orange-900/40 flex items-center justify-center">
                <AlertTriangle size={18} className="text-orange-500" />
              </div>
              <div>
                <h3 className="font-bold" style={{ color: 'hsl(var(--foreground))' }}>
                  {pendingAction === 'delete' ? t('admin.blog.deletePosts', 'Delete Posts') : pendingAction === 'publish' ? t('admin.blog.publishPosts', 'Publish Posts') : t('admin.blog.unpublishPosts', 'Unpublish Posts')}
                </h3>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{selectedIds.size} {t('admin.blog.postsSelected', 'post(s) selected')}</p>
              </div>
            </div>
            <p className="text-sm mb-5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              {pendingAction === 'delete'
                ? t('admin.blog.confirmDelete', `Are you sure you want to permanently delete ${selectedIds.size} post(s)? This action cannot be undone.`)
                : pendingAction === 'publish'
                ? t('admin.blog.confirmPublish', `This will publish ${selectedIds.size} post(s) and make them visible on the public blog.`)
                : t('admin.blog.confirmUnpublish', `This will move ${selectedIds.size} post(s) back to draft status.`)}
            </p>
            <div className="flex gap-3">
              <button onClick={() => setPendingAction(null)} className="flex-1 btn-secondary text-sm py-2">{t('admin.blog.cancel', 'Cancel')}</button>
              <button
                onClick={confirmBulkAction}
                className={`flex-1 text-sm py-2 rounded-lg font-semibold transition-all ${pendingAction === 'delete' ? 'bg-red-500 hover:bg-red-600 text-white' : 'btn-primary'}`}
              >
                {pendingAction === 'delete' ? t('admin.blog.delete', 'Delete') : pendingAction === 'publish' ? t('admin.blog.publish', 'Publish') : t('admin.blog.unpublish', 'Unpublish')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Single Delete Confirmation Modal */}
      {deleteTargetId && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="card p-6 max-w-sm w-full shadow-2xl">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-xl bg-red-100 dark:bg-red-900/40 flex items-center justify-center">
                <Trash2 size={18} className="text-red-500" />
              </div>
              <div>
                <h3 className="font-bold" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.blog.deletePost', 'Delete Post')}</h3>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.blog.cannotBeUndone', 'This action cannot be undone')}</p>
              </div>
            </div>
            <p className="text-sm mb-5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
              {t('admin.blog.confirmDeleteSingle', 'Are you sure you want to delete')} &quot;{posts.find(p => p.id === deleteTargetId)?.title}&quot;?
            </p>
            <div className="flex gap-3">
              <button onClick={() => setDeleteTargetId(null)} className="flex-1 btn-secondary text-sm py-2">{t('admin.blog.cancel', 'Cancel')}</button>
              <button onClick={confirmDelete} className="flex-1 text-sm py-2 rounded-lg font-semibold bg-red-500 hover:bg-red-600 text-white transition-colors">{t('admin.blog.delete', 'Delete')}</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
