"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useQuery } from "@tanstack/react-query";
import {
  ChevronLeft,
  ChevronRight,
  Upload,
  Plus,
  Trash2,
  FileText,
  Check,
  AlertCircle,
  Bot,
  Loader2,
  BookOpen,
  CreditCard,
  CheckCircle2,
  X,
  Copy,
} from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils/cn";
import { paperApi, publicApi, aiApi } from "@/lib/api/client";
import type { Category } from "@/types";
import { useTranslation } from "@/lib/hooks/use-translation";
import { usePaymentsEnabled } from "@/lib/hooks/use-payments-enabled";
import { normalizePastedText } from "@/lib/utils/normalize-text";

/* ───── Zod schema ───── */

const coauthorSchema = z.object({
  nameHi: z.string().min(1, "हिन्दी नाम आवश्यक"),
  nameEn: z.string().min(1, "English name required"),
  email: z.string().email("Invalid email").optional().or(z.literal("")),
  institution: z.string().optional(),
  authorOrder: z.number(),
  corresponding: z.boolean(),
});

const submitSchema = z.object({
  title: z.string().min(1, "शीर्षक आवश्यक / Title required"),
  abstract: z.string().min(1, "सारांश आवश्यक / Abstract required"),
  keywords: z.string().min(1, "कीवर्ड आवश्यक / Keywords required"),
  categoryId: z.string().min(1, "श्रेणी चुनें / Select category"),
  coauthors: z.array(coauthorSchema),
});

type SubmitValues = z.infer<typeof submitSchema>;

const AI_UNAVAILABLE_HINT =
  "एआई सेवा इस सर्वर पर कॉन्फ़िगर नहीं है — शीर्षक और सारांश स्वयं भरें / " +
  "AI service is not configured on this server — enter title and abstract yourself";

const STEPS = [
  { label: "विवरण / Metadata" },
  { label: "सह-लेखक / Co-Authors" },
  { label: "अपलोड / Upload" },
  { label: "समीक्षा / Review" },
];

/* ───── Helpers ───── */

function detectScript(text: string): "devanagari" | "roman" {
  return /[\u0900-\u097F]/.test(text) ? "devanagari" : "roman";
}

/* ───── AI Transcript + Translation Block ───── */

function TranscriptTranslateBlock({
  label,
  transcript,
  translation,
  loading,
  isTitle,
}: {
  label: string;
  transcript: string;
  translation: string;
  loading: boolean;
  isTitle: boolean;
}) {
  return (
    <div className="bg-gradient-to-br from-indigo-50/50 to-blue-50/50 border border-indigo-100 rounded-lg p-4 space-y-3">
      <div className="flex items-center justify-between">
        <p className="text-xs font-semibold text-indigo-700 uppercase tracking-wide flex items-center gap-1.5">
          <Bot className="h-3.5 w-3.5" />
          <span>{`AI ${label}`}</span>
          <Loader2 className={cn("h-3.5 w-3.5 animate-spin", loading ? "opacity-100" : "opacity-0")} />
        </p>
        <span className={cn("text-[10px] text-indigo-400", loading ? "animate-pulse" : "invisible")}>
          {"प्रोसेसिंग / Processing..."}
        </span>
      </div>
      <div>
        <label className="block text-xs font-medium text-gray-600 mb-1">
          लिप्यंतरण / Transcript
          <span className="text-[10px] text-gray-400 ml-1">
            (देवनागरी ↔ रोमन / Devanagari ↔ Roman)
          </span>
        </label>
        <textarea
          readOnly
          value={loading ? "..." : transcript}
          className={cn(
            "w-full border rounded-md px-3 py-2 text-sm bg-white resize-none focus:outline-none",
            transcript
              ? "border-indigo-200 text-gray-800"
              : "border-gray-200 text-gray-300",
            isTitle ? "h-10" : "h-20"
          )}
          placeholder={
            loading
              ? "AI प्रोसेसिंग..."
              : "यहाँ लिप्यंतरण दिखाई देगा / Transcription will appear here"
          }
        />
      </div>
      <div>
        <label className="block text-xs font-medium text-gray-600 mb-1">
          अनुवाद / Translation
          <span className="text-[10px] text-gray-400 ml-1">
            (हिन्दी ↔ अंग्रेज़ी / Hindi ↔ English)
          </span>
        </label>
        <textarea
          readOnly
          value={loading ? "..." : translation}
          className={cn(
            "w-full border rounded-md px-3 py-2 text-sm bg-white resize-none focus:outline-none",
            translation
              ? "border-indigo-200 text-gray-800"
              : "border-gray-200 text-gray-300",
            isTitle ? "h-10" : "h-20"
          )}
          placeholder={
            loading
              ? "AI प्रोसेसिंग..."
              : "यहाँ अनुवाद दिखाई देगा / Translation will appear here"
          }
        />
      </div>
    </div>
  );
}

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

