"use client";

import { useState, useRef, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Loader2, ArrowLeft, FileText, Clock, Tag, User, BookOpen, Upload, AlertTriangle, Pencil, Save, X, Plus, Trash2, MessageSquare, Star, Wallet } from "lucide-react";
import Link from "next/link";
import { paperApi } from "@/lib/api/client";
import { useAuthStore } from "@/lib/store/auth-store";
import { paperListFor } from "@/lib/utils/paper-back-destination";
import type { PaperDetail, PaperCoauthor, ReviewSummary } from "@/types";

const statusColors: Record<string, string> = {
  DRAFT: "bg-gray-100 text-gray-600",
  PAYMENT_PENDING: "bg-amber-100 text-amber-800",
  SUBMITTED: "bg-blue-100 text-blue-700",
  SCREENING: "bg-indigo-100 text-indigo-700",
  PENDING_ASSIGNMENT: "bg-amber-100 text-amber-700",
  UNDER_REVIEW: "bg-purple-100 text-purple-700",
  REVISION_REQUESTED: "bg-orange-100 text-orange-700",
  REVISION_SUBMITTED: "bg-cyan-100 text-cyan-700",
  REVIEW_COMPLETE: "bg-teal-100 text-teal-700",
  ACCEPTED: "bg-emerald-100 text-emerald-700",
  REJECTED: "bg-red-100 text-red-700",
  PUBLISHED: "bg-green-100 text-green-700",
  WITHDRAWN: "bg-gray-100 text-gray-500",
};

const statusLabelsHi: Record<string, string> = {
  DRAFT: "मसौदा",
  PAYMENT_PENDING: "शुल्क भुगतान शेष",
  SUBMITTED: "प्रस्तुत",
  SCREENING: "स्क्रीनिंग",
  PENDING_ASSIGNMENT: "समीक्षक नियुक्ति हेतु",
  UNDER_REVIEW: "समीक्षाधीन",
  REVISION_REQUESTED: "संशोधन अनुरोध",
  REVISION_SUBMITTED: "संशोधन प्रस्तुत",
  REVIEW_COMPLETE: "समीक्षा पूर्ण",
  ACCEPTED: "स्वीकृत",
  REJECTED: "अस्वीकृत",
  PUBLISHED: "प्रकाशित",
  WITHDRAWN: "वापस लिया",
};

