"use client";

import { useState, useMemo } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils/cn";
import { magazineApi, adminApi } from "@/lib/api/client";

/* ───── Types matching backend DTOs ───── */

/** "15 जुलाई, 2026" from an ISO date; falls back to the legacy quarter label. */
function issueDateLabel(iso: string | null | undefined, fallback: string): string {
  if (!iso) return fallback || "—";
  const [y, m, d] = iso.split("-").map(Number);
  const months = ["जनवरी","फ़रवरी","मार्च","अप्रैल","मई","जून","जुलाई","अगस्त","सितम्बर","अक्टूबर","नवम्बर","दिसम्बर"];
  return `${d} ${months[m - 1]}, ${y}`;
}

interface PaperResponse {
  id: string;
  referenceNo: string;
  titleHi: string;
  titleEn: string;
  categoryNameHi?: string;
  categoryNameEn?: string;
  authorNameHi?: string;
  authorNameEn?: string;
  status: string;
}

interface MagazinePaperResponse {
  paperId: string;
  titleHi: string;
  titleEn: string;
  authorNameHi: string;
  authorNameEn: string;
  paperOrder: number;
  pageStart?: number;
  pageEnd?: number;
  hasPdf: boolean;
}

interface MagazineResponse {
  id: string;
  volume: number;
  issue: number;
  quarter: string;
  /** ISO date; the journal is dated ("15 July, 2020"), not quartered. Null on old rows. */
  publicationDate?: string | null;
  coverTitleHi?: string;
  coverTitleEn?: string;
  status: "DRAFT" | "READY" | "PUBLISHED";
  downloadCount: number;
  paperCount: number;
  /** True once cover artwork has been uploaded; it becomes page one of the issue. */
  hasCover?: boolean;
  /** Pages in the generated issue; null until it has been generated. */
  pageCount?: number | null;
  publishedAt?: string;
  papers: MagazinePaperResponse[];
}

/* ───── Badge ───── */

function Badge({ color = "gray", children }: { color?: "green" | "indigo" | "amber" | "gray"; children: React.ReactNode }) {
  const colors = { green: "bg-emerald-100 text-emerald-700", indigo: "bg-indigo-100 text-indigo-700", amber: "bg-amber-100 text-amber-700", gray: "bg-gray-100 text-gray-600" };
  return <span className={cn("rounded-full px-2.5 py-1 text-xs font-medium", colors[color])}>{children}</span>;
}

/* ───── Page ───── */

