"use client";

import * as React from "react";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import ImageExtension from "@tiptap/extension-image";
import LinkExtension from "@tiptap/extension-link";
import Placeholder from "@tiptap/extension-placeholder";
import Underline from "@tiptap/extension-underline";
import {
  Bold,
  Italic,
  Underline as UnderlineIcon,
  Strikethrough,
  Code,
  Heading2,
  Heading3,
  Heading4,
  List,
  ListOrdered,
  Quote,
  Minus,
  Link as LinkIcon,
  Unlink,
  Image as ImageIcon,
  Undo2,
  Redo2,
  CodeSquare,
  UploadCloud,
  Check,
  Slash,
  Sparkles,
  Eraser,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { FloatingInput } from "@/components/ui/floating-input";
import { calculateReadingStats, ReadingStats } from "@/lib/reading-time";
import { toast } from "sonner";

export interface TiptapEditorProps {
  content?: string;
  contentJson?: any;
  onChange: (html: string, json: any) => void;
  onStatsChange?: (stats: ReadingStats) => void;
  placeholder?: string;
  className?: string;
}

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

export function TiptapEditor({
  content,
  contentJson,
  onChange,
  onStatsChange,
  placeholder = "Start writing your article... Type '/' for quick block insertion.",
  className = "",
}: TiptapEditorProps) {
  // Image Insertion Modal State
  const [imageModalOpen, setImageModalOpen] = React.useState(false);
  const [imageTab, setImageTab] = React.useState<"LIBRARY" | "UPLOAD">("LIBRARY");
  const [mediaItems, setMediaItems] = React.useState<MediaItem[]>([]);
  const [selectedMediaUrl, setSelectedMediaUrl] = React.useState<string>("");
  const [imageAlt, setImageAlt] = React.useState<string>("");
  const [loadingMedia, setLoadingMedia] = React.useState(false);
  const [uploadingImage, setUploadingImage] = React.useState(false);

  // Link Modal State
  const [linkModalOpen, setLinkModalOpen] = React.useState(false);
  const [linkUrl, setLinkUrl] = React.useState("");

  // Right-Click Context Menu State
  const [contextMenu, setContextMenu] = React.useState<{ x: number; y: number } | null>(null);

  // Slash Command Menu State
  const [slashMenuOpen, setSlashMenuOpen] = React.useState(false);

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

  // Keep stable callback refs to avoid infinite effect loops
  const onStatsChangeRef = React.useRef(onStatsChange);
  React.useEffect(() => {
    onStatsChangeRef.current = onStatsChange;
  }, [onStatsChange]);

  const onChangeRef = React.useRef(onChange);
  React.useEffect(() => {
    onChangeRef.current = onChange;
  }, [onChange]);

  const hasInitializedStatsRef = React.useRef(false);

  const editor = useEditor({
    immediatelyRender: false,
    extensions: [
      StarterKit.configure({
        heading: {
          levels: [2, 3, 4, 5, 6],
        },
      }),
      Underline,
      ImageExtension.configure({
        inline: false,
        allowBase64: false,
        HTMLAttributes: {
          class: "rounded-2xl border border-neutral-200 dark:border-neutral-800 my-6 max-h-[500px] object-cover shadow-sm mx-auto",
        },
      }),
      LinkExtension.configure({
        openOnClick: false,
        HTMLAttributes: {
          class: "text-blue-600 underline underline-offset-4 hover:text-blue-800 transition dark:text-blue-400 dark:hover:text-blue-300",
        },
      }),
      Placeholder.configure({
        placeholder,
      }),
    ],
    content: contentJson || content || "",
    editorProps: {
      attributes: {
        class:
          "prose prose-neutral dark:prose-invert max-w-none min-h-[440px] px-6 py-5 focus:outline-none text-[15px] leading-relaxed",
      },
      handleKeyDown: (view, event) => {
        if (event.key === "/" && !event.ctrlKey && !event.metaKey) {
          // Open quick slash menu
          setSlashMenuOpen(true);
        } else if (event.key === "Escape") {
          setSlashMenuOpen(false);
          setContextMenu((prev) => (prev !== null ? null : prev));
        }
        return false;
      },
    },
    onUpdate: ({ editor }) => {
      const html = editor.getHTML();
      const json = editor.getJSON();
      const currentStats = calculateReadingStats(html);
      setStats(currentStats);
      onStatsChangeRef.current?.(currentStats);
      onChangeRef.current(html, json);
    },
  });

  // Calculate initial reading stats on load safely once
  React.useEffect(() => {
    if (editor && !hasInitializedStatsRef.current) {
      hasInitializedStatsRef.current = true;
      const initialStats = calculateReadingStats(editor.getHTML());
      setStats(initialStats);
      onStatsChangeRef.current?.(initialStats);
    }
  }, [editor]);

  // Keep editor in sync if contentJson changes externally (e.g. revision restore)
  React.useEffect(() => {
    if (!editor) return;
    if (contentJson && JSON.stringify(editor.getJSON()) !== JSON.stringify(contentJson)) {
      editor.commands.setContent(contentJson);
    } else if (content && editor.getHTML() !== content && !contentJson) {
      editor.commands.setContent(content);
    }
  }, [contentJson, content, editor]);

  // Close context menu and slash menu on outside click safely
  React.useEffect(() => {
    const handleWindowClick = () => {
      setContextMenu((prev) => (prev !== null ? null : prev));
    };
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        setContextMenu((prev) => (prev !== null ? null : prev));
        setSlashMenuOpen(false);
      }
    };
    window.addEventListener("click", handleWindowClick);
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("click", handleWindowClick);
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, []);

  // Load media items when image modal opens
  const openImageModal = async () => {
    setImageModalOpen(true);
    setSelectedMediaUrl("");
    setImageAlt("");
    setImageTab("LIBRARY");
    try {
      setLoadingMedia(true);
      const res = await fetch("/api/admin/media?limit=40");
      if (res.ok) {
        const data = await res.json();
        setMediaItems(data.items || []);
      }
    } catch (e) {
      console.error("Failed to load media items:", e);
    } finally {
      setLoadingMedia(false);
    }
  };

  const handleUploadImage = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    try {
      setUploadingImage(true);
      const formData = new FormData();
      formData.append("file", file);
      formData.append("alt", imageAlt || file.name);
      formData.append("category", "inline");

      const res = await fetch("/api/admin/media", {
        method: "POST",
        body: formData,
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Image upload failed.");

      toast.success("Image uploaded & added to Media Library!");
      // Insert into editor immediately
      editor?.chain().focus().setImage({ src: data.media.url, alt: data.media.alt || imageAlt }).run();
      setImageModalOpen(false);
    } catch (err: any) {
      toast.error(err.message || "Upload failed.");
    } finally {
      setUploadingImage(false);
      e.target.value = "";
    }
  };

  const handleInsertSelectedMedia = () => {
    if (!selectedMediaUrl) {
      toast.error("Please select an image first.");
      return;
    }
    editor?.chain().focus().setImage({ src: selectedMediaUrl, alt: imageAlt }).run();
    setImageModalOpen(false);
  };

  const openLinkModal = () => {
    const previousUrl = editor?.getAttributes("link").href || "";
    setLinkUrl(previousUrl);
    setLinkModalOpen(true);
  };

  const handleSaveLink = () => {
    if (linkUrl.trim() === "") {
      editor?.chain().focus().extendMarkRange("link").unsetLink().run();
    } else {
      let formatted = linkUrl.trim();
      if (!/^https?:\/\//i.test(formatted) && !formatted.startsWith("/")) {
        formatted = `https://${formatted}`;
      }
      editor?.chain().focus().extendMarkRange("link").setLink({ href: formatted }).run();
    }
    setLinkModalOpen(false);
  };

  // Slash command block insertion handler
  const executeSlashCommand = (action: () => void) => {
    if (!editor) return;
    action();
    setSlashMenuOpen(false);
  };

  if (!editor) return null;

  // Heading Level Helper (H1 strictly excluded — article title is the only H1)
  const currentHeading = editor.isActive("heading", { level: 2 })
    ? "h2"
    : editor.isActive("heading", { level: 3 })
    ? "h3"
    : editor.isActive("heading", { level: 4 })
    ? "h4"
    : editor.isActive("heading", { level: 5 })
    ? "h5"
    : editor.isActive("heading", { level: 6 })
    ? "h6"
    : "p";

  return (
    <div className={`relative rounded-2xl border border-neutral-200 bg-white shadow-xs dark:border-neutral-800 dark:bg-neutral-900 ${className}`}>
      {/* Sticky Editorial Toolbar — Remains accessible while scrolling long articles */}
      <div className="sticky top-14 z-20 flex flex-wrap items-center gap-1 border-b border-neutral-200 bg-neutral-50/95 p-2 backdrop-blur-md dark:border-neutral-800 dark:bg-neutral-900/95 rounded-t-2xl shadow-xs">
        {/* Undo / Redo */}
        <div className="flex items-center gap-0.5 border-r border-neutral-200 pr-1.5 dark:border-neutral-800">
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => editor.chain().focus().undo().run()}
            disabled={!editor.can().undo()}
            className="h-8 w-8 p-0 text-neutral-600 dark:text-neutral-300"
            title="Undo (Ctrl+Z)"
          >
            <Undo2 className="h-4 w-4" />
          </Button>
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => editor.chain().focus().redo().run()}
            disabled={!editor.can().redo()}
            className="h-8 w-8 p-0 text-neutral-600 dark:text-neutral-300"
            title="Redo (Ctrl+Y)"
          >
            <Redo2 className="h-4 w-4" />
          </Button>
        </div>

        {/* Heading Hierarchy Selector (shadcn Select: H2-H6 only) */}
        <div className="border-r border-neutral-200 pr-1.5 dark:border-neutral-800">
          <Select
            value={currentHeading}
            onValueChange={(val) => {
              try {
                if (!editor) return;
                if (val === "p") {
                  editor.chain().focus().setParagraph().run();
                } else if (val === "h2") {
                  editor.chain().focus().toggleHeading({ level: 2 }).run();
                } else if (val === "h3") {
                  editor.chain().focus().toggleHeading({ level: 3 }).run();
                } else if (val === "h4") {
                  editor.chain().focus().toggleHeading({ level: 4 }).run();
                } else if (val === "h5") {
                  editor.chain().focus().toggleHeading({ level: 5 }).run();
                } else if (val === "h6") {
                  editor.chain().focus().toggleHeading({ level: 6 }).run();
                }
              } catch (err) {
                console.error("Editor format error:", err);
              }
            }}
          >
            <SelectTrigger className="h-8 w-[140px] text-xs font-semibold" aria-label="Text style and heading level">
              <SelectValue placeholder="Style" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="p" className="text-xs">Normal text (Paragraph)</SelectItem>
              <SelectItem value="h2" className="text-xs font-bold">Heading 2 (H2)</SelectItem>
              <SelectItem value="h3" className="text-xs font-bold">Heading 3 (H3)</SelectItem>
              <SelectItem value="h4" className="text-xs font-bold">Heading 4 (H4)</SelectItem>
              <SelectItem value="h5" className="text-xs font-semibold">Heading 5 (H5)</SelectItem>
              <SelectItem value="h6" className="text-xs font-medium">Heading 6 (H6)</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* Formatting Marks */}
        <div className="flex items-center gap-0.5 border-r border-neutral-200 pr-1.5 dark:border-neutral-800">
          <Button
            type="button"
            variant={editor.isActive("bold") ? "secondary" : "ghost"}
            size="sm"
            onClick={() => editor.chain().focus().toggleBold().run()}
            className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
            title="Bold (Ctrl+B)"
          >
            <Bold className="h-4 w-4" />
          </Button>
          <Button
            type="button"
            variant={editor.isActive("italic") ? "secondary" : "ghost"}
            size="sm"
            onClick={() => editor.chain().focus().toggleItalic().run()}
            className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
            title="Italic (Ctrl+I)"
          >
            <Italic className="h-4 w-4" />
          </Button>
          <Button
            type="button"
            variant={editor.isActive("underline") ? "secondary" : "ghost"}
            size="sm"
            onClick={() => editor.chain().focus().toggleUnderline().run()}
            className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
            title="Underline (Ctrl+U)"
          >
            <UnderlineIcon className="h-4 w-4" />
          </Button>
          <Button
            type="button"
            variant={editor.isActive("strike") ? "secondary" : "ghost"}
            size="sm"
            onClick={() => editor.chain().focus().toggleStrike().run()}
            className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
            title="Strikethrough"
          >
            <Strikethrough className="h-4 w-4" />
          </Button>
          <Button
            type="button"
            variant={editor.isActive("code") ? "secondary" : "ghost"}
            size="sm"
            onClick={() => editor.chain().focus().toggleCode().run()}
            className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
            title="Inline Code"
          >
            <Code className="h-4 w-4" />
          </Button>
        </div>

        {/* Blocks & Lists */}
        <div className="flex items-center gap-0.5 border-r border-neutral-200 pr-1.5 dark:border-neutral-800">
          <Button
            type="button"
            variant={editor.isActive("bulletList") ? "secondary" : "ghost"}
            size="sm"
            onClick={() => editor.chain().focus().toggleBulletList().run()}
            className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
            title="Bullet List"
          >
            <List className="h-4 w-4" />
          </Button>
          <Button
            type="button"
            variant={editor.isActive("orderedList") ? "secondary" : "ghost"}
            size="sm"
            onClick={() => editor.chain().focus().toggleOrderedList().run()}
            className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
            title="Numbered List"
          >
            <ListOrdered className="h-4 w-4" />
          </Button>
          <Button
            type="button"
            variant={editor.isActive("blockquote") ? "secondary" : "ghost"}
            size="sm"
            onClick={() => editor.chain().focus().toggleBlockquote().run()}
            className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
            title="Blockquote"
          >
            <Quote className="h-4 w-4" />
          </Button>
          <Button
            type="button"
            variant={editor.isActive("codeBlock") ? "secondary" : "ghost"}
            size="sm"
            onClick={() => editor.chain().focus().toggleCodeBlock().run()}
            className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
            title="Code Block"
          >
            <CodeSquare className="h-4 w-4" />
          </Button>
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={() => editor.chain().focus().setHorizontalRule().run()}
            className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
            title="Horizontal Divider Rule"
          >
            <Minus className="h-4 w-4" />
          </Button>
        </div>

        {/* Links & Media */}
        <div className="flex items-center gap-0.5 border-r border-neutral-200 pr-1.5 dark:border-neutral-800">
          <Button
            type="button"
            variant={editor.isActive("link") ? "secondary" : "ghost"}
            size="sm"
            onClick={openLinkModal}
            className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
            title="Insert / Edit Link"
          >
            <LinkIcon className="h-4 w-4" />
          </Button>
          {editor.isActive("link") && (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={() => editor.chain().focus().unsetLink().run()}
              className="h-8 w-8 p-0 text-neutral-700 dark:text-neutral-300"
              title="Remove Link"
            >
              <Unlink className="h-4 w-4" />
            </Button>
          )}
          <Button
            type="button"
            variant="ghost"
            size="sm"
            onClick={openImageModal}
            className="h-8 gap-1 px-2 text-xs font-semibold text-neutral-700 dark:text-neutral-300"
            title="Insert Image from Media Library"
          >
            <ImageIcon className="h-4 w-4 text-emerald-600" />
            <span className="hidden sm:inline">Add Image</span>
          </Button>
        </div>

        {/* Quick Slash Commands Trigger */}
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={() => setSlashMenuOpen(!slashMenuOpen)}
          className="h-8 gap-1 px-2 text-xs font-semibold text-neutral-600 dark:text-neutral-300"
          title="Quick Block Insert Menu (/)"
        >
          <Slash className="h-3.5 w-3.5 text-blue-500" />
          <span className="hidden md:inline">Blocks</span>
        </Button>
      </div>

      {/* Floating Slash Command Palette */}
      {slashMenuOpen && (
        <div className="absolute left-4 top-16 z-30 w-64 rounded-xl border border-neutral-200 bg-white p-2 shadow-xl dark:border-neutral-800 dark:bg-neutral-900 animate-in fade-in-0 zoom-in-95">
          <div className="px-2 py-1 text-[10px] font-bold uppercase tracking-wider text-neutral-400">
            Insert Content Block
          </div>
          <div className="space-y-0.5">
            <button
              type="button"
              onClick={() => executeSlashCommand(() => editor.chain().focus().toggleHeading({ level: 2 }).run())}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800 text-left font-semibold"
            >
              <Heading2 className="h-4 w-4 text-neutral-500" />
              <span>Heading 2 (H2)</span>
            </button>
            <button
              type="button"
              onClick={() => executeSlashCommand(() => editor.chain().focus().toggleHeading({ level: 3 }).run())}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800 text-left font-medium"
            >
              <Heading3 className="h-4 w-4 text-neutral-500" />
              <span>Heading 3 (H3)</span>
            </button>
            <button
              type="button"
              onClick={() => executeSlashCommand(() => editor.chain().focus().toggleHeading({ level: 4 }).run())}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800 text-left font-medium"
            >
              <Heading4 className="h-4 w-4 text-neutral-500" />
              <span>Heading 4 (H4)</span>
            </button>
            <button
              type="button"
              onClick={() => executeSlashCommand(() => editor.chain().focus().toggleBlockquote().run())}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800 text-left"
            >
              <Quote className="h-4 w-4 text-neutral-500" />
              <span>Callout Blockquote</span>
            </button>
            <button
              type="button"
              onClick={() => executeSlashCommand(() => editor.chain().focus().toggleCodeBlock().run())}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800 text-left font-mono"
            >
              <CodeSquare className="h-4 w-4 text-neutral-500" />
              <span>Code Block</span>
            </button>
            <button
              type="button"
              onClick={() => executeSlashCommand(() => openImageModal())}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800 text-left font-medium text-emerald-600 dark:text-emerald-400"
            >
              <ImageIcon className="h-4 w-4 text-emerald-500" />
              <span>Media Library Image</span>
            </button>
            <button
              type="button"
              onClick={() => executeSlashCommand(() => editor.chain().focus().setHorizontalRule().run())}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800 text-left"
            >
              <Minus className="h-4 w-4 text-neutral-500" />
              <span>Horizontal Rule Divider</span>
            </button>
            <button
              type="button"
              onClick={() => executeSlashCommand(() => editor.chain().focus().unsetAllMarks().clearNodes().run())}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-500 hover:bg-neutral-100 dark:text-neutral-400 dark:hover:bg-neutral-800 text-left"
            >
              <Eraser className="h-4 w-4 text-neutral-400" />
              <span>Clear Formatting</span>
            </button>
          </div>
        </div>
      )}

      {/* Editor Content Canvas with Right-Click Context Menu */}
      <div
        onContextMenu={(e) => {
          e.preventDefault();
          setContextMenu({ x: e.clientX, y: e.clientY });
        }}
      >
        <EditorContent editor={editor} />
      </div>

      {/* Editor Footer / Word Count & Read Time Bar */}
      <div className="flex items-center justify-between border-t border-neutral-100 px-6 py-2.5 text-xs text-neutral-500 dark:border-neutral-800 dark:text-neutral-400 bg-neutral-50/50 dark:bg-neutral-950/50 rounded-b-2xl">
        <div className="flex items-center gap-3">
          <span className="font-semibold text-neutral-700 dark:text-neutral-300">
            {stats.words.toLocaleString()} words
          </span>
          <span>•</span>
          <span className="flex items-center gap-1 text-emerald-600 dark:text-emerald-400 font-medium">
            <Sparkles className="h-3 w-3" />
            <span>{stats.readTime}</span>
          </span>
        </div>
        <div className="text-[11px] text-neutral-400 hidden sm:block">
          Right-click inside editor for context menu • Type &apos;/&apos; for blocks
        </div>
      </div>

      {/* Floating Right-Click Context Menu */}
      {contextMenu && (
        <div
          className="fixed z-50 w-52 rounded-xl border border-neutral-200 bg-white/95 p-1.5 shadow-2xl backdrop-blur-md dark:border-neutral-800 dark:bg-neutral-900/95 animate-in fade-in-0 zoom-in-95"
          style={{
            top: Math.min(contextMenu.y, typeof window !== "undefined" ? window.innerHeight - 340 : contextMenu.y),
            left: Math.min(contextMenu.x, typeof window !== "undefined" ? window.innerWidth - 220 : contextMenu.x),
          }}
          onClick={(e) => e.stopPropagation()}
        >
          <div className="px-2 py-1 text-[10px] font-bold uppercase tracking-wider text-neutral-400">
            Quick Actions
          </div>
          <div className="space-y-0.5">
            <button
              type="button"
              onClick={() => {
                editor.chain().focus().toggleBold().run();
                setContextMenu(null);
              }}
              className="flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"
            >
              <div className="flex items-center gap-2">
                <Bold className="h-3.5 w-3.5" />
                <span>Bold</span>
              </div>
              <span className="text-[10px] text-neutral-400 font-mono">Ctrl+B</span>
            </button>
            <button
              type="button"
              onClick={() => {
                editor.chain().focus().toggleItalic().run();
                setContextMenu(null);
              }}
              className="flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"
            >
              <div className="flex items-center gap-2">
                <Italic className="h-3.5 w-3.5" />
                <span>Italic</span>
              </div>
              <span className="text-[10px] text-neutral-400 font-mono">Ctrl+I</span>
            </button>
            <button
              type="button"
              onClick={() => {
                editor.chain().focus().toggleUnderline().run();
                setContextMenu(null);
              }}
              className="flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"
            >
              <div className="flex items-center gap-2">
                <UnderlineIcon className="h-3.5 w-3.5" />
                <span>Underline</span>
              </div>
              <span className="text-[10px] text-neutral-400 font-mono">Ctrl+U</span>
            </button>
            <button
              type="button"
              onClick={() => {
                openLinkModal();
                setContextMenu(null);
              }}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"
            >
              <LinkIcon className="h-3.5 w-3.5" />
              <span>Insert / Edit Link</span>
            </button>
            <button
              type="button"
              onClick={() => {
                openImageModal();
                setContextMenu(null);
              }}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-emerald-600 hover:bg-emerald-50 dark:text-emerald-400 dark:hover:bg-emerald-950/30"
            >
              <ImageIcon className="h-3.5 w-3.5" />
              <span>Insert Image</span>
            </button>
            <div className="my-1 border-t border-neutral-100 dark:border-neutral-800" />
            <button
              type="button"
              onClick={() => {
                editor.chain().focus().toggleHeading({ level: 2 }).run();
                setContextMenu(null);
              }}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800 font-semibold"
            >
              <Heading2 className="h-3.5 w-3.5" />
              <span>Heading 2</span>
            </button>
            <button
              type="button"
              onClick={() => {
                editor.chain().focus().toggleHeading({ level: 3 }).run();
                setContextMenu(null);
              }}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"
            >
              <Heading3 className="h-3.5 w-3.5" />
              <span>Heading 3</span>
            </button>
            <button
              type="button"
              onClick={() => {
                editor.chain().focus().toggleHeading({ level: 4 }).run();
                setContextMenu(null);
              }}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"
            >
              <Heading4 className="h-3.5 w-3.5" />
              <span>Heading 4</span>
            </button>
            <button
              type="button"
              onClick={() => {
                editor.chain().focus().toggleBulletList().run();
                setContextMenu(null);
              }}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"
            >
              <List className="h-3.5 w-3.5" />
              <span>Bullet List</span>
            </button>
            <button
              type="button"
              onClick={() => {
                editor.chain().focus().toggleBlockquote().run();
                setContextMenu(null);
              }}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800"
            >
              <Quote className="h-3.5 w-3.5" />
              <span>Blockquote</span>
            </button>
            <div className="my-1 border-t border-neutral-100 dark:border-neutral-800" />
            <button
              type="button"
              onClick={() => {
                editor.chain().focus().unsetAllMarks().clearNodes().run();
                setContextMenu(null);
              }}
              className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-neutral-500 hover:bg-neutral-100 dark:hover:bg-neutral-800"
            >
              <Eraser className="h-3.5 w-3.5" />
              <span>Clear Formatting</span>
            </button>
          </div>
        </div>
      )}

      {/* IMAGE INSERTION MODAL */}
      <Dialog open={imageModalOpen} onOpenChange={setImageModalOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Insert Image into Article</DialogTitle>
            <DialogDescription>
              Upload a new asset (automatically synced to your Media Library) or select an existing image.
            </DialogDescription>
          </DialogHeader>

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

          {imageTab === "LIBRARY" ? (
            <div className="space-y-4 pt-3">
              {loadingMedia ? (
                <div className="py-12 text-center text-xs text-neutral-500">
                  Loading media library assets...
                </div>
              ) : mediaItems.length === 0 ? (
                <div className="py-12 text-center text-xs text-neutral-500">
                  No images found in library. Switch to Upload to add your first image.
                </div>
              ) : (
                <div className="grid grid-cols-3 sm:grid-cols-4 gap-3 max-h-[300px] overflow-y-auto p-1">
                  {mediaItems.map((item) => (
                    <div
                      key={item.id}
                      onClick={() => {
                        setSelectedMediaUrl(item.url);
                        if (!imageAlt) setImageAlt(item.alt || item.filename);
                      }}
                      className={`group relative aspect-video cursor-pointer overflow-hidden rounded-xl border-2 transition ${
                        selectedMediaUrl === item.url
                          ? "border-emerald-600 ring-2 ring-emerald-600/20"
                          : "border-neutral-200 hover:border-neutral-400 dark:border-neutral-800"
                      }`}
                    >
                      <img
                        src={item.url}
                        alt={item.alt}
                        className="h-full w-full object-cover"
                      />
                      {selectedMediaUrl === item.url && (
                        <div className="absolute top-1.5 right-1.5 rounded-full bg-emerald-600 p-0.5 text-white">
                          <Check className="h-3 w-3" />
                        </div>
                      )}
                      <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>
              )}

              <FloatingInput
                id="editor-image-alt"
                label="Image Alt Text (Accessibility & SEO)"
                value={imageAlt}
                onChange={(e) => setImageAlt(e.target.value)}
                placeholder="Describe image content..."
              />

              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setImageModalOpen(false)}
                >
                  Cancel
                </Button>
                <Button
                  type="button"
                  onClick={handleInsertSelectedMedia}
                  disabled={!selectedMediaUrl}
                  className="bg-emerald-600 hover:bg-emerald-700 text-white"
                >
                  Insert Image
                </Button>
              </DialogFooter>
            </div>
          ) : (
            <div className="space-y-4 py-4">
              <FloatingInput
                id="editor-upload-alt"
                label="Image Alt Text (Accessibility & SEO)"
                value={imageAlt}
                onChange={(e) => setImageAlt(e.target.value)}
                placeholder="Describe graphic..."
              />

              <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 bg-neutral-50/50 dark:bg-neutral-950/50">
                <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 choose file or drag and drop
                </span>
                <span className="text-xs text-neutral-400 mt-1">
                  Supports PNG, JPEG, and WebP (up to 5MB)
                </span>
                <input
                  type="file"
                  accept="image/png,image/jpeg,image/webp,image/gif,image/bmp,image/tiff,image/avif"
                  onChange={handleUploadImage}
                  disabled={uploadingImage}
                  className="hidden"
                />
              </label>

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

      {/* LINK INSERTION MODAL */}
      <Dialog open={linkModalOpen} onOpenChange={setLinkModalOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Insert / Edit Hyperlink</DialogTitle>
            <DialogDescription>
              Enter a destination URL or leave empty to remove link.
            </DialogDescription>
          </DialogHeader>

          <div className="pt-2">
            <FloatingInput
              id="editor-link-url"
              label="Destination URL"
              value={linkUrl}
              onChange={(e) => setLinkUrl(e.target.value)}
              placeholder="https://example.com or /blog/article-slug"
              autoFocus
            />
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => setLinkModalOpen(false)}
            >
              Cancel
            </Button>
            <Button type="button" onClick={handleSaveLink}>
              Save Link
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
