"use client";

/**
 * Blog Post Modal - Simplified Create/Edit Form
 * Features:
 * - Quick Create mode for fast blog post creation
 * - Full mode for detailed editing
 * - Bilingual support (Arabic + English)
 * - Auto-generates slug from title
 * - One-click publish
 */

import { useState, useEffect, useCallback } from "react";
import {
  X,
  Sparkles,
  Loader2,
  Save,
  Globe,
  Languages,
  Zap,
  ChevronDown,
  ChevronUp,
  Eye,
  EyeOff,
  FileText,
} from "lucide-react";
import type {
  BlogPostListItem,
  CreateBlogPostInput,
} from "@/lib/types/blog-management.types";
import TemplateSelector from "./TemplateSelector";
import type { BlogTemplate } from "@/lib/blog-templates";

interface BlogPostModalProps {
  post: BlogPostListItem | null;
  onClose: () => void;
  onSuccess: () => void;
}

interface LanguageContent {
  title: string;
  slug: string;
  excerpt: string;
  content: string;
}

type CreateMode = "quick" | "full";

export default function BlogPostModal({
  post,
  onClose,
  onSuccess,
}: BlogPostModalProps) {
  const isEdit = !!post;

  // Mode selection (quick vs full)
  const [createMode, setCreateMode] = useState<CreateMode>(
    isEdit ? "full" : "quick",
  );
  const [activeTab, setActiveTab] = useState<"en" | "ar">("en");
  const [createBothLanguages, setCreateBothLanguages] = useState(!isEdit);

  // English content
  const [enContent, setEnContent] = useState<LanguageContent>({
    title: post?.lang === "en" ? post.title : "",
    slug: post?.lang === "en" ? post.slug : "",
    excerpt: post?.lang === "en" ? post.excerpt : "",
    content: post?.lang === "en" ? (post as any).content || "" : "",
  });

  // Arabic content
  const [arContent, setArContent] = useState<LanguageContent>({
    title: post?.lang === "ar" ? post.title : "",
    slug: post?.lang === "ar" ? post.slug : "",
    excerpt: post?.lang === "ar" ? post.excerpt : "",
    content: post?.lang === "ar" ? (post as any).content || "" : "",
  });

  // Shared fields
  const [sharedData, setSharedData] = useState({
    author: post?.author || "Mawidi Team",
    tags: post?.tags?.join(", ") || "",
    status: post?.status || "PUBLISHED", // Default to PUBLISHED for quick create
    featured: post?.featured || false,
  });

  const [coverImage, setCoverImage] = useState<string | null>(
    post?.cover_image || null,
  );
  const [saving, setSaving] = useState(false);
  const [saveProgress, setSaveProgress] = useState<string>("");
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [showTemplateSelector, setShowTemplateSelector] = useState(false);

  // Handle template selection
  const handleTemplateSelect = useCallback(
    (template: BlogTemplate, lang: "en" | "ar") => {
      if (lang === "en") {
        setEnContent((prev) => ({
          ...prev,
          title: template.titleTemplate,
          content: template.contentTemplate,
          excerpt: "",
        }));
        // Also set tags if not already set
        if (!sharedData.tags) {
          handleSharedChange("tags", template.tags.join(", "));
        }
      } else {
        setArContent((prev) => ({
          ...prev,
          title: template.titleTemplateAr,
          content: template.contentTemplateAr,
          excerpt: "",
        }));
        // Also set tags if not already set
        if (!sharedData.tags) {
          handleSharedChange("tags", template.tagsAr.join(", "));
        }
      }
      setShowTemplateSelector(false);
    },
    [sharedData.tags],
  );

  // Auto-generate English slug from title
  useEffect(() => {
    if (!isEdit && enContent.title && !enContent.slug) {
      const slug = enContent.title
        .toLowerCase()
        .trim()
        .replace(/[^a-z0-9\s-]/g, "")
        .replace(/\s+/g, "-")
        .replace(/-+/g, "-")
        .replace(/^-+|-+$/g, "");
      setEnContent((prev) => ({ ...prev, slug }));
    }
  }, [enContent.title, isEdit]);

  // Auto-generate Arabic slug
  useEffect(() => {
    if (!isEdit && arContent.title && !arContent.slug) {
      const slug = arContent.title
        .trim()
        .replace(/\s+/g, "-")
        .replace(/[^\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF0-9-]/g, "")
        .replace(/-+/g, "-")
        .replace(/^-+|-+$/g, "");
      setArContent((prev) => ({ ...prev, slug: slug || `ar-${Date.now()}` }));
    }
  }, [arContent.title, isEdit]);

  // Auto-generate excerpt from content (first 150 chars)
  const autoGenerateExcerpt = useCallback((content: string): string => {
    const plainText = content
      .replace(/[#*_`\[\]]/g, "")
      .replace(/\n+/g, " ")
      .trim();
    return plainText.slice(0, 150) + (plainText.length > 150 ? "..." : "");
  }, []);

  // Quick mode: auto-generate excerpt when content changes
  useEffect(() => {
    if (createMode === "quick" && !isEdit) {
      if (enContent.content && !enContent.excerpt) {
        setEnContent((prev) => ({
          ...prev,
          excerpt: autoGenerateExcerpt(prev.content),
        }));
      }
      if (arContent.content && !arContent.excerpt) {
        setArContent((prev) => ({
          ...prev,
          excerpt: autoGenerateExcerpt(prev.content),
        }));
      }
    }
  }, [
    enContent.content,
    arContent.content,
    createMode,
    isEdit,
    autoGenerateExcerpt,
  ]);

  const handleEnChange = (field: keyof LanguageContent, value: string) => {
    setEnContent((prev) => ({ ...prev, [field]: value }));
  };

  const handleArChange = (field: keyof LanguageContent, value: string) => {
    setArContent((prev) => ({ ...prev, [field]: value }));
  };

  const handleSharedChange = (field: string, value: any) => {
    setSharedData((prev) => ({ ...prev, [field]: value }));
  };

  const validateContent = (
    content: LanguageContent,
    lang: string,
    isQuick: boolean,
  ): string | null => {
    if (!content.title || content.title.length < 5) {
      return `${lang} title must be at least 5 characters`;
    }
    if (!content.content || content.content.length < (isQuick ? 50 : 100)) {
      return `${lang} content must be at least ${isQuick ? 50 : 100} characters`;
    }
    return null;
  };

  const createPost = async (content: LanguageContent, lang: "en" | "ar") => {
    const tagsArray = sharedData.tags
      .split(",")
      .map((t) => t.trim())
      .filter((t) => t.length > 0);

    // Auto-generate excerpt if empty
    const excerpt = content.excerpt || autoGenerateExcerpt(content.content);

    // Auto-generate slug if empty
    const slug =
      content.slug ||
      content.title
        .toLowerCase()
        .trim()
        .replace(/[^a-z0-9\s-\u0600-\u06FF]/g, "")
        .replace(/\s+/g, "-")
        .replace(/-+/g, "-");

    const payload: CreateBlogPostInput = {
      title: content.title,
      slug,
      lang,
      excerpt,
      content: content.content,
      author: sharedData.author,
      tags:
        tagsArray.length > 0 ? tagsArray : [lang === "ar" ? "عام" : "General"],
      status: sharedData.status as "DRAFT" | "PUBLISHED" | "ARCHIVED",
      featured: sharedData.featured,
      generateAiImage: !coverImage,
    };

    const res = await fetch("/api/staff/dashboard/blog", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    const data = await res.json();

    if (!res.ok) {
      throw new Error(
        data.error ||
          `Failed to save ${lang === "en" ? "English" : "Arabic"} post`,
      );
    }

    return data;
  };

  const updatePost = async (content: LanguageContent) => {
    const tagsArray = sharedData.tags
      .split(",")
      .map((t) => t.trim())
      .filter((t) => t.length > 0);

    const payload = {
      title: content.title,
      slug: content.slug,
      excerpt: content.excerpt || autoGenerateExcerpt(content.content),
      content: content.content,
      author: sharedData.author,
      tags: tagsArray,
      status: sharedData.status,
      featured: sharedData.featured,
    };

    const res = await fetch(`/api/staff/dashboard/blog/${post!.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });

    const data = await res.json();

    if (!res.ok) {
      throw new Error(data.error || "Failed to update blog post");
    }

    return data;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    setSaveProgress("");

    const isQuick = createMode === "quick";

    try {
      if (isEdit) {
        const content = post!.lang === "en" ? enContent : arContent;
        const error = validateContent(
          content,
          post!.lang === "en" ? "English" : "Arabic",
          isQuick,
        );
        if (error) {
          alert(error);
          setSaving(false);
          return;
        }

        setSaveProgress("Updating post...");
        await updatePost(content);
        onSuccess();
      } else if (createBothLanguages) {
        const enError = validateContent(enContent, "English", isQuick);
        const arError = validateContent(arContent, "Arabic", isQuick);

        if (enError) {
          setActiveTab("en");
          alert(enError);
          setSaving(false);
          return;
        }

        if (arError) {
          setActiveTab("ar");
          alert(arError);
          setSaving(false);
          return;
        }

        setSaveProgress("Creating English post...");
        await createPost(enContent, "en");

        setSaveProgress("Creating Arabic post...");
        await createPost(arContent, "ar");

        onSuccess();
      } else {
        const content = activeTab === "en" ? enContent : arContent;
        const error = validateContent(
          content,
          activeTab === "en" ? "English" : "Arabic",
          isQuick,
        );
        if (error) {
          alert(error);
          setSaving(false);
          return;
        }

        setSaveProgress(
          `Creating ${activeTab === "en" ? "English" : "Arabic"} post...`,
        );
        await createPost(content, activeTab);
        onSuccess();
      }
    } catch (error) {
      console.error("Save error:", error);
      alert(
        error instanceof Error ? error.message : "Failed to save blog post",
      );
    } finally {
      setSaving(false);
      setSaveProgress("");
    }
  };

  const renderQuickCreateForm = () => (
    <div className="space-y-6">
      {/* Language tabs */}
      {createBothLanguages && (
        <div className="border-b border-gray-200">
          <nav className="flex -mb-px">
            <button
              type="button"
              onClick={() => setActiveTab("en")}
              className={`flex items-center gap-2 px-6 py-3 font-semibold text-sm border-b-2 transition ${
                activeTab === "en"
                  ? "border-brand-green text-brand-green"
                  : "border-transparent text-gray-500 hover:text-gray-700"
              }`}
            >
              EN
              {enContent.title && (
                <span className="w-2 h-2 bg-green-500 rounded-full" />
              )}
            </button>
            <button
              type="button"
              onClick={() => setActiveTab("ar")}
              className={`flex items-center gap-2 px-6 py-3 font-semibold text-sm border-b-2 transition ${
                activeTab === "ar"
                  ? "border-brand-green text-brand-green"
                  : "border-transparent text-gray-500 hover:text-gray-700"
              }`}
            >
              AR
              {arContent.title && (
                <span className="w-2 h-2 bg-green-500 rounded-full" />
              )}
            </button>
          </nav>
        </div>
      )}

      {/* Quick form fields */}
      <div
        className={activeTab === "ar" ? "text-right" : ""}
        dir={activeTab === "ar" ? "rtl" : "ltr"}
      >
        {/* Title */}
        <div className="mb-4">
          <label className="block text-sm font-semibold text-gray-700 mb-2">
            {activeTab === "ar" ? "العنوان *" : "Title *"}
          </label>
          <input
            type="text"
            value={activeTab === "en" ? enContent.title : arContent.title}
            onChange={(e) =>
              activeTab === "en"
                ? handleEnChange("title", e.target.value)
                : handleArChange("title", e.target.value)
            }
            className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green text-lg"
            placeholder={
              activeTab === "ar"
                ? "أدخل عنوان المقال..."
                : "Enter a catchy title..."
            }
            autoFocus
          />
        </div>

        {/* Content */}
        <div className="mb-4">
          <div className="flex items-center justify-between mb-2">
            <label className="block text-sm font-semibold text-gray-700">
              {activeTab === "ar" ? "المحتوى *" : "Content *"}
            </label>
            {!isEdit && (
              <button
                type="button"
                onClick={() => setShowTemplateSelector(true)}
                className="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-brand-green bg-brand-green/10 hover:bg-brand-green/20 rounded-lg transition"
              >
                <FileText className="w-4 h-4" />
                {activeTab === "ar" ? "استخدام قالب" : "Use Template"}
              </button>
            )}
          </div>
          <textarea
            value={activeTab === "en" ? enContent.content : arContent.content}
            onChange={(e) =>
              activeTab === "en"
                ? handleEnChange("content", e.target.value)
                : handleArChange("content", e.target.value)
            }
            className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green font-mono text-sm"
            rows={10}
            placeholder={
              activeTab === "ar"
                ? "اكتب محتوى المقال هنا... (يدعم Markdown)"
                : "Write your blog post content here... (Markdown supported)"
            }
          />
          <p className="mt-1 text-xs text-gray-500">
            {activeTab === "ar"
              ? `${arContent.content.length} حرف (الحد الأدنى 50)`
              : `${enContent.content.length} characters (min 50)`}
          </p>
        </div>

        {/* Tags (optional) */}
        <div className="mb-4">
          <label className="block text-sm font-semibold text-gray-700 mb-2">
            {activeTab === "ar" ? "الوسوم (اختياري)" : "Tags (optional)"}
          </label>
          <input
            type="text"
            value={sharedData.tags}
            onChange={(e) => handleSharedChange("tags", e.target.value)}
            className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-brand-green"
            placeholder={
              activeTab === "ar"
                ? "مثال: تقنية, أعمال, صحة"
                : "e.g., technology, business, health"
            }
          />
        </div>
      </div>

      {/* Publish toggle */}
      <div className="flex items-center justify-between p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-lg">
        <div className="flex items-center gap-3">
          {sharedData.status === "PUBLISHED" ? (
            <Eye className="w-5 h-5 text-green-600" />
          ) : (
            <EyeOff className="w-5 h-5 text-gray-500" />
          )}
          <div>
            <p className="font-semibold text-gray-900">
              {sharedData.status === "PUBLISHED"
                ? "Publish immediately"
                : "Save as draft"}
            </p>
            <p className="text-xs text-gray-600">
              {sharedData.status === "PUBLISHED"
                ? "Post will be visible on the blog page"
                : "Post will be saved but not visible"}
            </p>
          </div>
        </div>
        <label className="relative inline-flex items-center cursor-pointer">
          <input
            type="checkbox"
            checked={sharedData.status === "PUBLISHED"}
            onChange={(e) =>
              handleSharedChange(
                "status",
                e.target.checked ? "PUBLISHED" : "DRAFT",
              )
            }
            className="sr-only peer"
          />
          <div className="w-11 h-6 bg-gray-300 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-brand-green/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand-green" />
        </label>
      </div>

      {/* Advanced options toggle */}
      <button
        type="button"
        onClick={() => setShowAdvanced(!showAdvanced)}
        className="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-700"
      >
        {showAdvanced ? (
          <ChevronUp className="w-4 h-4" />
        ) : (
          <ChevronDown className="w-4 h-4" />
        )}
        {showAdvanced ? "Hide" : "Show"} advanced options
      </button>

      {showAdvanced && (
        <div className="space-y-4 p-4 bg-gray-50 rounded-lg">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Author
              </label>
              <input
                type="text"
                value={sharedData.author}
                onChange={(e) => handleSharedChange("author", e.target.value)}
                className="w-full px-3 py-2 border rounded-lg text-sm"
              />
            </div>
            <div className="flex items-center">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={sharedData.featured}
                  onChange={(e) =>
                    handleSharedChange("featured", e.target.checked)
                  }
                  className="w-4 h-4 text-brand-green rounded"
                />
                <span className="text-sm font-medium text-gray-700">
                  Featured post
                </span>
              </label>
            </div>
          </div>

          <div className="flex items-center gap-2 text-sm text-gray-600 bg-white p-3 rounded border">
            <Sparkles className="w-4 h-4 text-brand-green" />
            AI will generate a cover image automatically
          </div>
        </div>
      )}
    </div>
  );

  const renderFullForm = () => (
    <div className="space-y-6">
      {/* Language Toggle */}
      {!isEdit && (
        <div className="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-xl p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Globe className="w-5 h-5 text-blue-600" />
              <div>
                <p className="font-semibold text-gray-900">Bilingual Post</p>
                <p className="text-sm text-gray-600">
                  Create both English and Arabic versions
                </p>
              </div>
            </div>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={createBothLanguages}
                onChange={(e) => setCreateBothLanguages(e.target.checked)}
                className="sr-only peer"
              />
              <div className="w-11 h-6 bg-gray-300 rounded-full peer peer-checked:bg-brand-green peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all" />
            </label>
          </div>
        </div>
      )}

      {/* Language Tabs */}
      <div className="border-b border-gray-200">
        <nav className="flex -mb-px">
          <button
            type="button"
            onClick={() => setActiveTab("en")}
            className={`flex items-center gap-2 px-6 py-3 font-semibold text-sm border-b-2 transition ${
              activeTab === "en"
                ? "border-brand-green text-brand-green"
                : "border-transparent text-gray-500 hover:text-gray-700"
            }`}
          >
            English
            {createBothLanguages && enContent.title && (
              <span className="w-2 h-2 bg-green-500 rounded-full" />
            )}
          </button>
          <button
            type="button"
            onClick={() => setActiveTab("ar")}
            className={`flex items-center gap-2 px-6 py-3 font-semibold text-sm border-b-2 transition ${
              activeTab === "ar"
                ? "border-brand-green text-brand-green"
                : "border-transparent text-gray-500 hover:text-gray-700"
            }`}
          >
            Arabic
            {createBothLanguages && arContent.title && (
              <span className="w-2 h-2 bg-green-500 rounded-full" />
            )}
          </button>
        </nav>
      </div>

      {/* Content Form */}
      <div
        className={`space-y-5 ${activeTab === "ar" ? "text-right" : ""}`}
        dir={activeTab === "ar" ? "rtl" : "ltr"}
      >
        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2">
            {activeTab === "ar" ? "العنوان *" : "Title *"}
          </label>
          <input
            type="text"
            value={activeTab === "en" ? enContent.title : arContent.title}
            onChange={(e) =>
              activeTab === "en"
                ? handleEnChange("title", e.target.value)
                : handleArChange("title", e.target.value)
            }
            className="w-full px-4 py-2.5 border rounded-lg focus:ring-2 focus:ring-brand-green"
            required
            minLength={5}
          />
        </div>

        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2">
            {activeTab === "ar" ? "رابط URL *" : "URL Slug *"}
          </label>
          <input
            type="text"
            value={activeTab === "en" ? enContent.slug : arContent.slug}
            onChange={(e) =>
              activeTab === "en"
                ? handleEnChange("slug", e.target.value)
                : handleArChange("slug", e.target.value)
            }
            className="w-full px-4 py-2.5 border rounded-lg focus:ring-2 focus:ring-brand-green font-mono text-sm"
            required
          />
        </div>

        <div>
          <label className="block text-sm font-semibold text-gray-700 mb-2">
            {activeTab === "ar" ? "الملخص *" : "Excerpt *"}
          </label>
          <textarea
            value={activeTab === "en" ? enContent.excerpt : arContent.excerpt}
            onChange={(e) =>
              activeTab === "en"
                ? handleEnChange("excerpt", e.target.value)
                : handleArChange("excerpt", e.target.value)
            }
            className="w-full px-4 py-2.5 border rounded-lg focus:ring-2 focus:ring-brand-green"
            required
            rows={3}
          />
        </div>

        <div>
          <div className="flex items-center justify-between mb-2">
            <label className="block text-sm font-semibold text-gray-700">
              {activeTab === "ar" ? "المحتوى *" : "Content *"}
            </label>
            {!isEdit && (
              <button
                type="button"
                onClick={() => setShowTemplateSelector(true)}
                className="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-brand-green bg-brand-green/10 hover:bg-brand-green/20 rounded-lg transition"
              >
                <FileText className="w-4 h-4" />
                {activeTab === "ar" ? "استخدام قالب" : "Use Template"}
              </button>
            )}
          </div>
          <textarea
            value={activeTab === "en" ? enContent.content : arContent.content}
            onChange={(e) =>
              activeTab === "en"
                ? handleEnChange("content", e.target.value)
                : handleArChange("content", e.target.value)
            }
            className="w-full px-4 py-2.5 border rounded-lg focus:ring-2 focus:ring-brand-green font-mono text-sm"
            required
            rows={10}
          />
        </div>
      </div>

      {/* Shared Settings */}
      <div className="border-t pt-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Settings</h3>

        <div className="grid grid-cols-2 gap-4 mb-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Author
            </label>
            <input
              type="text"
              value={sharedData.author}
              onChange={(e) => handleSharedChange("author", e.target.value)}
              className="w-full px-3 py-2 border rounded-lg"
              required
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Tags
            </label>
            <input
              type="text"
              value={sharedData.tags}
              onChange={(e) => handleSharedChange("tags", e.target.value)}
              className="w-full px-3 py-2 border rounded-lg"
              placeholder="tag1, tag2"
            />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Status
            </label>
            <select
              value={sharedData.status}
              onChange={(e) => handleSharedChange("status", e.target.value)}
              className="w-full px-3 py-2 border rounded-lg"
            >
              <option value="DRAFT">Draft</option>
              <option value="PUBLISHED">Published</option>
              <option value="ARCHIVED">Archived</option>
            </select>
          </div>
          <div className="flex items-center">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={sharedData.featured}
                onChange={(e) =>
                  handleSharedChange("featured", e.target.checked)
                }
                className="w-4 h-4 text-brand-green rounded"
              />
              <span className="text-sm font-medium text-gray-700">
                Featured Post
              </span>
            </label>
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4 overflow-y-auto">
      <div className="bg-white rounded-xl shadow-2xl max-w-4xl w-full my-8 max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b flex-shrink-0">
          <div className="flex items-center gap-4">
            <h2 className="text-2xl font-bold text-gray-900">
              {isEdit ? "Edit Blog Post" : "Create Blog Post"}
            </h2>

            {/* Mode switcher (only for create) */}
            {!isEdit && (
              <div className="flex bg-gray-100 rounded-lg p-1">
                <button
                  type="button"
                  onClick={() => setCreateMode("quick")}
                  className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-md transition ${
                    createMode === "quick"
                      ? "bg-white text-brand-green shadow-sm"
                      : "text-gray-600 hover:text-gray-900"
                  }`}
                >
                  <Zap className="w-4 h-4" />
                  Quick
                </button>
                <button
                  type="button"
                  onClick={() => setCreateMode("full")}
                  className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-md transition ${
                    createMode === "full"
                      ? "bg-white text-brand-green shadow-sm"
                      : "text-gray-600 hover:text-gray-900"
                  }`}
                >
                  <Languages className="w-4 h-4" />
                  Full
                </button>
              </div>
            )}
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto">
          <div className="p-6">
            {/* Bilingual toggle for quick mode */}
            {createMode === "quick" && !isEdit && (
              <div className="mb-6 flex items-center justify-between p-3 bg-blue-50 border border-blue-200 rounded-lg">
                <div className="flex items-center gap-2">
                  <Languages className="w-4 h-4 text-blue-600" />
                  <span className="text-sm font-medium text-gray-900">
                    Create in both languages
                  </span>
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={createBothLanguages}
                    onChange={(e) => setCreateBothLanguages(e.target.checked)}
                    className="sr-only peer"
                  />
                  <div className="w-9 h-5 bg-gray-300 rounded-full peer peer-checked:bg-blue-600 peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all" />
                </label>
              </div>
            )}

            {createMode === "quick" && !isEdit
              ? renderQuickCreateForm()
              : renderFullForm()}
          </div>

          {/* Footer */}
          <div className="flex items-center justify-between gap-3 p-6 border-t bg-gray-50 flex-shrink-0">
            <div className="text-sm text-gray-600">
              {saveProgress && (
                <span className="flex items-center gap-2 text-brand-green">
                  <Loader2 className="w-4 h-4 animate-spin" />
                  {saveProgress}
                </span>
              )}
              {!saveProgress && createBothLanguages && !isEdit && (
                <span className="flex items-center gap-2">
                  <Languages className="w-4 h-4" />
                  Will create 2 posts (EN + AR)
                </span>
              )}
            </div>

            <div className="flex items-center gap-3">
              <button
                type="button"
                onClick={onClose}
                className="px-6 py-2.5 border border-gray-300 rounded-lg hover:bg-gray-100 transition font-medium"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={saving}
                className="px-6 py-2.5 bg-brand-green text-white rounded-lg hover:bg-emerald-600 disabled:opacity-50 disabled:cursor-not-allowed transition font-semibold flex items-center gap-2"
              >
                {saving ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Saving...
                  </>
                ) : (
                  <>
                    <Save className="w-4 h-4" />
                    {isEdit
                      ? "Update Post"
                      : sharedData.status === "PUBLISHED"
                        ? "Publish Now"
                        : "Save Draft"}
                  </>
                )}
              </button>
            </div>
          </div>
        </form>
      </div>

      {/* Template Selector Modal */}
      {showTemplateSelector && (
        <TemplateSelector
          onSelect={handleTemplateSelect}
          onClose={() => setShowTemplateSelector(false)}
          activeLanguage={activeTab}
        />
      )}
    </div>
  );
}