export default function PaperDetailPage() {
  const params = useParams();
  const router = useRouter();
  const role = useAuthStore((s) => s.user?.role);
  const backTo = paperListFor(role);
  const queryClient = useQueryClient();
  const id = params.id as string;

  // Revision upload state
  const [revisionFile, setRevisionFile] = useState<File | null>(null);
  const [changeNotes, setChangeNotes] = useState("");
  const [uploading, setUploading] = useState(false);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Edit mode state
  const [editing, setEditing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [editTitleHi, setEditTitleHi] = useState("");
  const [editTitleEn, setEditTitleEn] = useState("");
  const [editAbstractHi, setEditAbstractHi] = useState("");
  const [editAbstractEn, setEditAbstractEn] = useState("");
  const [editKeywords, setEditKeywords] = useState("");
  const [editCoauthors, setEditCoauthors] = useState<PaperCoauthor[]>([]);

  const { data: paper, isLoading, isError } = useQuery<PaperDetail>({
    queryKey: ["paper", id],
    queryFn: async () => {
      const res = await paperApi.get(id);
      return res.data;
    },
    enabled: !!id,
  });

  // Populate edit fields when paper loads or edit mode starts
  useEffect(() => {
    if (paper && editing) {
      setEditTitleHi(paper.titleHi || "");
      setEditTitleEn(paper.titleEn || "");
      setEditAbstractHi(paper.abstractHi || "");
      setEditAbstractEn(paper.abstractEn || "");
      setEditKeywords((paper.keywords || []).join(", "));
      setEditCoauthors(paper.coauthors ? paper.coauthors.map(ca => ({ ...ca })) : []);
    }
  }, [paper, editing]);

  const isRevisionRequested = paper?.status === "REVISION_REQUESTED";

  const startEditing = () => {
    setSaveError(null);
    setEditing(true);
  };

  const cancelEditing = () => {
    setEditing(false);
    setSaveError(null);
  };

  const handleSave = async () => {
    setSaving(true);
    setSaveError(null);
    try {
      await paperApi.update(id, {
        titleHi: editTitleHi,
        titleEn: editTitleEn,
        abstractHi: editAbstractHi,
        abstractEn: editAbstractEn,
        keywords: editKeywords.split(",").map(k => k.trim()).filter(Boolean),
        coauthors: editCoauthors.map(ca => ({
          nameHi: ca.nameHi,
          nameEn: ca.nameEn,
          email: ca.email || "",
          institution: ca.institution || "",
          authorOrder: ca.authorOrder,
          corresponding: ca.corresponding,
        })),
      });
      setEditing(false);
      queryClient.invalidateQueries({ queryKey: ["paper", id] });
      queryClient.invalidateQueries({ queryKey: ["author-papers"] });
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
      setSaveError(msg || "सहेजने में त्रुटि / Failed to save changes");
    }
    setSaving(false);
  };

  const addCoauthor = () => {
    setEditCoauthors(prev => [...prev, {
      nameHi: "",
      nameEn: "",
      email: "",
      institution: "",
      authorOrder: prev.length + 1,
      corresponding: false,
    }]);
  };

  const removeCoauthor = (index: number) => {
    setEditCoauthors(prev => prev.filter((_, i) => i !== index).map((ca, i) => ({ ...ca, authorOrder: i + 1 })));
  };

  const updateCoauthor = (index: number, field: keyof PaperCoauthor, value: string | boolean) => {
    setEditCoauthors(prev => prev.map((ca, i) => i === index ? { ...ca, [field]: value } : ca));
  };

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-3">
        <Loader2 className="h-8 w-8 animate-spin text-indigo-500" />
        <p className="text-sm text-gray-400">शोधपत्र लोड हो रहा है... / Loading paper...</p>
      </div>
    );
  }

  if (isError || !paper) {
    return (
      <div className="mx-auto max-w-3xl px-4 py-8">
        <div className="rounded-2xl border border-red-200 bg-red-50 p-12 text-center">
          <p className="text-sm text-red-600">शोधपत्र लोड करने में त्रुटि / Error loading paper</p>
          <Link href={backTo.href} className="mt-4 inline-block text-sm text-indigo-600 hover:underline">
            <ArrowLeft className="mr-1 inline h-3 w-3" /> {backTo.labelHi} / {backTo.labelEn}
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-4xl px-4 sm:px-6 py-8">
      {/* Back button + Edit toggle */}
      <div className="mb-6 flex items-center justify-between">
        <Link
          href={backTo.href}
          className="flex items-center gap-1.5 text-sm text-gray-500 hover:text-indigo-600 transition-colors"
        >
          <ArrowLeft className="h-4 w-4" />
          {backTo.labelHi} / {backTo.labelEn}
        </Link>
        {isRevisionRequested && !editing ? (
          <button
            onClick={startEditing}
            className="flex items-center gap-1.5 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 transition-colors"
          >
            <Pencil className="h-3.5 w-3.5" />
            संपादित करें / Edit
          </button>
        ) : null}
        {editing ? (
          <div className="flex items-center gap-2">
            <button
              onClick={cancelEditing}
              className="flex items-center gap-1.5 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-600 hover:bg-gray-50 transition-colors"
            >
              <X className="h-3.5 w-3.5" />
              रद्द करें / Cancel
            </button>
            <button
              onClick={handleSave}
              disabled={saving}
              className="flex items-center gap-1.5 rounded-lg bg-green-600 px-4 py-2 text-sm font-medium text-white hover:bg-green-700 disabled:bg-gray-300 transition-colors"
            >
              {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />}
              सहेजें / Save
            </button>
          </div>
        ) : null}
      </div>

      {saveError ? (
        <div className="mb-4 rounded-lg bg-red-50 border border-red-200 px-4 py-2 text-sm text-red-600">
          {saveError}
        </div>
      ) : null}

      {/* Header */}
      <div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm">
        <div className="flex flex-wrap items-start justify-between gap-3 mb-4">
          <div className="flex-1">
            <p className="text-[10px] font-mono text-gray-400 mb-1">{paper.referenceNo}</p>
            {editing ? (
              <div className="space-y-2">
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1">शीर्षक (हिन्दी) / Title (Hindi)</label>
                  <input
                    type="text"
                    value={editTitleHi}
                    onChange={(e) => setEditTitleHi(e.target.value)}
                    className="w-full rounded-lg border border-gray-200 px-3 py-2 text-base font-bold text-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-400"
                  />
                </div>
                <div>
                  <label className="block text-xs font-medium text-gray-500 mb-1">शीर्षक (English) / Title (English)</label>
                  <input
                    type="text"
                    value={editTitleEn}
                    onChange={(e) => setEditTitleEn(e.target.value)}
                    className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-indigo-400"
                  />
                </div>
              </div>
            ) : (
              <>
                <h1 className="text-xl font-bold text-gray-900 leading-snug">{paper.titleHi}</h1>
                {paper.titleEn ? (
                  <p className="mt-1 text-sm text-gray-500">{paper.titleEn}</p>
                ) : null}
              </>
            )}
          </div>
          <span className={`shrink-0 rounded-full px-3 py-1 text-xs font-medium ${statusColors[paper.status] || "bg-gray-100 text-gray-600"}`}>
            {statusLabelsHi[paper.status] || paper.status}
          </span>
        </div>

        {/* A held paper is invisible to reviewers, and nothing on this page would
            otherwise say why it has stopped moving. */}
        {paper.status === "PAYMENT_PENDING" && (
          <div className="mb-4 flex flex-col gap-3 rounded-md border border-amber-200 bg-amber-50 p-4 sm:flex-row sm:items-center sm:justify-between">
            <div className="flex items-start gap-2 text-sm text-amber-900">
              <Wallet className="mt-0.5 h-4 w-4 shrink-0" />
              <span>
                समीक्षा शुल्क बाकी है — पुष्टि होने तक यह शोधपत्र समीक्षकों को नहीं भेजा जाएगा।
                <br />
                <span className="text-amber-700">
                  The review fee is outstanding. This paper is not sent to reviewers
                  until it is confirmed.
                </span>
              </span>
            </div>
            <button
              onClick={() => router.push(`/papers/${id}/payment`)}
              className="shrink-0 rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-700"
            >
              भुगतान पृष्ठ खोलें / Open payment page
            </button>
          </div>
        )}

        {/* Meta */}
        <div className="flex flex-wrap gap-x-5 gap-y-2 text-xs text-gray-500 border-t border-gray-100 pt-4">
          {(paper.categoryNameHi || paper.categoryNameEn) ? (
            <span className="flex items-center gap-1">
              <Tag className="h-3 w-3" />
              {paper.categoryNameHi || paper.categoryNameEn}
            </span>
          ) : null}
          {paper.manuscriptName ? (
            <span className="flex items-center gap-1">
              <FileText className="h-3 w-3" />
              {paper.manuscriptName}
            </span>
          ) : null}
          {paper.doi ? (
            <span className="flex items-center gap-1">
              <BookOpen className="h-3 w-3" />
              DOI: {paper.doi}
            </span>
          ) : null}
        </div>
      </div>

      {/* Revision Upload — shown only when REVISION_REQUESTED */}
      {isRevisionRequested ? (
        <div className="mt-5 rounded-2xl border-2 border-orange-200 bg-orange-50 p-5 shadow-sm">
          <div className="flex items-start gap-3 mb-4">
            <AlertTriangle className="h-5 w-5 text-orange-500 shrink-0 mt-0.5" />
            <div>
              <h2 className="text-sm font-semibold text-orange-800">
                संशोधन अनुरोध / Revision Requested
              </h2>
              <p className="text-xs text-orange-600 mt-1">
                कृपया ऊपर &quot;संपादित करें&quot; बटन से विवरण संपादित करें और नीचे संशोधित पांडुलिपि अपलोड करें।
                <br />
                Please use the &quot;Edit&quot; button above to update details and upload the revised manuscript below.
              </p>
              {/* Show admin notes from the latest status history entry */}
              {paper.statusHistory && paper.statusHistory.length > 0 ? (() => {
                const revisionEntry = [...paper.statusHistory].reverse().find(sh => sh.toStatus === "REVISION_REQUESTED");
                return revisionEntry?.notes ? (
                  <div className="mt-2 rounded-lg bg-white/60 px-3 py-2 text-xs text-orange-700">
                    <span className="font-medium">टिप्पणी / Notes:</span> {revisionEntry.notes}
                  </div>
                ) : null;
              })() : null}
            </div>
          </div>

          <div className="space-y-3">
            {/* File input */}
            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                संशोधित पांडुलिपि / Revised Manuscript *
              </label>
              <div
                className="flex items-center gap-3 rounded-lg border-2 border-dashed border-orange-300 bg-white px-4 py-3 cursor-pointer hover:border-orange-400 transition"
                onClick={() => fileInputRef.current?.click()}
              >
                <Upload className="h-5 w-5 text-orange-400" />
                <div className="flex-1 text-sm">
                  {revisionFile ? (
                    <span className="font-medium text-gray-800">{revisionFile.name}</span>
                  ) : (
                    <span className="text-gray-400">फ़ाइल चुनें / Choose file (.pdf, .docx)</span>
                  )}
                </div>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept=".pdf,.docx,.doc"
                  className="hidden"
                  onChange={(e) => {
                    setRevisionFile(e.target.files?.[0] || null);
                    setUploadError(null);
                  }}
                />
              </div>
            </div>

            {/* Change notes */}
            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                परिवर्तन विवरण / Change Notes
              </label>
              <textarea
                rows={3}
                className="w-full rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 resize-none"
                placeholder="क्या बदलाव किए गए हैं... / Describe what changes were made..."
                value={changeNotes}
                onChange={(e) => setChangeNotes(e.target.value)}
              />
            </div>

            {/* Error */}
            {uploadError ? (
              <p className="text-xs text-red-600">{uploadError}</p>
            ) : null}

            {/* Submit */}
            <button
              disabled={!revisionFile || uploading}
              onClick={async () => {
                if (!revisionFile) return;
                setUploading(true);
                setUploadError(null);
                try {
                  const formData = new FormData();
                  formData.append("manuscript", revisionFile);
                  if (changeNotes.trim()) {
                    formData.append("changeNotes", changeNotes.trim());
                  }
                  await paperApi.uploadRevision(id, formData);
                  setRevisionFile(null);
                  setChangeNotes("");
                  queryClient.invalidateQueries({ queryKey: ["paper", id] });
                  queryClient.invalidateQueries({ queryKey: ["author-papers"] });
                } catch (err: unknown) {
                  const msg = (err as { response?: { data?: { message?: string } } })?.response?.data?.message;
                  setUploadError(msg || "संशोधन अपलोड विफल / Failed to upload revision");
                }
                setUploading(false);
              }}
              className="flex items-center justify-center gap-2 rounded-lg bg-orange-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-orange-700 disabled:bg-gray-300 transition-colors w-full sm:w-auto"
            >
              {uploading ? (
                <><Loader2 className="h-4 w-4 animate-spin" /> अपलोड हो रहा है...</>
              ) : (
                <><Upload className="h-4 w-4" /> संशोधन अपलोड करें / Upload Revision</>
              )}
            </button>
          </div>
        </div>
      ) : null}

      {/* Keywords */}
      <div className="mt-5 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
        <h2 className="mb-3 text-sm font-semibold text-gray-700">
          बीज शब्द / Keywords
        </h2>
        {editing ? (
          <div>
            <input
              type="text"
              value={editKeywords}
              onChange={(e) => setEditKeywords(e.target.value)}
              className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              placeholder="कॉमा से अलग करें / Comma separated keywords"
            />
            <p className="mt-1 text-[10px] text-gray-400">कॉमा (,) से अलग करें / Separate with commas</p>
          </div>
        ) : (
          paper.keywords && paper.keywords.length > 0 ? (
            <div className="flex flex-wrap gap-2">
              {paper.keywords.map((kw) => (
                <span key={kw} className="rounded-full bg-indigo-50 px-3 py-1 text-xs font-medium text-indigo-700">
                  {kw}
                </span>
              ))}
            </div>
          ) : (
            <p className="text-xs text-gray-400">कोई बीज शब्द नहीं / No keywords</p>
          )
        )}
      </div>

      {/* Abstract */}
      <div className="mt-5 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
        <h2 className="mb-3 text-sm font-semibold text-gray-700">
          सारांश / Abstract
        </h2>
        {editing ? (
          <div className="space-y-3">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">सारांश (हिन्दी) / Abstract (Hindi)</label>
              <textarea
                rows={5}
                value={editAbstractHi}
                onChange={(e) => setEditAbstractHi(e.target.value)}
                className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400 resize-none"
              />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">सारांश (English) / Abstract (English)</label>
              <textarea
                rows={5}
                value={editAbstractEn}
                onChange={(e) => setEditAbstractEn(e.target.value)}
                className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400 resize-none"
              />
            </div>
          </div>
        ) : (
          <>
            {paper.abstractHi ? (
              <p className="text-sm text-gray-700 leading-relaxed whitespace-pre-line">{paper.abstractHi}</p>
            ) : null}
            {paper.abstractEn && paper.abstractHi ? (
              <hr className="my-4 border-gray-100" />
            ) : null}
            {paper.abstractEn ? (
              <p className="text-sm text-gray-600 leading-relaxed whitespace-pre-line">{paper.abstractEn}</p>
            ) : null}
            {!paper.abstractHi && !paper.abstractEn ? (
              <p className="text-xs text-gray-400">कोई सारांश नहीं / No abstract</p>
            ) : null}
          </>
        )}
      </div>

      {/* Reviewer Comments */}
      {paper.reviews && paper.reviews.length > 0 ? (
        <div className="mt-5 rounded-2xl border border-indigo-100 bg-white p-5 shadow-sm">
          <h2 className="mb-4 text-sm font-semibold text-gray-700">
            <MessageSquare className="mr-1 inline h-3.5 w-3.5" />
            समीक्षक टिप्पणियाँ / Reviewer Comments
          </h2>
          <div className="space-y-4">
            {paper.reviews.map((review: ReviewSummary, i: number) => {
              const recColors: Record<string, string> = {
                ACCEPT: "bg-green-100 text-green-700",
                MINOR_REVISION: "bg-yellow-100 text-yellow-700",
                MAJOR_REVISION: "bg-orange-100 text-orange-700",
                REJECT: "bg-red-100 text-red-700",
              };
              const recLabels: Record<string, string> = {
                ACCEPT: "स्वीकृत / Accept",
                MINOR_REVISION: "लघु संशोधन / Minor Revision",
                MAJOR_REVISION: "बृहत संशोधन / Major Revision",
                REJECT: "अस्वीकृत / Reject",
              };
              return (
                <div key={i} className="rounded-xl border border-gray-100 bg-gray-50 p-4">
                  <div className="flex items-center justify-between mb-3">
                    <span className="text-xs font-medium text-gray-500">
                      समीक्षक / Reviewer #{i + 1}
                    </span>
                    {review.recommendation ? (
                      <span className={`rounded-full px-2.5 py-0.5 text-[10px] font-medium ${recColors[review.recommendation] || "bg-gray-100 text-gray-600"}`}>
                        {recLabels[review.recommendation] || review.recommendation}
                      </span>
                    ) : null}
                  </div>

                  {/* Scores */}
                  {review.overallScore != null ? (
                    <div className="mb-3 grid grid-cols-3 sm:grid-cols-6 gap-2 text-center">
                      {[
                        { label: "मौलिकता", en: "Originality", val: review.originalityScore },
                        { label: "विधि", en: "Method", val: review.methodologyScore },
                        { label: "स्पष्टता", en: "Clarity", val: review.clarityScore },
                        { label: "प्रासंगिकता", en: "Relevance", val: review.relevanceScore },
                        { label: "संदर्भ", en: "References", val: review.referencesScore },
                        { label: "कुल", en: "Overall", val: review.overallScore },
                      ].map((s) => (
                        <div key={s.en} className="rounded-lg bg-white border border-gray-100 px-2 py-1.5">
                          <p className="text-[10px] text-gray-400">{s.label}</p>
                          <p className="text-sm font-semibold text-gray-700">
                            {s.val != null ? (typeof s.val === "number" ? s.val : Number(s.val).toFixed(1)) : "–"}
                          </p>
                        </div>
                      ))}
                    </div>
                  ) : null}

                  {/* Comments */}
                  {review.commentsToAuthor ? (
                    <div className="rounded-lg bg-white border border-gray-100 px-4 py-3">
                      <p className="text-xs font-medium text-gray-500 mb-1">टिप्पणियाँ / Comments</p>
                      <p className="text-sm text-gray-700 whitespace-pre-line leading-relaxed">
                        {review.commentsToAuthor}
                      </p>
                    </div>
                  ) : null}

                  {review.completedAt ? (
                    <p className="mt-2 text-[10px] text-gray-400 text-right">
                      {new Date(review.completedAt).toLocaleString("hi-IN", {
                        day: "numeric", month: "long", year: "numeric",
                        hour: "2-digit", minute: "2-digit",
                      })}
                    </p>
                  ) : null}
                </div>
              );
            })}
          </div>
        </div>
      ) : null}

      {/* Co-authors */}
      <div className="mt-5 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
        <h2 className="mb-3 text-sm font-semibold text-gray-700">
          <User className="mr-1 inline h-3.5 w-3.5" />
          सह-लेखक / Co-authors
        </h2>
        {editing ? (
          <div className="space-y-4">
            {editCoauthors.map((ca, i) => (
              <div key={i} className="rounded-lg border border-gray-200 p-3 space-y-2">
                <div className="flex items-center justify-between">
                  <span className="text-xs font-medium text-gray-500">सह-लेखक #{ca.authorOrder}</span>
                  <button onClick={() => removeCoauthor(i)} className="text-red-400 hover:text-red-600">
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  <input
                    type="text"
                    placeholder="नाम (हिन्दी)"
                    value={ca.nameHi}
                    onChange={(e) => updateCoauthor(i, "nameHi", e.target.value)}
                    className="rounded border border-gray-200 px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
                  />
                  <input
                    type="text"
                    placeholder="Name (English)"
                    value={ca.nameEn}
                    onChange={(e) => updateCoauthor(i, "nameEn", e.target.value)}
                    className="rounded border border-gray-200 px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
                  />
                  <input
                    type="email"
                    placeholder="Email"
                    value={ca.email || ""}
                    onChange={(e) => updateCoauthor(i, "email", e.target.value)}
                    className="rounded border border-gray-200 px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
                  />
                  <input
                    type="text"
                    placeholder="संस्थान / Institution"
                    value={ca.institution || ""}
                    onChange={(e) => updateCoauthor(i, "institution", e.target.value)}
                    className="rounded border border-gray-200 px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
                  />
                </div>
                <label className="flex items-center gap-2 text-xs text-gray-600">
                  <input
                    type="checkbox"
                    checked={ca.corresponding}
                    onChange={(e) => updateCoauthor(i, "corresponding", e.target.checked)}
                    className="rounded border-gray-300"
                  />
                  पत्राचार लेखक / Corresponding Author
                </label>
              </div>
            ))}
            <button
              onClick={addCoauthor}
              className="flex items-center gap-1.5 text-sm text-indigo-600 hover:text-indigo-800"
            >
              <Plus className="h-3.5 w-3.5" />
              सह-लेखक जोड़ें / Add Co-author
            </button>
          </div>
        ) : (
          paper.coauthors && paper.coauthors.length > 0 ? (
            <div className="space-y-3">
              {paper.coauthors
                .sort((a, b) => a.authorOrder - b.authorOrder)
                .map((ca, i) => (
                  <div key={i} className="flex items-start gap-3 text-sm">
                    <span className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-gray-100 text-[10px] font-bold text-gray-500">
                      {ca.authorOrder}
                    </span>
                    <div>
                      <p className="font-medium text-gray-800">
                        {ca.nameHi || ca.nameEn}
                        {ca.corresponding ? (
                          <span className="ml-2 text-[10px] text-amber-600">*पत्राचार / Corresponding</span>
                        ) : null}
                      </p>
                      {ca.nameEn && ca.nameHi ? (
                        <p className="text-xs text-gray-400">{ca.nameEn}</p>
                      ) : null}
                      {ca.institution ? (
                        <p className="text-xs text-gray-400">{ca.institution}</p>
                      ) : null}
                      {ca.email ? (
                        <p className="text-xs text-gray-400">{ca.email}</p>
                      ) : null}
                    </div>
                  </div>
                ))}
            </div>
          ) : (
            <p className="text-xs text-gray-400">कोई सह-लेखक नहीं / No co-authors</p>
          )
        )}
      </div>

      {/* Status History */}
      {paper.statusHistory && paper.statusHistory.length > 0 ? (
        <div className="mt-5 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm">
          <h2 className="mb-3 text-sm font-semibold text-gray-700">
            <Clock className="mr-1 inline h-3.5 w-3.5" />
            स्थिति इतिहास / Status History
          </h2>
          <div className="space-y-3">
            {paper.statusHistory.map((sh, i) => (
              <div key={i} className="flex items-start gap-3">
                <div className="mt-1 h-2 w-2 shrink-0 rounded-full bg-indigo-400" />
                <div className="text-sm">
                  <p className="font-medium text-gray-800">
                    {statusLabelsHi[sh.toStatus] || sh.toStatus}
                  </p>
                  {sh.notes ? (
                    <p className="text-xs text-gray-500">{sh.notes}</p>
                  ) : null}
                  <p className="text-[10px] text-gray-400">
                    {new Date(sh.createdAt).toLocaleString("hi-IN", {
                      day: "numeric",
                      month: "long",
                      year: "numeric",
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      ) : null}
    </div>
  );
}
