"use client";

import * as React from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { toast } from "sonner";
import {
  ArrowLeft,
  Save,
  Clock,
  Send,
  Eye,
  History,
  Sparkles,
  CheckCircle2,
  AlertTriangle,
  XCircle,
  Image as ImageIcon,
  ExternalLink,
  RotateCcw,
  Shield,
  UploadCloud,
  Check,
  Calendar as CalendarIcon,
  BookOpen,
  Globe,
  UserCheck,
  Trash2,
  FolderTree,
  Plus,
  Share2,
  Bell,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { invalidateAdminCache } from "@/lib/admin/client-cache";
import { Badge } from "@/components/ui/badge";
import { FloatingInput, FloatingTextarea } from "@/components/ui/floating-input";
import { FloatingSelect } from "@/components/ui/floating-select";
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 { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { Skeleton } from "@/components/ui/skeleton";
import { TiptapEditor } from "@/components/admin/tiptap-editor";
import { calculateReadingStats, ReadingStats } from "@/lib/reading-time";
import { PushSendDialog } from "@/components/admin/push-send-dialog";

interface AuthorItem {
  id: string;
  name: string;
  email: string;
  role: string;
  level: string;
  avatarText: string;
  avatarColor: string;
  bio: string;
  profileSlug?: string;
}

interface BlogSection {
  id: string;
  title: string;
  content: string;
  bulletPoints?: string[];
  callout?: {
    type: "info" | "warning" | "security";
    text: string;
  };
}

interface PostData {
  id: string;
  slug: string;
  title: string;
  excerpt: string;
  category: string;
  status: "DRAFT" | "SCHEDULED" | "PUBLISHED" | "ARCHIVED";
  publishedDate: string;
  scheduledFor?: string | null;
  readTime: string;
  wordCount?: number;
  authorId?: string;
  author: {
    name: string;
    role: string;
    avatarText?: string;
    avatarColor?: string;
    bio?: string;
    profileSlug?: string;
  };
  featuredImage?: string | null;
  featuredImageAlt?: string | null;
  sections?: BlogSection[];
  contentHtml?: string;
  contentJson?: any;
  seoTitle?: string | null;
  metaDescription?: string | null;
  canonicalUrl?: string | null;
  robots?: string | null;
  ogTitle?: string | null;
  ogDescription?: string | null;
  ogImage?: string | null;
  ogImageId?: string | null;
  twitterTitle?: string | null;
  twitterDescription?: string | null;
  twitterImage?: string | null;
  twitterImageId?: string | null;
  categoryId?: string;
  featuredImageId?: string | null;
  version: number;
  updatedAt: string;
  liveSlug?: string;
  hasWorkingDraft?: boolean;
}

interface RevisionItem {
  id: string;
  version: number;
  changeSummary: string;
  actorName: string;
  timestamp: string;
}

interface MediaItem {
  id: string;
  filename: string;
  url: string;
  alt: string;
  mimeType: string;
  size: number;
}

function sectionsToHtml(sections: BlogSection[]): string {
  if (!sections || sections.length === 0) return "";
  return sections
    .map((s) => {
      let part = `<h2>${s.title}</h2><p>${s.content.replace(/\n\n/g, "</p><p>")}</p>`;
      if (s.bulletPoints && s.bulletPoints.length > 0) {
        part += `<ul>${s.bulletPoints.map((bp) => `<li>${bp}</li>`).join("")}</ul>`;
      }
      return part;
    })
    .join("\n");
}

export default function ArticleStudioPage() {
  const params = useParams();
  const router = useRouter();
  const id = params.id as string;

  const [post, setPost] = React.useState<PostData | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);

  // Author accounts directory from admin users
  const [authors, setAuthors] = React.useState<AuthorItem[]>([]);

  // Live reading stats
  const [readingStats, setReadingStats] = React.useState<ReadingStats>({
    words: 0,
    minutes: 1,
    readTime: "1 min read",
  });

  // Autosave Status: "SAVED" | "SAVING" | "UNSAVED" | "ERROR"
  const [saveStatus, setSaveStatus] = React.useState<"SAVED" | "SAVING" | "UNSAVED" | "ERROR">("SAVED");
  const [lastSavedTime, setLastSavedTime] = React.useState<string | null>(null);
  const isDirtyRef = React.useRef(false);
  const postRef = React.useRef<PostData | null>(null);

  // Modals & Panels
  const [publishModalOpen, setPublishModalOpen] = React.useState(false);
  const [discardModalOpen, setDiscardModalOpen] = React.useState(false);
  const [scheduleModalOpen, setScheduleModalOpen] = React.useState(false);
  const [scheduleCalendarOpen, setScheduleCalendarOpen] = React.useState(false);
  const [scheduleDate, setScheduleDate] = React.useState<Date | undefined>(undefined);
  const [scheduleTime, setScheduleTime] = React.useState("09:00");
  const [scheduleTimezone, setScheduleTimezone] = React.useState("UTC");
  const [revisionsOpen, setRevisionsOpen] = React.useState(false);
  const [revisions, setRevisions] = React.useState<RevisionItem[]>([]);
  const [mediaPickerOpen, setMediaPickerOpen] = React.useState(false);
  const [mediaPickerTab, setMediaPickerTab] = React.useState<"LIBRARY" | "UPLOAD">("LIBRARY");
  const [mediaPickerTarget, setMediaPickerTarget] = React.useState<"featured" | "og" | "twitter">("featured");
  const [mediaItems, setMediaItems] = React.useState<MediaItem[]>([]);
  const [mediaUploading, setMediaUploading] = React.useState(false);
  const [previewSyncing, setPreviewSyncing] = React.useState(false);

  // Push Notification State
  const [pushModalOpen, setPushModalOpen] = React.useState(false);
  const [pushSending, setPushSending] = React.useState(false);
  const [subscriberCount, setSubscriberCount] = React.useState<number | null>(null);
  const [pushTitle, setPushTitle] = React.useState("");
  const [pushBody, setPushBody] = React.useState("");

  // Categories directory from MongoDB
  const [categories, setCategories] = React.useState<Array<{ id: string; name: string; slug: string }>>([]);
  const [categoriesLoading, setCategoriesLoading] = React.useState(true);
  const [addCategoryOpen, setAddCategoryOpen] = React.useState(false);
  const [newCatName, setNewCatName] = React.useState("");
  const [newCatSlug, setNewCatSlug] = React.useState("");
  const [savingCategory, setSavingCategory] = React.useState(false);

  const loadCategories = React.useCallback(async () => {
    try {
      setCategoriesLoading(true);
      const res = await fetch("/api/admin/categories");
      if (res.ok) {
        const data = await res.json();
        setCategories(data.categories || []);
      }
    } catch (e) {
      console.error("Failed to load categories:", e);
    } finally {
      setCategoriesLoading(false);
    }
  }, []);

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

  // Preflight check evaluation
  const [preflightErrors, setPreflightErrors] = React.useState<string[]>([]);
  const [preflightWarnings, setPreflightWarnings] = React.useState<string[]>([]);

  // Load authors directory from admin accounts
  React.useEffect(() => {
    async function loadAuthors() {
      try {
        const res = await fetch("/api/admin/authors");
        if (res.ok) {
          const data = await res.json();
          setAuthors(data.authors || []);
        }
      } catch (e) {
        console.error("Failed to load authors:", e);
      }
    }
    loadAuthors();
  }, []);

  // Load post from MongoDB
  const fetchPost = React.useCallback(async () => {
    try {
      setLoading(true);
      const res = await fetch(`/api/admin/posts/${id}`);
      if (!res.ok) {
        if (res.status === 404) throw new Error("Post not found.");
        throw new Error("Failed to load article from database.");
      }
      const data = await res.json();
      const loadedPost: PostData = data.post;

      // Gracefully populate initial contentHtml from sections if first edit in Tiptap
      if (!loadedPost.contentHtml && loadedPost.sections && loadedPost.sections.length > 0) {
        loadedPost.contentHtml = sectionsToHtml(loadedPost.sections);
      }

      // Calculate initial reading stats
      const initialStats = calculateReadingStats(loadedPost.contentHtml || "");
      setReadingStats(initialStats);
      loadedPost.readTime = initialStats.readTime;
      loadedPost.wordCount = initialStats.words;

      setPost(loadedPost);
      postRef.current = loadedPost;
      setLastSavedTime(new Date(loadedPost.updatedAt).toLocaleTimeString());
      setSaveStatus("SAVED");
      isDirtyRef.current = false;
    } catch (err: any) {
      setError(err.message || "Failed to load article.");
    } finally {
      setLoading(false);
    }
  }, [id]);

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

  // Evaluate Preflight Checks whenever post changes
  React.useEffect(() => {
    if (!post) return;
    const errors: string[] = [];
    const warnings: string[] = [];

    if (!post.title || post.title.trim().length === 0) {
      errors.push("Title is required.");
    }
    if (!post.slug || post.slug.trim().length === 0) {
      errors.push("URL Slug is required.");
    }
    const hasHtml = post.contentHtml && post.contentHtml.replace(/<[^>]*>/g, "").trim().length > 0;
    const hasSections = post.sections && post.sections.length > 0;
    if (!hasHtml && !hasSections) {
      errors.push("Article body content cannot be empty.");
    }

    if (!post.excerpt || post.excerpt.trim().length < 20) {
      warnings.push("Excerpt is brief or missing; article cards will lack summaries.");
    }
    if (!post.seoTitle || post.seoTitle.trim().length === 0) {
      errors.push("SEO title is required before publishing.");
    }
    if (!post.metaDescription || post.metaDescription.trim().length === 0) {
      errors.push("Meta description is required before publishing.");
    }
    if (!post.featuredImage) {
      warnings.push("No featured image selected; default branding cover will be used.");
    }

    setPreflightErrors(errors);
    setPreflightWarnings(warnings);
  }, [post]);

  // Core Save to MongoDB function
  const savePostToServer = React.useCallback(
    async (postToSave: PostData) => {
      try {
        setSaveStatus("SAVING");
        const res = await fetch(`/api/admin/posts/${id}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(postToSave),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || "Save failed.");

        setPost((prev) => (prev ? { ...prev, ...data.post } : data.post));
        postRef.current = data.post;
        setLastSavedTime(new Date().toLocaleTimeString());
        setSaveStatus("SAVED");
        isDirtyRef.current = false;
        invalidateAdminCache("posts");
      } catch (err: any) {
        console.error("Save error:", err);
        setSaveStatus("ERROR");
        toast.error(err.message || "Failed to save draft to database.");
      }
    },
    [id]
  );

  // Debounced Autosave (2.5s delay after typing)
  React.useEffect(() => {
    if (!isDirtyRef.current || !post) return;
    setSaveStatus("UNSAVED");

    const timer = setTimeout(() => {
      if (isDirtyRef.current && postRef.current) {
        savePostToServer(postRef.current);
      }
    }, 2500);

    return () => clearTimeout(timer);
  }, [post, savePostToServer]);

  // Warn before leaving if unsaved changes exist
  React.useEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (isDirtyRef.current) {
        e.preventDefault();
        e.returnValue = "";
      }
    };
    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => window.removeEventListener("beforeunload", handleBeforeUnload);
  }, []);

  // Manual Instant Save
  const handleManualSave = () => {
    if (!post) return;
    savePostToServer(post);
    toast.success(
      post.status === "PUBLISHED"
        ? "Draft changes saved to MongoDB! (Live version remains unchanged)"
        : "Article saved to MongoDB!"
    );
  };

  const updateField = (field: keyof PostData, value: any) => {
    setPost((prev) => {
      if (!prev) return prev;
      const updated = { ...prev, [field]: value };
      postRef.current = updated;
      isDirtyRef.current = true;
      return updated;
    });
  };

  const handleTitleChange = (val: string) => {
    setPost((prev) => {
      if (!prev) return prev;
      const updated: PostData = { ...prev, title: val };
      if (prev.status === "DRAFT" && (!prev.slug || prev.slug.startsWith("draft-") || prev.slug === "")) {
        updated.slug = val.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
      }
      postRef.current = updated;
      isDirtyRef.current = true;
      return updated;
    });
  };

  const handleAuthorChange = (selectedAuthorId: string) => {
    const chosen = authors.find((a) => a.id === selectedAuthorId);
    if (!chosen) return;

    setPost((prev) => {
      if (!prev) return prev;
      const updated: PostData = {
        ...prev,
        authorId: chosen.id,
        author: {
          name: chosen.name,
          role: chosen.role,
          avatarText: chosen.avatarText,
          avatarColor: chosen.avatarColor,
          bio: chosen.bio,
          profileSlug: chosen.profileSlug,
        },
      };
      postRef.current = updated;
      isDirtyRef.current = true;
      return updated;
    });
  };

  // Revisions Handlers
  const loadRevisions = async () => {
    setRevisionsOpen(true);
    try {
      const res = await fetch(`/api/admin/posts/${id}/revisions`);
      if (res.ok) {
        const data = await res.json();
        setRevisions(data.revisions || []);
      }
    } catch (e) {
      console.error("Failed to load revisions:", e);
    }
  };

  const restoreRevision = async (revId: string) => {
    try {
      toast.loading("Restoring historical revision...", { id: "rest" });
      const res = await fetch(`/api/admin/posts/${id}/revisions`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ revisionId: revId }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Restore failed.");

      toast.success("Revision restored as a new version!", { id: "rest" });
      setPost(data.post);
      postRef.current = data.post;
      setRevisionsOpen(false);
    } catch (err: any) {
      toast.error(err.message || "Failed to restore revision.", { id: "rest" });
    }
  };

  // Stable Editor Callbacks
  const handleEditorChange = React.useCallback((html: string, json: any) => {
    setPost((prev) => {
      if (!prev) return prev;
      const updated: PostData = { ...prev, contentHtml: html, contentJson: json };
      postRef.current = updated;
      isDirtyRef.current = true;
      return updated;
    });
  }, []);

  const handleStatsChange = React.useCallback((newStats: ReadingStats) => {
    setReadingStats(newStats);
    setPost((prev) => {
      if (!prev) return prev;
      if (prev.readTime === newStats.readTime && prev.wordCount === newStats.words) {
        return prev;
      }
      const updated: PostData = { ...prev, readTime: newStats.readTime, wordCount: newStats.words };
      postRef.current = updated;
      return updated;
    });
  }, []);

  // Category Creation Handler (Dialog inside Post Studio)
  const handleCreateCategory = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newCatName.trim()) {
      toast.error("Category name is required.");
      return;
    }
    try {
      setSavingCategory(true);
      const res = await fetch("/api/admin/categories", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: newCatName.trim(),
          slug: newCatSlug.trim() || undefined,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to create category.");

      toast.success(`Category "${data.category.name}" created!`);
      await loadCategories();
      updateField("category", data.category.name);
      updateField("categoryId", data.category.id);
      setAddCategoryOpen(false);
      setNewCatName("");
      setNewCatSlug("");
    } catch (err: any) {
      toast.error(err.message || "Failed to create category.");
    } finally {
      setSavingCategory(false);
    }
  };

  // Media Picker Handlers (Reused for Featured, OG, and Twitter images)
  const openMediaPickerFor = (target: "featured" | "og" | "twitter") => {
    setMediaPickerTarget(target);
    setMediaPickerOpen(true);
    setMediaPickerTab("LIBRARY");
    fetch("/api/admin/media?limit=60")
      .then((r) => r.json())
      .then((d) => setMediaItems(d.items || []))
      .catch((e) => console.error("Failed to load media items:", e));
  };

  const handleSelectMedia = (item: MediaItem) => {
    if (mediaPickerTarget === "featured") {
      updateField("featuredImage", item.url);
      updateField("featuredImageId", item.id);
      updateField("featuredImageAlt", item.alt || post?.title || "");
    } else if (mediaPickerTarget === "og") {
      updateField("ogImage", item.url);
      updateField("ogImageId", item.id);
    } else if (mediaPickerTarget === "twitter") {
      updateField("twitterImage", item.url);
      updateField("twitterImageId", item.id);
    }
    setMediaPickerOpen(false);
  };

  const handleMediaUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    try {
      setMediaUploading(true);
      const formData = new FormData();
      formData.append("file", file);
      formData.append("alt", post?.title || "");
      const category =
        mediaPickerTarget === "featured"
          ? "featured"
          : mediaPickerTarget === "og" || mediaPickerTarget === "twitter"
          ? "social"
          : "general";
      formData.append("category", category);

      const res = await fetch("/api/admin/media", {
        method: "POST",
        body: formData,
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Upload failed.");

      toast.success("Image uploaded to Media Library!");
      handleSelectMedia(data.media);
    } catch (err: any) {
      toast.error(err.message || "Upload failed.");
    } finally {
      setMediaUploading(false);
      e.target.value = "";
    }
  };

  // Preview Action with Atomic Draft Flush
  const handlePreviewClick = async () => {
    if (!post) return;
    try {
      setPreviewSyncing(true);
      if (isDirtyRef.current && postRef.current) {
        toast.loading("Saving working draft before preview...", { id: "prev-sync" });
        await savePostToServer(postRef.current);
        toast.dismiss("prev-sync");
      }
      window.open(`/admin/preview/${post.id}`, "_blank", "noopener,noreferrer");
    } catch (err: any) {
      toast.error("Failed to save working draft for preview.", { id: "prev-sync" });
    } finally {
      setPreviewSyncing(false);
    }
  };

  // Publishing Actions
  const handlePublishOrUpdateLive = async () => {
    if (preflightErrors.length > 0) {
      toast.error(`Cannot publish: ${preflightErrors[0]}`);
      return;
    }
    const isLive = post?.status === "PUBLISHED";
    try {
      toast.loading(isLive ? "Updating live website..." : "Publishing to public website...", { id: "pub" });

      // Atomic flush: if local draft is dirty, save to server before publishing
      if (isDirtyRef.current && postRef.current) {
        await savePostToServer(postRef.current);
      }

      const res = await fetch(`/api/admin/posts/${id}/publish`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: isLive ? "update-live" : "publish",
          draftUpdates: postRef.current || undefined,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to publish.");

      toast.success(
        isLive
          ? "Live article updated successfully on public site!"
          : "Article is now live on Quto AI!",
        { id: "pub" }
      );
      setPost(data.post);
      postRef.current = data.post;
      setPublishModalOpen(false);
      isDirtyRef.current = false;
      setSaveStatus("SAVED");
      setLastSavedTime(new Date().toLocaleTimeString());
      invalidateAdminCache("posts");
    } catch (err: any) {
      toast.error(err.message || "Failed to publish.", { id: "pub" });
    }
  };

  const handleDiscardDraft = async () => {
    try {
      toast.loading("Discarding working draft...", { id: "disc" });
      const res = await fetch(`/api/admin/posts/${id}/publish`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "discard-draft" }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to discard draft.");

      toast.success("Working draft discarded. Reverted to live version!", { id: "disc" });
      setPost(data.post);
      postRef.current = data.post;
      setDiscardModalOpen(false);
      isDirtyRef.current = false;
      invalidateAdminCache("posts");
    } catch (err: any) {
      toast.error(err.message || "Discard failed.", { id: "disc" });
    }
  };

  const handleSchedule = async () => {
    if (!scheduleDate) {
      toast.error("Please pick a publication date.");
      return;
    }
    const dateStr = scheduleDate.toISOString().split("T")[0];
    const combinedIso = new Date(`${dateStr}T${scheduleTime}:00Z`).toISOString();
    if (new Date(combinedIso).getTime() <= Date.now()) {
      toast.error("Scheduled date & time must be in the future.");
      return;
    }

    try {
      toast.loading("Scheduling publication...", { id: "sched" });
      const res = await fetch(`/api/admin/posts/${id}/publish`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "schedule", scheduledFor: combinedIso }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to schedule.");

      toast.success(`Scheduled for ${new Date(combinedIso).toLocaleString()}!`, { id: "sched" });
      setPost(data.post);
      postRef.current = data.post;
      setScheduleModalOpen(false);
    } catch (err: any) {
      toast.error(err.message || "Scheduling failed.", { id: "sched" });
    }
  };

  // Push Notification Handlers
  const openPushModal = () => {
    if (!post) return;
    setPushModalOpen(true);
  };

  // SHAPE-MATCHED SKELETON (Prevents Layout Shift)
  if (loading) {
    return (
      <div className="space-y-6 pb-20 animate-in fade-in-0 duration-150">
        {/* Header Bar Skeleton */}
        <div className="sticky top-0 z-30 -mx-6 -mt-6 border-b border-neutral-200 bg-white/95 px-6 py-3.5 backdrop-blur-sm dark:border-neutral-800 dark:bg-neutral-900/95 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Skeleton className="h-8 w-8 rounded-lg" />
            <div className="space-y-1.5">
              <Skeleton className="h-4 w-48 rounded" />
              <Skeleton className="h-3 w-32 rounded" />
            </div>
          </div>
          <div className="flex items-center gap-2">
            <Skeleton className="h-8 w-20 rounded-md" />
            <Skeleton className="h-8 w-20 rounded-md" />
            <Skeleton className="h-8 w-20 rounded-md" />
          </div>
        </div>

        {/* 2-Column Studio Grid Skeleton */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
          {/* Main Writing Canvas Skeleton */}
          <div className="lg:col-span-8 space-y-6">
            <div className="rounded-2xl border border-neutral-200 bg-white p-6 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 space-y-4">
              <Skeleton className="h-14 w-full rounded-xl" />
              <Skeleton className="h-5 w-64 rounded" />
              <Skeleton className="h-24 w-full rounded-xl" />
            </div>
            <div className="rounded-2xl border border-neutral-200 bg-white shadow-xs dark:border-neutral-800 dark:bg-neutral-900 overflow-hidden">
              <Skeleton className="h-12 w-full border-b border-neutral-200 dark:border-neutral-800" />
              <div className="p-6 space-y-3">
                <Skeleton className="h-6 w-3/4 rounded" />
                <Skeleton className="h-4 w-full rounded" />
                <Skeleton className="h-4 w-5/6 rounded" />
                <Skeleton className="h-4 w-2/3 rounded" />
                <Skeleton className="h-32 w-full rounded-xl mt-4" />
              </div>
            </div>
          </div>

          {/* Right Panel Skeleton */}
          <div className="lg:col-span-4 space-y-6">
            <div className="rounded-2xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 space-y-3">
              <Skeleton className="h-4 w-32 rounded" />
              <Skeleton className="h-36 w-full rounded-xl" />
              <Skeleton className="h-14 w-full rounded-xl" />
            </div>
            <div className="rounded-2xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 space-y-3">
              <Skeleton className="h-4 w-28 rounded" />
              <Skeleton className="h-14 w-full rounded-xl" />
              <Skeleton className="h-14 w-full rounded-xl" />
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (error || !post) {
    return (
      <div className="mx-auto max-w-lg py-16 text-center">
        <AlertTriangle className="mx-auto h-10 w-10 text-amber-500" />
        <h2 className="mt-3 text-base font-bold text-neutral-900 dark:text-white">
          {error || "Article Not Found"}
        </h2>
        <p className="mt-1 text-xs text-neutral-500">
          The requested article does not exist or you lack editorial permissions to access it.
        </p>
        <Link href="/admin/posts" className="mt-4 inline-block">
          <Button variant="outline" className="text-xs">
            Back to Articles
          </Button>
        </Link>
      </div>
    );
  }

  const isPublishedPost = post.status === "PUBLISHED";
  const hasWorkingChanges = isPublishedPost && post.hasWorkingDraft;
  const isSlugChanged = isPublishedPost && post.liveSlug && post.slug !== post.liveSlug;

  // Author dropdown options
  const authorOptions = authors.map((a) => ({
    value: a.id,
    label: (
      <div className="flex items-center gap-2">
        <span
          className={`h-5 w-5 rounded-full bg-gradient-to-tr ${a.avatarColor} text-white flex items-center justify-center text-[9px] font-bold`}
        >
          {a.avatarText}
        </span>
        <span className="font-medium text-xs">{a.name}</span>
        <span className="text-[10px] text-neutral-400 font-normal">({a.role})</span>
      </div>
    ),
  }));

  return (
    <div className="space-y-6 pb-20">
      {/* Studio Header Bar — Non-clipping sticky layout with deliberate bottom separation */}
      <div className="sticky top-0 z-30 -mx-6 -mt-6 md:-mx-8 md:-mt-8 mb-8 border-b border-neutral-200 bg-white/95 px-6 md:px-8 py-3.5 backdrop-blur-md dark:border-neutral-800 dark:bg-neutral-900/95 shadow-xs">
        <div className="flex flex-wrap items-center justify-between gap-3">
          {/* Back & Title Status */}
          <div className="flex items-center gap-3">
            <Link
              href="/admin/posts"
              className="rounded-lg p-1.5 text-neutral-500 hover:bg-neutral-100 dark:hover:bg-neutral-800 transition"
              title="Return to Articles list"
            >
              <ArrowLeft className="h-4 w-4" />
            </Link>
            <div>
              <div className="flex items-center gap-2">
                <span className="text-xs font-semibold text-neutral-900 dark:text-white truncate max-w-[200px] sm:max-w-xs">
                  {post.title || "Untitled Article"}
                </span>
                <Badge
                  variant="outline"
                  className={`text-[10px] uppercase font-mono ${
                    post.status === "PUBLISHED"
                      ? "bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/50 dark:text-emerald-300"
                      : post.status === "SCHEDULED"
                      ? "bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-950/50 dark:text-blue-300"
                      : post.status === "ARCHIVED"
                      ? "bg-neutral-100 text-neutral-600 border-neutral-300"
                      : "bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950/50 dark:text-amber-300"
                  }`}
                >
                  {post.status}
                </Badge>
                {hasWorkingChanges && (
                  <Badge
                    variant="outline"
                    className="text-[10px] font-mono bg-amber-50 text-amber-800 border-amber-300 dark:bg-amber-950/50 dark:text-amber-300"
                  >
                    Draft Saved (Uncommitted)
                  </Badge>
                )}
              </div>
              <div className="flex items-center gap-2 text-[11px] text-neutral-400">
                <span>Version {post.version}</span>
                <span>•</span>
                <span className="font-mono text-neutral-600 dark:text-neutral-300">
                  {readingStats.words.toLocaleString()} words • {readingStats.readTime}
                </span>
                <span>•</span>
                {saveStatus === "SAVED" && (
                  <span className="text-emerald-600 dark:text-emerald-400 flex items-center gap-1">
                    <CheckCircle2 className="h-3 w-3" />
                    <span>Saved to draft {lastSavedTime}</span>
                  </span>
                )}
                {saveStatus === "SAVING" && (
                  <span className="text-blue-600 dark:text-blue-400 animate-pulse">
                    Saving draft to MongoDB...
                  </span>
                )}
                {saveStatus === "UNSAVED" && (
                  <span className="text-amber-600 dark:text-amber-400">
                    Unsaved changes...
                  </span>
                )}
                {saveStatus === "ERROR" && (
                  <span className="text-red-600 dark:text-red-400 flex items-center gap-1">
                    <XCircle className="h-3 w-3" />
                    <span>Save failed</span>
                  </span>
                )}
              </div>
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex items-center gap-2">
            {hasWorkingChanges && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => setDiscardModalOpen(true)}
                className="gap-1 text-xs text-red-600 hover:bg-red-50 dark:hover:bg-red-950/30 border-red-200"
                title="Discard uncommitted working changes and revert to live version"
              >
                <RotateCcw className="h-3.5 w-3.5" />
                <span className="hidden sm:inline">Discard Draft</span>
              </Button>
            )}

            <Button
              variant="outline"
              size="sm"
              onClick={loadRevisions}
              className="gap-1 text-xs"
              title="View revision history"
            >
              <History className="h-3.5 w-3.5" />
              <span className="hidden sm:inline">Revisions</span>
            </Button>

            {/* PREVIEW: Atomically syncs dirty draft before opening /admin/preview/[id] */}
            <Button
              variant="outline"
              size="sm"
              onClick={handlePreviewClick}
              disabled={previewSyncing}
              className="gap-1 text-xs"
              title="Preview working draft in new tab"
            >
              <Eye className="h-3.5 w-3.5" />
              <span className="hidden sm:inline">{previewSyncing ? "Saving..." : "Preview"}</span>
            </Button>

            <Button
              variant="outline"
              size="sm"
              onClick={handleManualSave}
              disabled={saveStatus === "SAVING"}
              className="gap-1 text-xs"
            >
              <Save className="h-3.5 w-3.5" />
              <span>{isPublishedPost ? "Save Draft" : "Save"}</span>
            </Button>

            {post.status !== "PUBLISHED" && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => setScheduleModalOpen(true)}
                className="gap-1 text-xs text-blue-600 border-blue-200 hover:bg-blue-50 dark:hover:bg-blue-950/30"
              >
                <Clock className="h-3.5 w-3.5" />
                <span className="hidden sm:inline">Schedule</span>
              </Button>
            )}

            {post.status === "PUBLISHED" && (
              <Button
                variant="outline"
                size="sm"
                onClick={openPushModal}
                className="gap-1 text-xs text-purple-600 border-purple-200 hover:bg-purple-50 dark:hover:bg-purple-950/30"
                title="Send web push notification to subscribers"
              >
                <Bell className="h-3.5 w-3.5" />
                <span className="hidden sm:inline">Send Push</span>
              </Button>
            )}

            <Button
              size="sm"
              onClick={() => setPublishModalOpen(true)}
              className="gap-1 text-xs bg-emerald-600 hover:bg-emerald-700 text-white font-semibold"
            >
              <Send className="h-3.5 w-3.5" />
              <span>{isPublishedPost ? "Update Live" : "Publish"}</span>
            </Button>
          </div>
        </div>
      </div>

      {/* WORKING VERSION ISOLATION BANNER — Distinct vertical spacing from header and writing canvas */}
      {isPublishedPost && (
        <div className="mb-8">
          <div className={`rounded-2xl border p-4.5 text-xs shadow-xs transition ${
            hasWorkingChanges
              ? "border-amber-200 bg-amber-50/90 text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/60 dark:text-amber-200"
              : "border-emerald-200 bg-emerald-50/90 text-emerald-900 dark:border-emerald-900/50 dark:bg-emerald-950/60 dark:text-emerald-200"
          }`}>
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div className="flex items-center gap-2.5">
                <Globe className="h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
                <div>
                  <strong>Public Live Version:</strong> Currently live at{" "}
                  <Link
                    href={`/blog/${post.liveSlug || post.slug}`}
                    target="_blank"
                    className="font-mono underline underline-offset-2 hover:opacity-80"
                  >
                    /blog/{post.liveSlug || post.slug}
                  </Link>
                  .{" "}
                  {hasWorkingChanges ? (
                    <span className="font-semibold text-amber-700 dark:text-amber-300">
                      You have uncommitted changes in your working draft. Public visitors will NOT see these changes until you click &quot;Update Live&quot;.
                    </span>
                  ) : (
                    <span>All editorial content is currently in sync with the live website.</span>
                  )}
                </div>
              </div>
              {hasWorkingChanges && (
                <Button
                  size="sm"
                  onClick={() => setPublishModalOpen(true)}
                  className="h-7 text-xs bg-emerald-600 hover:bg-emerald-700 text-white shadow-xs"
                >
                  Update Live Now
                </Button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 2-Column WordPress-Style Editorial Layout */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
        {/* LEFT COLUMN: Main Writing Canvas (8 cols) */}
        <div className="lg:col-span-8 space-y-6">
          {/* Article Title & Headline */}
          <div className="rounded-2xl border border-neutral-200 bg-white p-6 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 space-y-4">
            <FloatingInput
              id="post-article-title"
              label="Article Title *"
              required
              value={post.title}
              onChange={(e) => handleTitleChange(e.target.value)}
              className="text-base font-bold"
            />

            {/* URL Slug Preview & Safety Alert */}
            <div className="space-y-1.5 pt-1">
              <div className="flex items-center gap-2 text-xs text-neutral-500">
                <span className="select-none text-neutral-400 font-mono">
                  https://qutoai.com/blog/
                </span>
                <input
                  value={post.slug}
                  onChange={(e) =>
                    updateField(
                      "slug",
                      e.target.value.toLowerCase().replace(/[^a-z0-9-]+/g, "-")
                    )
                  }
                  placeholder="custom-url-slug"
                  className="font-mono text-xs font-semibold text-neutral-800 dark:text-neutral-200 bg-transparent border-b border-dashed border-neutral-300 focus:border-neutral-900 focus:outline-none dark:border-neutral-700 dark:focus:border-white"
                />
              </div>

              {isSlugChanged && (
                <div className="rounded-lg bg-amber-50 p-2 text-[11px] text-amber-800 dark:bg-amber-950/40 dark:text-amber-300 border border-amber-200 dark:border-amber-900/50 flex items-center gap-1.5">
                  <AlertTriangle className="h-3.5 w-3.5 shrink-0" />
                  <span>
                    Working slug differs from live slug (<code>{post.liveSlug}</code>). Updating live will automatically register a 301 Permanent Redirect to preserve SEO.
                  </span>
                </div>
              )}
            </div>

            {/* Editorial Excerpt */}
            <FloatingTextarea
              id="post-article-excerpt"
              label="Article Excerpt (Editorial Summary for cards & SERP)"
              rows={2}
              value={post.excerpt}
              onChange={(e) => updateField("excerpt", e.target.value)}
            />
          </div>

          {/* Professional Tiptap Rich Text Editor */}
          <div className="space-y-2">
            <div className="flex items-center justify-between px-1">
              <label className="text-xs font-bold text-neutral-700 uppercase tracking-wider dark:text-neutral-300">
                Article Body Content
              </label>
              <span className="text-[11px] text-neutral-400">
                Prose formatting • Media asset insertion • Autolinking • Right-click menu
              </span>
            </div>

            <TiptapEditor
              content={post.contentHtml}
              contentJson={post.contentJson}
              onChange={handleEditorChange}
              onStatsChange={handleStatsChange}
              placeholder="Write an authoritative guide, insert headings, quotes, code, and images..."
            />
          </div>

          {/* Collapsible SEO & Schema Section */}
          <div className="rounded-2xl border border-neutral-200 bg-white p-6 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 space-y-4">
            <div className="flex items-center justify-between border-b border-neutral-100 pb-3 dark:border-neutral-800">
              <div className="flex items-center gap-2">
                <Sparkles className="h-4 w-4 text-blue-500" />
                <h3 className="font-bold text-sm text-neutral-900 dark:text-white">
                  Search Engine Optimization (SEO) & Social Cards
                </h3>
              </div>
              <span className="text-[11px] text-neutral-400">
                OpenGraph & SERP Snippets
              </span>
            </div>

            <div className="space-y-6">
              {/* SECTION 1: Google SERP & Canonical */}
              <div className="space-y-4">
                <div className="text-xs font-bold text-neutral-700 dark:text-neutral-300 uppercase tracking-wider">
                  Google Search Metadata (SERP)
                </div>

                <FloatingInput
                  id="post-seo-title"
                  label="SEO Title Tag * (Required for publish)"
                  value={post.seoTitle || ""}
                  onChange={(e) => updateField("seoTitle", e.target.value)}
                  helper={`${post.seoTitle?.length || 0} / 60 recommended characters`}
                  required
                />

                <FloatingTextarea
                  id="post-meta-desc"
                  label="Meta Description * (Required for publish)"
                  rows={2}
                  value={post.metaDescription || ""}
                  onChange={(e) => updateField("metaDescription", e.target.value)}
                  helper={`${post.metaDescription?.length || 0} / 160 recommended characters`}
                  required
                />

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <FloatingInput
                    id="post-canonical"
                    label="Canonical URL Override"
                    value={post.canonicalUrl || ""}
                    onChange={(e) => updateField("canonicalUrl", e.target.value)}
                    placeholder={`https://qutoai.com/blog/${post.slug}`}
                  />

                  <FloatingSelect
                    id="post-robots"
                    label="Robots Indexing Directive"
                    value={post.robots || "index, follow"}
                    onValueChange={(val) => updateField("robots", val)}
                    options={[
                      { value: "index, follow", label: "index, follow (Standard Public Search)" },
                      { value: "noindex, follow", label: "noindex, follow (Hide from search engines)" },
                      { value: "noindex, nofollow", label: "noindex, nofollow (Private / No links followed)" },
                    ]}
                  />
                </div>

                {/* SERP Search Preview Box */}
                <div className="rounded-xl border border-neutral-200 bg-neutral-50/60 p-4 dark:border-neutral-800 dark:bg-neutral-950/60">
                  <span className="text-[10px] font-bold text-neutral-400 uppercase tracking-wider">
                    Google Search Snippet Preview
                  </span>
                  <div className="mt-2 space-y-1 text-left">
                    <div className="text-[11px] text-neutral-500 font-mono flex items-center gap-1">
                      <span>https://qutoai.com</span>
                      <span>›</span>
                      <span>blog</span>
                      <span>›</span>
                      <span className="font-semibold text-neutral-700 dark:text-neutral-300">
                        {post.slug}
                      </span>
                    </div>
                    <div className="text-sm font-semibold text-blue-600 dark:text-blue-400 line-clamp-1">
                      {post.seoTitle || post.title || "Untitled Article"}
                    </div>
                    <p className="text-xs text-neutral-600 dark:text-neutral-400 line-clamp-2 leading-relaxed">
                      {post.metaDescription || post.excerpt || "Article summary will appear in search results."}
                    </p>
                  </div>
                </div>
              </div>

              {/* SECTION 2: OpenGraph (Facebook, LinkedIn, Slack) */}
              <div className="space-y-4 pt-4 border-t border-neutral-100 dark:border-neutral-800">
                <div className="flex items-center justify-between">
                  <div className="text-xs font-bold text-neutral-700 dark:text-neutral-300 uppercase tracking-wider flex items-center gap-1.5">
                    <Share2 className="h-3.5 w-3.5 text-blue-600" />
                    <span>OpenGraph (OG) Metadata</span>
                  </div>
                  <span className="text-[11px] text-neutral-400">Social cards on Facebook, LinkedIn & Slack</span>
                </div>

                <FloatingInput
                  id="post-og-title"
                  label="OG Title (Optional override)"
                  value={post.ogTitle || ""}
                  onChange={(e) => updateField("ogTitle", e.target.value)}
                  placeholder={post.seoTitle || post.title || "Title fallback"}
                  helper={`Active preview fallback: "${post.ogTitle || post.seoTitle || post.title || 'Untitled'}"`}
                />

                <FloatingTextarea
                  id="post-og-desc"
                  label="OG Description (Optional override)"
                  rows={2}
                  value={post.ogDescription || ""}
                  onChange={(e) => updateField("ogDescription", e.target.value)}
                  placeholder={post.metaDescription || post.excerpt || "Description fallback"}
                  helper={`Active preview fallback: "${post.ogDescription || post.metaDescription || post.excerpt || 'Article summary'}"`}
                />

                {/* OG Image Picker */}
                <div className="space-y-2">
                  <label className="text-xs font-semibold text-neutral-700 dark:text-neutral-300">
                    OpenGraph Image (1200x630px recommended)
                  </label>
                  {post.ogImage ? (
                    <div className="space-y-2">
                      <div className="relative aspect-video max-w-sm overflow-hidden rounded-xl border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-800">
                        <img src={post.ogImage} alt="OG Social Card" className="h-full w-full object-cover" />
                      </div>
                      <div className="flex items-center gap-2">
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          onClick={() => openMediaPickerFor("og")}
                          className="text-xs"
                        >
                          Change OG Image
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            updateField("ogImage", null);
                            updateField("ogImageId", null);
                          }}
                          className="text-xs text-red-500 hover:text-red-600"
                        >
                          Remove (Fallback to Featured)
                        </Button>
                      </div>
                    </div>
                  ) : (
                    <div className="flex items-center justify-between p-3 rounded-xl border border-neutral-200 bg-neutral-50/50 dark:border-neutral-800 dark:bg-neutral-900/50">
                      <div className="text-xs text-neutral-500">
                        No custom OG image selected.{" "}
                        <span className="font-semibold text-neutral-700 dark:text-neutral-300">
                          {post.featuredImage ? "Falling back to Featured Image." : "Falling back to default branding OG."}
                        </span>
                      </div>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => openMediaPickerFor("og")}
                        className="text-xs"
                      >
                        Select OG Image
                      </Button>
                    </div>
                  )}
                </div>
              </div>

              {/* SECTION 3: X / Twitter Card */}
              <div className="space-y-4 pt-4 border-t border-neutral-100 dark:border-neutral-800">
                <div className="flex items-center justify-between">
                  <div className="text-xs font-bold text-neutral-700 dark:text-neutral-300 uppercase tracking-wider flex items-center gap-1.5">
                    <span>X / Twitter Cards</span>
                  </div>
                  <span className="text-[11px] text-neutral-400">Preview on X feeds</span>
                </div>

                <FloatingInput
                  id="post-twitter-title"
                  label="X / Twitter Title (Optional override)"
                  value={post.twitterTitle || ""}
                  onChange={(e) => updateField("twitterTitle", e.target.value)}
                  placeholder={post.ogTitle || post.seoTitle || post.title || "Title fallback"}
                />

                <FloatingTextarea
                  id="post-twitter-desc"
                  label="X / Twitter Description (Optional override)"
                  rows={2}
                  value={post.twitterDescription || ""}
                  onChange={(e) => updateField("twitterDescription", e.target.value)}
                  placeholder={post.ogDescription || post.metaDescription || post.excerpt || "Description fallback"}
                />

                {/* Twitter Image Picker */}
                <div className="space-y-2">
                  <label className="text-xs font-semibold text-neutral-700 dark:text-neutral-300">
                    X / Twitter Card Image
                  </label>
                  {post.twitterImage ? (
                    <div className="space-y-2">
                      <div className="relative aspect-video max-w-sm overflow-hidden rounded-xl border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-800">
                        <img src={post.twitterImage} alt="Twitter Card" className="h-full w-full object-cover" />
                      </div>
                      <div className="flex items-center gap-2">
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          onClick={() => openMediaPickerFor("twitter")}
                          className="text-xs"
                        >
                          Change X Image
                        </Button>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            updateField("twitterImage", null);
                            updateField("twitterImageId", null);
                          }}
                          className="text-xs text-red-500 hover:text-red-600"
                        >
                          Remove (Fallback)
                        </Button>
                      </div>
                    </div>
                  ) : (
                    <div className="flex items-center justify-between p-3 rounded-xl border border-neutral-200 bg-neutral-50/50 dark:border-neutral-800 dark:bg-neutral-900/50">
                      <div className="text-xs text-neutral-500">
                        No custom X image selected.{" "}
                        <span className="font-semibold text-neutral-700 dark:text-neutral-300">
                          {post.ogImage ? "Falling back to OpenGraph Image." : post.featuredImage ? "Falling back to Featured Image." : "Falling back to default site image."}
                        </span>
                      </div>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => openMediaPickerFor("twitter")}
                        className="text-xs"
                      >
                        Select X Image
                      </Button>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* RIGHT COLUMN: Supporting Editorial Side Panel (4 cols) */}
        <div className="lg:col-span-4 space-y-6">
          {/* Card 1: Featured Image (Single Source of Truth) */}
          <div className="rounded-2xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 space-y-3">
            <div className="flex items-center justify-between border-b border-neutral-100 pb-2.5 dark:border-neutral-800">
              <h3 className="text-xs font-bold text-neutral-900 dark:text-white uppercase tracking-wider flex items-center gap-1.5">
                <ImageIcon className="h-3.5 w-3.5 text-emerald-600" />
                <span>Featured Image</span>
              </h3>
              <span className="text-[10px] text-neutral-400">Cards & Hero</span>
            </div>

            {post.featuredImage ? (
              <div className="space-y-3">
                <div className="relative aspect-video w-full overflow-hidden rounded-xl border border-neutral-200 bg-neutral-100 dark:border-neutral-800 dark:bg-neutral-800">
                  <img
                    src={post.featuredImage}
                    alt={post.featuredImageAlt || post.title}
                    className="h-full w-full object-cover"
                  />
                </div>

                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => openMediaPickerFor("featured")}
                    className="w-1/2 text-xs"
                  >
                    Change Image
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => {
                      updateField("featuredImage", null);
                      updateField("featuredImageId", null);
                      updateField("featuredImageAlt", null);
                    }}
                    className="w-1/2 text-xs text-red-500 hover:text-red-600"
                  >
                    Remove
                  </Button>
                </div>
              </div>
            ) : (
              <div
                onClick={() => openMediaPickerFor("featured")}
                className="flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-neutral-200 p-6 text-center cursor-pointer hover:border-neutral-400 dark:border-neutral-800 transition bg-neutral-50/50 dark:bg-neutral-950/50"
              >
                <ImageIcon className="h-8 w-8 text-neutral-400 mb-1" />
                <span className="text-xs font-semibold text-neutral-700 dark:text-neutral-300">
                  Select Featured Image
                </span>
                <span className="text-[10px] text-neutral-400 mt-0.5">
                  Feeds blog card, inner hero, and OpenGraph
                </span>
              </div>
            )}

            <FloatingInput
              id="post-featured-alt"
              label="Image Alt Text (Accessibility & SEO)"
              value={post.featuredImageAlt || ""}
              onChange={(e) => updateField("featuredImageAlt", e.target.value)}
              placeholder="Description of graphic..."
            />
          </div>

          {/* Card 2: Publishing Status & Timing */}
          <div className="rounded-2xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 space-y-3">
            <h3 className="text-xs font-bold text-neutral-900 dark:text-white uppercase tracking-wider border-b border-neutral-100 pb-2.5 dark:border-neutral-800">
              Publishing Controls
            </h3>

            <FloatingSelect
              id="post-status"
              label="Article Lifecycle Status"
              value={post.status}
              onValueChange={(val: any) => updateField("status", val)}
              options={[
                { value: "DRAFT", label: "Draft (Internal Work)" },
                { value: "SCHEDULED", label: "Scheduled (Pending Date)" },
                { value: "PUBLISHED", label: "Published (Live to World)" },
                { value: "ARCHIVED", label: "Archived (Unlisted)" },
              ]}
            />

            {post.status === "SCHEDULED" && post.scheduledFor && (
              <div className="rounded-xl border border-blue-200 bg-blue-50 p-3 text-xs text-blue-800 dark:border-blue-900/50 dark:bg-blue-950/50 dark:text-blue-300 flex items-center gap-2">
                <Clock className="h-4 w-4 shrink-0" />
                <span>Scheduled for: {new Date(post.scheduledFor).toLocaleString()}</span>
              </div>
            )}

            {/* Preflight Summary */}
            <div className="pt-2 border-t border-neutral-100 dark:border-neutral-800">
              <div className="flex items-center justify-between text-xs font-semibold">
                <span>Preflight Check:</span>
                {preflightErrors.length === 0 ? (
                  <span className="text-emerald-600 flex items-center gap-1">
                    <CheckCircle2 className="h-3.5 w-3.5" />
                    <span>Ready to Publish</span>
                  </span>
                ) : (
                  <span className="text-red-600 flex items-center gap-1">
                    <XCircle className="h-3.5 w-3.5" />
                    <span>{preflightErrors.length} Issue(s)</span>
                  </span>
                )}
              </div>

              {preflightErrors.length > 0 && (
                <ul className="mt-2 space-y-1 text-[11px] text-red-600">
                  {preflightErrors.map((err, i) => (
                    <li key={i}>• {err}</li>
                  ))}
                </ul>
              )}
            </div>
          </div>

          {/* Card 3: Taxonomy & Author Attribution */}
          <div className="rounded-2xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 space-y-4">
            <h3 className="text-xs font-bold text-neutral-900 dark:text-white uppercase tracking-wider border-b border-neutral-100 pb-2.5 dark:border-neutral-800">
              Taxonomy & Editorial Attribution
            </h3>

            {/* CATEGORY SELECTOR: Sourced dynamically from MongoDB categories collection */}
            <div className="space-y-1.5">
              {categoriesLoading ? (
                <Skeleton className="h-14 w-full rounded-xl" />
              ) : (
                <FloatingSelect
                  id="post-category"
                  label="Article Category"
                  value={post.category}
                  onValueChange={(val) => {
                    const found = categories.find((c) => c.name === val);
                    updateField("category", val);
                    if (found) updateField("categoryId", found.id);
                  }}
                  options={categories.map((c) => ({
                    value: c.name,
                    label: c.name,
                  }))}
                />
              )}
              <div className="flex justify-end">
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  onClick={() => setAddCategoryOpen(true)}
                  className="h-6 text-[11px] text-neutral-500 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-neutral-100 gap-1 px-1.5"
                >
                  <Plus className="h-3 w-3" />
                  <span>Add Category</span>
                </Button>
              </div>
            </div>

            {/* AUTHOR SELECTOR: Sourced strictly from real admin / sub-admin accounts */}
            <FloatingSelect
              id="post-author"
              label="Author Attribution *"
              value={post.authorId || authors.find((a) => a.name === post.author?.name)?.id || ""}
              onValueChange={handleAuthorChange}
              options={authorOptions}
            />

            {/* Author Profile Information Display (Derived from Account) */}
            {post.author && (
              <div className="rounded-xl border border-neutral-100 bg-neutral-50/80 p-3 text-xs dark:border-neutral-800 dark:bg-neutral-950/80 space-y-1.5">
                <div className="flex items-center gap-2">
                  <UserCheck className="h-3.5 w-3.5 text-emerald-600" />
                  <span className="font-semibold text-neutral-900 dark:text-white">
                    {post.author.name}
                  </span>
                  <span className="text-[10px] text-neutral-500 font-mono">
                    ({post.author.role})
                  </span>
                </div>
                <p className="text-[11px] text-neutral-500 leading-relaxed">
                  Role is automatically resolved from the admin user account.
                </p>
              </div>
            )}

            {/* Derived Reading Stats Display */}
            <div className="rounded-xl border border-neutral-200 bg-neutral-50/50 p-3 text-xs dark:border-neutral-800 dark:bg-neutral-950/50 flex items-center justify-between">
              <span className="font-semibold text-neutral-700 dark:text-neutral-300 flex items-center gap-1.5">
                <BookOpen className="h-3.5 w-3.5 text-blue-500" />
                <span>Estimated Read Time</span>
              </span>
              <span className="font-bold text-neutral-900 dark:text-white font-mono">
                {readingStats.readTime}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* REVISION HISTORY MODAL */}
      <Dialog open={revisionsOpen} onOpenChange={setRevisionsOpen}>
        <DialogContent className="max-w-xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Revision History</DialogTitle>
            <DialogDescription>
              Restoring a revision creates a new version without destroying historical records.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-2 py-3">
            {revisions.length === 0 ? (
              <div className="py-8 text-center text-xs text-neutral-400">
                No previous revisions recorded yet. Revisions are created automatically on publish and restore.
              </div>
            ) : (
              revisions.map((rev) => (
                <div
                  key={rev.id}
                  className="flex items-center justify-between rounded-xl border border-neutral-200 p-3.5 dark:border-neutral-800 hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition"
                >
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="text-xs font-bold">Version {rev.version}</span>
                      <span className="text-[10px] text-neutral-400">
                        {new Date(rev.timestamp).toLocaleString()}
                      </span>
                    </div>
                    <p className="mt-1 text-xs text-neutral-600 dark:text-neutral-400">
                      {rev.changeSummary}
                    </p>
                    <span className="text-[10px] text-neutral-400">By {rev.actorName}</span>
                  </div>

                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => restoreRevision(rev.id)}
                    className="text-xs gap-1"
                  >
                    <RotateCcw className="h-3 w-3" />
                    <span>Restore</span>
                  </Button>
                </div>
              ))
            )}
          </div>
        </DialogContent>
      </Dialog>

      {/* MEDIA PICKER MODAL */}
      <Dialog open={mediaPickerOpen} onOpenChange={setMediaPickerOpen}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>
              {mediaPickerTarget === "featured"
                ? "Featured Image Selector"
                : mediaPickerTarget === "og"
                ? "OpenGraph Social Image Selector"
                : "X / Twitter Card Image Selector"}
            </DialogTitle>
            <DialogDescription>
              Select an asset from your central Media Library or upload a new image.
            </DialogDescription>
          </DialogHeader>

          <div className="flex border-b border-neutral-200 dark:border-neutral-800">
            <button
              type="button"
              onClick={() => setMediaPickerTab("LIBRARY")}
              className={`pb-2 px-3 text-xs font-semibold border-b-2 transition ${
                mediaPickerTab === "LIBRARY"
                  ? "border-neutral-900 text-neutral-900 dark:border-white dark:text-white"
                  : "border-transparent text-neutral-500 hover:text-neutral-900"
              }`}
            >
              Media Library Assets
            </button>
            <button
              type="button"
              onClick={() => setMediaPickerTab("UPLOAD")}
              className={`pb-2 px-3 text-xs font-semibold border-b-2 transition ${
                mediaPickerTab === "UPLOAD"
                  ? "border-neutral-900 text-neutral-900 dark:border-white dark:text-white"
                  : "border-transparent text-neutral-500 hover:text-neutral-900"
              }`}
            >
              Upload New Graphic
            </button>
          </div>

          {mediaPickerTab === "LIBRARY" ? (
            <div className="space-y-3 pt-3">
              <div className="grid grid-cols-3 sm:grid-cols-4 gap-3 max-h-[340px] overflow-y-auto p-1">
                {mediaItems.map((item) => (
                  <div
                    key={item.id}
                    onClick={() => {
                      handleSelectMedia(item);
                      toast.success("Image selected from library!");
                    }}
                    className="group relative aspect-video cursor-pointer overflow-hidden rounded-xl border-2 border-neutral-200 hover:border-neutral-900 dark:border-neutral-800 transition"
                  >
                    <img
                      src={item.url}
                      alt={item.alt}
                      className="h-full w-full object-cover"
                    />
                    <div className="absolute inset-x-0 bottom-0 bg-black/60 p-1 text-[10px] text-white truncate px-1.5">
                      {item.filename}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <div className="space-y-4 py-6">
              <label className="flex flex-col items-center justify-center border-2 border-dashed border-neutral-300 hover:border-neutral-500 rounded-2xl p-8 cursor-pointer transition">
                <UploadCloud className="h-10 w-10 text-neutral-400 mb-2" />
                <span className="text-sm font-semibold text-neutral-800 dark:text-neutral-200">
                  Click to upload featured graphic
                </span>
                <span className="text-xs text-neutral-400 mt-1">
                  Supports PNG, JPEG, WebP (up to 5MB)
                </span>
                <input
                  type="file"
                  accept="image/png,image/jpeg,image/webp"
                  onChange={handleMediaUpload}
                  disabled={mediaUploading}
                  className="hidden"
                />
              </label>

              {mediaUploading && (
                <div className="text-center text-xs text-neutral-500 animate-pulse">
                  Uploading to media storage...
                </div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* SCHEDULE MODAL — Popover + Calendar Date Picker */}
      <Dialog open={scheduleModalOpen} onOpenChange={setScheduleModalOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Schedule Publication</DialogTitle>
            <DialogDescription>
              Article will automatically transition to live publication at the target timestamp.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-2">
            <div>
              <label className="text-xs font-semibold block mb-1.5 text-neutral-700 dark:text-neutral-300">
                Target Date *
              </label>
              <Popover open={scheduleCalendarOpen} onOpenChange={setScheduleCalendarOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    className="h-11 w-full justify-start text-left font-normal text-xs rounded-xl"
                  >
                    <CalendarIcon className="mr-2 h-4 w-4 text-neutral-500" />
                    {scheduleDate ? (
                      scheduleDate.toLocaleDateString()
                    ) : (
                      <span className="text-neutral-400">Select publication date...</span>
                    )}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="start">
                  <Calendar
                    selected={scheduleDate}
                    onSelect={(d) => {
                      setScheduleDate(d);
                      setScheduleCalendarOpen(false);
                    }}
                    minDate={new Date()}
                  />
                </PopoverContent>
              </Popover>
            </div>

            <div>
              <FloatingInput
                id="schedule-time"
                label="Target Time (HH:MM)"
                value={scheduleTime}
                onChange={(e) => setScheduleTime(e.target.value)}
                placeholder="09:00"
              />
            </div>

            <FloatingSelect
              id="schedule-timezone"
              label="Target Timezone"
              value={scheduleTimezone}
              onValueChange={setScheduleTimezone}
              options={[
                { value: "UTC", label: "UTC (Coordinated Universal Time)" },
                { value: "America/New_York", label: "Eastern Time (ET / New York)" },
                { value: "America/Los_Angeles", label: "Pacific Time (PT / Los Angeles)" },
                { value: "Europe/London", label: "London (GMT/BST)" },
                { value: "Asia/Kolkata", label: "India Standard Time (IST)" },
              ]}
            />
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setScheduleModalOpen(false)}
            >
              Cancel
            </Button>
            <Button onClick={handleSchedule} disabled={!scheduleDate}>
              Confirm Schedule
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* DISCARD WORKING DRAFT CONFIRMATION */}
      <AlertDialog open={discardModalOpen} onOpenChange={setDiscardModalOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Discard Working Draft Changes?</AlertDialogTitle>
            <AlertDialogDescription>
              This will discard all uncommitted changes made to this draft and revert your editor back to the current live published version of the article. This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Keep Draft</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDiscardDraft}
              className="bg-red-600 hover:bg-red-700 text-white"
            >
              Discard Changes
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* PUBLISH / UPDATE LIVE CONFIRMATION MODAL */}
      <AlertDialog open={publishModalOpen} onOpenChange={setPublishModalOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {isPublishedPost ? "Commit Updates to Live Article?" : "Publish Article Live to Public Website?"}
            </AlertDialogTitle>
            <AlertDialogDescription className="space-y-3 pt-1">
              <p>
                {isPublishedPost
                  ? "Your working draft changes will be committed to the public live website, sitemap, OpenGraph metadata, and Schema.org records."
                  : "This will transition the article status to PUBLISHED and make it discoverable by readers and search engines."}
              </p>

              {isSlugChanged && (
                <div className="rounded-xl border border-amber-200 bg-amber-50 p-3 text-xs text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/50 dark:text-amber-200">
                  <div className="flex items-start gap-2 font-semibold">
                    <AlertTriangle className="h-4 w-4 shrink-0 text-amber-600 mt-0.5" />
                    <span>Warning: Public URL is Changing!</span>
                  </div>
                  <p className="mt-1">
                    The URL will change from <code>/blog/{post.liveSlug}</code> to <code>/blog/{post.slug}</code>. An automatic 301 Permanent Redirect will be created to preserve search ranking link equity.
                  </p>
                </div>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>

          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handlePublishOrUpdateLive}
              className="bg-emerald-600 hover:bg-emerald-700 text-white font-semibold"
            >
              {isPublishedPost ? "Confirm & Update Live" : "Publish Now"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* ADD CATEGORY DIALOG */}
      <Dialog open={addCategoryOpen} onOpenChange={setAddCategoryOpen}>
        <DialogContent className="sm:max-w-[440px]">
          <form onSubmit={handleCreateCategory}>
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <FolderTree className="h-5 w-5 text-neutral-600 dark:text-neutral-400" />
                <span>Add New Category</span>
              </DialogTitle>
              <DialogDescription>
                Create a persistent category. It will be saved to MongoDB and immediately selected for this post.
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-4 py-4">
              <FloatingInput
                id="modal-new-cat-name"
                label="Category Name *"
                value={newCatName}
                onChange={(e) => {
                  setNewCatName(e.target.value);
                  setNewCatSlug(
                    e.target.value
                      .toLowerCase()
                      .replace(/[^a-z0-9]+/g, "-")
                      .replace(/(^-|-$)+/g, "")
                  );
                }}
                required
                autoFocus
              />

              <FloatingInput
                id="modal-new-cat-slug"
                label="Category Slug *"
                value={newCatSlug}
                onChange={(e) => setNewCatSlug(e.target.value)}
                required
              />
            </div>

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setAddCategoryOpen(false)}
                disabled={savingCategory}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={savingCategory}>
                {savingCategory ? "Creating..." : "Save & Select Category"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* SEND PUSH NOTIFICATION MODAL */}
      <PushSendDialog
        open={pushModalOpen}
        onOpenChange={setPushModalOpen}
        post={post}
      />
    </div>
  );
}