export default function PaperSubmission() {
  const router = useRouter();
  const [step, setStep] = useState(0);
  const [file, setFile] = useState<File | null>(null);
  const [submitting, setSubmitting] = useState(false);

  // Where the author goes after submitting. A paper with a fee owed comes back
  // as PAYMENT_PENDING and must be taken to the payment page — it does not reach
  // a reviewer until the fee is confirmed.
  const [paperId, setPaperId] = useState("");
  const [paymentPending, setPaymentPending] = useState(false);
  const [consentOriginal, setConsentOriginal] = useState(false);
  const [consentCopyright, setConsentCopyright] = useState(false);

  // Success
  const [showSuccess, setShowSuccess] = useState(false);
  const [refNumber, setRefNumber] = useState("");

  // AI — one result per field: "title" | "abstract"
  const [aiProcessing, setAiProcessing] = useState<string | null>(null);
  const [aiResults, setAiResults] = useState<
    Record<string, { transcript: string; translation: string }>
  >({});

  const form = useForm<SubmitValues>({
    resolver: zodResolver(submitSchema),
    defaultValues: {
      title: "",
      abstract: "",
      keywords: "",
      categoryId: "",
      coauthors: [],
    },
  });

  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "coauthors",
  });

  const { t: cms } = useTranslation("SUBMIT");

  const { data: categories, isLoading: catLoading } = useQuery<Category[]>({
    queryKey: ["public-categories"],
    queryFn: async () => {
      const res = await publicApi.categories();
      return res.data?.content ?? res.data ?? [];
    },
  });

  /* ─── AI Process (single field → transliterate + translate in parallel) ─── */

  // Instances without a provider key must not offer the AI controls at all:
  // the endpoints return 503 there, and a failed run leaves aiResults empty so
  // resolveHiEn() falls back to the author's own text.
  const { data: aiStatus } = useQuery({
    queryKey: ["ai-status"],
    queryFn: async () => (await aiApi.status()).data,
    staleTime: Infinity,
    retry: false,
  });
  const aiAvailable = aiStatus?.configured === true;
  const { paymentsEnabled } = usePaymentsEnabled();

  async function processAiField(fieldName: "title" | "abstract") {
    const text = form.getValues(fieldName);
    if (!text.trim() || !aiAvailable) return;

    setAiProcessing(fieldName);
    try {
      const script = detectScript(text);
      const fromLang = script === "devanagari" ? "Hindi" : "English";
      const toLang = script === "devanagari" ? "English" : "Hindi";

      const [transcriptRes, translateRes] = await Promise.all([
        aiApi.transliterate(text),
        aiApi.translate(text, fromLang, toLang),
      ]);

      const transcript = transcriptRes.data?.transliterated ?? "";
      const translation = translateRes.data?.translated ?? "";

      // Only keep a genuine result. Anything blank stays unset so it can never
      // be written into the Hindi/English column pair on submit.
      if (!transcript && !translation) {
        toast.error("AI ने कोई परिणाम नहीं दिया / AI returned no result");
        setAiProcessing(null);
        return;
      }

      setAiResults((prev) => ({
        ...prev,
        [fieldName]: { transcript, translation },
      }));
    } catch (err: unknown) {
      const status = (err as { response?: { status?: number } })?.response?.status;
      toast.error(
        status === 429
          ? "बहुत अधिक AI अनुरोध — कृपया कुछ समय बाद पुनः प्रयास करें / Too many AI requests — please try again shortly"
          : status === 503
            ? "एआई सेवा उपलब्ध नहीं है / AI service is unavailable"
            : "AI प्रोसेसिंग विफल / AI processing failed"
      );
    }
    setAiProcessing(null);
  }

  /* ─── Resolve single field → Hi + En for backend submission ─── */

  function resolveHiEn(fieldName: "title" | "abstract"): {
    hi: string;
    en: string;
  } {
    const raw = form.getValues(fieldName);
    const script = detectScript(raw);
    const translation = aiResults[fieldName]?.translation ?? "";

    if (script === "devanagari") {
      return { hi: raw, en: translation || raw };
    } else {
      return { hi: translation || raw, en: raw };
    }
  }

  /* ─── Navigation ─── */

  async function goNext() {
    if (step === 0) {
      const valid = await form.trigger(["title", "abstract", "keywords"]);
      if (!valid) return;
    }
    if (step === 1) {
      const valid = await form.trigger(["categoryId"]);
      if (!valid) return;
    }
    if (step === 2 && !file) {
      toast.error("कृपया पांडुलिपि अपलोड करें / Please upload manuscript");
      return;
    }
    setStep((s) => Math.min(s + 1, 3));
  }

  function goBack() {
    setStep((s) => Math.max(s - 1, 0));
  }

  /* ─── Submit → Payment → Success ─── */

  /** Format paise as rupees, e.g. 82600 → "₹826.00" */
  const inr = (paise: number) => `₹${(paise / 100).toFixed(2)}`;

  /**
   * Pasted abstracts often arrive with HTML-escaped characters (&#39; for an
   * apostrophe) from Word/web/AI sources — decode right after the paste lands
   * so the author sees clean text and clean text is what gets saved.
   */
  const normalizeFieldOnPaste = (field: "title" | "abstract" | "keywords") =>
    (e: React.ClipboardEvent) => {
      const el = e.target as HTMLInputElement | HTMLTextAreaElement;
      setTimeout(() => {
        const cleaned = normalizePastedText(el.value);
        if (cleaned !== el.value) {
          form.setValue(field, cleaned, { shouldValidate: true });
        }
      }, 0);
    };

  async function handleSubmitClick() {
    const valid = await form.trigger();
    if (!valid) {
      toast.error(
        "कृपया सभी आवश्यक फ़ील्ड भरें / Please fill all required fields"
      );
      return;
    }
    if (!file) {
      toast.error("कृपया पांडुलिपि अपलोड करें / Please upload manuscript");
      return;
    }
    if (!consentOriginal || !consentCopyright) {
      toast.error(
        "कृपया दोनों घोषणाओं पर सहमति दें / Please accept both declarations"
      );
      return;
    }
    // Payment used to be collected here, in a Razorpay popup that never worked:
    // it posted a literal "temp-paper-id" to an endpoint that never called the
    // gateway. Fees are now collected after submission, against a real paper,
    // and reconciled by hand — so submitting is just submitting.
    await doSubmit();
  }

  async function doSubmit() {
    setSubmitting(true);

    try {
      const values = form.getValues();
      const titleResolved = resolveHiEn("title");
      const abstractResolved = resolveHiEn("abstract");

      const fd = new FormData();

      // Backend expects "data" as a JSON blob part and "manuscript" as the file
      const dataPayload = {
        originalityDeclared: consentOriginal,
        copyrightAssigned: consentCopyright,
        titleHi: normalizePastedText(titleResolved.hi),
        titleEn: normalizePastedText(titleResolved.en),
        abstractHi: normalizePastedText(abstractResolved.hi),
        abstractEn: normalizePastedText(abstractResolved.en),
        keywords: values.keywords ? values.keywords.split(",").map((k: string) => k.trim()).filter(Boolean) : [],
        categoryId: parseInt(values.categoryId, 10),
        coauthors: values.coauthors.length > 0 ? values.coauthors : undefined,
      };
      fd.append("data", new Blob([JSON.stringify(dataPayload)], { type: "application/json" }));
      fd.append("manuscript", file!);

      const res = await paperApi.submit(fd);
      const ref =
        res.data?.referenceNo ??
        `AP-${new Date().getFullYear()}-${String(Math.floor(Math.random() * 9000) + 1000)}`;
      setRefNumber(ref);
      setPaperId(res.data?.id ?? "");
      setPaymentPending(res.data?.status === "PAYMENT_PENDING");
      setShowSuccess(true);
    } catch (err: unknown) {
      const e = err as {
        response?: { status?: number; data?: { message?: string } };
      };
      // Expired/invalid sessions surface as bodyless 401/403 from the
      // security filter — say so instead of a generic failure.
      if (e.response?.status === 401 || e.response?.status === 403) {
        toast.error(
          "सत्र समाप्त हो गया है — कृपया पुनः लॉगिन करके जमा करें / Session expired — please log in again and resubmit"
        );
      } else {
        toast.error(e.response?.data?.message ?? "Submission failed / जमा विफल");
      }
    } finally {
      setSubmitting(false);
    }
  }

  function handleSuccessClose(action: "dashboard" | "new") {
    setShowSuccess(false);
    if (action === "dashboard") {
      router.push("/author");
    } else {
      form.reset();
      setFile(null);
      setStep(0);
      setAiResults({});
      setRefNumber("");
    }
  }

  /* ─── Shared styles ─── */

  const inputCls =
    "w-full rounded-md border border-gray-300 px-3 py-2 text-sm shadow-sm placeholder:text-gray-400 focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500";
  const labelCls = "block text-sm font-medium text-gray-700 mb-1";
  const errCls = "text-xs text-red-500 mt-1";

  const values = form.watch();
  const selectedCategory = categories?.find(
    (c) => String(c.id) === values.categoryId
  ) ?? null;
  const titleResolved = resolveHiEn("title");
  const abstractResolved = resolveHiEn("abstract");

  return (
    <div className="max-w-3xl mx-auto px-4 py-8">
      <h1 className="text-2xl font-bold text-gray-900 mb-2">
        {cms("submit_header.title", "Submit Paper")}
      </h1>
      <p className="text-gray-500 text-sm mb-8">
        {cms("submit_header.subtitle", "Complete all steps to submit your manuscript for review")}
      </p>

      {/* ─── Stepper ─── */}
      <div className="flex items-center gap-2 mb-8 overflow-x-auto pb-2">
        {STEPS.map((s, i) => (
          <div key={i} className="flex items-center gap-2 shrink-0">
            <div
              className={cn(
                "flex items-center justify-center h-8 w-8 rounded-full text-xs font-bold transition",
                i < step
                  ? "bg-indigo-600 text-white"
                  : i === step
                    ? "bg-indigo-100 text-indigo-700 ring-2 ring-indigo-600"
                    : "bg-gray-100 text-gray-400"
              )}
            >
              {i < step ? <Check className="h-4 w-4" /> : i + 1}
            </div>
            <span
              className={cn(
                "text-xs font-medium hidden sm:inline",
                i <= step ? "text-gray-900" : "text-gray-400"
              )}
            >
              {cms(`submit_steps.step_${i + 1}`, s.label)}
            </span>
            {i < STEPS.length - 1 && (
              <div
                className={cn(
                  "w-8 h-0.5",
                  i < step ? "bg-indigo-600" : "bg-gray-200"
                )}
              />
            )}
          </div>
        ))}
      </div>

      <div className="rounded-lg border border-gray-200 bg-white shadow-sm p-6">
        {/* ════════ Step 1: Metadata ════════ */}
        {step === 0 && (
          <div className="space-y-5">
            <h3 className="text-lg font-semibold text-gray-900">
              {cms("submit_metadata.section_title", "Paper Details")}
            </h3>

            {aiStatus && !aiAvailable && (
              <p className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900">
                {AI_UNAVAILABLE_HINT}
              </p>
            )}

            {/* Single Title field */}
            <div>
              <label className={labelCls}>
                {cms("submit_metadata.title_label", "Title")} <span className="text-red-500">*</span>
              </label>
              <div className="flex gap-2">
                <input
                  className={inputCls}
                  placeholder="अपने शोधपत्र का पूरा शीर्षक दर्ज करें (हिन्दी या English)"
                  {...form.register("title")}
                  onPaste={normalizeFieldOnPaste("title")}
                />
                <button
                  type="button"
                  onClick={() => processAiField("title")}
                  disabled={
                    !values.title?.trim() || aiProcessing === "title" || !aiAvailable
                  }
                  title={aiAvailable ? undefined : AI_UNAVAILABLE_HINT}
                  className="shrink-0 inline-flex items-center gap-1.5 rounded-md bg-indigo-600 px-3 py-2 text-xs font-semibold text-white shadow hover:bg-indigo-700 transition disabled:opacity-40 disabled:cursor-not-allowed"
                >
                  {aiProcessing === "title" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Bot className="h-3.5 w-3.5" />}
                  <span>{aiProcessing === "title" ? "प्रोसेसिंग" : "AI प्रोसेस"}</span>
                </button>
              </div>
              {form.formState.errors.title && (
                <p className={errCls}>{form.formState.errors.title.message}</p>
              )}
            </div>

            {/* AI Result: Title */}
            {aiAvailable && (
              <TranscriptTranslateBlock
                label="शीर्षक / Title"
                transcript={aiResults.title?.transcript ?? ""}
                translation={aiResults.title?.translation ?? ""}
                loading={aiProcessing === "title"}
                isTitle={true}
              />
            )}

            {/* Single Abstract field */}
            <div>
              <label className={labelCls}>
                {cms("submit_metadata.abstract_label", "Abstract")} <span className="text-red-500">*</span>
              </label>
              <div className="flex flex-col gap-2">
                <textarea
                  rows={5}
                  className={inputCls}
                  placeholder="अपने शोध का संक्षिप्त सारांश प्रदान करें (हिन्दी या English, 250–350 शब्द)"
                  {...form.register("abstract")}
                  onPaste={normalizeFieldOnPaste("abstract")}
                />
                <button
                  type="button"
                  onClick={() => processAiField("abstract")}
                  disabled={
                    !values.abstract?.trim() || aiProcessing === "abstract" || !aiAvailable
                  }
                  title={aiAvailable ? undefined : AI_UNAVAILABLE_HINT}
                  className="self-end inline-flex items-center gap-1.5 rounded-md bg-indigo-600 px-3 py-2 text-xs font-semibold text-white shadow hover:bg-indigo-700 transition disabled:opacity-40 disabled:cursor-not-allowed"
                >
                  {aiProcessing === "abstract" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Bot className="h-3.5 w-3.5" />}
                  <span>{aiProcessing === "abstract" ? "प्रोसेसिंग" : "AI प्रोसेस करें"}</span>
                </button>
              </div>
              {form.formState.errors.abstract && (
                <p className={errCls}>
                  {form.formState.errors.abstract.message}
                </p>
              )}
            </div>

            {/* AI Result: Abstract */}
            {aiAvailable && (
              <TranscriptTranslateBlock
                label="सारांश / Abstract"
                transcript={aiResults.abstract?.transcript ?? ""}
                translation={aiResults.abstract?.translation ?? ""}
                loading={aiProcessing === "abstract"}
                isTitle={false}
              />
            )}

            {/* Keywords */}
            <div>
              <label className={labelCls}>
                {cms("submit_metadata.keywords_label", "Keywords")} <span className="text-red-500">*</span>
              </label>
              <input
                className={inputCls}
                placeholder="जैसे: मशीन लर्निंग, NLP, डीप लर्निंग"
                {...form.register("keywords")}
                onPaste={normalizeFieldOnPaste("keywords")}
              />
              {form.formState.errors.keywords && (
                <p className={errCls}>
                  {form.formState.errors.keywords.message}
                </p>
              )}
              <p className="text-xs text-gray-400 mt-1">
                {cms("submit_metadata.keywords_hint", "Separate with commas")}
              </p>
            </div>
          </div>
        )}

        {/* ════════ Step 2: Category & Coauthors ════════ */}
        {step === 1 && (
          <div className="space-y-6">
            <div>
              <label className={labelCls}>
                {cms("submit_coauthors.category_label", "Category")} <span className="text-red-500">*</span>
              </label>
              {catLoading ? (
                <div className="flex items-center gap-2 text-sm text-gray-400">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  श्रेणियाँ लोड हो रही हैं...
                </div>
              ) : (
                <select className={inputCls} {...form.register("categoryId")}>
                  <option value="">— श्रेणी चुनें / Select —</option>
                  {(categories ?? [])
                    .filter((c) => c.active)
                    .map((c) => (
                      <option key={c.id} value={String(c.id)}>
                        {c.nameHi} / {c.nameEn}
                      </option>
                    ))}
                </select>
              )}
              {form.formState.errors.categoryId && (
                <p className={errCls}>
                  {form.formState.errors.categoryId.message}
                </p>
              )}
            </div>

            <div>
              <div className="flex items-center justify-between mb-3">
                <label className="text-sm font-medium text-gray-700">
                  {cms("submit_coauthors.coauthors_label", "Co-Authors")}
                </label>
                <button
                  type="button"
                  onClick={() =>
                    append({
                      nameHi: "",
                      nameEn: "",
                      email: "",
                      institution: "",
                      authorOrder: fields.length + 1,
                      corresponding: false,
                    })
                  }
                  className="inline-flex items-center gap-1 rounded-md bg-indigo-50 px-3 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100 transition"
                >
                  <Plus className="h-3.5 w-3.5" />
                  {cms("submit_coauthors.add_coauthor", "Add Co-Author")}
                </button>
              </div>

              {fields.length === 0 && (
                <p className="text-sm text-gray-400 py-4 text-center">
                  {cms("submit_coauthors.no_coauthors", "No co-authors added")}
                </p>
              )}

              <div className="space-y-4">
                {fields.map((field, index) => (
                  <div
                    key={field.id}
                    className="rounded-lg border border-gray-200 p-4 relative"
                  >
                    <button
                      type="button"
                      onClick={() => remove(index)}
                      className="absolute top-3 right-3 text-red-400 hover:text-red-600"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                    <p className="text-xs font-semibold text-gray-500 mb-3">
                      सह-लेखक #{index + 1}
                    </p>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <div>
                        <label className="text-xs text-gray-500">
                          नाम (हिन्दी)
                        </label>
                        <input
                          className={inputCls}
                          {...form.register(`coauthors.${index}.nameHi`)}
                        />
                      </div>
                      <div>
                        <label className="text-xs text-gray-500">
                          Name (English)
                        </label>
                        <input
                          className={inputCls}
                          {...form.register(`coauthors.${index}.nameEn`)}
                        />
                      </div>
                      <div>
                        <label className="text-xs text-gray-500">
                          ईमेल / Email
                        </label>
                        <input
                          type="email"
                          className={inputCls}
                          {...form.register(`coauthors.${index}.email`)}
                        />
                      </div>
                      <div>
                        <label className="text-xs text-gray-500">
                          संस्थान / Institution
                        </label>
                        <input
                          className={inputCls}
                          {...form.register(`coauthors.${index}.institution`)}
                        />
                      </div>
                    </div>
                    <label className="flex items-center gap-2 mt-3 text-sm text-gray-600">
                      <input
                        type="checkbox"
                        className="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                        {...form.register(`coauthors.${index}.corresponding`)}
                      />
                      पत्राचार लेखक / Corresponding author
                    </label>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* ════════ Step 3: Upload ════════ */}
        {step === 2 && (
          <div className="space-y-4">
            <h3 className="text-lg font-semibold text-gray-900">
              {cms("submit_upload.section_title", "Upload Manuscript")}
            </h3>
            <div
              className={cn(
                "rounded-lg border-2 border-dashed p-10 text-center transition",
                file
                  ? "border-indigo-300 bg-indigo-50"
                  : "border-gray-300 bg-gray-50 hover:border-gray-400"
              )}
            >
              {file ? (
                <div className="flex flex-col items-center gap-2">
                  <FileText className="h-10 w-10 text-indigo-500" />
                  <p className="text-sm font-medium text-gray-900">
                    {file.name}
                  </p>
                  <p className="text-xs text-gray-500">
                    {(file.size / (1024 * 1024)).toFixed(2)} MB
                  </p>
                  <button
                    type="button"
                    onClick={() => setFile(null)}
                    className="text-xs text-red-500 hover:underline mt-1"
                  >
                    {cms("submit_upload.remove_file", "Remove")}
                  </button>
                </div>
              ) : (
                <label className="cursor-pointer flex flex-col items-center gap-2">
                  <Upload className="h-10 w-10 text-gray-400" />
                  <p className="text-sm text-gray-600">
                    {cms("submit_upload.drag_text", "Click or drag file")}
                  </p>
                  <p className="text-xs text-gray-400">
                    {cms("submit_upload.file_formats", "PDF, DOCX, LaTeX — max 25MB")}
                  </p>
                  <input
                    type="file"
                    accept=".pdf,.doc,.docx,.tex"
                    className="hidden"
                    onChange={(e) => {
                      const f = e.target.files?.[0];
                      if (!f) return;
                      if (f.size > 25 * 1024 * 1024) {
                        toast.error(
                          "फ़ाइल 25MB से बड़ी है / File exceeds 25MB"
                        );
                        return;
                      }
                      setFile(f);
                    }}
                  />
                </label>
              )}
            </div>
          </div>
        )}

        {/* ════════ Step 4: Review & Submit ════════ */}
        {step === 3 && (
          <div className="space-y-5">
            <h3 className="text-lg font-semibold text-gray-900">
              {cms("submit_review.section_title", "Review & Submit")}
            </h3>

            <div className="rounded-lg border border-gray-200 divide-y divide-gray-100">
              <div className="px-4 py-3">
                <p className="text-xs text-gray-500 mb-0.5">
                  शीर्षक (हिन्दी)
                </p>
                <p className="text-sm text-gray-900">
                  {titleResolved.hi || "—"}
                </p>
              </div>
              <div className="px-4 py-3">
                <p className="text-xs text-gray-500 mb-0.5">Title (English)</p>
                <p className="text-sm text-gray-900 italic">
                  {titleResolved.en || "—"}
                </p>
              </div>
              <div className="px-4 py-3">
                <p className="text-xs text-gray-500 mb-0.5">
                  सारांश (हिन्दी)
                </p>
                <p className="text-sm text-gray-900 line-clamp-3">
                  {abstractResolved.hi || "—"}
                </p>
              </div>
              <div className="px-4 py-3">
                <p className="text-xs text-gray-500 mb-0.5">
                  Abstract (English)
                </p>
                <p className="text-sm text-gray-900 italic line-clamp-3">
                  {abstractResolved.en || "—"}
                </p>
              </div>
              <div className="px-4 py-3">
                <p className="text-xs text-gray-500 mb-0.5">
                  मुख्य शब्द / Keywords
                </p>
                <p className="text-sm text-gray-900">
                  {values.keywords || "—"}
                </p>
              </div>
              <div className="px-4 py-3">
                <p className="text-xs text-gray-500 mb-0.5">
                  श्रेणी / Category
                </p>
                <p className="text-sm text-gray-900">
                  {selectedCategory
                    ? `${selectedCategory.nameHi} / ${selectedCategory.nameEn}`
                    : "—"}
                </p>
              </div>
              <div className="px-4 py-3">
                <p className="text-xs text-gray-500 mb-0.5">
                  सह-लेखक / Co-Authors
                </p>
                {values.coauthors.length === 0 ? (
                  <p className="text-sm text-gray-400">कोई नहीं / None</p>
                ) : (
                  <ul className="text-sm text-gray-900 space-y-0.5">
                    {values.coauthors.map((ca, i) => (
                      <li key={i}>
                        {ca.nameHi} / {ca.nameEn}
                        {ca.corresponding && (
                          <span className="text-xs text-indigo-600 ml-1">
                            {"[पत्राचार]"}
                          </span>
                        )}
                      </li>
                    ))}
                  </ul>
                )}
              </div>
              <div className="px-4 py-3">
                <p className="text-xs text-gray-500 mb-0.5">
                  पांडुलिपि / Manuscript
                </p>
                <p className="text-sm text-gray-900">
                  {file
                    ? `${file.name} (${(file.size / (1024 * 1024)).toFixed(2)} MB)`
                    : "—"}
                </p>
              </div>
            </div>

            {(aiResults.title || aiResults.abstract) && (
              <div className="flex items-center gap-2 text-xs text-indigo-600 bg-indigo-50 rounded-md px-3 py-2">
                <Bot className="h-4 w-4 shrink-0" />
                <span>{"AI द्वारा स्वचालित अनुवाद शामिल / Includes AI auto-translation"}</span>
              </div>
            )}

            {(!values.title || !file) && (
              <div className="flex items-center gap-2 text-sm text-amber-600 bg-amber-50 rounded-md px-3 py-2">
                <AlertCircle className="h-4 w-4 shrink-0" />
                <span>{"कुछ आवश्यक फ़ील्ड अधूरे हैं / Some required fields are incomplete"}</span>
              </div>
            )}

            {/* Author declarations — both required before submission */}
            <div className="space-y-3 rounded-lg border border-gray-200 bg-gray-50 p-4">
              <p className="text-sm font-semibold text-gray-900">
                {cms("submit_review.consent_heading", "घोषणाएँ / Declarations")}
              </p>
              <label className="flex items-start gap-3 cursor-pointer">
                <input
                  type="checkbox"
                  checked={consentOriginal}
                  onChange={(e) => setConsentOriginal(e.target.checked)}
                  className="mt-1 h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                />
                <span className="text-sm text-gray-700">
                  {cms(
                    "submit_review.consent_originality",
                    "मैं प्रमाणित करता/करती हूँ कि यह शोधपत्र मेरी मौलिक रचना है; यह पहले कहीं प्रकाशित नहीं हुआ है और किसी अन्य पत्रिका में विचाराधीन नहीं है। / I certify that this article is my original work; it has not been published anywhere and is not under consideration by any other journal."
                  )}
                </span>
              </label>
              <label className="flex items-start gap-3 cursor-pointer">
                <input
                  type="checkbox"
                  checked={consentCopyright}
                  onChange={(e) => setConsentCopyright(e.target.checked)}
                  className="mt-1 h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                />
                <span className="text-sm text-gray-700">
                  {cms(
                    "submit_review.consent_copyright",
                    "मैं इस शोधपत्र का कॉपीराइट शोध संचयन को सौंपता/सौंपती हूँ, ताकि वे इसे प्रिंट एवं डिजिटल रूप में प्रकाशित कर सकें। / I assign the copyright of this article to Shodh Sanchayan, authorising its publication in print and digital form."
                  )}
                </span>
              </label>
            </div>

            {/* Said before submitting, not after: the fee and the hold are
                both things an author should know about in advance. Hidden when
                the editor has the payment section switched off — otherwise it
                promises a payment page that will never open, for a fee nobody
                is charging. */}
            {paymentsEnabled && (
            <div className="flex items-start gap-2 text-sm text-indigo-700 bg-indigo-50 rounded-md px-3 py-2">
              <CreditCard className="h-4 w-4 shrink-0 mt-0.5" />
              <span>
                {cms(
                  "submit_review.payment_notice",
                  "समीक्षा शुल्क एवं GST देय होगा — जमा करने के बाद भुगतान पृष्ठ खुलेगा। शुल्क की पुष्टि के बाद ही शोधपत्र समीक्षा में जाता है। / Review fee plus GST is payable — the payment page opens after you submit. Your paper enters review once the fee is confirmed."
                )}
              </span>
            </div>
            )}
          </div>
        )}

        {/* ─── Guidelines + Navigation ─── */}
        <div className="mt-8 pt-6 border-t border-gray-100">
          <div className="mb-4">
            <a
              href="/guidelines"
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1.5 text-sm text-indigo-600 hover:text-indigo-700 hover:underline"
            >
              <BookOpen className="h-4 w-4" />
              📋 जमा करने के दिशानिर्देश / Submission Guidelines
            </a>
          </div>

          <div className="flex items-center justify-between">
            <button
              type="button"
              onClick={goBack}
              disabled={step === 0}
              className={cn(
                "inline-flex items-center gap-1.5 rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition",
                step === 0 && "invisible"
              )}
            >
              <ChevronLeft className="h-4 w-4" />
              {cms("submit_review.back_button", "Back")}
            </button>

            {step < 3 ? (
              <button
                type="button"
                onClick={goNext}
                className="inline-flex items-center gap-1.5 rounded-md bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow hover:bg-indigo-700 transition"
              >
                {cms("submit_review.next_button", "Next")}
                <ChevronRight className="h-4 w-4" />
              </button>
            ) : (
              <button
                type="button"
                onClick={handleSubmitClick}
                disabled={submitting}
                className="inline-flex items-center gap-1.5 rounded-md bg-indigo-600 px-6 py-2.5 text-sm font-semibold text-white shadow hover:bg-indigo-700 transition disabled:opacity-50"
              >
                {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : <CheckCircle2 className="h-4 w-4" />}
                <span>{submitting ? "जमा हो रहा है..." : cms("submit_review.submit_button", "जमा करें / Submit")}</span>
              </button>
            )}
          </div>
        </div>
      </div>

      {/* ═══════════ Success Popup ═══════════ */}
      <div className={cn("fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm px-4", showSuccess ? "" : "hidden")}>
        <div className="bg-white rounded-xl shadow-2xl w-full max-w-md overflow-hidden">
            <div className="bg-gradient-to-r from-emerald-500 to-green-500 px-6 py-6 text-white text-center relative">
              <button
                onClick={() => handleSuccessClose("dashboard")}
                className="absolute top-3 right-3 text-white/70 hover:text-white"
              >
                <X className="h-5 w-5" />
              </button>
              <div className="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-3">
                <Check className="h-8 w-8" />
              </div>
              <h3 className="text-xl font-bold">
                शोधपत्र सफलतापूर्वक जमा हुआ!
              </h3>
              <p className="text-sm text-emerald-100 mt-1">
                Paper Submitted Successfully
              </p>
            </div>
            <div className="px-6 py-6">
              <div className="bg-gray-50 border-2 border-dashed border-gray-300 rounded-lg p-4 text-center mb-5">
                <p className="text-xs text-gray-500 mb-1">
                  संदर्भ संख्या / Reference Number
                </p>
                <div className="flex items-center justify-center gap-2">
                  <p className="text-2xl font-bold text-gray-900 font-mono tracking-wider">
                    {refNumber}
                  </p>
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(refNumber);
                      toast.success("कॉपी हुआ / Copied!");
                    }}
                    className="text-gray-400 hover:text-gray-600"
                  >
                    <Copy className="h-4 w-4" />
                  </button>
                </div>
              </div>
              {paymentPending ? (
                <div className="bg-amber-50 border border-amber-200 rounded-lg px-4 py-3 mb-5">
                  <p className="text-xs font-semibold text-amber-900 mb-2">
                    अगला चरण / Next step:
                  </p>
                  <p className="text-xs text-amber-800">
                    समीक्षा शुल्क का भुगतान बाकी है। शुल्क की पुष्टि होने तक यह शोधपत्र
                    समीक्षकों को नहीं भेजा जाएगा।
                    <br />
                    <span className="text-amber-700">
                      The review fee is still due. This paper is not sent to reviewers
                      until the fee is confirmed.
                    </span>
                  </p>
                </div>
              ) : (
                <div className="bg-blue-50 rounded-lg px-4 py-3 mb-5">
                  <p className="text-xs font-semibold text-blue-800 mb-2">
                    अगले चरण / Next Steps:
                  </p>
                  <ol className="text-xs text-blue-700 space-y-1 list-decimal list-inside">
                    <li>प्रशासक प्रारंभिक जाँच करेंगे / Admin screening</li>
                    <li>समीक्षक सौंपे जाएँगे / Reviewer(s) assigned</li>
                    <li>स्थिति अपडेट ईमेल पर मिलेंगे / Updates via email</li>
                  </ol>
                </div>
              )}

              {/* When a fee is owed, paying is the only action that matters —
                  anything else leaves the paper sitting where no reviewer sees it. */}
              {paymentPending && paperId ? (
                <div className="space-y-2">
                  <button
                    onClick={() => router.push(`/papers/${paperId}/payment`)}
                    className="w-full rounded-lg bg-indigo-600 text-white py-2.5 text-sm font-semibold hover:bg-indigo-700 transition"
                  >
                    शुल्क का भुगतान करें / Pay the review fee
                  </button>
                  <button
                    onClick={() => handleSuccessClose("dashboard")}
                    className="w-full rounded-lg border border-gray-200 text-gray-700 py-2 text-sm font-medium hover:bg-gray-50 transition"
                  >
                    बाद में / Later
                  </button>
                </div>
              ) : (
                <div className="flex gap-3">
                  <button
                    onClick={() => handleSuccessClose("dashboard")}
                    className="flex-1 rounded-lg bg-indigo-600 text-white py-2.5 text-sm font-semibold hover:bg-indigo-700 transition"
                  >
                    डैशबोर्ड पर जाएँ / Dashboard
                  </button>
                  <button
                    onClick={() => handleSuccessClose("new")}
                    className="flex-1 rounded-lg border border-gray-200 text-gray-700 py-2.5 text-sm font-medium hover:bg-gray-50 transition"
                  >
                    नया शोधपत्र / New Submission
                  </button>
                </div>
              )}
            </div>
        </div>
      </div>
    </div>
  );
}