"use client";

import { useState, useTransition } from "react";
import Image from "next/image";
import {
  BookOpen, Tag, Images, Building2, MessageSquare, Users,
  Plus, Edit2, Trash2, X, CheckCircle, XCircle, Loader2,
  Eye, EyeOff, Star, StarOff, Mail, Calendar
} from "lucide-react";
import {
  saveCategoryAction, deleteCategoryAction,
  saveJournalAction, deleteJournalAction, toggleJournalFeatured,
  importPublicSeedJournalsAction,
  saveSlideAction, deleteSlideAction,
  savePublicationAction, deletePublicationAction,
  saveTestimonialAction, deleteTestimonialAction,
  toggleSubscriberActive, deleteSubscriberAction,
} from "./actions";

// ── Types ─────────────────────────────────────────────────────────────────────

type Category = { id: string; name: string; slug: string };
type Journal = {
  id: string; title: string; slug: string; excerpt: string | null; content: string;
  coverImage: string | null; status: string; isFeatured: boolean;
  createdAt: string; publishedAt: string | null;
  category: Category | null;
  author: { name: string; email: string };
};
type Slide = {
  id: string; imageUrl: string; title: string | null; subtitle: string | null;
  ctaText: string | null; ctaLink: string | null; isActive: boolean; sortOrder: number;
};
type Publication = {
  id: string; name: string; description: string | null; logoUrl: string | null;
  websiteUrl: string | null; isActive: boolean; sortOrder: number;
};
type Testimonial = {
  id: string; name: string; position: string | null; company: string | null;
  content: string; avatarUrl: string | null; rating: number; isActive: boolean;
};
type Subscriber = {
  id: string; email: string; name: string | null; institution: string | null;
  interests: string | null; isActive: boolean; subscribedAt: string;
};

type Props = {
  journals: Journal[];
  categories: Category[];
  slides: Slide[];
  publications: Publication[];
  testimonials: Testimonial[];
  subscribers: Subscriber[];
  adminUserId: string;
};

const TABS = [
  { id: "journals", label: "Journals", icon: BookOpen },
  { id: "categories", label: "Categories", icon: Tag },
  { id: "slider", label: "Slider", icon: Images },
  { id: "publications", label: "Publications", icon: Building2 },
  { id: "testimonials", label: "Testimonials", icon: MessageSquare },
  { id: "subscribers", label: "Subscribers", icon: Users },
] as const;
type TabId = (typeof TABS)[number]["id"];

const STATUS_COLORS: Record<string, string> = {
  draft: "bg-neutral-100 text-neutral-600",
  published: "bg-emerald-100 text-emerald-700",
  flagged: "bg-red-100 text-red-700",
};

// ── Helpers ───────────────────────────────────────────────────────────────────

function useToast() {
  const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
  function show(type: "ok" | "err", text: string) {
    setMsg({ type, text });
    setTimeout(() => setMsg(null), 4000);
  }
  const Toast = msg ? (
    <div className={`fixed bottom-6 right-6 z-50 flex items-center gap-2.5 px-4 py-3 rounded-xl shadow-lg text-sm font-medium border ${msg.type === "ok" ? "bg-emerald-50 text-emerald-800 border-emerald-200" : "bg-red-50 text-red-700 border-red-200"}`}>
      {msg.type === "ok" ? <CheckCircle size={16} /> : <XCircle size={16} />}
      {msg.text}
    </div>
  ) : null;
  return { show, Toast };
}

function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: React.ReactNode }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-neutral-100">
          <h3 className="font-bold text-neutral-800">{title}</h3>
          <button onClick={onClose} className="text-neutral-400 hover:text-neutral-600"><X size={18} /></button>
        </div>
        <div className="p-6">{children}</div>
      </div>
    </div>
  );
}

function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="block text-sm font-medium text-neutral-700 mb-1.5">{label}</label>
      {children}
      {hint && <p className="text-xs text-neutral-500 mt-1">{hint}</p>}
    </div>
  );
}

function normalizeImageSrc(value: string | null | undefined): string {
  const input = (value ?? "").trim();
  if (!input) return "";
  if (input.startsWith("http://") || input.startsWith("https://") || input.startsWith("data:") || input.startsWith("blob:")) {
    return input;
  }
  if (input.startsWith("//")) {
    return `https:${input}`;
  }
  if (input.startsWith("/")) {
    return input;
  }
  return `/${input}`;
}

