"use client";

import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import {
  FileText,
  Plus,
  Search,
  Filter,
  MoreVertical,
  Edit,
  Eye,
  Copy,
  Archive,
  Trash2,
  Calendar,
  CheckCircle2,
  Clock,
  AlertCircle,
  ExternalLink,
  ChevronLeft,
  ChevronRight,
  ArrowUpDown,
  FileCode,
  Sparkles,
  Bell,
} from "lucide-react";
import { PushSendDialog } from "@/components/admin/push-send-dialog";
import { useAdminAuth } from "@/components/admin/admin-auth-provider";
import { fetchWithAdminCache, invalidateAdminCache } from "@/lib/admin/client-cache";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

interface PostItem {
  id: string;
  slug: string;
  title: string;
  excerpt: string;
  category: string;
  status: "DRAFT" | "SCHEDULED" | "PUBLISHED" | "ARCHIVED";
  publishedDate: string;
  scheduledFor?: string | null;
  updatedAt: string;
  author: {
    name: string;
    role: string;
  };
  featuredImage?: string | null;
  coverIllustration?: string;
  seoTitle?: string | null;
  metaDescription?: string | null;
  sections?: any[];
}

export default function AdminPostsPage() {
  const router = useRouter();
  const [posts, setPosts] = React.useState<PostItem[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [statusFilter, setStatusFilter] = React.useState<string>("ALL");
  const [categoryFilter, setCategoryFilter] = React.useState<string>("All");
  const [searchQuery, setSearchQuery] = React.useState("");
  const [page, setPage] = React.useState(1);
  const [totalPages, setTotalPages] = React.useState(1);
  const [totalCount, setTotalCount] = React.useState(0);
  const [sortBy, setSortBy] = React.useState("publishedDate");

  // Create Draft Modal State
  const [createOpen, setCreateOpen] = React.useState(false);
  const [newTitle, setNewTitle] = React.useState("");
  const [newCategory, setNewCategory] = React.useState("Voice AI Guides");
  const [creating, setCreating] = React.useState(false);

  // Delete Draft Confirmation Modal State
  const [postToDelete, setPostToDelete] = React.useState<PostItem | null>(null);
  const [deleting, setDeleting] = React.useState(false);

  // Push Notification state
  const [pushOpen, setPushOpen] = React.useState(false);
  const [pushPost, setPushPost] = React.useState<PostItem | null>(null);
  const { user, permissions } = useAdminAuth();
  const canSendPush = React.useMemo(() => {
    if (!user) return false;
    const isMain = user.level === "MAIN_ADMIN" || user.role === "MAIN_ADMIN";
    const hasPerm = permissions?.includes("notifications.send");
    return Boolean(isMain || hasPerm);
  }, [user, permissions]);

  // Fetch posts from live MongoDB with smart caching
  const fetchPosts = React.useCallback(async (forceFresh = false) => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        status: statusFilter,
        page: page.toString(),
        limit: "15",
        sortBy,
      });
      if (categoryFilter !== "All") params.set("category", categoryFilter);
      if (searchQuery.trim()) params.set("search", searchQuery.trim());

      const data = await fetchWithAdminCache<{
        posts?: PostItem[];
        pagination?: { totalPages: number; total: number };
      }>(`/api/admin/posts?${params.toString()}`, {
        tags: ["posts"],
        forceFresh,
      });

      setPosts(data.posts || []);
      setTotalPages(data.pagination?.totalPages || 1);
      setTotalCount(data.pagination?.total || 0);
    } catch (err: any) {
      toast.error(err.message || "Failed to load posts.");
    } finally {
      setLoading(false);
    }
  }, [statusFilter, categoryFilter, searchQuery, page, sortBy]);

  React.useEffect(() => {
    fetchPosts();
  }, [fetchPosts]);

  // Handle Quick Create Draft
  const handleCreateDraft = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newTitle.trim()) {
      toast.error("Please provide an article title.");
      return;
    }
    try {
      setCreating(true);
      const res = await fetch("/api/admin/posts", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: newTitle.trim(),
          category: newCategory,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to create draft.");

      invalidateAdminCache("posts");
      toast.success("Draft created in MongoDB!");
      setCreateOpen(false);
      setNewTitle("");
      router.push(`/admin/posts/${data.post.id}`);
    } catch (err: any) {
      toast.error(err.message || "Failed to create draft.");
    } finally {
      setCreating(false);
    }
  };

  // Handle Duplicate Article
  const handleDuplicate = async (postId: string) => {
    try {
      toast.loading("Duplicating article...", { id: "dup" });
      const res = await fetch(`/api/admin/posts/${postId}/duplicate`, {
        method: "POST",
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to duplicate post.");
      invalidateAdminCache("posts");
      toast.success("Article duplicated as new draft!", { id: "dup" });
      fetchPosts(true);
    } catch (err: any) {
      toast.error(err.message || "Duplicate failed.", { id: "dup" });
    }
  };

  // Handle Archive Article
  const handleArchive = async (postId: string) => {
    try {
      toast.loading("Archiving article...", { id: "arch" });
      const res = await fetch(`/api/admin/posts/${postId}/publish`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "archive" }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to archive post.");
      invalidateAdminCache("posts");
      toast.success("Article archived from public view.", { id: "arch" });
      fetchPosts(true);
    } catch (err: any) {
      toast.error(err.message || "Archive failed.", { id: "arch" });
    }
  };

  // Handle Cancel Schedule
  const handleCancelSchedule = async (postId: string) => {
    try {
      toast.loading("Cancelling schedule...", { id: "canc" });
      const res = await fetch(`/api/admin/posts/${postId}/publish`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "cancel-schedule" }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to cancel schedule.");
      invalidateAdminCache("posts");
      toast.success("Schedule cancelled. Reverted to draft.", { id: "canc" });
      fetchPosts(true);
    } catch (err: any) {
      toast.error(err.message || "Operation failed.", { id: "canc" });
    }
  };

  // Handle Delete Draft (AlertDialog confirmation)
  const confirmDeleteDraft = async () => {
    if (!postToDelete) return;
    try {
      setDeleting(true);
      const res = await fetch(`/api/admin/posts/${postToDelete.id}`, {
        method: "DELETE",
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to delete draft.");
      invalidateAdminCache("posts");
      toast.success("Draft deleted.");
      setPostToDelete(null);
      fetchPosts(true);
    } catch (err: any) {
      toast.error(err.message || "Failed to delete.");
    } finally {
      setDeleting(false);
    }
  };

  // Compute editorial completeness score
  const calculateSeoScore = (post: PostItem) => {
    let score = 20;
    if (post.title && post.title.length >= 10) score += 15;
    if (post.excerpt && post.excerpt.length >= 20) score += 15;
    if (post.seoTitle) score += 15;
    if (post.metaDescription && post.metaDescription.length >= 50) score += 15;
    if (post.featuredImage) score += 10;
    if (post.sections && post.sections.length >= 2) score += 10;
    return Math.min(score, 100);
  };

  return (
    <div className="space-y-6">
      {/* Header & Quick Action */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-neutral-900 dark:text-white">
            Articles & Guides
          </h1>
          <p className="text-xs text-neutral-500">
            Authoritative source of truth for Quto AI public blog posts ({totalCount} total in MongoDB).
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button
            onClick={() => setCreateOpen(true)}
            className="gap-1.5 bg-neutral-900 text-xs font-semibold text-white shadow-xs hover:bg-neutral-800 dark:bg-white dark:text-neutral-900 dark:hover:bg-neutral-100"
          >
            <Plus className="h-4 w-4" />
            <span>Create Article</span>
          </Button>
        </div>
      </div>

      {/* Filter Tabs & Search Controls */}
      <div className="flex flex-col gap-4 rounded-xl border border-neutral-200 bg-white p-4 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
        <div className="flex flex-wrap items-center justify-between gap-3">
          {/* Status Tabs */}
          <div className="flex flex-wrap gap-1 rounded-lg bg-neutral-100 p-1 dark:bg-neutral-800/60 text-xs font-medium">
            {[
              { label: "All Posts", value: "ALL" },
              { label: "Published", value: "PUBLISHED" },
              { label: "Scheduled", value: "SCHEDULED" },
              { label: "Drafts", value: "DRAFT" },
              { label: "Archived", value: "ARCHIVED" },
            ].map((tab) => (
              <button
                key={tab.value}
                onClick={() => {
                  setStatusFilter(tab.value);
                  setPage(1);
                }}
                className={`rounded-md px-3 py-1.5 transition ${
                  statusFilter === tab.value
                    ? "bg-white text-neutral-900 font-semibold shadow-xs dark:bg-neutral-900 dark:text-white"
                    : "text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>

          {/* Search input */}
          <div className="relative w-full sm:w-72">
            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-neutral-400" />
            <Input
              placeholder="Search title, slug, author..."
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                setPage(1);
              }}
              className="pl-8 text-xs"
            />
          </div>
        </div>

        {/* Category & Sorting Secondary Bar */}
        <div className="flex flex-wrap items-center justify-between gap-3 border-t border-neutral-100 pt-3 dark:border-neutral-800/60 text-xs">
          <div className="flex items-center gap-2">
            <span className="text-neutral-500 font-medium">Category:</span>
            <Select
              value={categoryFilter}
              onValueChange={(val) => {
                setCategoryFilter(val);
                setPage(1);
              }}
            >
              <SelectTrigger className="h-8 w-44 text-xs">
                <SelectValue placeholder="All Categories" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="All">All Categories</SelectItem>
                <SelectItem value="Voice AI Guides">Voice AI Guides</SelectItem>
                <SelectItem value="Compliance & Security">Compliance & Security</SelectItem>
                <SelectItem value="Architecture & Latency">Architecture & Latency</SelectItem>
                <SelectItem value="Platform Alternatives">Platform Alternatives</SelectItem>
                <SelectItem value="Customer Operations">Customer Operations</SelectItem>
                <SelectItem value="Cost Optimization">Cost Optimization</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="flex items-center gap-2">
            <span className="text-neutral-500 font-medium">Sort by:</span>
            <Select
              value={sortBy}
              onValueChange={(val) => setSortBy(val)}
            >
              <SelectTrigger className="h-8 w-48 text-xs">
                <SelectValue placeholder="Sort by" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="publishedDate">Publish Date (Newest)</SelectItem>
                <SelectItem value="updatedAt">Recently Updated</SelectItem>
                <SelectItem value="createdAt">Created Date</SelectItem>
                <SelectItem value="title">Title (A-Z)</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </div>

      {/* Posts Container: Desktop Table + Mobile Cards */}
      <div className="overflow-hidden rounded-xl border border-neutral-200 bg-white shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
        {/* DESKTOP TABLE VIEW (md and up) */}
        <div className="hidden md:block overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead className="border-b border-neutral-200 bg-neutral-50/75 text-[11px] font-semibold text-neutral-500 uppercase tracking-wider dark:border-neutral-800 dark:bg-neutral-950/50">
              <tr>
                <th className="w-16 px-4 py-3">Image</th>
                <th className="px-4 py-3">Article</th>
                <th className="px-4 py-3">Category</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">Author</th>
                <th className="px-4 py-3">Date</th>
                <th className="px-4 py-3 text-center">SEO Health</th>
                <th className="px-4 py-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-neutral-100 dark:divide-neutral-800">
              {loading ? (
                Array.from({ length: 8 }).map((_, idx) => (
                  <tr key={idx} className="animate-pulse">
                    <td className="px-4 py-3.5 w-16">
                      <Skeleton className="h-10 w-14 rounded-md bg-neutral-200 dark:bg-neutral-800" />
                    </td>
                    <td className="px-4 py-3.5">
                      <Skeleton className="h-4 w-52 mb-1.5 bg-neutral-200 dark:bg-neutral-800" />
                      <Skeleton className="h-3 w-32 bg-neutral-100 dark:bg-neutral-800/60" />
                    </td>
                    <td className="px-4 py-3.5">
                      <Skeleton className="h-4 w-28 bg-neutral-200 dark:bg-neutral-800" />
                    </td>
                    <td className="px-4 py-3.5">
                      <Skeleton className="h-5 w-20 rounded-full bg-neutral-200 dark:bg-neutral-800" />
                    </td>
                    <td className="px-4 py-3.5">
                      <Skeleton className="h-4 w-28 mb-1 bg-neutral-200 dark:bg-neutral-800" />
                      <Skeleton className="h-3 w-16 bg-neutral-100 dark:bg-neutral-800/60" />
                    </td>
                    <td className="px-4 py-3.5">
                      <Skeleton className="h-4 w-20 bg-neutral-200 dark:bg-neutral-800" />
                    </td>
                    <td className="px-4 py-3.5 text-center">
                      <Skeleton className="h-5 w-12 mx-auto rounded-full bg-neutral-200 dark:bg-neutral-800" />
                    </td>
                    <td className="px-4 py-3.5 text-right">
                      <div className="flex items-center justify-end gap-1">
                        <Skeleton className="h-7 w-7 rounded-md bg-neutral-200 dark:bg-neutral-800" />
                        <Skeleton className="h-7 w-7 rounded-md bg-neutral-200 dark:bg-neutral-800" />
                        <Skeleton className="h-7 w-7 rounded-md bg-neutral-200 dark:bg-neutral-800" />
                      </div>
                    </td>
                  </tr>
                ))
              ) : posts.length === 0 ? (
                <tr>
                  <td colSpan={8} className="py-12 text-center text-neutral-500">
                    <p className="font-medium text-sm">No articles match your criteria.</p>
                    <p className="text-xs text-neutral-400 mt-1">
                      Try adjusting your search query or filters, or create a new draft.
                    </p>
                  </td>
                </tr>
              ) : (
                posts.map((post) => {
                  const seoScore = calculateSeoScore(post);
                  const bannerImg =
                    post.featuredImage ||
                    post.coverIllustration ||
                    (post.sections?.find(
                      (s: any) => s.type === "image" || s.type === "hero"
                    ) as any)?.content?.imageUrl ||
                    null;

                  return (
                    <tr
                      key={post.id}
                      className="transition hover:bg-neutral-50/60 dark:hover:bg-neutral-800/40"
                    >
                      {/* Banner Thumbnail */}
                      <td className="px-4 py-3.5 w-16 shrink-0">
                        <div className="relative h-10 w-14 overflow-hidden rounded-md border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-800 shrink-0">
                          {bannerImg ? (
                            <img
                              src={bannerImg}
                              alt=""
                              loading="lazy"
                              className="h-full w-full object-cover"
                            />
                          ) : (
                            <div className="flex h-full w-full items-center justify-center text-neutral-400">
                              <FileText className="h-4 w-4" />
                            </div>
                          )}
                        </div>
                      </td>

                      {/* Title & Slug */}
                      <td className="px-4 py-3.5 max-w-xs sm:max-w-sm">
                        <Link
                          href={`/admin/posts/${post.id}`}
                          className="font-semibold text-neutral-900 hover:underline dark:text-white line-clamp-1 block"
                        >
                          {post.title}
                        </Link>
                        <div className="flex items-center gap-1.5 text-[11px] text-neutral-400 mt-0.5">
                          <span>/blog/{post.slug}</span>
                        </div>
                      </td>

                      {/* Category */}
                      <td className="px-4 py-3.5 text-neutral-600 dark:text-neutral-400">
                        {post.category}
                      </td>

                      {/* Status Badge */}
                      <td className="px-4 py-3.5 whitespace-nowrap">
                        {post.status === "PUBLISHED" && (
                          <Badge className="bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/40 dark:text-emerald-300 dark:border-emerald-800">
                            Published
                          </Badge>
                        )}
                        {post.status === "SCHEDULED" && (
                          <Badge className="bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-800">
                            Scheduled
                          </Badge>
                        )}
                        {post.status === "DRAFT" && (
                          <Badge className="bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-950/40 dark:text-blue-300 dark:border-blue-800">
                            Draft
                          </Badge>
                        )}
                        {post.status === "ARCHIVED" && (
                          <Badge className="bg-neutral-100 text-neutral-700 border-neutral-300 dark:bg-neutral-800 dark:text-neutral-300">
                            Archived
                          </Badge>
                        )}
                      </td>

                      {/* Author */}
                      <td className="px-4 py-3.5 whitespace-nowrap text-neutral-600 dark:text-neutral-400">
                        <div className="font-medium text-neutral-900 dark:text-white">
                          {post.author?.name || "Quto Editorial"}
                        </div>
                        <div className="text-[10px] text-neutral-400">
                          {post.author?.role || "Staff"}
                        </div>
                      </td>

                      {/* Date */}
                      <td suppressHydrationWarning className="px-4 py-3.5 whitespace-nowrap text-neutral-500">
                        {post.status === "SCHEDULED" && post.scheduledFor ? (
                          <div className="flex items-center gap-1 text-amber-600 dark:text-amber-400 font-medium">
                            <Clock className="h-3 w-3" />
                            <span>{new Date(post.scheduledFor).toLocaleDateString("en-US")}</span>
                          </div>
                        ) : (
                          <div>{new Date(post.publishedDate || post.updatedAt).toLocaleDateString("en-US")}</div>
                        )}
                      </td>

                      {/* SEO Score */}
                      <td className="px-4 py-3.5 text-center">
                        <span
                          className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-bold ${
                            seoScore >= 80
                              ? "bg-emerald-100 text-emerald-800 dark:bg-emerald-950/60 dark:text-emerald-300"
                              : seoScore >= 60
                              ? "bg-amber-100 text-amber-800 dark:bg-amber-950/60 dark:text-amber-300"
                              : "bg-red-100 text-red-800 dark:bg-red-950/60 dark:text-red-300"
                          }`}
                        >
                          {seoScore}%
                        </span>
                      </td>

                      {/* Actions Menu */}
                      <td className="px-4 py-3.5 text-right whitespace-nowrap">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                              <MoreVertical className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end" className="w-44 text-xs">
                            <DropdownMenuItem asChild>
                              <Link href={`/admin/posts/${post.id}`} className="cursor-pointer">
                                <Edit className="mr-2 h-3.5 w-3.5" />
                                <span>Edit in Studio</span>
                              </Link>
                            </DropdownMenuItem>

                            <DropdownMenuItem asChild>
                              <Link
                                href={`/admin/preview/${post.id}`}
                                target="_blank"
                                className="cursor-pointer"
                              >
                                <Eye className="mr-2 h-3.5 w-3.5" />
                                <span>Secure Preview</span>
                              </Link>
                            </DropdownMenuItem>

                            {post.status === "PUBLISHED" && (
                              <DropdownMenuItem asChild>
                                <Link
                                  href={`/blog/${post.slug}`}
                                  target="_blank"
                                  className="cursor-pointer text-emerald-600 dark:text-emerald-400"
                                >
                                  <ExternalLink className="mr-2 h-3.5 w-3.5" />
                                  <span>View Live Page</span>
                                </Link>
                              </DropdownMenuItem>
                            )}

                            {post.status === "PUBLISHED" && canSendPush && (
                              <DropdownMenuItem
                                onClick={() => {
                                  setPushPost(post);
                                  setPushOpen(true);
                                }}
                                className="cursor-pointer text-purple-600 dark:text-purple-400 focus:text-purple-600"
                              >
                                <Bell className="mr-2 h-3.5 w-3.5" />
                                <span>Send Push Notification</span>
                              </DropdownMenuItem>
                            )}

                            <DropdownMenuSeparator />

                            <DropdownMenuItem
                              onClick={() => handleDuplicate(post.id)}
                              className="cursor-pointer"
                            >
                              <Copy className="mr-2 h-3.5 w-3.5" />
                              <span>Duplicate Post</span>
                            </DropdownMenuItem>

                            {post.status === "SCHEDULED" && (
                              <DropdownMenuItem
                                onClick={() => handleCancelSchedule(post.id)}
                                className="cursor-pointer text-amber-600"
                              >
                                <Clock className="mr-2 h-3.5 w-3.5" />
                                <span>Cancel Schedule</span>
                              </DropdownMenuItem>
                            )}

                            {post.status === "PUBLISHED" && (
                              <DropdownMenuItem
                                onClick={() => handleArchive(post.id)}
                                className="cursor-pointer text-amber-600"
                              >
                                <Archive className="mr-2 h-3.5 w-3.5" />
                                <span>Archive from Public</span>
                              </DropdownMenuItem>
                            )}

                            {/* DELETE IS ALLOWED ONLY FOR DRAFTS (Published Delete Safety) */}
                            {post.status === "DRAFT" && (
                              <DropdownMenuItem
                                onClick={() => setPostToDelete(post)}
                                className="cursor-pointer text-red-600 focus:text-red-600"
                              >
                                <Trash2 className="mr-2 h-3.5 w-3.5" />
                                <span>Delete Draft</span>
                              </DropdownMenuItem>
                            )}
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* MOBILE CARD VIEW (md:hidden) */}
        <div className="md:hidden divide-y divide-neutral-100 dark:divide-neutral-800">
          {loading ? (
            Array.from({ length: 4 }).map((_, idx) => (
              <div key={idx} className="p-4 space-y-3 animate-pulse">
                <div className="flex items-start gap-3">
                  <Skeleton className="h-16 w-20 rounded-lg bg-neutral-200 dark:bg-neutral-800 shrink-0" />
                  <div className="flex-1 space-y-2">
                    <Skeleton className="h-3 w-24 bg-neutral-200 dark:bg-neutral-800" />
                    <Skeleton className="h-4 w-full bg-neutral-200 dark:bg-neutral-800" />
                    <Skeleton className="h-3 w-36 bg-neutral-100 dark:bg-neutral-800/60" />
                  </div>
                </div>
              </div>
            ))
          ) : posts.length === 0 ? (
            <div className="py-12 text-center text-neutral-500 p-4">
              <p className="font-medium text-sm">No articles match your criteria.</p>
              <p className="text-xs text-neutral-400 mt-1">
                Try adjusting your search query or filters, or create a new draft.
              </p>
            </div>
          ) : (
            posts.map((post) => {
              const seoScore = calculateSeoScore(post);
              const bannerImg =
                post.featuredImage ||
                post.coverIllustration ||
                (post.sections?.find(
                  (s: any) => s.type === "image" || s.type === "hero"
                ) as any)?.content?.imageUrl ||
                null;

              return (
                <div
                  key={post.id}
                  className="p-4 space-y-3 transition hover:bg-neutral-50/50 dark:hover:bg-neutral-800/20"
                >
                  <div className="flex items-start gap-3">
                    {/* Thumbnail */}
                    <div className="relative h-16 w-20 shrink-0 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-800">
                      {bannerImg ? (
                        <img
                          src={bannerImg}
                          alt=""
                          loading="lazy"
                          className="h-full w-full object-cover"
                        />
                      ) : (
                        <div className="flex h-full w-full items-center justify-center text-neutral-400">
                          <FileText className="h-6 w-6" />
                        </div>
                      )}
                    </div>

                    {/* Meta & Title */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between gap-1.5 mb-1">
                        <span className="text-[11px] font-semibold text-cyan-600 dark:text-cyan-400 truncate">
                          {post.category}
                        </span>

                        {post.status === "PUBLISHED" && (
                          <Badge className="bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/40 dark:text-emerald-300 text-[10px] px-1.5 py-0">
                            Published
                          </Badge>
                        )}
                        {post.status === "SCHEDULED" && (
                          <Badge className="bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950/40 dark:text-amber-300 text-[10px] px-1.5 py-0">
                            Scheduled
                          </Badge>
                        )}
                        {post.status === "DRAFT" && (
                          <Badge className="bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-950/40 dark:text-blue-300 text-[10px] px-1.5 py-0">
                            Draft
                          </Badge>
                        )}
                        {post.status === "ARCHIVED" && (
                          <Badge className="bg-neutral-100 text-neutral-700 border-neutral-300 dark:bg-neutral-800 dark:text-neutral-300 text-[10px] px-1.5 py-0">
                            Archived
                          </Badge>
                        )}
                      </div>

                      <Link
                        href={`/admin/posts/${post.id}`}
                        className="font-semibold text-xs sm:text-sm text-neutral-900 dark:text-white hover:underline line-clamp-2"
                      >
                        {post.title}
                      </Link>
                    </div>
                  </div>

                  {/* Card Footer: Author, Date, SEO, Actions */}
                  <div className="flex items-center justify-between pt-1 border-t border-neutral-100 dark:border-neutral-800 text-[11px] text-neutral-500">
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-neutral-700 dark:text-neutral-300">
                        {post.author?.name || "Staff"}
                      </span>
                      <span>•</span>
                      <span suppressHydrationWarning>
                        {new Date(post.publishedDate || post.updatedAt).toLocaleDateString("en-US", {
                          dateStyle: "short",
                        })}
                      </span>
                    </div>

                    <div className="flex items-center gap-2">
                      <span
                        className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold ${
                          seoScore >= 80
                            ? "bg-emerald-100 text-emerald-800 dark:bg-emerald-950/60 dark:text-emerald-300"
                            : seoScore >= 60
                            ? "bg-amber-100 text-amber-800 dark:bg-amber-950/60 dark:text-amber-300"
                            : "bg-red-100 text-red-800 dark:bg-red-950/60 dark:text-red-300"
                        }`}
                      >
                        SEO {seoScore}%
                      </span>

                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="sm" className="h-7 w-7 p-0">
                            <MoreVertical className="h-3.5 w-3.5" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-44 text-xs">
                          <DropdownMenuItem asChild>
                            <Link href={`/admin/posts/${post.id}`} className="cursor-pointer">
                              <Edit className="mr-2 h-3.5 w-3.5" />
                              <span>Edit in Studio</span>
                            </Link>
                          </DropdownMenuItem>

                          <DropdownMenuItem asChild>
                            <Link
                              href={`/admin/preview/${post.id}`}
                              target="_blank"
                              className="cursor-pointer"
                            >
                              <Eye className="mr-2 h-3.5 w-3.5" />
                              <span>Secure Preview</span>
                            </Link>
                          </DropdownMenuItem>

                          {post.status === "PUBLISHED" && (
                            <DropdownMenuItem asChild>
                              <Link
                                href={`/blog/${post.slug}`}
                                target="_blank"
                                className="cursor-pointer text-emerald-600 dark:text-emerald-400"
                              >
                                <ExternalLink className="mr-2 h-3.5 w-3.5" />
                                <span>View Live Page</span>
                              </Link>
                            </DropdownMenuItem>
                          )}

                          {post.status === "PUBLISHED" && canSendPush && (
                            <DropdownMenuItem
                              onClick={() => {
                                setPushPost(post);
                                setPushOpen(true);
                              }}
                              className="cursor-pointer text-purple-600 dark:text-purple-400 focus:text-purple-600"
                            >
                              <Bell className="mr-2 h-3.5 w-3.5" />
                              <span>Send Push Notification</span>
                            </DropdownMenuItem>
                          )}

                          <DropdownMenuSeparator />

                          <DropdownMenuItem
                            onClick={() => handleDuplicate(post.id)}
                            className="cursor-pointer"
                          >
                            <Copy className="mr-2 h-3.5 w-3.5" />
                            <span>Duplicate Post</span>
                          </DropdownMenuItem>

                          {post.status === "SCHEDULED" && (
                            <DropdownMenuItem
                              onClick={() => handleCancelSchedule(post.id)}
                              className="cursor-pointer text-amber-600"
                            >
                              <Clock className="mr-2 h-3.5 w-3.5" />
                              <span>Cancel Schedule</span>
                            </DropdownMenuItem>
                          )}

                          {post.status === "PUBLISHED" && (
                            <DropdownMenuItem
                              onClick={() => handleArchive(post.id)}
                              className="cursor-pointer text-amber-600"
                            >
                              <Archive className="mr-2 h-3.5 w-3.5" />
                              <span>Archive from Public</span>
                            </DropdownMenuItem>
                          )}

                          {post.status === "DRAFT" && (
                            <DropdownMenuItem
                              onClick={() => setPostToDelete(post)}
                              className="cursor-pointer text-red-600 focus:text-red-600"
                            >
                              <Trash2 className="mr-2 h-3.5 w-3.5" />
                              <span>Delete Draft</span>
                            </DropdownMenuItem>
                          )}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>

        {/* Pagination Bar */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between border-t border-neutral-100 px-4 py-3 dark:border-neutral-800 text-xs">
            <span className="text-neutral-500">
              Page {page} of {totalPages} ({totalCount} articles)
            </span>
            <div className="flex items-center gap-1.5">
              <Button
                variant="outline"
                size="sm"
                disabled={page <= 1}
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                className="h-8 px-2 text-xs"
              >
                <ChevronLeft className="h-3.5 w-3.5" />
                <span>Previous</span>
              </Button>
              <Button
                variant="outline"
                size="sm"
                disabled={page >= totalPages}
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                className="h-8 px-2 text-xs"
              >
                <span>Next</span>
                <ChevronRight className="h-3.5 w-3.5" />
              </Button>
            </div>
          </div>
        )}
      </div>

      {/* Create Draft Dialog */}
      <Dialog open={createOpen} onOpenChange={setCreateOpen}>
        <DialogContent className="sm:max-w-md">
          <form onSubmit={handleCreateDraft}>
            <DialogHeader>
              <DialogTitle className="text-base font-bold">Create Article Draft</DialogTitle>
              <DialogDescription className="text-xs">
                Creates a new draft post in MongoDB and opens the Studio editor.
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-3.5 py-4 text-xs">
              <div className="space-y-1">
                <label className="font-semibold text-neutral-700 dark:text-neutral-300">
                  Article Title *
                </label>
                <Input
                  placeholder="e.g., Enterprise Voice AI Latency Optimization Guide"
                  value={newTitle}
                  onChange={(e) => setNewTitle(e.target.value)}
                  required
                  className="text-xs"
                  autoFocus
                />
              </div>

              <div className="space-y-1">
                <label className="font-semibold text-neutral-700 dark:text-neutral-300">
                  Topic Category
                </label>
                <Select
                  value={newCategory}
                  onValueChange={(val) => setNewCategory(val)}
                >
                  <SelectTrigger className="w-full text-xs">
                    <SelectValue placeholder="Select Category" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="Voice AI Guides">Voice AI Guides</SelectItem>
                    <SelectItem value="Compliance & Security">Compliance & Security</SelectItem>
                    <SelectItem value="Architecture & Latency">Architecture & Latency</SelectItem>
                    <SelectItem value="Platform Alternatives">Platform Alternatives</SelectItem>
                    <SelectItem value="Customer Operations">Customer Operations</SelectItem>
                    <SelectItem value="Cost Optimization">Cost Optimization</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setCreateOpen(false)}
                className="text-xs"
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={creating}
                className="bg-neutral-900 text-xs text-white hover:bg-neutral-800 dark:bg-white dark:text-neutral-900"
              >
                {creating ? "Creating Draft..." : "Continue to Studio"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* Delete Draft Alert Dialog (Requirement 43: shadcn AlertDialog, NOT window.confirm) */}
      <AlertDialog open={!!postToDelete} onOpenChange={(open) => !open && setPostToDelete(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Draft Article?</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete &ldquo;{postToDelete?.title}&rdquo;? This draft will be
              permanently removed from MongoDB. This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDeleteDraft}
              disabled={deleting}
              className="bg-red-600 text-white hover:bg-red-700"
            >
              {deleting ? "Deleting..." : "Permanently Delete"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Push Notification Broadcast Dialog */}
      <PushSendDialog
        open={pushOpen}
        onOpenChange={setPushOpen}
        post={pushPost}
      />
    </div>
  );
}
