"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import Header from "@/components/Header";
import {
  initializeAtsStorage,
  readApplicantsFromStorage,
  readApplicantByIdFromStorage,
  readPositionByIdFromStorage,
  writeApplicantsToStorage,
  type ApplicantWithPosition,
} from "@/components/initialPositionsData";
import {
  appendEventToStorage,
  initializeEventStreamStorage,
  readEventsForApplicant,
  type AtsEvent,
} from "@/components/eventStream";
import { formatEventForRecruiter } from "@/components/hrEventFormatter";

type EvaluationPolicy = {
  policyId: string;
  job_description: string;
  overall_summary: string;
  hard_requirements: string[];
};

type ScreeningEvaluation = {
  candidate_name?: string;
  candidate_phone_number?: string;
  overall_fit_score?: number | string;
  matching_skills?: string[];
  skill_gaps?: string[];
  overall_summary?: string;
  raw?: string;
};

type ScorecardRecommendation = "hire" | "no_hire" | "strong_hire";

const SCREENING_POLICIES_STORAGE_KEY = "ats.screeningPolicies.v1";

function clonePolicy(policy: EvaluationPolicy): EvaluationPolicy {
  return {
    policyId: policy.policyId,
    job_description: policy.job_description,
    overall_summary: policy.overall_summary,
    hard_requirements: [...policy.hard_requirements],
  };
}