// ── Main Component ────────────────────────────────────────────────────────────

export default function AdminJournalsClient(props: Props) {
  const [tab, setTab] = useState<TabId>("journals");
  const { show, Toast } = useToast();
  const [isPending, startTransition] = useTransition();

  // Journals
  const [journalModal, setJournalModal] = useState<Journal | "new" | null>(null);
  const [journalForm, setJournalForm] = useState({ title: "", slug: "", excerpt: "", content: "", coverImage: "", categoryId: "", status: "draft", isFeatured: false });

  // Categories
  const [categoryModal, setCategoryModal] = useState<Category | "new" | null>(null);
  const [categoryForm, setCategoryForm] = useState({ name: "", slug: "" });

  // Slides
  const [slideModal, setSlideModal] = useState<Slide | "new" | null>(null);
  const [slideForm, setSlideForm] = useState({ imageUrl: "", title: "", subtitle: "", ctaText: "", ctaLink: "", sortOrder: 0, isActive: true });
  const [slideFile, setSlideFile] = useState<File | null>(null);

  // Publications
  const [publicationModal, setPublicationModal] = useState<Publication | "new" | null>(null);
  const [publicationForm, setPublicationForm] = useState({ name: "", description: "", logoUrl: "", websiteUrl: "", sortOrder: 0, isActive: true });

  // Testimonials
  const [testimonialModal, setTestimonialModal] = useState<Testimonial | "new" | null>(null);
  const [testimonialForm, setTestimonialForm] = useState({ name: "", position: "", company: "", content: "", avatarUrl: "", rating: 5, isActive: true });

  // ── Handlers ──────────────────────────────────────────────────────────────

  function openJournalModal(j: Journal | "new") {
    if (j === "new") {
      setJournalForm({ title: "", slug: "", excerpt: "", content: "", coverImage: "", categoryId: "", status: "draft", isFeatured: false });
    } else {
      setJournalForm({ title: j.title, slug: j.slug, excerpt: j.excerpt || "", content: j.content, coverImage: j.coverImage || "", categoryId: j.category?.id || "", status: j.status, isFeatured: j.isFeatured });
    }
    setJournalModal(j);
  }

  function openCategoryModal(c: Category | "new") {
    if (c === "new") {
      setCategoryForm({ name: "", slug: "" });
    } else {
      setCategoryForm({ name: c.name, slug: c.slug });
    }
    setCategoryModal(c);
  }

  function openSlideModal(s: Slide | "new") {
    if (s === "new") {
      setSlideForm({ imageUrl: "", title: "", subtitle: "", ctaText: "", ctaLink: "", sortOrder: 0, isActive: true });
    } else {
      setSlideForm({ imageUrl: s.imageUrl, title: s.title || "", subtitle: s.subtitle || "", ctaText: s.ctaText || "", ctaLink: s.ctaLink || "", sortOrder: s.sortOrder, isActive: s.isActive });
    }
    setSlideFile(null);
    setSlideModal(s);
  }

  function openPublicationModal(p: Publication | "new") {
    if (p === "new") {
      setPublicationForm({ name: "", description: "", logoUrl: "", websiteUrl: "", sortOrder: 0, isActive: true });
    } else {
      setPublicationForm({ name: p.name, description: p.description || "", logoUrl: p.logoUrl || "", websiteUrl: p.websiteUrl || "", sortOrder: p.sortOrder, isActive: p.isActive });
    }
    setPublicationModal(p);
  }

  function openTestimonialModal(t: Testimonial | "new") {
    if (t === "new") {
      setTestimonialForm({ name: "", position: "", company: "", content: "", avatarUrl: "", rating: 5, isActive: true });
    } else {
      setTestimonialForm({ name: t.name, position: t.position || "", company: t.company || "", content: t.content, avatarUrl: t.avatarUrl || "", rating: t.rating, isActive: t.isActive });
    }
    setTestimonialModal(t);
  }

  async function handleJournalSubmit(e: React.FormEvent) {
    e.preventDefault();
    const form = new FormData();
    if (journalModal !== "new") form.append("id", (journalModal as Journal).id);
    form.append("title", journalForm.title);
    form.append("slug", journalForm.slug);
    form.append("excerpt", journalForm.excerpt);
    form.append("content", journalForm.content);
    form.append("coverImage", journalForm.coverImage);
    form.append("categoryId", journalForm.categoryId);
    form.append("status", journalForm.status);
    form.append("authorId", props.adminUserId);
    form.append("isFeatured", journalForm.isFeatured.toString());

    startTransition(async () => {
      const res = await saveJournalAction(form);
      if (res.ok) {
        show("ok", journalModal === "new" ? "Journal created!" : "Journal updated!");
        setJournalModal(null);
      } else {
        show("err", res.error || "Failed to save journal");
      }
    });
  }

  async function handleCategorySubmit(e: React.FormEvent) {
    e.preventDefault();
    const form = new FormData();
    if (categoryModal !== "new") form.append("id", (categoryModal as Category).id);
    form.append("name", categoryForm.name);
    form.append("slug", categoryForm.slug);

    startTransition(async () => {
      const res = await saveCategoryAction(form);
      if (res.ok) {
        show("ok", categoryModal === "new" ? "Category created!" : "Category updated!");
        setCategoryModal(null);
      } else {
        show("err", res.error || "Failed to save category");
      }
    });
  }

  async function handleSlideSubmit(e: React.FormEvent) {
    e.preventDefault();
    const form = new FormData();
    if (slideModal !== "new") form.append("id", (slideModal as Slide).id);
    form.append("imageUrl", slideForm.imageUrl);
    if (slideFile) form.append("imageFile", slideFile);
    form.append("title", slideForm.title);
    form.append("subtitle", slideForm.subtitle);
    form.append("ctaText", slideForm.ctaText);
    form.append("ctaLink", slideForm.ctaLink);
    form.append("sortOrder", slideForm.sortOrder.toString());
    form.append("isActive", slideForm.isActive.toString());

    startTransition(async () => {
      const res = await saveSlideAction(form);
      if (res.ok) {
        show("ok", slideModal === "new" ? "Slide created!" : "Slide updated!");
        setSlideModal(null);
      } else {
        show("err", res.error || "Failed to save slide");
      }
    });
  }

  async function handlePublicationSubmit(e: React.FormEvent) {
    e.preventDefault();
    const form = new FormData();
    if (publicationModal !== "new") form.append("id", (publicationModal as Publication).id);
    form.append("name", publicationForm.name);
    form.append("description", publicationForm.description);
    form.append("logoUrl", publicationForm.logoUrl);
    form.append("websiteUrl", publicationForm.websiteUrl);
    form.append("sortOrder", publicationForm.sortOrder.toString());
    form.append("isActive", publicationForm.isActive.toString());

    startTransition(async () => {
      const res = await savePublicationAction(form);
      if (res.ok) {
        show("ok", publicationModal === "new" ? "Publication created!" : "Publication updated!");
        setPublicationModal(null);
      } else {
        show("err", res.error || "Failed to save publication");
      }
    });
  }

  async function handleTestimonialSubmit(e: React.FormEvent) {
    e.preventDefault();
    const form = new FormData();
    if (testimonialModal !== "new") form.append("id", (testimonialModal as Testimonial).id);
    form.append("name", testimonialForm.name);
    form.append("position", testimonialForm.position);
    form.append("company", testimonialForm.company);
    form.append("content", testimonialForm.content);
    form.append("avatarUrl", testimonialForm.avatarUrl);
    form.append("rating", testimonialForm.rating.toString());
    form.append("isActive", testimonialForm.isActive.toString());

    startTransition(async () => {
      const res = await saveTestimonialAction(form);
      if (res.ok) {
        show("ok", testimonialModal === "new" ? "Testimonial created!" : "Testimonial updated!");
        setTestimonialModal(null);
      } else {
        show("err", res.error || "Failed to save testimonial");
      }
    });
  }

  return (
    <div className="p-8">
      {Toast}
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-neutral-900">Journal Management</h1>
        <p className="text-neutral-500 text-sm mt-0.5">Manage journals, categories, slider, publications, testimonials & subscribers</p>
      </div>

      {/* Tabs */}
      <div className="flex gap-2 mb-6 border-b border-neutral-200">
        {TABS.map((t) => {
          const Icon = t.icon;
          return (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={`flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${tab === t.id ? "border-navy-600 text-navy-700" : "border-transparent text-neutral-500 hover:text-neutral-700"}`}
            >
              <Icon size={16} />
              {t.label}
            </button>
          );
        })}
      </div>

      {/* Journals Tab */}
      {tab === "journals" && (
        <div>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-neutral-800">Journals ({props.journals.length})</h2>
            <div className="flex items-center gap-2">
              <button
                onClick={() => startTransition(async () => {
                  const res = await importPublicSeedJournalsAction();
                  if (res.ok) {
                    show("ok", `Imported ${res.imported} and updated ${res.updated} journals.`);
                  } else {
                    show("err", res.error || "Failed to import journals");
                  }
                })}
                className="flex items-center gap-2 px-4 py-2.5 bg-emerald-600 text-white text-sm font-semibold rounded-lg hover:bg-emerald-700 disabled:opacity-60"
                disabled={isPending}
              >
                {isPending ? <Loader2 size={16} className="animate-spin" /> : <BookOpen size={16} />} Import Public Journals
              </button>
              <button onClick={() => openJournalModal("new")} className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800">
                <Plus size={16} /> Add Journal
              </button>
            </div>
          </div>
          <div className="grid gap-4">
            {props.journals.map((j) => (
              <div key={j.id} className="bg-white border border-neutral-200 rounded-xl p-4 flex items-start justify-between gap-4">
                <div className="w-20 h-14 rounded-lg overflow-hidden bg-neutral-100 shrink-0">
                  {normalizeImageSrc(j.coverImage) ? (
                    <img
                      src={normalizeImageSrc(j.coverImage)}
                      alt={j.title}
                      className="w-full h-full object-cover"
                      onError={(e) => {
                        e.currentTarget.style.display = "none";
                      }}
                    />
                  ) : null}
                </div>
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-2">
                    <h3 className="font-semibold text-neutral-900">{j.title}</h3>
                    <span className={`px-2 py-0.5 text-xs font-medium rounded-full ${STATUS_COLORS[j.status]}`}>{j.status}</span>
                    {j.isFeatured && <Star size={14} className="text-amber-500 fill-amber-500" />}
                  </div>
                  <p className="text-sm text-neutral-600 mb-2">{j.excerpt || "No excerpt"}</p>
                  <div className="flex items-center gap-3 text-xs text-neutral-500">
                    <span>{j.category?.name || "Uncategorized"}</span>
                    <span>•</span>
                    <span>By {j.author.name}</span>
                    <span>•</span>
                    <span>{new Date(j.createdAt).toLocaleDateString()}</span>
                  </div>
                </div>
                <div className="flex gap-2">
                  <button onClick={() => startTransition(async () => {
                    const res = await toggleJournalFeatured(j.id, !j.isFeatured);
                    if (res.ok) show("ok", j.isFeatured ? "Removed from featured" : "Featured!");
                  })} className="p-2 text-neutral-400 hover:text-amber-600">
                    {j.isFeatured ? <StarOff size={16} /> : <Star size={16} />}
                  </button>
                  <button onClick={() => openJournalModal(j)} className="p-2 text-neutral-400 hover:text-blue-600">
                    <Edit2 size={16} />
                  </button>
                  <button onClick={() => startTransition(async () => {
                    if (confirm("Delete this journal?")) {
                      const res = await deleteJournalAction(j.id);
                      if (res.ok) show("ok", "Journal deleted!");
                    }
                  })} className="p-2 text-neutral-400 hover:text-red-600">
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Categories Tab */}
      {tab === "categories" && (
        <div>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-neutral-800">Categories ({props.categories.length})</h2>
            <button onClick={() => openCategoryModal("new")} className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800">
              <Plus size={16} /> Add Category
            </button>
          </div>
          <div className="grid gap-3">
            {props.categories.map((c) => (
              <div key={c.id} className="bg-white border border-neutral-200 rounded-xl p-4 flex items-center justify-between">
                <div>
                  <h3 className="font-semibold text-neutral-900">{c.name}</h3>
                  <p className="text-sm text-neutral-500">/{c.slug}</p>
                </div>
                <div className="flex gap-2">
                  <button onClick={() => openCategoryModal(c)} className="p-2 text-neutral-400 hover:text-blue-600">
                    <Edit2 size={16} />
                  </button>
                  <button onClick={() => startTransition(async () => {
                    if (confirm("Delete this category?")) {
                      const res = await deleteCategoryAction(c.id);
                      if (res.ok) show("ok", "Category deleted!");
                      else show("err", "Cannot delete category with journals");
                    }
                  })} className="p-2 text-neutral-400 hover:text-red-600">
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Slider Tab */}
      {tab === "slider" && (
        <div>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-neutral-800">Journal Slider ({props.slides.length})</h2>
            <button onClick={() => openSlideModal("new")} className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800">
              <Plus size={16} /> Add Slide
            </button>
          </div>
          <div className="grid gap-4">
            {props.slides.map((s) => (
              <div key={s.id} className="bg-white border border-neutral-200 rounded-xl p-4 flex items-start gap-4">
                <Image
                  src={normalizeImageSrc(s.imageUrl)}
                  alt={s.title || "Slide"}
                  width={128}
                  height={80}
                  className="w-32 h-20 object-cover rounded-lg"
                />
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <h3 className="font-semibold text-neutral-900">{s.title || "Untitled"}</h3>
                    {s.isActive ? <Eye size={14} className="text-emerald-600" /> : <EyeOff size={14} className="text-neutral-400" />}
                  </div>
                  <p className="text-sm text-neutral-600 mb-1">{s.subtitle}</p>
                  <p className="text-xs text-neutral-500">Order: {s.sortOrder}</p>
                </div>
                <div className="flex gap-2">
                  <button onClick={() => openSlideModal(s)} className="p-2 text-neutral-400 hover:text-blue-600">
                    <Edit2 size={16} />
                  </button>
                  <button onClick={() => startTransition(async () => {
                    if (confirm("Delete this slide?")) {
                      const res = await deleteSlideAction(s.id);
                      if (res.ok) show("ok", "Slide deleted!");
                    }
                  })} className="p-2 text-neutral-400 hover:text-red-600">
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Publications Tab */}
      {tab === "publications" && (
        <div>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-neutral-800">Publications ({props.publications.length})</h2>
            <button onClick={() => openPublicationModal("new")} className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800">
              <Plus size={16} /> Add Publication
            </button>
          </div>
          <div className="grid gap-3">
            {props.publications.map((p) => (
              <div key={p.id} className="bg-white border border-neutral-200 rounded-xl p-4 flex items-center justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-1">
                    <h3 className="font-semibold text-neutral-900">{p.name}</h3>
                    {p.isActive ? <Eye size={14} className="text-emerald-600" /> : <EyeOff size={14} className="text-neutral-400" />}
                  </div>
                  <p className="text-sm text-neutral-600">{p.description || "No description"}</p>
                  {p.websiteUrl && <a href={p.websiteUrl} target="_blank" rel="noopener noreferrer" className="text-xs text-blue-600 hover:underline">{p.websiteUrl}</a>}
                </div>
                <div className="flex gap-2">
                  <button onClick={() => openPublicationModal(p)} className="p-2 text-neutral-400 hover:text-blue-600">
                    <Edit2 size={16} />
                  </button>
                  <button onClick={() => startTransition(async () => {
                    if (confirm("Delete this publication?")) {
                      const res = await deletePublicationAction(p.id);
                      if (res.ok) show("ok", "Publication deleted!");
                    }
                  })} className="p-2 text-neutral-400 hover:text-red-600">
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Testimonials Tab */}
      {tab === "testimonials" && (
        <div>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-neutral-800">Testimonials ({props.testimonials.length})</h2>
            <button onClick={() => openTestimonialModal("new")} className="flex items-center gap-2 px-4 py-2.5 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800">
              <Plus size={16} /> Add Testimonial
            </button>
          </div>
          <div className="grid gap-4">
            {props.testimonials.map((t) => (
              <div key={t.id} className="bg-white border border-neutral-200 rounded-xl p-4">
                <div className="flex items-start justify-between gap-4 mb-3">
                  <div className="flex items-start gap-3">
                    <div className="w-12 h-12 rounded-full bg-neutral-200 flex-shrink-0" />
                    <div>
                      <h3 className="font-semibold text-neutral-900">{t.name}</h3>
                      <p className="text-sm text-neutral-600">{t.position}{t.company && `, ${t.company}`}</p>
                      <div className="flex items-center gap-1 mt-1">
                        {Array.from({ length: t.rating }).map((_, i) => <Star key={i} size={12} className="text-amber-500 fill-amber-500" />)}
                      </div>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <button onClick={() => openTestimonialModal(t)} className="p-2 text-neutral-400 hover:text-blue-600">
                      <Edit2 size={16} />
                    </button>
                    <button onClick={() => startTransition(async () => {
                      if (confirm("Delete this testimonial?")) {
                        const res = await deleteTestimonialAction(t.id);
                        if (res.ok) show("ok", "Testimonial deleted!");
                      }
                    })} className="p-2 text-neutral-400 hover:text-red-600">
                      <Trash2 size={16} />
                    </button>
                  </div>
                </div>
                <p className="text-sm text-neutral-700">{t.content}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Subscribers Tab */}
      {tab === "subscribers" && (
        <div>
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-neutral-800">Journal Subscribers ({props.subscribers.length})</h2>
          </div>
          <div className="bg-white border border-neutral-200 rounded-xl overflow-hidden">
            <table className="w-full">
              <thead className="bg-neutral-50 border-b border-neutral-200">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-neutral-500 uppercase">Email</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-neutral-500 uppercase">Name</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-neutral-500 uppercase">Institution</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-neutral-500 uppercase">Subscribed</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-neutral-500 uppercase">Status</th>
                  <th className="px-4 py-3 text-right text-xs font-medium text-neutral-500 uppercase">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-neutral-100">
                {props.subscribers.map((s) => (
                  <tr key={s.id} className="hover:bg-neutral-50">
                    <td className="px-4 py-3 text-sm text-neutral-900">{s.email}</td>
                    <td className="px-4 py-3 text-sm text-neutral-600">{s.name || "-"}</td>
                    <td className="px-4 py-3 text-sm text-neutral-600">{s.institution || "-"}</td>
                    <td className="px-4 py-3 text-sm text-neutral-600">{new Date(s.subscribedAt).toLocaleDateString()}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex px-2 py-0.5 text-xs font-medium rounded-full ${s.isActive ? "bg-emerald-100 text-emerald-700" : "bg-neutral-100 text-neutral-600"}`}>
                        {s.isActive ? "Active" : "Inactive"}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-right">
                      <div className="flex gap-2 justify-end">
                        <button onClick={() => startTransition(async () => {
                          const res = await toggleSubscriberActive(s.id, !s.isActive);
                          if (res.ok) show("ok", s.isActive ? "Deactivated" : "Activated");
                        })} className="p-2 text-neutral-400 hover:text-blue-600">
                          {s.isActive ? <EyeOff size={16} /> : <Eye size={16} />}
                        </button>
                        <button onClick={() => startTransition(async () => {
                          if (confirm("Delete this subscriber?")) {
                            const res = await deleteSubscriberAction(s.id);
                            if (res.ok) show("ok", "Subscriber deleted!");
                          }
                        })} className="p-2 text-neutral-400 hover:text-red-600">
                          <Trash2 size={16} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Journal Modal */}
      {journalModal && (
        <Modal title={journalModal === "new" ? "Add Journal" : "Edit Journal"} onClose={() => setJournalModal(null)}>
          <form onSubmit={handleJournalSubmit} className="space-y-4">
            <Field label="Title">
              <input value={journalForm.title} onChange={e => setJournalForm({ ...journalForm, title: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" required />
            </Field>
            <Field label="Slug">
              <input value={journalForm.slug} onChange={e => setJournalForm({ ...journalForm, slug: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" required />
            </Field>
            <Field label="Excerpt">
              <textarea value={journalForm.excerpt} onChange={e => setJournalForm({ ...journalForm, excerpt: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" rows={2} />
            </Field>
            <Field label="Content">
              <textarea value={journalForm.content} onChange={e => setJournalForm({ ...journalForm, content: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" rows={6} required />
            </Field>
            <Field label="Cover Image URL">
              <input value={journalForm.coverImage} onChange={e => setJournalForm({ ...journalForm, coverImage: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <Field label="Category">
              <select value={journalForm.categoryId} onChange={e => setJournalForm({ ...journalForm, categoryId: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg">
                <option value="">Uncategorized</option>
                {props.categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </Field>
            <Field label="Status">
              <select value={journalForm.status} onChange={e => setJournalForm({ ...journalForm, status: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg">
                <option value="draft">Draft</option>
                <option value="published">Published</option>
                <option value="flagged">Flagged</option>
              </select>
            </Field>
            <label className="flex items-center gap-2">
              <input type="checkbox" checked={journalForm.isFeatured} onChange={e => setJournalForm({ ...journalForm, isFeatured: e.target.checked })} />
              <span className="text-sm text-neutral-700">Featured</span>
            </label>
            <div className="flex gap-3 justify-end pt-2">
              <button type="button" onClick={() => setJournalModal(null)} className="px-4 py-2 text-sm font-medium text-neutral-600 hover:text-neutral-800">Cancel</button>
              <button type="submit" disabled={isPending} className="px-4 py-2 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800 disabled:opacity-50">
                {isPending ? <Loader2 className="animate-spin" size={16} /> : journalModal === "new" ? "Create" : "Update"}
              </button>
            </div>
          </form>
        </Modal>
      )}

      {/* Category Modal */}
      {categoryModal && (
        <Modal title={categoryModal === "new" ? "Add Category" : "Edit Category"} onClose={() => setCategoryModal(null)}>
          <form onSubmit={handleCategorySubmit} className="space-y-4">
            <Field label="Name">
              <input value={categoryForm.name} onChange={e => setCategoryForm({ ...categoryForm, name: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" required />
            </Field>
            <Field label="Slug">
              <input value={categoryForm.slug} onChange={e => setCategoryForm({ ...categoryForm, slug: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" required />
            </Field>
            <div className="flex gap-3 justify-end pt-2">
              <button type="button" onClick={() => setCategoryModal(null)} className="px-4 py-2 text-sm font-medium text-neutral-600 hover:text-neutral-800">Cancel</button>
              <button type="submit" disabled={isPending} className="px-4 py-2 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800 disabled:opacity-50">
                {isPending ? <Loader2 className="animate-spin" size={16} /> : categoryModal === "new" ? "Create" : "Update"}
              </button>
            </div>
          </form>
        </Modal>
      )}

      {/* Slide Modal */}
      {slideModal && (
        <Modal title={slideModal === "new" ? "Add Slide" : "Edit Slide"} onClose={() => setSlideModal(null)}>
          <form onSubmit={handleSlideSubmit} className="space-y-4">
            <Field label="Image URL">
              <input value={slideForm.imageUrl} onChange={e => setSlideForm({ ...slideForm, imageUrl: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <Field label="Or Upload Image From PC" hint="If you upload a file, it will be used instead of the URL.">
              <input
                type="file"
                accept="image/*"
                onChange={e => setSlideFile(e.target.files?.[0] ?? null)}
                className="w-full px-3 py-2 border border-neutral-200 rounded-lg"
              />
            </Field>
            <Field label="Title">
              <input value={slideForm.title} onChange={e => setSlideForm({ ...slideForm, title: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <Field label="Subtitle">
              <input value={slideForm.subtitle} onChange={e => setSlideForm({ ...slideForm, subtitle: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <Field label="CTA Text">
              <input value={slideForm.ctaText} onChange={e => setSlideForm({ ...slideForm, ctaText: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <Field label="CTA Link">
              <input value={slideForm.ctaLink} onChange={e => setSlideForm({ ...slideForm, ctaLink: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <Field label="Sort Order">
              <input type="number" value={slideForm.sortOrder} onChange={e => setSlideForm({ ...slideForm, sortOrder: parseInt(e.target.value) || 0 })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <label className="flex items-center gap-2">
              <input type="checkbox" checked={slideForm.isActive} onChange={e => setSlideForm({ ...slideForm, isActive: e.target.checked })} />
              <span className="text-sm text-neutral-700">Active</span>
            </label>
            <div className="flex gap-3 justify-end pt-2">
              <button type="button" onClick={() => setSlideModal(null)} className="px-4 py-2 text-sm font-medium text-neutral-600 hover:text-neutral-800">Cancel</button>
              <button type="submit" disabled={isPending} className="px-4 py-2 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800 disabled:opacity-50">
                {isPending ? <Loader2 className="animate-spin" size={16} /> : slideModal === "new" ? "Create" : "Update"}
              </button>
            </div>
          </form>
        </Modal>
      )}

      {/* Publication Modal */}
      {publicationModal && (
        <Modal title={publicationModal === "new" ? "Add Publication" : "Edit Publication"} onClose={() => setPublicationModal(null)}>
          <form onSubmit={handlePublicationSubmit} className="space-y-4">
            <Field label="Name">
              <input value={publicationForm.name} onChange={e => setPublicationForm({ ...publicationForm, name: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" required />
            </Field>
            <Field label="Description">
              <textarea value={publicationForm.description} onChange={e => setPublicationForm({ ...publicationForm, description: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" rows={3} />
            </Field>
            <Field label="Logo URL">
              <input value={publicationForm.logoUrl} onChange={e => setPublicationForm({ ...publicationForm, logoUrl: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <Field label="Website URL">
              <input value={publicationForm.websiteUrl} onChange={e => setPublicationForm({ ...publicationForm, websiteUrl: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <Field label="Sort Order">
              <input type="number" value={publicationForm.sortOrder} onChange={e => setPublicationForm({ ...publicationForm, sortOrder: parseInt(e.target.value) || 0 })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <label className="flex items-center gap-2">
              <input type="checkbox" checked={publicationForm.isActive} onChange={e => setPublicationForm({ ...publicationForm, isActive: e.target.checked })} />
              <span className="text-sm text-neutral-700">Active</span>
            </label>
            <div className="flex gap-3 justify-end pt-2">
              <button type="button" onClick={() => setPublicationModal(null)} className="px-4 py-2 text-sm font-medium text-neutral-600 hover:text-neutral-800">Cancel</button>
              <button type="submit" disabled={isPending} className="px-4 py-2 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800 disabled:opacity-50">
                {isPending ? <Loader2 className="animate-spin" size={16} /> : publicationModal === "new" ? "Create" : "Update"}
              </button>
            </div>
          </form>
        </Modal>
      )}

      {/* Testimonial Modal */}
      {testimonialModal && (
        <Modal title={testimonialModal === "new" ? "Add Testimonial" : "Edit Testimonial"} onClose={() => setTestimonialModal(null)}>
          <form onSubmit={handleTestimonialSubmit} className="space-y-4">
            <Field label="Name">
              <input value={testimonialForm.name} onChange={e => setTestimonialForm({ ...testimonialForm, name: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" required />
            </Field>
            <Field label="Position">
              <input value={testimonialForm.position} onChange={e => setTestimonialForm({ ...testimonialForm, position: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <Field label="Company">
              <input value={testimonialForm.company} onChange={e => setTestimonialForm({ ...testimonialForm, company: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <Field label="Content">
              <textarea value={testimonialForm.content} onChange={e => setTestimonialForm({ ...testimonialForm, content: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" rows={4} required />
            </Field>
            <Field label="Avatar URL">
              <input value={testimonialForm.avatarUrl} onChange={e => setTestimonialForm({ ...testimonialForm, avatarUrl: e.target.value })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg" />
            </Field>
            <Field label="Rating">
              <select value={testimonialForm.rating} onChange={e => setTestimonialForm({ ...testimonialForm, rating: parseInt(e.target.value) })} className="w-full px-3 py-2 border border-neutral-200 rounded-lg">
                {[1, 2, 3, 4, 5].map(r => <option key={r} value={r}>{r} Star{r > 1 ? "s" : ""}</option>)}
              </select>
            </Field>
            <label className="flex items-center gap-2">
              <input type="checkbox" checked={testimonialForm.isActive} onChange={e => setTestimonialForm({ ...testimonialForm, isActive: e.target.checked })} />
              <span className="text-sm text-neutral-700">Active</span>
            </label>
            <div className="flex gap-3 justify-end pt-2">
              <button type="button" onClick={() => setTestimonialModal(null)} className="px-4 py-2 text-sm font-medium text-neutral-600 hover:text-neutral-800">Cancel</button>
              <button type="submit" disabled={isPending} className="px-4 py-2 bg-navy-700 text-white text-sm font-semibold rounded-lg hover:bg-navy-800 disabled:opacity-50">
                {isPending ? <Loader2 className="animate-spin" size={16} /> : testimonialModal === "new" ? "Create" : "Update"}
              </button>
            </div>
          </form>
        </Modal>
      )}
    </div>
  );
}