export default function MagazineBuilder() {
  const queryClient = useQueryClient();
  const [tab, setTab] = useState<"builder" | "past">("builder");

  const [volume, setVolume] = useState(5);
  const [issue, setIssue] = useState(2);
  // Sent as an ISO date. It is printed on every page of the issue — running
  // head, sidebar, title page — so it is required for a new issue.
  const [publicationDate, setPublicationDate] = useState("");
  const [coverTitleHi, setCoverTitleHi] = useState("");
  const [coverTitleEn, setCoverTitleEn] = useState("");
  const [editorialHi, setEditorialHi] = useState("");
  // The journal's cover is commissioned artwork, so the editor supplies it.
  // Without one the issue opens on its title page, which is what the printed
  // issue carries immediately inside the cover anyway.
  const [coverFile, setCoverFile] = useState<File | null>(null);
  const [issuePages, setIssuePages] = useState<number | null>(null);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [filterCat, setFilterCat] = useState("all");
  const [generating, setGenerating] = useState(false);
  const [generated, setGenerated] = useState(false);

  // Fetch accepted papers
  const { data: acceptedPapers = [], isLoading: papersLoading } = useQuery<PaperResponse[]>({
    queryKey: ["papers-for-magazine"],
    queryFn: async () => {
      // Fetch both ACCEPTED and PUBLISHED papers for magazine inclusion
      const [accepted, published] = await Promise.all([
        adminApi.papers({ status: "ACCEPTED", size: 100 }),
        adminApi.papers({ status: "PUBLISHED", size: 100 }),
      ]);
      const a: PaperResponse[] = accepted.data?.content ?? accepted.data ?? [];
      const p: PaperResponse[] = published.data?.content ?? published.data ?? [];
      // Deduplicate by id
      const map = new Map<string, PaperResponse>();
      [...a, ...p].forEach(paper => map.set(paper.id, paper));
      return Array.from(map.values());
    },
  });

  // Fetch past issues
  const { data: pastIssues = [], isLoading: issuesLoading } = useQuery<MagazineResponse[]>({
    queryKey: ["past-magazines"],
    queryFn: async () => {
      const res = await magazineApi.list();
      const all: MagazineResponse[] = res.data?.content ?? res.data ?? [];
      return all.sort((a, b) => (b.publishedAt ? new Date(b.publishedAt).getTime() : 0) - (a.publishedAt ? new Date(a.publishedAt).getTime() : 0));
    },
  });

  const [createdMagazineId, setCreatedMagazineId] = useState<string | null>(null);
  const [publishing, setPublishing] = useState(false);

  // Create mutation
  const createMutation = useMutation({
    mutationFn: () => magazineApi.create({ volume, issue, publicationDate: publicationDate || undefined, coverTitleHi: coverTitleHi || undefined, coverTitleEn: coverTitleEn || undefined, editorialHi: editorialHi || undefined, papers: selectedIds.map((id, i) => ({ paperId: id, order: i + 1 })) }),
    onSuccess: (res) => {
      const id = res.data?.id;
      if (id) setCreatedMagazineId(id);
      queryClient.invalidateQueries({ queryKey: ["past-magazines"] });
    },
  });

  // Derived
  const categories = useMemo(() => { const cats = new Set(acceptedPapers.map(p => p.categoryNameHi || p.categoryNameEn || "").filter(Boolean)); return ["all", ...Array.from(cats)]; }, [acceptedPapers]);
  const filteredPapers = filterCat === "all" ? acceptedPapers : acceptedPapers.filter(p => p.categoryNameHi === filterCat || p.categoryNameEn === filterCat);
  const selectedPapers = selectedIds.map(id => acceptedPapers.find(p => p.id === id)).filter(Boolean) as PaperResponse[];
  const estimatedPages = selectedPapers.length * 14;

  // Handlers
  const togglePaper = (id: string) => setSelectedIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  const toggleAll = () => { if (selectedIds.length === acceptedPapers.length) setSelectedIds([]); else setSelectedIds(acceptedPapers.map(p => p.id)); };
  const moveUp = (idx: number) => { if (idx === 0) return; setSelectedIds(prev => { const n = [...prev];[n[idx - 1], n[idx]] = [n[idx], n[idx - 1]]; return n; }); };
  const moveDown = (idx: number) => { if (idx === selectedIds.length - 1) return; setSelectedIds(prev => { const n = [...prev];[n[idx], n[idx + 1]] = [n[idx + 1], n[idx]]; return n; }); };
  const removePaper = (id: string) => setSelectedIds(prev => prev.filter(x => x !== id));

  async function handleGenerate() {
    if (selectedIds.length === 0) { toast.error("कम से कम एक शोधपत्र चुनें / Select at least one paper"); return; }
    setGenerating(true);
    try {
      const createRes = await createMutation.mutateAsync();
      const id = createRes.data?.id;
      if (id) {
        // The cover has to be stored before the issue is laid out: it is page
        // one, and every folio after it depends on whether it is there.
        if (coverFile) await magazineApi.uploadCover(id, coverFile);
        const res = await magazineApi.generatePdfs(id);
        setIssuePages(res.data?.pageCount ?? null);
      }
      setGenerated(true);
      toast.success("PDF तैयार है / PDF generated");
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      toast.error(msg || "PDF बनाने में त्रुटि / Error generating PDF");
    }
    setGenerating(false);
  }

  const resetBuilder = () => { setGenerated(false); setCreatedMagazineId(null); setSelectedIds([]); setCoverTitleHi(""); setCoverTitleEn(""); setEditorialHi(""); setCoverFile(null); setIssuePages(null); };
  const inputCls = "w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500";

  return (
    <div className="mx-auto max-w-7xl px-4 sm:px-6 py-8">
      {/* Header + Tabs */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          {/* The journal is half-yearly — शोध अर्धवार्षिकी — dated 15 January and
              15 July. "Quarterly" was never true of it. */}
          <h1 className="text-2xl font-bold text-gray-900">अर्धवार्षिक पत्रिका <span className="text-lg font-normal text-gray-400">/ Half-yearly Journal</span></h1>
          <p className="mt-0.5 text-sm text-gray-500">प्रकाशित शोधपत्रों को पत्रिका अंक में संकलित करें</p>
        </div>
        <div className="flex gap-2 self-start">
          <button onClick={() => { setTab("builder"); setGenerated(false); }} className={cn("rounded-xl px-4 py-2 text-xs font-medium transition-colors", tab === "builder" ? "bg-indigo-600 text-white" : "border border-gray-200 bg-white text-gray-700 hover:bg-gray-50")}>✏️ नया अंक / Build New</button>
          <button onClick={() => setTab("past")} className={cn("rounded-xl px-4 py-2 text-xs font-medium transition-colors", tab === "past" ? "bg-indigo-600 text-white" : "border border-gray-200 bg-white text-gray-700 hover:bg-gray-50")}>📚 पिछले अंक ({pastIssues.length})</button>
        </div>
      </div>

      {/* PAST ISSUES */}
      {tab === "past" && (
        <div className="overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm">
          <div className="border-b border-gray-100 px-5 py-4"><h2 className="font-semibold text-gray-900">प्रकाशित अंक / Published Issues</h2></div>
          {issuesLoading ? (
            <div className="flex items-center justify-center gap-2 py-12"><Loader2 className="h-5 w-5 animate-spin text-indigo-500" /><span className="text-sm text-gray-400">लोड हो रहा है...</span></div>
          ) : pastIssues.length === 0 ? (
            <div className="py-12 text-center text-sm text-gray-400">कोई अंक नहीं / No issues yet</div>
          ) : (
            <div className="divide-y divide-gray-50">
              {pastIssues.map(iss => (
                <div key={iss.id} className="px-5 py-4 hover:bg-gray-50 transition-colors">
                  <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">
                    <div className="flex h-16 w-14 shrink-0 flex-col items-center justify-center rounded-lg bg-gradient-to-br from-indigo-600 to-blue-500 text-white py-2 px-1">
                      <span className="text-[8px] uppercase tracking-wider opacity-75">AP</span>
                      <span className="text-sm font-bold">{issueDateLabel(iss.publicationDate, iss.quarter)}</span>
                    </div>
                    <div className="flex-1">
                      <p className="text-sm font-semibold text-gray-900">खंड {iss.volume}, अंक {iss.issue}</p>
                      <p className="text-xs text-gray-400">Vol. {iss.volume}, Issue {iss.issue}{iss.coverTitleHi ? ` — ${iss.coverTitleHi}` : ""}</p>
                      <div className="mt-1.5 flex flex-wrap gap-3 text-[10px] text-gray-500">
                        {iss.publishedAt && <span>📅 {new Date(iss.publishedAt).toLocaleDateString("hi-IN", { month: "long", year: "numeric" })}</span>}
                        <span>📄 {iss.paperCount} शोधपत्र</span>
                        {iss.pageCount ? <span>📖 {iss.pageCount} पृष्ठ</span> : null}
                        {iss.hasCover ? <span>🖼️ आवरण</span> : null}
                        <span>⬇️ {iss.downloadCount} डाउनलोड</span>
                      </div>
                    </div>
                    <div className="flex items-center gap-2 self-end sm:self-center">
                      <Badge color={iss.status === "PUBLISHED" ? "green" : "amber"}>{iss.status === "PUBLISHED" ? "प्रकाशित" : "ड्राफ़्ट"}</Badge>
                      <button className="rounded-lg bg-indigo-50 px-3 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100">PDF देखें</button>
                      <button className="rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-50">संपादित</button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
          <div className="border-t border-gray-100 bg-gray-50/50 px-5 py-3 text-center text-xs text-gray-400">कुल {pastIssues.length} अंक</div>
        </div>
      )}

      {/* BUILDER */}
      {tab === "builder" && !generated && (
        <div className="grid gap-6 sm:grid-cols-3">
          {/* Left sidebar */}
          <div className="sm:col-span-1">
            <div className="sticky top-24 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
              <h2 className="mb-4 font-semibold text-gray-900">अंक विवरण <span className="text-xs font-normal text-gray-400">/ Issue Details</span></h2>
              <div className="space-y-4">
                <div className="grid grid-cols-2 gap-3">
                  <div><label className="block text-xs font-medium text-gray-500 mb-1">खंड</label><input type="number" className={inputCls} value={volume} onChange={e => setVolume(Number(e.target.value))} /></div>
                  <div><label className="block text-xs font-medium text-gray-500 mb-1">अंक</label><input type="number" className={inputCls} value={issue} onChange={e => setIssue(Number(e.target.value))} /></div>
                </div>
                <div><label className="block text-xs font-medium text-gray-500 mb-1">प्रकाशन तिथि / Publication date *</label><input type="date" className={inputCls} value={publicationDate} onChange={e => setPublicationDate(e.target.value)} /></div>
                <div><label className="block text-xs font-medium text-gray-500 mb-1">शीर्षक (हिन्दी) *</label><input className={inputCls} value={coverTitleHi} onChange={e => setCoverTitleHi(e.target.value)} placeholder="AI एवं स्वास्थ्य में प्रगति" /></div>
                <div><label className="block text-xs font-medium text-gray-500 mb-1">Title (English)</label><input className={inputCls} value={coverTitleEn} onChange={e => setCoverTitleEn(e.target.value)} placeholder="Advances in AI & Health" /></div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1">आवरण चित्र / Cover artwork</label>
                  <input
                    type="file"
                    accept="image/png,image/jpeg"
                    onChange={e => setCoverFile(e.target.files?.[0] ?? null)}
                    className="w-full text-xs text-gray-600 file:mr-3 file:rounded-lg file:border-0 file:bg-indigo-50 file:px-3 file:py-1.5 file:text-xs file:font-medium file:text-indigo-700 hover:file:bg-indigo-100"
                  />
                  <p className="mt-1 text-[10px] text-gray-400">
                    {coverFile ? `${coverFile.name} — पृष्ठ 1 बनेगा` : "वैकल्पिक — बिना आवरण के अंक शीर्षक पृष्ठ से आरम्भ होगा"}
                  </p>
                </div>
                <div><label className="block text-xs font-medium text-gray-500 mb-1">संपादकीय</label><textarea className={cn(inputCls, "h-24 resize-none")} value={editorialHi} onChange={e => setEditorialHi(e.target.value)} placeholder="संपादक का प्राक्कथन..." /></div>
                <div className="space-y-2 border-t border-gray-100 pt-3">
                  <div className="flex justify-between text-xs"><span className="text-gray-400">चयनित</span><span className="font-bold text-gray-900">{selectedIds.length} / {acceptedPapers.length}</span></div>
                  <div className="flex justify-between text-xs"><span className="text-gray-400">पृष्ठ</span><span className="font-bold text-gray-900">~{estimatedPages}</span></div>
                </div>
                <button onClick={handleGenerate} disabled={selectedIds.length === 0 || generating} className="flex w-full items-center justify-center gap-2 rounded-xl bg-emerald-600 py-2.5 text-sm font-semibold text-white hover:bg-emerald-700 disabled:bg-gray-300 transition-colors">
                  {generating ? <><Loader2 className="h-4 w-4 animate-spin" /> PDF बन रहा है...</> : "📄 PDF बनाएँ / Generate PDF"}
                </button>
              </div>
            </div>
          </div>

          {/* Right: papers + TOC */}
          <div className="sm:col-span-2 space-y-5">
            <div className="overflow-hidden rounded-2xl border border-gray-100 bg-white shadow-sm">
              <div className="flex flex-col gap-3 border-b border-gray-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
                <h2 className="font-semibold text-gray-900">शोधपत्र चुनें <span className="text-xs font-normal text-gray-400">/ Select Papers</span></h2>
                <div className="flex items-center gap-2 flex-wrap">
                  <select className="rounded-lg border border-gray-200 bg-white px-2 py-1 text-xs text-gray-600 focus:outline-none" value={filterCat} onChange={e => setFilterCat(e.target.value)}>
                    <option value="all">सभी / All</option>
                    {categories.filter(c => c !== "all").map(c => <option key={c} value={c}>{c}</option>)}
                  </select>
                  <button onClick={toggleAll} className="text-xs font-medium text-indigo-600 hover:text-indigo-700">{selectedIds.length === acceptedPapers.length ? "सभी हटाएँ" : "सभी चुनें"}</button>
                </div>
              </div>
              {papersLoading ? (
                <div className="flex items-center justify-center gap-2 py-12"><Loader2 className="h-5 w-5 animate-spin text-indigo-500" /><span className="text-sm text-gray-400">लोड हो रहा है...</span></div>
              ) : filteredPapers.length === 0 ? (
                <div className="py-12 text-center text-sm text-gray-400">कोई स्वीकृत शोधपत्र नहीं / No accepted papers</div>
              ) : (
                <div className="divide-y divide-gray-50">
                  {filteredPapers.map(p => {
                    const isSel = selectedIds.includes(p.id);
                    return (
                      <div key={p.id} className={cn("flex cursor-pointer items-start gap-3 px-5 py-4 transition-colors", isSel ? "bg-indigo-50" : "hover:bg-gray-50")} onClick={() => togglePaper(p.id)}>
                        <div className={cn("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-md border-2 transition-colors", isSel ? "border-indigo-600 bg-indigo-600" : "border-gray-300")}>{isSel && <span className="text-xs font-bold text-white">✓</span>}</div>
                        <div className="min-w-0 flex-1">
                          <p className="text-sm font-medium text-gray-900">{p.titleHi}</p>
                          <p className="text-xs text-gray-400">{p.titleEn}</p>
                          <div className="mt-1 flex items-center gap-3"><span className="text-xs text-gray-400">{p.authorNameHi || p.authorNameEn || p.referenceNo}</span>{(p.categoryNameHi || p.categoryNameEn) && <Badge color="gray">{p.categoryNameHi || p.categoryNameEn}</Badge>}</div>
                        </div>
                        {isSel && <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-indigo-100 text-xs font-bold text-indigo-700">{selectedIds.indexOf(p.id) + 1}</span>}
                      </div>
                    );
                  })}
                </div>
              )}
              <div className="border-t border-gray-100 bg-gray-50/50 px-5 py-2 text-[10px] text-gray-400">{filteredPapers.length} दिखा रहे · {selectedIds.length} चयनित</div>
            </div>

            {/* TOC Preview */}
            {selectedPapers.length > 0 && (
              <div className="rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
                <h3 className="mb-3 font-semibold text-gray-900">विषय सूची <span className="text-xs font-normal text-gray-400">/ TOC Preview</span></h3>
                <div className="overflow-hidden rounded-xl border border-gray-100">
                  <div className="bg-gradient-to-r from-indigo-600 to-blue-500 px-5 py-6 text-center text-white">
                    <p className="mb-1 text-xs uppercase tracking-widest opacity-75">शैक्षणिक प्रेस / Academic Press</p>
                    <p className="text-lg font-bold">खंड {volume} · अंक {issue} · {issueDateLabel(publicationDate, "")}</p>
                    <p className="mt-1 text-sm opacity-75">{coverTitleHi || coverTitleEn || "—"}</p>
                  </div>
                  {editorialHi && <div className="border-b border-indigo-100 bg-indigo-50 px-5 py-3"><p className="mb-1 text-[10px] font-semibold uppercase text-indigo-600">संपादकीय</p><p className="text-xs italic text-indigo-800">{editorialHi.substring(0, 150)}{editorialHi.length > 150 ? "..." : ""}</p></div>}
                  <div className="space-y-1 p-4">
                    <p className="mb-3 text-xs font-medium uppercase tracking-wide text-gray-400">विषय सूची / Contents</p>
                    {selectedPapers.map((paper, order) => (
                      <div key={paper.id} className="group flex items-center gap-2 rounded-lg px-2 py-2 hover:bg-gray-50">
                        <div className="flex shrink-0 flex-col gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
                          <button onClick={() => moveUp(order)} disabled={order === 0} className="text-[10px] text-gray-400 hover:text-indigo-600 disabled:opacity-30">▲</button>
                          <button onClick={() => moveDown(order)} disabled={order === selectedPapers.length - 1} className="text-[10px] text-gray-400 hover:text-indigo-600 disabled:opacity-30">▼</button>
                        </div>
                        <span className="w-5 shrink-0 font-mono text-xs text-gray-300">{order + 1}.</span>
                        <div className="min-w-0 flex-1"><p className="truncate text-sm text-gray-800">{paper.titleHi}</p><p className="text-[10px] text-gray-400">{paper.titleEn}</p></div>
                        <span className="shrink-0 text-[10px] text-gray-400">{paper.authorNameHi || paper.authorNameEn || ""}</span>
                        <button onClick={e => { e.stopPropagation(); removePaper(paper.id); }} className="shrink-0 text-gray-300 opacity-0 hover:text-red-500 group-hover:opacity-100 transition-opacity text-xs">✕</button>
                      </div>
                    ))}
                  </div>
                  <div className="flex justify-between border-t border-gray-100 bg-gray-50 px-5 py-2 text-[10px] text-gray-400"><span>{selectedPapers.length} शोधपत्र</span><span>~{estimatedPages} पृष्ठ</span></div>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* SUCCESS */}
      {tab === "builder" && generated && (
        <div className="mx-auto max-w-lg rounded-2xl border border-gray-100 bg-white p-8 text-center shadow-sm">
          <div className="mx-auto mb-5 flex h-20 w-20 items-center justify-center rounded-full bg-emerald-100 text-4xl">📄</div>
          <h2 className="mb-1 text-xl font-bold text-gray-900">पत्रिका PDF तैयार है!</h2>
          <p className="text-sm text-gray-500">Magazine PDF Generated Successfully</p>
          <div className="mt-6 space-y-2 rounded-xl bg-gray-50 p-5 text-left">
            <div className="flex justify-between text-sm"><span className="text-gray-500">अंक</span><span className="font-medium text-gray-900">खंड {volume}, अंक {issue} ({issueDateLabel(publicationDate, "")})</span></div>
            <div className="flex justify-between text-sm"><span className="text-gray-500">शीर्षक</span><span className="font-medium text-gray-900">{coverTitleHi || coverTitleEn || "—"}</span></div>
            <div className="flex justify-between text-sm"><span className="text-gray-500">शोधपत्र</span><span className="font-medium text-gray-900">{selectedPapers.length}</span></div>
            <div className="flex justify-between text-sm"><span className="text-gray-500">पृष्ठ</span><span className="font-medium text-gray-900">{issuePages ?? `~${estimatedPages}`}</span></div>
          </div>
          <div className="mt-6 flex justify-center gap-3">
            <button
              onClick={async () => {
                if (!createdMagazineId) return;
                try {
                  const res = await magazineApi.downloadIssuePdf(createdMagazineId);
                  const blob = new Blob([res.data], { type: "application/pdf" });
                  const url = URL.createObjectURL(blob);
                  const a = document.createElement("a");
                  a.href = url;
                  a.download = `magazine-vol${volume}-issue${issue}.pdf`;
                  a.click();
                  URL.revokeObjectURL(url);
                } catch {
                  toast.error("PDF डाउनलोड में त्रुटि / Error downloading PDF");
                }
              }}
              className="rounded-xl bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-indigo-700"
            >
              ⬇️ पूरा अंक डाउनलोड
            </button>
            <button
              disabled={publishing}
              onClick={async () => {
                if (!createdMagazineId) return;
                setPublishing(true);
                try {
                  await magazineApi.publish(createdMagazineId);
                  toast.success("पत्रिका प्रकाशित हो गई / Magazine published!");
                  queryClient.invalidateQueries({ queryKey: ["past-magazines"] });
                } catch {
                  toast.error("प्रकाशन में त्रुटि / Error publishing magazine");
                }
                setPublishing(false);
              }}
              className="rounded-xl bg-emerald-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-emerald-700 disabled:bg-gray-300"
            >
              {publishing ? "प्रकाशित हो रहा है..." : "🌐 प्रकाशित करें"}
            </button>
          </div>
          <div className="mt-3 flex justify-center gap-3">
            <button onClick={() => setGenerated(false)} className="rounded-lg px-4 py-2 text-sm text-gray-500 hover:bg-gray-100">← संपादित करें</button>
            <button onClick={resetBuilder} className="rounded-lg px-4 py-2 text-sm text-gray-500 hover:bg-gray-100">+ नया अंक</button>
          </div>
        </div>
      )}
    </div>
  );
}