function getNextPolicyId(policyId: string) {
  const match = policyId.match(/^(.*#v)(\d+)\.(\d+)$/i);
  if (!match) {
    return `${policyId}_v2.0`;
  }
  const major = Number(match[2]);
  const minor = Number(match[3]);
  return `${match[1]}${major}.${minor + 1}`;
}

function getNextUniquePolicyId(basePolicyId: string, existingPolicyIds: Set<string>) {
  let nextId = getNextPolicyId(basePolicyId);
  while (existingPolicyIds.has(nextId)) {
    nextId = getNextPolicyId(nextId);
  }
  return nextId;
}

function normalizePolicies(rawPolicies: EvaluationPolicy[]) {
  const usedIds = new Set<string>();
  return rawPolicies.map((policy) => {
    let normalizedId = policy.policyId;
    if (usedIds.has(normalizedId)) {
      normalizedId = getNextUniquePolicyId(normalizedId, usedIds);
    }
    usedIds.add(normalizedId);
    return {
      ...policy,
      policyId: normalizedId,
      hard_requirements: Array.isArray(policy.hard_requirements)
        ? [...policy.hard_requirements]
        : [],
    };
  });
}

function getOfferSigningStatusSummary(status?: string) {
  const normalized = status?.trim().toUpperCase();
  const summaryByStatus: Record<string, string> = {
    DRAFT: "Offer package is in draft and the embedded eSign session is ready for sending.",
    SHARED: "Offer package has been shared and is waiting for participant action.",
    "PARTIALLY SIGNED":
      "Offer package is partially signed and still in progress with remaining signers.",
    EXECUTED: "Offer package is fully executed and all required signatures are complete.",
    CANCELLED: "Offer package was cancelled and can no longer be signed.",
    EXPIRED: "Offer package has expired and requires a new signing session.",
    DELETED: "Offer package was deleted from the eSign workflow.",
  };

  if (normalized && summaryByStatus[normalized]) {
    return summaryByStatus[normalized];
  }
  if (normalized) {
    return `Offer package status is ${status}.`;
  }
  return "Offer package is in the embedded eSign workflow and awaiting status updates.";
}

export default function ApplicantPage() {
  const params = useParams<{ id: string }>();
  const router = useRouter();
  const searchParams = useSearchParams();
  const applicantId = params?.id ?? "";
  const routePositionId = searchParams.get("positionId");
  const [applicant, setApplicant] = useState<ApplicantWithPosition | null>(null);
  const [events, setEvents] = useState<AtsEvent[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showUploadToast, setShowUploadToast] = useState(false);
  const [offerToast, setOfferToast] = useState<{
    type: "loading" | "success";
    message: string;
  } | null>(null);
  const [actionToast, setActionToast] = useState<string | null>(null);
  const [isDispositionModalOpen, setIsDispositionModalOpen] = useState(false);
  const [isResumePreviewOpen, setIsResumePreviewOpen] = useState(false);
  const [isSendingSessionModalOpen, setIsSendingSessionModalOpen] = useState(false);
  const [sendingSessionUrl, setSendingSessionUrl] = useState<string | null>(null);
  const [isScreeningModalOpen, setIsScreeningModalOpen] = useState(false);
  const [isOfferSessionOpen, setIsOfferSessionOpen] = useState(true);
  const [screeningRunMode, setScreeningRunMode] = useState<"initial" | "rerun">("initial");
  const [screeningPolicies, setScreeningPolicies] = useState<EvaluationPolicy[]>([]);
  const [selectedPolicyId, setSelectedPolicyId] = useState<string>("");
  const [screeningPolicyDraft, setScreeningPolicyDraft] = useState<EvaluationPolicy | null>(null);
  const [selectedPolicyBaseline, setSelectedPolicyBaseline] = useState<EvaluationPolicy | null>(null);
  const [isPolicyDraftEditable, setIsPolicyDraftEditable] = useState(false);
  const [isRunningScreening, setIsRunningScreening] = useState(false);
  const [screeningResult, setScreeningResult] = useState<ScreeningEvaluation | null>(null);
  const [screeningError, setScreeningError] = useState<string | null>(null);
  const [selectedDisposition, setSelectedDisposition] = useState<"hired" | "closed">("hired");
  const [scorecardRecommendation, setScorecardRecommendation] = useState<ScorecardRecommendation | "">("");
  const [scorecardRating, setScorecardRating] = useState<1 | 2 | 3 | 4 | 5 | null>(null);
  const [scorecardComments, setScorecardComments] = useState("");
  const isOfferFlowRunningRef = useRef(false);
  const policyFieldClass = isPolicyDraftEditable
    ? "rounded-md border border-slate-300 px-3 py-2 text-slate-800"
    : "rounded-md border border-slate-300 bg-slate-100 px-3 py-2 text-slate-500";
  const OFFER_SENT_TOAST_FLAG_KEY = "ats.offerLetterSentAfterSessionClose";

  useEffect(() => {
    setIsLoading(true);
    initializeAtsStorage();
    initializeEventStreamStorage();

    const foundApplicant = readApplicantByIdFromStorage(applicantId) ?? null;
    const foundEvents = readEventsForApplicant(applicantId);

    const timeout = window.setTimeout(() => {
      setApplicant(foundApplicant);
      setEvents(foundEvents);
      setIsLoading(false);
    }, 220);

    return () => {
      window.clearTimeout(timeout);
    };
  }, [applicantId]);

  useEffect(() => {
    if (searchParams.get("uploaded") !== "1") {
      return;
    }

    setShowUploadToast(true);
    const timeout = window.setTimeout(() => {
      setShowUploadToast(false);
    }, 3000);

    return () => {
      window.clearTimeout(timeout);
    };
  }, [searchParams]);

  useEffect(() => {
    if (typeof window === "undefined") {
      return;
    }
    if (window.sessionStorage.getItem(OFFER_SENT_TOAST_FLAG_KEY) !== "1") {
      return;
    }

    window.sessionStorage.removeItem(OFFER_SENT_TOAST_FLAG_KEY);
    setOfferToast({
      type: "success",
      message: "Offer Letter Sent for eSignature",
    });

    const timeout = window.setTimeout(() => {
      setOfferToast(null);
    }, 2400);

    return () => {
      window.clearTimeout(timeout);
    };
  }, [OFFER_SENT_TOAST_FLAG_KEY]);

  useEffect(() => {
    const recommendation = applicant?.scorecard?.recommendation;
    const rating = applicant?.scorecard?.rating;
    setScorecardRecommendation(
      recommendation === "hire" || recommendation === "no_hire" || recommendation === "strong_hire"
        ? recommendation
        : ""
    );
    setScorecardRating(
      rating === 1 || rating === 2 || rating === 3 || rating === 4 || rating === 5 ? rating : null
    );
    setScorecardComments(applicant?.scorecard?.comments ?? "");
  }, [applicant?.id, applicant?.scorecard?.recommendation, applicant?.scorecard?.rating, applicant?.scorecard?.comments]);

  function refreshApplicantAndEvents() {
    const foundApplicant = readApplicantByIdFromStorage(applicantId) ?? null;
    setApplicant(foundApplicant);
    setEvents(readEventsForApplicant(applicantId));
  }

  function moveApplicantStage(nextStageId: string) {
    if (!applicant) {
      return;
    }

    const positionApplicants = readApplicantsFromStorage(applicant.positionId);
    const nextApplicants = positionApplicants.map((item) =>
      item.id === applicant.id ? { ...item, stageId: nextStageId } : item
    );
    writeApplicantsToStorage(applicant.positionId, nextApplicants);
  }

  function saveScreeningEvaluation(evaluation: ScreeningEvaluation, screeningPolicyId: string) {
    if (!applicant) {
      return;
    }

    const positionApplicants = readApplicantsFromStorage(applicant.positionId);
    const completedAt = new Date().toISOString();
    const nextApplicants = positionApplicants.map((item) =>
      item.id === applicant.id
        ? {
            ...item,
            screeningEvaluation: evaluation,
            screeningPolicyId,
            screeningCompletedAt: completedAt,
          }
        : item
    );
    writeApplicantsToStorage(applicant.positionId, nextApplicants);
  }

  function saveOfferLetterSessionInfo(input: {
    embeddedSessionURL?: string;
    folderAccessURLForAuthor?: string;
    folderId?: string | number | null;
    esignStatus?: string;
  }) {
    if (!applicant) {
      return;
    }
    const updatedAt = new Date().toISOString();
    const positionApplicants = readApplicantsFromStorage(applicant.positionId);
    const nextApplicants = positionApplicants.map((item) =>
      item.id === applicant.id
        ? {
            ...item,
            offerLetterEmbeddedSessionUrl:
              typeof input.embeddedSessionURL === "string" && input.embeddedSessionURL.length > 0
                ? input.embeddedSessionURL
                : item.offerLetterEmbeddedSessionUrl,
            offerLetterAuthorAccessUrl:
              typeof input.folderAccessURLForAuthor === "string" &&
              input.folderAccessURLForAuthor.length > 0
                ? input.folderAccessURLForAuthor
                : item.offerLetterAuthorAccessUrl,
            offerLetterFolderId:
              typeof input.folderId === "string" || typeof input.folderId === "number"
                ? input.folderId
                : item.offerLetterFolderId,
            offerLetterEsignStatus:
              typeof input.esignStatus === "string" && input.esignStatus.length > 0
                ? input.esignStatus
                : item.offerLetterEsignStatus,
            offerLetterSessionUpdatedAt: updatedAt,
          }
        : item
    );
    writeApplicantsToStorage(applicant.positionId, nextApplicants);
  }

  function saveScorecard() {
    if (!applicant || applicant.stageId !== "resume_review_screening") {
      return;
    }
    if (!scorecardRecommendation || !scorecardRating) {
      return;
    }

    const updatedAt = new Date().toISOString();
    const positionApplicants = readApplicantsFromStorage(applicant.positionId);
    const nextApplicants = positionApplicants.map((item) =>
      item.id === applicant.id
        ? {
            ...item,
            scorecard: {
              recommendation: scorecardRecommendation,
              rating: scorecardRating,
              comments: scorecardComments.trim(),
              updatedAt,
            },
          }
        : item
    );
    writeApplicantsToStorage(applicant.positionId, nextApplicants);

    appendEventToStorage({
      eventType: "ApplicantScorecardSubmitted",
      traceId: applicant.positionId,
      payload: {
        streamCategory: "applicants_stream",
        streamId: `applicants:${applicant.positionId}`,
        positionId: applicant.positionId,
        applicantId: applicant.id,
        applicantName: applicant.name,
        recommendation: scorecardRecommendation,
        rating: scorecardRating,
        comments: scorecardComments.trim(),
        updatedAt,
      },
    });

    refreshApplicantAndEvents();
    showActionToast("Scorecard saved");
  }

  function runOfferLetterSendFlow(source: "manager_action" | "available_action") {
    if (!applicant || isOfferFlowRunningRef.current) {
      return;
    }

    isOfferFlowRunningRef.current = true;

    let cancelled = false;

    setOfferToast({
      type: "loading",
      message: "Creating eSign Sending Session",
    });

    const positionTitle = readPositionByIdFromStorage(applicant.positionId)?.title ?? "Unknown Position";

    appendEventToStorage({
      eventType: "ApplicantOfferLetterInitiated",
      traceId: applicant.positionId,
      payload: {
        streamCategory: "manager_actions_stream",
        streamId: `manager-actions:${applicant.positionId}`,
        action: source === "manager_action" ? "send_applicant_offer_letter" : "send_offer_letter",
        positionId: applicant.positionId,
        positionTitle,
        applicantId: applicant.id,
        applicantName: applicant.name,
        startedAt: new Date().toISOString(),
      },
    });
    setEvents(readEventsForApplicant(applicantId));

    const nameParts = applicant.name.trim().split(/\s+/).filter(Boolean);
    const firstName = nameParts[0] ?? "Applicant";
    const lastName = nameParts.slice(1).join(" ") || "Applicant";
    const fallbackEmail = `${firstName}.${lastName}`
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, ".")
      .replace(/^\.+|\.+$/g, "");
    const emailId = applicant.email?.trim() || `${fallbackEmail || "applicant"}@example.com`;

    void (async () => {
      const response = await fetch("/api/offer-letter/run-esign-offer-letter", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          firstName,
          lastName,
          emailId,
        }),
      });

      const data = (await response.json()) as {
        embeddedSessionURL?: string;
        folderAccessURLForAuthor?: string;
        folderId?: string | number;
        esignStatus?: string;
        error?: string;
      };

      if (!response.ok) {
        throw new Error(data.error ?? "Failed to send offer letter.");
      }

      if (cancelled) {
        isOfferFlowRunningRef.current = false;
        return;
      }

      if (applicant.stageId !== "offer_letter_sent" && applicant.stageId !== "hired_or_closed") {
        moveApplicantStage("offer_letter_sent");
        appendEventToStorage({
          eventType: "ApplicantStageMoved",
          traceId: applicant.positionId,
          payload: {
            streamCategory: "applicants_stream",
            streamId: `applicants:${applicant.positionId}`,
            positionId: applicant.positionId,
            applicantId: applicant.id,
            applicantName: applicant.name,
            fromStageId: applicant.stageId,
            toStageId: "offer_letter_sent",
            movedAt: new Date().toISOString(),
          },
        });
      }

      const embeddedSessionURL = data.embeddedSessionURL;
      saveOfferLetterSessionInfo({
        embeddedSessionURL,
        folderAccessURLForAuthor: data.folderAccessURLForAuthor,
        folderId: data.folderId,
        esignStatus: data.esignStatus,
      });

      appendEventToStorage({
        eventType: "ApplicantOfferLetterSent",
        traceId: applicant.positionId,
        payload: {
          streamCategory: "manager_actions_stream",
          streamId: `manager-actions:${applicant.positionId}`,
          action: "applicant_offer_letter_sent",
          positionId: applicant.positionId,
          positionTitle,
          applicantId: applicant.id,
          applicantName: applicant.name,
          folderId: data.folderId ?? null,
          folderAccessURLForAuthor: data.folderAccessURLForAuthor ?? null,
          embeddedSessionURL: embeddedSessionURL ?? null,
          esignStatus: data.esignStatus ?? null,
          sentAt: new Date().toISOString(),
        },
      });
      refreshApplicantAndEvents();

      setOfferToast({
        type: "success",
        message: "Sending Session Creation Successful",
      });
      if (embeddedSessionURL) {
        setSendingSessionUrl(embeddedSessionURL);
        setIsSendingSessionModalOpen(true);
      }

      const params = new URLSearchParams();
      if (routePositionId) {
        params.set("positionId", routePositionId);
      }
      if (searchParams.get("uploaded") === "1") {
        params.set("uploaded", "1");
      }

      const query = params.toString();
      router.replace(query ? `/applicants/${applicantId}?${query}` : `/applicants/${applicantId}`);

      window.setTimeout(() => {
        setOfferToast(null);
      }, 2200);
      isOfferFlowRunningRef.current = false;
    })().catch((error: unknown) => {
      if (cancelled) {
        isOfferFlowRunningRef.current = false;
        return;
      }
      const message = error instanceof Error ? error.message : "Failed to send offer letter.";
      setOfferToast(null);
      showActionToast(message);
      isOfferFlowRunningRef.current = false;
    });

    return () => {
      cancelled = true;
      isOfferFlowRunningRef.current = false;
    };
  }

  useEffect(() => {
    if (searchParams.get("sendOffer") !== "1" || !applicant) {
      return;
    }
    const cleanup = runOfferLetterSendFlow("manager_action");
    return cleanup;
  }, [applicant, searchParams]);

  useEffect(() => {
    if (searchParams.get("openAIScreening") !== "1" || !applicant) {
      return;
    }
    if (applicant.stageId !== "new_applied") {
      return;
    }

    void openScreeningProcess("initial");

    const params = new URLSearchParams(searchParams.toString());
    params.delete("openAIScreening");
    const query = params.toString();
    router.replace(query ? `/applicants/${applicantId}?${query}` : `/applicants/${applicantId}`);
  }, [applicant, applicantId, router, searchParams]);

  useEffect(() => {
    if (!applicant || typeof applicant.offerLetterFolderId === "undefined") {
      return;
    }

    let cancelled = false;
    const folderId = String(applicant.offerLetterFolderId);
    const previousStatus = applicant.offerLetterEsignStatus ?? "";

    void (async () => {
      try {
        const response = await fetch(
          `/api/offer-letter/get-esign-status?folderId=${encodeURIComponent(folderId)}`
        );
        if (!response.ok) {
          return;
        }

        const data = (await response.json()) as {
          esignStatus?: string | null;
          folderAccessURLForAuthor?: string | null;
        };
        const nextStatus = typeof data.esignStatus === "string" ? data.esignStatus : "";
        const nextAuthorAccessUrl =
          typeof data.folderAccessURLForAuthor === "string" ? data.folderAccessURLForAuthor : "";

        if (nextAuthorAccessUrl && nextAuthorAccessUrl !== applicant.offerLetterAuthorAccessUrl) {
          saveOfferLetterSessionInfo({
            folderId: applicant.offerLetterFolderId,
            folderAccessURLForAuthor: nextAuthorAccessUrl,
          });
          refreshApplicantAndEvents();
        }

        if (!nextStatus || cancelled || nextStatus === previousStatus) {
          return;
        }

        saveOfferLetterSessionInfo({
          folderId: applicant.offerLetterFolderId,
          folderAccessURLForAuthor: nextAuthorAccessUrl || undefined,
          esignStatus: nextStatus,
        });

        appendEventToStorage({
          eventType: "ApplicantOfferLetterStatusUpdated",
          traceId: applicant.positionId,
          payload: {
            streamCategory: "manager_actions_stream",
            streamId: `manager-actions:${applicant.positionId}`,
            positionId: applicant.positionId,
            applicantId: applicant.id,
            applicantName: applicant.name,
            folderId: applicant.offerLetterFolderId,
            previousStatus: previousStatus || null,
            currentStatus: nextStatus,
            refreshedAt: new Date().toISOString(),
          },
        });

        refreshApplicantAndEvents();
      } catch {
        // Ignore refresh errors and keep existing status.
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [applicantId, applicant?.offerLetterFolderId]);

  function showActionToast(message: string) {
    setActionToast(message);
    window.setTimeout(() => {
      setActionToast(null);
    }, 2200);
  }

  function policiesEqual(a: EvaluationPolicy | null, b: EvaluationPolicy | null) {
    if (!a || !b) {
      return false;
    }
    return JSON.stringify(a) === JSON.stringify(b);
  }

  function persistScreeningPolicies(nextPolicies: EvaluationPolicy[]) {
    setScreeningPolicies(nextPolicies);
    if (typeof window !== "undefined") {
      window.localStorage.setItem(SCREENING_POLICIES_STORAGE_KEY, JSON.stringify(nextPolicies));
    }
  }

  function handlePolicySelection(nextPolicyId: string) {
    setSelectedPolicyId(nextPolicyId);
    setIsPolicyDraftEditable(false);
    const nextPolicy = screeningPolicies.find((policy) => policy.policyId === nextPolicyId);
    if (!nextPolicy) {
      return;
    }
    const cloned = clonePolicy(nextPolicy);
    setScreeningPolicyDraft(cloned);
    setSelectedPolicyBaseline(cloned);
    setScreeningResult(null);
    setScreeningError(null);
  }

  function createNewPolicyVersion() {
    if (!screeningPolicyDraft) {
      return;
    }

    const existingIds = new Set(screeningPolicies.map((policy) => policy.policyId));
    const newPolicyId = getNextUniquePolicyId(screeningPolicyDraft.policyId, existingIds);
    const newPolicy: EvaluationPolicy = {
      ...clonePolicy(screeningPolicyDraft),
      policyId: newPolicyId,
    };
    const nextPolicies = [...screeningPolicies, newPolicy];
    persistScreeningPolicies(nextPolicies);
    setSelectedPolicyId(newPolicy.policyId);
    setScreeningPolicyDraft(clonePolicy(newPolicy));
    setSelectedPolicyBaseline(clonePolicy(newPolicy));
    setIsPolicyDraftEditable(true);
  }

  async function openScreeningProcess(mode: "initial" | "rerun" = "initial") {
    setScreeningRunMode(mode);
    setIsScreeningModalOpen(true);
    setScreeningError(null);
    setScreeningResult(null);

    try {
      const response = await fetch("/api/screening/evaluation-policy");
      if (!response.ok) {
        throw new Error("Failed to load evaluation policy.");
      }
      const data = (await response.json()) as {
        policies?: EvaluationPolicy[];
        defaultPolicyId?: string;
      };
      if (!data.policies || !Array.isArray(data.policies) || data.policies.length === 0) {
        throw new Error("Policy payload missing.");
      }
      const normalizedPolicies = normalizePolicies(data.policies);
      const defaultPolicy =
        normalizedPolicies.find((policy) => policy.policyId === data.defaultPolicyId) ??
        normalizedPolicies[0];
      persistScreeningPolicies(normalizedPolicies);
      setSelectedPolicyId(defaultPolicy.policyId);
      setScreeningPolicyDraft(clonePolicy(defaultPolicy));
      setSelectedPolicyBaseline(clonePolicy(defaultPolicy));
      setIsPolicyDraftEditable(false);
    } catch (error) {
      const message = error instanceof Error ? error.message : "Failed to load policy.";
      setScreeningError(message);
    }
  }

  async function startScreeningProcess() {
    if (!applicant || !screeningPolicyDraft) {
      return;
    }
    if (screeningRunMode === "initial" && applicant.stageId !== "new_applied") {
      return;
    }

    setIsRunningScreening(true);
    setScreeningError(null);

    if (!policiesEqual(screeningPolicyDraft, selectedPolicyBaseline)) {
      appendEventToStorage({
        eventType: "ApplicantScreeningPolicyModified",
        traceId: applicant.positionId,
        payload: {
          streamCategory: "applicants_stream",
          streamId: `applicants:${applicant.positionId}`,
          positionId: applicant.positionId,
          applicantId: applicant.id,
          applicantName: applicant.name,
          policyId: screeningPolicyDraft.policyId,
          modifiedAt: new Date().toISOString(),
        },
      });
    }

    const nextPolicies = screeningPolicies.map((policy) =>
      policy.policyId === selectedPolicyId ? clonePolicy(screeningPolicyDraft) : policy
    );
    persistScreeningPolicies(nextPolicies);

    if (screeningRunMode === "initial") {
      appendEventToStorage({
        eventType: "ApplicantScreeningInitiated",
        traceId: applicant.positionId,
        payload: {
          streamCategory: "applicants_stream",
          streamId: `applicants:${applicant.positionId}`,
          positionId: applicant.positionId,
          applicantId: applicant.id,
          applicantName: applicant.name,
          initiatedAt: new Date().toISOString(),
        },
      });

      moveApplicantStage("resume_review_screening");
      appendEventToStorage({
        eventType: "ApplicantStageMoved",
        traceId: applicant.positionId,
        payload: {
          streamCategory: "applicants_stream",
          streamId: `applicants:${applicant.positionId}`,
          positionId: applicant.positionId,
          applicantId: applicant.id,
          applicantName: applicant.name,
          fromStageId: "new_applied",
          toStageId: "resume_review_screening",
          movedAt: new Date().toISOString(),
        },
      });
      refreshApplicantAndEvents();
    }

    try {
      const response = await fetch("/api/screening/run-evaluation", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ policy: screeningPolicyDraft }),
      });
      const data = (await response.json()) as {
        evaluation?: ScreeningEvaluation;
        error?: string;
      };

      if (!response.ok) {
        throw new Error(data.error ?? "Failed to run screening.");
      }

      const evaluation = data.evaluation ?? {};
      setScreeningResult(evaluation);
      saveScreeningEvaluation(evaluation, screeningPolicyDraft.policyId);
      appendEventToStorage({
        eventType: "ApplicantScreeningEvaluationCompleted",
        traceId: applicant.positionId,
        payload: {
          streamCategory: "applicants_stream",
          streamId: `applicants:${applicant.positionId}`,
          positionId: applicant.positionId,
          applicantId: applicant.id,
          applicantName: applicant.name,
          policyId: screeningPolicyDraft.policyId,
          completedAt: new Date().toISOString(),
          overallFitScore:
            typeof evaluation.overall_fit_score === "number" ||
            typeof evaluation.overall_fit_score === "string"
              ? evaluation.overall_fit_score
              : "Unknown",
        },
      });
      setSelectedPolicyBaseline(clonePolicy(screeningPolicyDraft));
      setIsScreeningModalOpen(false);
      showActionToast(
        screeningRunMode === "rerun"
          ? "AI Screening evaluation re-run completed"
          : "AI Screening completed successfully"
      );
    } catch (error) {
      const message = error instanceof Error ? error.message : "Failed to run screening.";
      setScreeningError(message);
      appendEventToStorage({
        eventType: "ApplicantScreeningEvaluationFailed",
        traceId: applicant.positionId,
        payload: {
          streamCategory: "applicants_stream",
          streamId: `applicants:${applicant.positionId}`,
          positionId: applicant.positionId,
          applicantId: applicant.id,
          applicantName: applicant.name,
          failedAt: new Date().toISOString(),
          reason: message,
        },
      });
    } finally {
      setIsRunningScreening(false);
      refreshApplicantAndEvents();
    }
  }

  function handleStartScreeningProcess() {
    void openScreeningProcess("initial");
  }

  function handleRerunScreeningProcess() {
    void openScreeningProcess("rerun");
  }

  function handleSendOfferFromAvailableActions() {
    runOfferLetterSendFlow("available_action");
  }

  function handleFinalizeDisposition() {
    if (!applicant || applicant.stageId !== "offer_letter_sent") {
      return;
    }

    moveApplicantStage("hired_or_closed");
    appendEventToStorage({
      eventType: "ApplicantStageMoved",
      traceId: applicant.positionId,
      payload: {
        streamCategory: "applicants_stream",
        streamId: `applicants:${applicant.positionId}`,
        positionId: applicant.positionId,
        applicantId: applicant.id,
        applicantName: applicant.name,
        fromStageId: "offer_letter_sent",
        toStageId: "hired_or_closed",
        movedAt: new Date().toISOString(),
      },
    });
    appendEventToStorage({
      eventType: "ApplicantHireCloseDecisionMade",
      traceId: applicant.positionId,
      payload: {
        streamCategory: "manager_actions_stream",
        streamId: `manager-actions:${applicant.positionId}`,
        positionId: applicant.positionId,
        applicantId: applicant.id,
        applicantName: applicant.name,
        disposition: selectedDisposition,
        decidedAt: new Date().toISOString(),
      },
    });

    refreshApplicantAndEvents();
    setIsDispositionModalOpen(false);
    showActionToast(
      selectedDisposition === "hired" ? "Applicant marked as hired" : "Applicant marked as closed"
    );
  }

  function downloadAuditLog() {
    const fileName = `applicant-${applicantId}-audit-log.json`;
    const json = JSON.stringify(events, null, 2);
    const blob = new Blob([json], { type: "application/json" });
    const url = window.URL.createObjectURL(blob);
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = fileName;
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
    window.URL.revokeObjectURL(url);
  }

  const backHref = routePositionId ? `/positions/${routePositionId}` : "/";

  return (
    <div className="min-h-screen flex flex-col">
      {offerToast && (
        <div
          className={`fixed left-1/2 top-6 z-50 -translate-x-1/2 rounded-md px-4 py-3 text-sm font-semibold text-white shadow-lg ${
            offerToast.type === "loading" ? "bg-slate-700" : "bg-emerald-600"
          }`}
        >
          {offerToast.message}
        </div>
      )}
      {showUploadToast && (
        <div className="fixed left-1/2 top-6 z-50 -translate-x-1/2 rounded-md bg-emerald-600 px-4 py-3 text-sm font-semibold text-white shadow-lg">
          Applicant uploaded successfully
        </div>
      )}
      {actionToast && (
        <div className="fixed left-1/2 top-20 z-50 -translate-x-1/2 rounded-md bg-slate-700 px-4 py-3 text-sm font-semibold text-white shadow-lg">
          {actionToast}
        </div>
      )}

      <Header />

      <div className="min-h-screen bg-gradient-to-b from-orange-50 via-white to-white text-slate-900">
        <section className="px-6 pt-12 md:px-12 lg:px-20">
          <Link
            href={backHref}
            className="text-sm font-semibold text-slate-600 underline underline-offset-4 hover:text-slate-900"
          >
            Back
          </Link>

          {isLoading ? (
            <div className="mt-4 rounded-xl border border-slate-200 bg-white p-6 animate-pulse">
              <div className="h-4 w-20 rounded bg-slate-200" />
              <div className="mt-3 h-10 w-2/3 rounded bg-slate-200" />
              <div className="mt-3 h-6 w-1/2 rounded bg-slate-200" />
              <div className="mt-2 h-4 w-1/3 rounded bg-slate-200" />
            </div>
          ) : applicant ? (
            <div className="mt-4 rounded-xl border border-slate-200 bg-white p-6">
              <p className="text-sm font-semibold uppercase tracking-wide text-slate-500">
                {applicant.id}
              </p>
              <div className="mt-2 flex items-center gap-3">
                <h1 className="text-4xl font-bold text-slate-900">{applicant.name}</h1>
                <button
                  type="button"
                  onClick={() => setIsResumePreviewOpen(true)}
                  className="h-10 rounded-md bg-slate-700 px-4 text-sm font-semibold text-white transition-colors hover:bg-slate-800"
                >
                  View Resume
                </button>
              </div>
              <p className="mt-2 text-lg text-slate-600">{applicant.role}</p>
              <p className="mt-1 text-sm text-slate-600">
                Position: {applicant.positionId} • Stage: {applicant.stageId}
              </p>
              {applicant.email && (
                <p className="mt-1 text-sm text-slate-600">Email: {applicant.email}</p>
              )}
              {applicant.resumeFileName && (
                <p className="mt-1 text-sm text-slate-600">Resume: {applicant.resumeFileName}</p>
              )}
              {applicant.screeningEvaluation && (
                <div className="mt-4 rounded-md border border-emerald-200 bg-emerald-50 p-4">
                  <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
                    <p className="text-sm font-semibold text-emerald-900">Latest Screening Evaluation</p>
                    <button
                      type="button"
                      onClick={handleRerunScreeningProcess}
                      className="h-9 rounded-md bg-slate-700 px-3 text-xs font-semibold text-white transition-colors hover:bg-slate-800"
                    >
                      Re-run AI Screening
                    </button>
                  </div>
                  <p className="mt-2 text-sm text-slate-700">
                    Candidate: {applicant.screeningEvaluation.candidate_name ?? "Unknown"} • Fit Score:{" "}
                    {typeof applicant.screeningEvaluation.overall_fit_score === "undefined"
                      ? "Unknown"
                      : String(applicant.screeningEvaluation.overall_fit_score)}
                  </p>
                  <p className="mt-1 text-sm text-slate-700">
                    Matching Skills:{" "}
                    {(applicant.screeningEvaluation.matching_skills ?? []).join(", ") || "None"}
                  </p>
                  <p className="mt-1 text-sm text-slate-700">
                    Skill Gaps: {(applicant.screeningEvaluation.skill_gaps ?? []).join(", ") || "None"}
                  </p>
                  {applicant.screeningEvaluation.overall_summary && (
                    <p className="mt-2 text-sm text-slate-700">
                      {applicant.screeningEvaluation.overall_summary}
                    </p>
                  )}
                  {applicant.screeningCompletedAt && (
                    <p className="mt-2 text-xs text-slate-500">
                      Completed: {new Date(applicant.screeningCompletedAt).toLocaleString()}
                    </p>
                  )}
                  {applicant.screeningPolicyId && (
                    <p className="mt-1 text-xs text-slate-500">
                      Policy Used: {applicant.screeningPolicyId}
                    </p>
                  )}
                </div>
              )}
            </div>
          ) : (
            <div className="mt-4 rounded-xl border border-slate-200 bg-white p-6">
              <h1 className="text-2xl font-bold text-slate-900">Applicant not found</h1>
              <p className="mt-2 text-slate-600">
                This applicant id does not exist in LocalStorage.
              </p>
            </div>
          )}
        </section>

        <section className="px-6 pb-16 pt-10 md:px-12 lg:px-20">
          {isLoading ? (
            <div className="mb-8 rounded-xl border border-slate-200 bg-white p-6 animate-pulse">
              <div className="h-8 w-56 rounded bg-slate-200" />
              <div className="mt-3 h-5 w-72 rounded bg-slate-200" />
              <div className="mt-5 h-11 w-56 rounded bg-slate-200" />
            </div>
          ) : (
          <div className="mb-8 rounded-xl border border-slate-200 bg-white p-6">
            <h2 className="text-3xl font-bold text-slate-900">Available Actions</h2>
            <p className="mt-2 text-base text-slate-600">
              Actions are shown based on the current applicant stage.
            </p>

            <div className="mt-5 flex flex-wrap gap-3">
              {applicant?.stageId === "new_applied" && (
                <button
                  type="button"
                  onClick={handleStartScreeningProcess}
                  className="h-11 rounded-md bg-orange-500 px-5 text-sm font-semibold text-white transition-colors hover:bg-orange-600"
                >
                  Start AI Screening Process
                </button>
              )}

              {applicant?.stageId === "resume_review_screening" && (
                <button
                  type="button"
                  onClick={handleSendOfferFromAvailableActions}
                  className="h-11 rounded-md bg-orange-500 px-5 text-sm font-semibold text-white transition-colors hover:bg-orange-600"
                >
                  Send Candidate an Offer Letter
                </button>
              )}

              {applicant?.stageId === "offer_letter_sent" && (
                <>
                  <button
                    type="button"
                    onClick={() => setIsDispositionModalOpen(true)}
                    className="h-11 rounded-md bg-orange-500 px-5 text-sm font-semibold text-white transition-colors hover:bg-orange-600"
                  >
                    Send to Hire or Closed
                  </button>
                </>
              )}

              {applicant?.stageId === "hired_or_closed" && (
                <p className="text-sm font-medium text-slate-600">
                  No further actions available for this applicant.
                </p>
              )}
            </div>
          </div>
          )}

          {!isLoading && applicant?.stageId === "resume_review_screening" && (
            <div className="mb-8 rounded-xl border border-slate-200 bg-white p-6">
              <h2 className="text-3xl font-bold text-slate-900">Scorecard</h2>
              <p className="mt-2 text-base text-slate-600">
                Record interviewer feedback for this applicant.
              </p>

              <div className="mt-5 grid gap-5">
                <div>
                  <p className="text-sm font-medium text-slate-700">Recommendation</p>
                  <div className="mt-2 flex flex-wrap gap-2">
                    {[
                      { value: "hire", label: "Hire" },
                      { value: "no_hire", label: "No Hire" },
                      { value: "strong_hire", label: "Strong Hire" },
                    ].map((option) => {
                      const isSelected = scorecardRecommendation === option.value;
                      return (
                        <button
                          key={option.value}
                          type="button"
                          onClick={() =>
                            setScorecardRecommendation(option.value as ScorecardRecommendation)
                          }
                          className={`h-10 rounded-md px-4 text-sm font-semibold transition-colors ${
                            isSelected
                              ? "bg-orange-500 text-white hover:bg-orange-600"
                              : "bg-slate-100 text-slate-700 hover:bg-slate-200"
                          }`}
                        >
                          {option.label}
                        </button>
                      );
                    })}
                  </div>
                </div>

                <div>
                  <p className="text-sm font-medium text-slate-700">Numeric Rating (1-5)</p>
                  <div className="mt-2 flex flex-wrap gap-2">
                    {[1, 2, 3, 4, 5].map((value) => {
                      const isSelected = scorecardRating === value;
                      return (
                        <button
                          key={value}
                          type="button"
                          onClick={() => setScorecardRating(value as 1 | 2 | 3 | 4 | 5)}
                          className={`h-10 w-10 rounded-md text-sm font-semibold transition-colors ${
                            isSelected
                              ? "bg-orange-500 text-white hover:bg-orange-600"
                              : "bg-slate-100 text-slate-700 hover:bg-slate-200"
                          }`}
                        >
                          {value}
                        </button>
                      );
                    })}
                  </div>
                </div>

                <label className="grid gap-1">
                  <span className="text-sm font-medium text-slate-700">
                    Strengths / Interviewer Comments
                  </span>
                  <textarea
                    value={scorecardComments}
                    onChange={(event) => setScorecardComments(event.target.value)}
                    rows={4}
                    className="rounded-md border border-slate-300 px-3 py-2 text-slate-800"
                  />
                </label>

                <div className="flex justify-end">
                  <button
                    type="button"
                    onClick={saveScorecard}
                    disabled={!scorecardRecommendation || !scorecardRating}
                    className="h-11 rounded-md bg-slate-700 px-5 text-sm font-semibold text-white transition-colors hover:bg-slate-800 disabled:cursor-not-allowed disabled:bg-slate-300"
                  >
                    Save Scorecard
                  </button>
                </div>
              </div>
            </div>
          )}

          {!isLoading &&
            (applicant?.stageId === "offer_letter_sent" || applicant?.stageId === "hired_or_closed") && (
              <>
                <section className="mb-8">
                  <button
                    type="button"
                    onClick={() => setIsOfferSessionOpen((current) => !current)}
                    className="flex items-center gap-3 text-left"
                  >
                    <h2 className="text-4xl font-bold text-slate-900">Offer Letter Signing Status</h2>
                    <span
                      className={`text-2xl text-slate-700 transition-transform ${
                        isOfferSessionOpen ? "rotate-180" : "rotate-0"
                      }`}
                    >
                      ˅
                    </span>
                  </button>
                  {!isOfferSessionOpen && (
                    <p className="mt-2 text-lg text-slate-600">
                      Expand to view embedded signing session and eSign status details.
                    </p>
                  )}
                </section>

                {isOfferSessionOpen && (
                  <section className="mb-8 rounded-xl border border-slate-200 bg-white p-6">
                    <p className="text-base text-slate-700">
                      {getOfferSigningStatusSummary(applicant?.offerLetterEsignStatus)}
                    </p>
                    <div className="mt-5 grid gap-2 text-sm text-slate-700">
                      <p>
                        <span className="font-semibold">Applicant:</span> {applicant?.name ?? "Unknown"}
                      </p>
                      <p>
                        <span className="font-semibold">Position:</span> {applicant?.positionId ?? "Unknown"}
                      </p>
                      <p>
                        <span className="font-semibold">Embedded eSign Status:</span>{" "}
                        {applicant?.offerLetterEsignStatus ??
                          (applicant?.stageId === "hired_or_closed"
                            ? "Session finalized"
                            : "Awaiting candidate decision")}
                      </p>
                      {applicant?.offerLetterSessionUpdatedAt && (
                        <p>
                          <span className="font-semibold">Last Updated:</span>{" "}
                          {new Date(applicant.offerLetterSessionUpdatedAt).toLocaleString()}
                        </p>
                      )}
                      {typeof applicant?.offerLetterFolderId !== "undefined" && (
                        <p>
                          <span className="font-semibold">Folder ID:</span>{" "}
                          {String(applicant.offerLetterFolderId)}
                        </p>
                      )}
                      {applicant?.offerLetterAuthorAccessUrl && (
                        <div>
                          <p>
                            <span className="font-semibold">Author Access URL:</span>{" "}
                            <a
                              href={applicant.offerLetterAuthorAccessUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="font-semibold text-orange-600 underline underline-offset-4"
                            >
                              Open embedded session in new tab
                            </a>
                          </p>
                          <div
                            style={{ height: "900px", width: "100%", overflow: "auto" }}
                            data-role="content"
                            className="relative mt-3 rounded-md border border-slate-200"
                          >
                            <iframe
                              id="esignIframe"
                              src={applicant.offerLetterAuthorAccessUrl}
                              style={{ width: "99%", height: "99%", position: "absolute" }}
                              frameBorder="0"
                            />
                          </div>
                        </div>
                      )}
                    </div>
                  </section>
                )}
              </>
            )}

          {isLoading ? (
            <>
              <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
                <div className="mt-2 h-10 w-44 rounded bg-slate-200 animate-pulse" />
                <div className="h-11 w-40 rounded-md bg-slate-200 animate-pulse" />
              </div>
              <div className="mt-6 rounded-xl border border-slate-200 bg-white p-4 animate-pulse">
                {Array.from({ length: 4 }).map((_, index) => (
                  <div key={`applicant-audit-skeleton-${index}`} className="py-3">
                    <div className="h-5 w-48 rounded bg-slate-200" />
                    <div className="mt-2 h-4 w-2/3 rounded bg-slate-200" />
                    <div className="mt-2 h-4 w-1/2 rounded bg-slate-200" />
                  </div>
                ))}
              </div>
            </>
          ) : (
            <>
              <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
                <div>
                  <h2 className="text-4xl font-bold text-slate-900">Audit Log</h2>
                  <p className="mt-2 text-lg text-slate-600">
                    Hiring activity timeline for this applicant.
                  </p>
                </div>
                <button
                  type="button"
                  onClick={downloadAuditLog}
                  className="h-11 rounded-md bg-slate-700 px-5 text-sm font-semibold text-white transition-colors hover:bg-slate-800"
                >
                  Download Audit Log
                </button>
              </div>

              <div className="mt-6 overflow-hidden rounded-xl border border-slate-200 bg-white">
                {events.length === 0 ? (
                  <p className="p-5 text-sm text-slate-600">No events found for this applicant.</p>
                ) : (
                  <ul className="divide-y divide-slate-200">
                    {events.map((event) => {
                      const formatted = formatEventForRecruiter(event);
                      const streamCategory =
                        typeof event.payload.streamCategory === "string"
                          ? event.payload.streamCategory
                          : "activity";

                      return (
                        <li key={event.eventId} className="p-4">
                          <p className="text-base font-semibold text-slate-900">{formatted.title}</p>
                          <p className="mt-1 text-sm text-slate-700">{formatted.detail}</p>
                          <div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-slate-500">
                            <span className="rounded-full bg-slate-100 px-2 py-1">{streamCategory}</span>
                            <span>{new Date(event.occurredAt).toLocaleString()}</span>
                            <span className="font-mono">{event.eventId}</span>
                          </div>
                        </li>
                      );
                    })}
                  </ul>
                )}
              </div>
            </>
          )}
        </section>
      </div>

      {isDispositionModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4 backdrop-blur-sm">
          <div className="w-full max-w-xl rounded-xl border border-slate-200 bg-white p-6 shadow-xl">
            <div className="flex items-center justify-between">
              <h3 className="text-2xl font-bold text-slate-900">Finalize Applicant Outcome</h3>
              <button
                type="button"
                onClick={() => setIsDispositionModalOpen(false)}
                className="text-sm font-semibold text-slate-500 underline underline-offset-4"
              >
                Close
              </button>
            </div>

            <p className="mt-3 text-slate-600">
              Choose whether this applicant should be marked as hired or closed.
            </p>

            <label className="mt-5 grid gap-1">
              <span className="text-sm font-medium text-slate-700">Outcome</span>
              <select
                value={selectedDisposition}
                onChange={(event) => setSelectedDisposition(event.target.value as "hired" | "closed")}
                className="rounded-md border border-slate-300 px-3 py-2 text-slate-800"
              >
                <option value="hired">Hired</option>
                <option value="closed">Closed</option>
              </select>
            </label>

            <div className="mt-6 flex justify-end">
              <button
                type="button"
                onClick={handleFinalizeDisposition}
                className="h-11 rounded-md bg-orange-500 px-5 text-sm font-semibold text-white transition-colors hover:bg-orange-600"
              >
                Confirm and Move
              </button>
            </div>
          </div>
        </div>
      )}

      {isResumePreviewOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4 backdrop-blur-sm">
          <div className="h-[85vh] w-[80vw] max-w-none rounded-xl border border-slate-200 bg-white p-6 shadow-xl">
            <div className="flex items-center justify-between">
              <h3 className="text-2xl font-bold text-slate-900">Resume Preview</h3>
              <button
                type="button"
                onClick={() => setIsResumePreviewOpen(false)}
                className="text-sm font-semibold text-slate-500 underline underline-offset-4"
              >
                Close
              </button>
            </div>

            <div className="mt-4 h-[calc(85vh-7.5rem)] overflow-hidden rounded-lg border border-slate-200">
              <iframe
                title="Sample Resume Preview"
                src="/sample-resume.pdf"
                className="h-full w-full"
              />
            </div>
          </div>
        </div>
      )}

      {isSendingSessionModalOpen && sendingSessionUrl && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4 backdrop-blur-sm">
          <div className="h-[90vh] w-[90vw] max-w-none rounded-xl border border-slate-200 bg-white pt-6 pb-6 pl-6 pr-6 shadow-xl">
            <div className="flex items-center justify-between">
              <h3 className="text-2xl font-bold text-slate-900">eSign Sending Session</h3>
              <button
                type="button"
                onClick={() => {
                  setIsSendingSessionModalOpen(false);
                  setSendingSessionUrl(null);
                  if (typeof window !== "undefined") {
                    window.sessionStorage.setItem(OFFER_SENT_TOAST_FLAG_KEY, "1");
                    window.location.reload();
                  }
                }}
                className="text-sm font-semibold text-slate-500 underline underline-offset-4"
              >
                Close
              </button>
            </div>

            <div className="mt-4 h-[calc(90vh-6rem)] rounded-lg border border-slate-200">
              <div
                style={{ height: "100%", width: "100%", overflow: "auto" }}
                data-role="content"
                className="relative"
              >
                <iframe
                  id="esignIframe"
                  src={sendingSessionUrl}
                  style={{ width: "99%", height: "99%", position: "absolute" }}
                  frameBorder="0"
                />
              </div>
            </div>
          </div>
        </div>
      )}

      {isScreeningModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4 backdrop-blur-sm">
          <div className="max-h-[90vh] w-full max-w-3xl overflow-auto rounded-xl border border-slate-200 bg-white p-6 shadow-xl">
            <div className="flex items-center justify-between">
              <h3 className="text-2xl font-bold text-slate-900">Screening Process</h3>
              <button
                type="button"
                onClick={() => setIsScreeningModalOpen(false)}
                className="text-sm font-semibold text-slate-500 underline underline-offset-4"
              >
                Close
              </button>
            </div>

            <p className="mt-3 text-slate-600">
              Review and edit the evaluation policy before starting AI screening.
            </p>

            {!screeningPolicyDraft ? (
              <div className="mt-5 rounded-md border border-slate-200 bg-slate-50 p-4 text-sm text-slate-600">
                {screeningError ? `Failed to load policy: ${screeningError}` : "Loading policy..."}
              </div>
            ) : (
              <div className="mt-5 grid gap-4">
                <div className="grid gap-3 md:grid-cols-[1fr_auto] md:items-end">
                  <label className="grid gap-1">
                    <span className="text-sm font-medium text-slate-700">Evaluation Policy</span>
                    <select
                      value={selectedPolicyId}
                      onChange={(event) => handlePolicySelection(event.target.value)}
                      className="rounded-md border border-slate-300 px-3 py-2 text-slate-800"
                    >
                      {screeningPolicies.map((policy) => (
                        <option key={policy.policyId} value={policy.policyId}>
                          {policy.policyId}
                        </option>
                      ))}
                    </select>
                  </label>
                  <button
                    type="button"
                    onClick={createNewPolicyVersion}
                    className="h-11 rounded-md bg-slate-700 px-4 text-sm font-semibold text-white transition-colors hover:bg-slate-800"
                  >
                    Create New Policy Version
                  </button>
                </div>
                {!isPolicyDraftEditable && (
                  <p className="text-sm text-slate-600">
                    Current policy versions are read-only. Create a new policy version to edit.
                  </p>
                )}

                <label className="grid gap-1">
                  <span className="text-sm font-medium text-slate-700">Job Description</span>
                  <textarea
                    value={screeningPolicyDraft.job_description}
                    onChange={(event) =>
                      setScreeningPolicyDraft((current) =>
                        current ? { ...current, job_description: event.target.value } : current
                      )
                    }
                    rows={5}
                    readOnly={!isPolicyDraftEditable}
                    className={policyFieldClass}
                  />
                </label>

                <label className="grid gap-1">
                  <span className="text-sm font-medium text-slate-700">Overall Summary Instruction</span>
                  <textarea
                    value={screeningPolicyDraft.overall_summary}
                    onChange={(event) =>
                      setScreeningPolicyDraft((current) =>
                        current ? { ...current, overall_summary: event.target.value } : current
                      )
                    }
                    rows={3}
                    readOnly={!isPolicyDraftEditable}
                    className={policyFieldClass}
                  />
                </label>

                <label className="grid gap-1">
                  <span className="text-sm font-medium text-slate-700">
                    Hard Requirements (comma-separated)
                  </span>
                  <input
                    value={screeningPolicyDraft.hard_requirements.join(", ")}
                    onChange={(event) =>
                      setScreeningPolicyDraft((current) =>
                        current
                          ? {
                              ...current,
                              hard_requirements: event.target.value
                                .split(",")
                                .map((value) => value.trim())
                                .filter(Boolean),
                            }
                          : current
                      )
                    }
                    readOnly={!isPolicyDraftEditable}
                    className={policyFieldClass}
                  />
                </label>

                {screeningError && (
                  <p className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                    {screeningError}
                  </p>
                )}

                {screeningResult && (
                  <div className="rounded-md border border-emerald-200 bg-emerald-50 p-4">
                    <p className="text-sm font-semibold text-emerald-900">AI Screening Result</p>
                    <p className="mt-2 text-sm text-slate-700">
                      Candidate: {screeningResult.candidate_name ?? "Unknown"} • Fit Score:{" "}
                      {typeof screeningResult.overall_fit_score === "undefined"
                        ? "Unknown"
                        : String(screeningResult.overall_fit_score)}
                    </p>
                    <p className="mt-1 text-sm text-slate-700">
                      Matching Skills: {(screeningResult.matching_skills ?? []).join(", ") || "None"}
                    </p>
                    <p className="mt-1 text-sm text-slate-700">
                      Skill Gaps: {(screeningResult.skill_gaps ?? []).join(", ") || "None"}
                    </p>
                    {screeningResult.overall_summary && (
                      <p className="mt-2 text-sm text-slate-700">{screeningResult.overall_summary}</p>
                    )}
                  </div>
                )}
              </div>
            )}

            <div className="mt-6 flex justify-end">
              <button
                type="button"
                onClick={() => void startScreeningProcess()}
                disabled={
                  !screeningPolicyDraft ||
                  isRunningScreening ||
                  (screeningRunMode === "initial" && applicant?.stageId !== "new_applied")
                }
                className="h-11 rounded-md bg-orange-500 px-5 text-sm font-semibold text-white transition-colors hover:bg-orange-600 disabled:cursor-not-allowed disabled:bg-slate-300"
              >
                {isRunningScreening
                  ? "Running AI Screening..."
                  : screeningRunMode === "rerun"
                  ? "Re-run AI Screening Evaluation"
                  : "Start AI Screening Process"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
