'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Cookies from 'js-cookie';
import { api } from '@/lib/api';
import { useAuth } from '@/components/auth-context';
import SearchableSelect from '@/components/SearchableSelect';
import { toast } from 'react-toastify';
import { showConfirmDelete } from '@/lib/confirm';
import { SKILL_OPTIONS } from '@/data/skills';
import { ResumePreviewModal } from '@/components/ResumePreviewModal';
import NotifyCandidateModal from '@/components/NotifyCandidateModal';
import CandidateAttachments from '@/components/candidates/CandidateAttachments';
import CandidateAICall from '@/components/candidates/CandidateAICall';
import JobDetailsModal from '@/components/JobDetailsModal';
import { formatDate, formatDateTime } from '@/lib/dates';
import { sourceLabel } from '@/lib/sources';

interface Candidate {
  id: number; first_name: string; last_name: string; email: string | null;
  phone_number: string; alternate_phone_number: string | null;
  current_company: string | null; current_role: string | null;
  current_ctc: string | null; expected_ctc: string | null;
  total_experience: string | null; fresher?: boolean; notice_period: number | null; notice_period_name?: string | null;
  current_location: string | null; city: string | null; state: string | null;
  highest_qualification: string | null; skills: string[]; status: string; source?: string;
  resume: string | null; created_at: string; updated_at: string;
}

interface AppRow {
  id: number; job: number; job_title: string; job_client: string | null;
  job_status: string; job_owner_name?: string; job_owner_email?: string;
  stage: number; stage_name: string; stage_outcome: string;
  added_by: string | null; created_at: string;
  interviewer: string; interview_date: string | null; interview_result: string; remark: string;
  activity?: string;
  round1_outcome: string; round1_outcome_label?: string; screening_answers?: { question: string; expected?: string; answer: string }[];
}

interface LogItem {
  id: number;
  application: number;
  candidate: number;
  job: number;
  job_title: string;
  performed_by_name: string;
  status_name: string;
  activity: string;
  remark: string;
  changes_summary: string;
  created_at: string;
}

const ACTIVITY_OPTIONS = [
  'Email',
  'Call',
  'Call (talked)',
  'Call (LVM)',
  'Meeting',
  'Other',
];

const ROUND1_OUTCOMES = [
  { value: '', label: '— Not set —' },
  { value: 'SCREENED_IN', label: 'Screened-In' },
  { value: 'SCREENED_OUT', label: 'Screened-Out' },
  { value: 'CALL_LATER', label: 'Call Me Later' },
  { value: 'NOT_INTERESTED', label: 'Not Interested' },
  { value: 'NO_RESPONSE', label: 'No Response' },
  { value: 'DEALBREAKER', label: 'Dealbreaker' },
];

const RESULTS = ['', 'Pending', 'Selected', 'Rejected', 'On Hold'];

const OUTCOME_BADGE: Record<string, string> = {
  IN_PROGRESS: 'text-[#405189] bg-[#405189]/10',
  WON: 'text-[#0ab39c] bg-[#0ab39c]/10',
  LOST: 'text-rose-600 bg-rose-500/10',
};

export default function CandidateDetailPage() {
  const router = useRouter();
  const { id } = useParams<{ id: string }>();
  const { user } = useAuth();
  const [c, setC] = useState<Candidate | null>(null);
  const [apps, setApps] = useState<AppRow[]>([]);
  const [stages, setStages] = useState<{ id: number; name: string }[]>([]);
  const [loading, setLoading] = useState(true);
  // Set when the API returns 403 for this candidate — the recruiter isn't
  // assigned to any JD this candidate applied to.
  const [denied, setDenied] = useState(false);
  const [notFound, setNotFound] = useState(false);
  /** Set for failures that are NOT 403/404 (e.g. a 500) so the page can say what
   *  really happened instead of claiming the candidate doesn't exist. */
  const [loadError, setLoadError] = useState('');
  const [resumeView, setResumeView] = useState<{ url: string; name: string } | null>(null);
  const [notifyOpen, setNotifyOpen] = useState(false);

  const [jobs, setJobs] = useState<{ id: number; title: string; client_name?: string | null }[]>([]);
  const [showAssign, setShowAssign] = useState(false);
  const [assignJobs, setAssignJobs] = useState<number[]>([]);
  const [assigning, setAssigning] = useState(false);
  const [jobSearch, setJobSearch] = useState('');

  const loadCandidate = useCallback(async () => {
    const detail = (await api.get(`/candidates/${id}/`)) as any;
    setC(detail?.data?.data ?? detail?.data ?? null);
  }, [id]);

  const loadPipeline = useCallback(async () => {
    const r = (await api.get(`/pipeline/applications/?candidate=${id}&page_size=200`)) as any;
    const data = r?.data?.results ?? r?.data ?? [];
    setApps(Array.isArray(data) ? data : []);
  }, [id]);

  // --- Comments (call notes / remarks) ---
  const [comments, setComments] = useState<{ id: number; comment: string; by: string | null; created_at: string }[]>([]);
  const [newComment, setNewComment] = useState('');
  const [addingComment, setAddingComment] = useState(false);

  const loadComments = useCallback(async () => {
    try {
      const r = (await api.get(`/candidates/${id}/comments/`)) as any;
      setComments(r?.data ?? []);
    } catch { setComments([]); }
  }, [id]);

  const loadJobs = useCallback(async () => {
    const r = (await api.get('/jobs/?page_size=500')) as any;
    const data = r?.data?.results ?? r?.data ?? [];
    // only Published job orders are assignable
    setJobs((Array.isArray(data) ? data : []).filter((j: any) => j.status === 'Published'));
  }, []);

  const [pipelineLogs, setPipelineLogs] = useState<LogItem[]>([]);
  const [loadingLogs, setLoadingLogs] = useState(false);
  const [logSearch, setLogSearch] = useState('');

  const loadPipelineLogs = useCallback(async () => {
    setLoadingLogs(true);
    try {
      const r = (await api.get(`/pipeline/logs/?candidate=${id}`)) as any;
      setPipelineLogs(r?.data?.results ?? r?.data ?? []);
    } catch {
      setPipelineLogs([]);
    } finally {
      setLoadingLogs(false);
    }
  }, [id]);

  useEffect(() => {
    (async () => {
      try {
        await loadCandidate();
        try {
          const st = (await api.get('/pipeline/stages/')) as any;
          setStages(st?.data ?? []);
        } catch { /* non-critical */ }
        await loadPipeline().catch(() => {});
        await loadJobs().catch(() => {});
        await loadComments().catch(() => {});
        await loadPipelineLogs().catch(() => {});
      } catch (err: any) {
        const status = err?.status || err?.response?.status;
        if (status === 403) {
          setDenied(true);
          return;
        }
        if (status === 404) {
          setNotFound(true);
          return;
        }
        if (status === 401) {
          Cookies.remove('access_token');
          router.push('/login');
          return;
        }
        // Anything else (500, network failure, bad gateway) is NOT "not found".
        // Reporting it as such hid a real server error behind a message that sent
        // people looking for a missing record. Show what actually happened.
        setLoadError(
          err instanceof Error && err.message
            ? err.message
            : `Could not load this candidate${status ? ` (server returned ${status})` : ''}.`,
        );
      } finally {
        setLoading(false);
      }
    })();
  }, [id, router, loadCandidate, loadPipeline, loadJobs, loadComments, loadPipelineLogs]);

  const assignToJob = async () => {
    if (!assignJobs.length) { toast.error('Pick at least one job order'); return; }
    setAssigning(true);
    let ok = 0, fail = 0;
    for (const j of assignJobs) {
      try {
        await api.post('/pipeline/applications/', { candidate: Number(id), job: Number(j) });
        ok++;
      } catch { fail++; }
    }
    setAssigning(false);
    setShowAssign(false); setAssignJobs([]);
    if (ok) toast.success(`Added to ${ok} job pipeline${ok === 1 ? '' : 's'}${fail ? ` (${fail} skipped)` : ''}`);
    else toast.error('Could not assign (already in those pipelines?)');
    loadPipeline();
  };

  // Edit pipeline entry modal state
  const [editApp, setEditApp] = useState<AppRow | null>(null);
  const [editStatus, setEditStatus] = useState<number | string>('');
  const [editActivity, setEditActivity] = useState<string>('');
  const [editRemark, setEditRemark] = useState<string>('');
  const [savingEdit, setSavingEdit] = useState<boolean>(false);
  // JD viewer modal (opened from the Ref. # link in the pipeline table).
  const [viewJob, setViewJob] = useState<{ id: number; title: string } | null>(null);
  // Optional candidate email notification on a status change (CATS-style).
  const [notifyOnSave, setNotifyOnSave] = useState<boolean>(false);
  const [notifySubject, setNotifySubject] = useState<string>('');
  const [notifyMessage, setNotifyMessage] = useState<string>('');

  const buildStatusEmail = (a: AppRow, oldName: string, newName: string) => {
    const now = new Date();
    const ts = now.toLocaleString('en-GB', {
      day: '2-digit', month: '2-digit', year: 'numeric',
      hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true,
    });
    const name = c ? `${c.first_name || ''} ${c.last_name || ''}`.trim() : 'Candidate';
    const recruiter = user?.full_name || user?.email || 'HR Team';
    const position = a.job_client ? `${a.job_title} (${a.job_client})` : a.job_title;
    return `* Auto generated message. Please DO NOT reply *
${ts}

Dear ${name},

This E-Mail is a notification that your status has been changed in our HR database for the position ${position}.

Your previous status was "${oldName}".
And now HR has updated your new status as "${newName}".

Regards,
${recruiter}
Indovision Services Pvt Ltd`;
  };

  const openEditModal = (a: AppRow) => {
    setEditApp(a);
    setEditStatus(a.stage || '');
    setEditActivity(a.activity || '');
    setEditRemark(a.remark || '');
    setNotifyOnSave(false);
    setNotifySubject(`Application status update — ${a.job_title}`);
    setNotifyMessage('');
  };

  // Regenerate the notification text when the chosen status changes (only while
  // the notify box is on; manual edits to the textarea otherwise stay intact).
  useEffect(() => {
    if (!editApp || !notifyOnSave) return;
    const oldName = stages.find((s) => s.id === editApp.stage)?.name || 'No Status';
    const newName = stages.find((s) => s.id === Number(editStatus))?.name || oldName;
    setNotifySubject(`Application status update — ${editApp.job_title}`);
    setNotifyMessage(buildStatusEmail(editApp, oldName, newName));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [editStatus, notifyOnSave, editApp]);

  const saveAppEdit = async () => {
    if (!editApp) return;
    setSavingEdit(true);
    try {
      await api.patch(`/pipeline/applications/${editApp.id}/`, {
        stage: editStatus ? Number(editStatus) : null,
        activity: editActivity,
        remark: editRemark,
      });
      if (notifyOnSave) {
        try {
          const res: any = await api.post(`/candidates/${id}/notify/`, {
            channels: ['EMAIL'],
            subject: notifySubject,
            message: notifyMessage,
          });
          const sent = res?.data?.sent ?? 0;
          if (sent > 0) toast.success('Pipeline entry updated and candidate notified by email.');
          else toast.warn('Entry updated, but the email could not be sent (candidate may have no email).');
        } catch {
          toast.warn('Entry updated, but the notification email failed to send.');
        }
      } else {
        toast.success('Pipeline entry updated');
      }
      setEditApp(null);
      loadPipeline();
      loadPipelineLogs();
    } catch (e: any) {
      toast.error(e?.message || 'Could not update entry');
    } finally {
      setSavingEdit(false);
    }
  };

  // R2: interview feedback + schedules per application
  const [feedbacks, setFeedbacks] = useState<Record<number, any[]>>({});
  const [schedules, setSchedules] = useState<Record<number, any[]>>({});
  const [fbDraft, setFbDraft] = useState<Record<number, any>>({});
  const [schedDraft, setSchedDraft] = useState<Record<number, any>>({});

  const loadR2 = async (appId: number) => {
    try {
      const [f, s] = await Promise.all([
        api.get(`/pipeline/feedback/?application=${appId}`) as Promise<any>,
        api.get(`/pipeline/schedules/?application=${appId}`) as Promise<any>,
      ]);
      setFeedbacks((m) => ({ ...m, [appId]: f?.data ?? [] }));
      setSchedules((m) => ({ ...m, [appId]: s?.data ?? [] }));
    } catch { /* optional */ }
  };

  const saveFeedback = async (appId: number) => {
    const d = fbDraft[appId] || {};
    if (!d.recommendation) { toast.warning('Pick a recommendation.'); return; }
    try {
      await api.post('/pipeline/feedback/', {
        application: appId, round: 'TECHNICAL', interviewer: d.interviewer || '',
        overall_score: d.overall_score ? Number(d.overall_score) : null,
        strengths: d.strengths || '', weaknesses: d.weaknesses || '', recommendation: d.recommendation,
      });
      toast.success('Feedback saved');
      setFbDraft((m) => ({ ...m, [appId]: {} }));
      loadR2(appId);
    } catch (e) { toast.error(e instanceof Error ? e.message : 'Save failed'); }
  };

  const saveSchedule = async (appId: number) => {
    const d = schedDraft[appId] || {};
    if (!d.scheduled_at) { toast.warning('Pick a date & time.'); return; }
    try {
      const r = (await api.post('/pipeline/schedules/', {
        application: appId, round: 'TECHNICAL', interviewer: d.interviewer || '',
        interviewer_email: d.interviewer_email || '', scheduled_at: d.scheduled_at,
        duration_minutes: Number(d.duration_minutes) || 45, location: d.location || '',
      })) as any;
      toast.success(r?.message || 'Interview scheduled');
      setSchedDraft((m) => ({ ...m, [appId]: {} }));
      loadR2(appId);
    } catch (e) { toast.error(e instanceof Error ? e.message : 'Schedule failed'); }
  };

  const cancelSchedule = async (sid: number, appId: number) => {
    const reason = window.prompt('Reason for cancellation (required):');
    if (!reason || !reason.trim()) return;
    try { await api.post(`/pipeline/schedules/${sid}/cancel/`, { reason: reason.trim() }); toast.success('Cancelled'); loadR2(appId); }
    catch (e) { toast.error(e instanceof Error ? e.message : 'Failed'); }
  };

  const addComment = async () => {
    if (!newComment.trim()) return;
    setAddingComment(true);
    try {
      await api.post(`/candidates/${id}/comments/`, { comment: newComment.trim() });
      setNewComment('');
      loadComments();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not add comment');
    } finally {
      setAddingComment(false);
    }
  };

  const deleteComment = async (commentId: number) => {
    const result = await showConfirmDelete('Delete this comment?');
    if (!result.isConfirmed) return;
    try {
      await api.delete(`/candidates/${id}/comments/${commentId}/`);
      loadComments();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not delete comment');
    }
  };

  // --- Key Skills inline editing (multi-select) ---
  const [editingSkills, setEditingSkills] = useState(false);
  const [skillsDraft, setSkillsDraft] = useState<string[]>([]);
  const [savingSkills, setSavingSkills] = useState(false);

  const saveSkills = async () => {
    setSavingSkills(true);
    try {
      await api.put(`/candidates/${id}/`, { skills: skillsDraft });
      toast.success('Skills updated');
      setEditingSkills(false);
      loadCandidate();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not update skills');
    } finally {
      setSavingSkills(false);
    }
  };

  const removeApp = async (a: AppRow) => {
    const result = await showConfirmDelete(
      `Remove this candidate from "${a.job_title}" pipeline? The stage history and interview details for this job order will be deleted.`
    );
    if (!result.isConfirmed) return;
    try {
      await api.delete(`/pipeline/applications/${a.id}/`);
      toast.success('Removed from pipeline');
      loadPipeline();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not remove');
    }
  };

  // local edits per application (interviewer / date / result / remark)
  const [edits, setEdits] = useState<Record<number, Partial<AppRow>>>({});
  const editVal = (a: AppRow, key: keyof AppRow) => (edits[a.id]?.[key] ?? a[key] ?? '') as string;
  const setEdit = (id: number, key: keyof AppRow, val: string) =>
    setEdits((e) => ({ ...e, [id]: { ...e[id], [key]: val } }));

  const fullName = c ? `${c.first_name} ${c.last_name}` : '';
  const initial = (fullName || 'U').charAt(0).toUpperCase();
  const locationStr = c ? [c.current_location, c.city, c.state].filter(Boolean).join(', ') : '';

  const Field = ({ icon, label, value }: { icon: string; label: string; value: React.ReactNode }) => (
    <div className="flex items-start gap-3 py-2">
      <span className="w-8 h-8 rounded-none bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-400 shrink-0"><i className={icon}></i></span>
      <div className="min-w-0">
        <p className="text-[11px] uppercase tracking-wide text-vz-muted">{label}</p>
        <p className="text-sm font-medium text-[#495057] dark:text-slate-200 break-words">{value || '—'}</p>
      </div>
    </div>
  );

  const SectionTitle = ({ icon, children }: { icon: string; children: React.ReactNode }) => (
    <h3 className="text-xs font-semibold uppercase tracking-wider text-vz-muted mb-2 flex items-center gap-2">
      <i className={`${icon} text-[#405189]`}></i> {children}
    </h3>
  );

  return (
        <main className="flex-1 p-4 sm:p-6 overflow-y-auto">
          {loading ? (
            <p className="text-vz-muted">Loading…</p>
          ) : denied ? (
            // Mirrors the JD module's access-denied state (JobDetailsContent):
            // the message replaces the content entirely, with no link back into
            // data the recruiter isn't permitted to see.
            <div className="flex items-center justify-center py-16 text-slate-500">
              You don&apos;t have permission to access this Candidate
            </div>
          ) : loadError ? (
            // A real server/network failure — distinct from a missing record, and
            // retryable without leaving the page.
            <div className="flex flex-col items-center justify-center gap-3 py-16 text-slate-500">
              <p className="text-sm">{loadError}</p>
              <button
                onClick={() => window.location.reload()}
                className="text-sm text-[#405189] hover:underline cursor-pointer"
              >
                <i className="fa-solid fa-rotate-right mr-1.5"></i>Try again
              </button>
            </div>
          ) : notFound || !c ? (
            <p className="text-vz-muted">Candidate not found.</p>
          ) : (
            <div className="max-w-6xl mx-auto space-y-5">
              <button onClick={() => router.push('/candidates')} className="text-sm text-[#405189] hover:underline">
                <i className="fa-solid fa-arrow-left mr-1.5"></i> Back to candidates
              </button>

              {/* Hero header */}
              <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none shadow-sm p-6 flex flex-wrap items-start gap-5">
                <span className="w-20 h-20 rounded-full bg-gradient-to-br from-[#405189] to-[#23b7e5] text-white flex items-center justify-center text-3xl font-bold shrink-0 ring-4 ring-[#405189]/10 shadow-sm">{initial}</span>
                <div className="min-w-0 flex-1">
                  <div className="flex items-center flex-wrap gap-2.5">
                    <h2 className="text-2xl font-bold text-slate-800 dark:text-white leading-tight">{fullName}</h2>
                    <span className={`text-[10px] tracking-wide font-black uppercase px-2 py-0.5 rounded-full ${
                      c.status === 'Verified' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300'
                        : c.status === 'Blocked' ? 'bg-rose-100 text-rose-700 dark:bg-rose-950/40 dark:text-rose-300'
                        : c.status === 'Profile Completed' ? 'bg-sky-100 text-sky-700 dark:bg-sky-950/40 dark:text-sky-300'
                        : 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300'
                    }`}>{c.status}</span>
                  </div>
                  <p className="text-sm text-vz-muted mt-0.5">{c.current_role || 'Candidate'}{c.current_company ? ` · ${c.current_company}` : ''}</p>

                  {/* Meta row: experience · CTC · location */}
                  <div className="flex flex-wrap items-center gap-x-5 gap-y-1.5 mt-3 text-sm text-slate-600 dark:text-slate-300">
                    <span className="inline-flex items-center gap-1.5">
                      <i className="fa-solid fa-briefcase text-slate-400"></i>
                      {c.fresher ? 'Fresher' : (c.total_experience ? `${c.total_experience} yrs` : 'Experience —')}
                    </span>
                    {(c.current_ctc || c.expected_ctc) && (
                      <span className="inline-flex items-center gap-1.5">
                        <i className="fa-solid fa-indian-rupee-sign text-slate-400"></i>
                        {c.current_ctc ? `${c.current_ctc} LPA` : '—'}{c.expected_ctc ? <span className="text-slate-400"> (expects {c.expected_ctc})</span> : null}
                      </span>
                    )}
                    {locationStr && (
                      <span className="inline-flex items-center gap-1.5">
                        <i className="fa-solid fa-location-dot text-slate-400"></i>{locationStr}
                      </span>
                    )}
                  </div>

                  {/* Contact row: copyable phone, WhatsApp, email, AI call — kept
                      on one line; the email chip truncates so nothing overflows. */}
                  <div className="flex items-center gap-2 mt-3 min-w-0">
                    <button
                      onClick={() => { navigator.clipboard?.writeText(c.phone_number || ''); toast.success('Phone number copied'); }}
                      title="Copy phone number"
                      className="shrink-0 inline-flex items-center gap-2 px-3 py-1.5 rounded-none bg-emerald-50 dark:bg-emerald-950/30 text-emerald-700 dark:text-emerald-300 text-xs font-bold border border-emerald-200/70 dark:border-emerald-900 hover:bg-emerald-100 transition cursor-pointer"
                    >
                      <i className="fa-solid fa-phone"></i>{c.phone_number}
                      <i className="fa-regular fa-copy text-emerald-500/70"></i>
                    </button>
                    {c.phone_number && (
                      <a
                        href={`https://wa.me/${(c.phone_number || '').replace(/\D/g, '').replace(/^0+/, '').replace(/^(?!91)/, '91')}`}
                        target="_blank" rel="noopener noreferrer"
                        className="shrink-0 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-none border border-[#0ab39c]/40 text-[#0ab39c] text-xs font-bold hover:bg-[#0ab39c]/5 transition"
                      >
                        <i className="fa-brands fa-whatsapp text-sm"></i> WhatsApp
                      </a>
                    )}
                    {c.email && (
                      <button
                        onClick={() => { navigator.clipboard?.writeText(c.email || ''); toast.success('Email copied'); }}
                        title={`Copy ${c.email}`}
                        className="min-w-0 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-none bg-slate-50 dark:bg-slate-800 text-slate-600 dark:text-slate-300 text-xs font-semibold border border-vz-border dark:border-slate-700 hover:bg-slate-100 transition max-w-[240px] cursor-pointer"
                      >
                        <i className="fa-regular fa-envelope text-[#405189] shrink-0"></i>
                        <span className="truncate">{c.email}</span>
                        <i className="fa-regular fa-copy text-slate-400 shrink-0"></i>
                      </button>
                    )}
                    {/* Single-candidate AI call + summary (permission-gated). */}
                    <span className="shrink-0"><CandidateAICall candidateId={id} /></span>
                  </div>
                </div>
                <div className="ml-auto flex items-center gap-2">
                  <button
                    onClick={() => router.push(`/candidates?edit=${id}`)}
                    className="border border-vz-border dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 text-xs font-bold px-4 py-2 rounded-none cursor-pointer"
                  >
                    <i className="fa-solid fa-pen-to-square mr-1.5"></i>Edit
                  </button>
                  <button
                    onClick={() => setNotifyOpen(true)}
                    className="border border-[#0ab39c]/40 text-[#0ab39c] hover:bg-[#0ab39c]/5 text-xs font-bold px-4 py-2 rounded-none cursor-pointer"
                  >
                    <i className="fa-solid fa-bell mr-1.5"></i>Notify
                  </button>
                  {c.resume ? (
                    <>
                      <button
                        onClick={() => setResumeView({ url: (c as any).resume_url || c.resume || '', name: `${c.first_name} ${c.last_name} — Resume` })}
                        className="bg-[#405189] hover:bg-[#364574] text-white text-xs font-medium px-4 py-2 rounded-none cursor-pointer"
                      >
                        <i className="fa-solid fa-eye mr-1.5"></i>View Resume
                      </button>
                      <a
                        href={(c as any).resume_url ? `${(c as any).resume_url}?dl=1` : (c.resume.startsWith('http') ? c.resume : `${(process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api/v1').replace('/api/v1', '')}${c.resume.startsWith('/') ? '' : '/media/'}${c.resume}`)}
                        download
                        className="border border-vz-border dark:border-slate-700 text-slate-600 dark:text-slate-300 text-xs font-medium px-4 py-2 rounded-none hover:bg-slate-50 dark:hover:bg-slate-800"
                      >
                        <i className="fa-solid fa-download mr-1.5"></i>Download
                      </a>
                    </>
                  ) : <span className="text-xs text-slate-400">No resume</span>}
                </div>
              </div>

              {/* Stat chips */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                {[
                  { icon: 'fa-solid fa-briefcase', tint: 'bg-[#405189]/10 text-[#405189]', label: 'Current Pay', value: c.current_ctc || '—' },
                  { icon: 'fa-solid fa-hand-holding-dollar', tint: 'bg-[#3577f1]/10 text-[#3577f1]', label: 'Desired Pay', value: c.expected_ctc || '—' },
                  { icon: 'fa-solid fa-clock', tint: 'bg-[#f7b84b]/15 text-[#dd9b19]', label: 'Notice Period', value: c.notice_period_name || (c.notice_period != null ? `${c.notice_period} days` : '—') },
                  { icon: 'fa-solid fa-diagram-project', tint: 'bg-[#0ab39c]/10 text-[#0ab39c]', label: 'In Pipelines', value: apps.length },
                ].map((s) => (
                  <div key={s.label} className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none p-4 shadow-sm flex items-center justify-between">
                    <div>
                      <p className="text-[11px] uppercase tracking-wide text-vz-muted">{s.label}</p>
                      <p className="text-lg font-semibold text-[#495057] dark:text-white mt-0.5">{s.value}</p>
                    </div>
                    <span className={`w-10 h-10 rounded-full flex items-center justify-center ${s.tint}`}><i className={s.icon}></i></span>
                  </div>
                ))}
              </div>

              <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
                {/* Left: details */}
                <div className="lg:col-span-1 space-y-5">
                  <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none shadow-sm p-5">
                    <SectionTitle icon="fa-solid fa-address-card">Contact</SectionTitle>
                    <Field icon="fa-regular fa-envelope" label="Email" value={c.email} />
                    <Field icon="fa-solid fa-phone" label="Phone" value={c.phone_number} />
                    <Field icon="fa-solid fa-mobile-screen" label="Alternate Phone" value={c.alternate_phone_number} />
                    <Field icon="fa-solid fa-location-dot" label="Location" value={locationStr} />
                    <Field icon="fa-solid fa-share-nodes" label="Source" value={sourceLabel(c.source)} />
                  </div>
                  <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none shadow-sm p-5">
                    <SectionTitle icon="fa-solid fa-user-tie">Professional</SectionTitle>
                    <Field icon="fa-solid fa-building" label="Current Employer" value={c.current_company} />
                    <Field icon="fa-solid fa-id-badge" label="Designation" value={c.current_role} />
                    <Field icon="fa-solid fa-graduation-cap" label="Highest Education" value={c.highest_qualification} />
                  </div>
                </div>

                {/* Right: skills + pipeline */}
                <div className="lg:col-span-2 space-y-5">
                  <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none shadow-sm p-5 h-[276px] flex flex-col">
                    <div className="flex items-center justify-between shrink-0">
                      <SectionTitle icon="fa-solid fa-tags">Key Skills</SectionTitle>
                      {!editingSkills ? (
                        <button onClick={() => { setSkillsDraft(c.skills || []); setEditingSkills(true); }}
                          className="text-xs font-bold text-[#405189] hover:underline cursor-pointer -mt-2">
                          <i className="fa-solid fa-pen-to-square mr-1"></i>Edit
                        </button>
                      ) : null}
                    </div>
                    <div className="flex-1 overflow-y-auto mt-1 pr-1">
                    {editingSkills ? (
                      <div className="space-y-3">
                        <SearchableSelect
                          isMulti
                          isCreatable
                          value={skillsDraft}
                          onChange={(vals: any) => setSkillsDraft(Array.isArray(vals) ? vals : [])}
                          options={SKILL_OPTIONS}
                          placeholder="Search or type a skill and press Enter…"
                        />
                        <div className="flex justify-end gap-2">
                          <button onClick={() => setEditingSkills(false)}
                            className="text-xs font-semibold px-4 py-1.5 rounded-none border border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-800 transition cursor-pointer">
                            Cancel
                          </button>
                          <button disabled={savingSkills} onClick={saveSkills}
                            className="bg-[#405189] hover:bg-[#364574] text-white text-xs font-semibold px-4 py-1.5 rounded-none disabled:opacity-50 cursor-pointer">
                            {savingSkills ? 'Saving…' : 'Save Skills'}
                          </button>
                        </div>
                      </div>
                    ) : c.skills?.length ? (
                      <div className="flex flex-wrap gap-1.5">
                        {c.skills.map((s) => <span key={s} className="text-xs font-medium bg-[#405189]/10 text-[#405189] px-2.5 py-1 rounded-none">{s}</span>)}
                      </div>
                    ) : <p className="text-sm text-slate-400">No skills listed.</p>}
                    </div>
                  </div>

                  <CandidateAttachments candidateId={id} />
                </div>
              </div>

              {/* Job Order Pipeline section */}
              <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none shadow-sm">
                <div className="px-5 py-3 border-b border-vz-border dark:border-slate-800 flex items-center gap-2">
                  <i className="fa-solid fa-diagram-project text-[#405189]"></i>
                  <h3 className="text-sm font-semibold text-[#495057] dark:text-white">Job Order Pipeline</h3>
                  <span className="text-xs text-vz-muted">{apps.length} order{apps.length === 1 ? '' : 's'}</span>
                  <button onClick={() => { setAssignJobs([]); setJobSearch(''); setShowAssign(true); }}
                    className="ml-auto bg-[#405189] hover:bg-[#364574] text-white text-xs font-medium px-3 py-1.5 rounded-none flex items-center gap-1.5">
                    <i className="fa-solid fa-plus"></i> Assign to Job Order
                  </button>
                </div>

                {apps.length === 0 ? (
                  <div className="py-10 flex flex-col items-center justify-center px-4 text-center text-slate-400">
                    <i className="fa-solid fa-diagram-project text-2xl block mb-2 opacity-40"></i>
                    Not in any job pipeline yet. Assign this candidate to a Job Order to start.
                  </div>
                ) : (
                  <div className="overflow-x-auto max-h-[260px] overflow-y-auto">
                    <table className="w-full text-xs">
                      <thead className="bg-slate-50 dark:bg-slate-950/90 backdrop-blur text-slate-400 text-left text-[10px] uppercase sticky top-0 z-10 border-b border-vz-border dark:border-slate-800">
                        <tr>
                          <th className="px-3 py-2 font-semibold">Ref. #</th>
                          <th className="px-3 py-2 font-semibold">Job Title</th>
                          <th className="px-3 py-2 font-semibold">Company</th>
                          <th className="px-3 py-2 font-semibold">Owner</th>
                          <th className="px-3 py-2 font-semibold">Result</th>
                          <th className="px-3 py-2 font-semibold">Status</th>
                          <th className="px-3 py-2 font-semibold">Added</th>
                          <th className="px-3 py-2 font-semibold text-right">Action</th>
                        </tr>
                      </thead>
                      <tbody>
                        {apps.map((a) => (
                          <tr key={a.id} className="border-t border-slate-100 dark:border-slate-800 transition hover:bg-slate-50 dark:hover:bg-slate-800/40">
                            <td className="px-3 py-2.5 font-extrabold text-[#405189]">#{a.job}</td>
                            <td className="px-3 py-2.5 font-bold text-slate-700 dark:text-slate-200 whitespace-nowrap">{a.job_title}</td>
                            <td className="px-3 py-2.5 text-slate-500 dark:text-slate-400 whitespace-nowrap">{a.job_client || 'Internal'}</td>
                            <td className="px-3 py-2.5 whitespace-nowrap font-medium text-slate-600 dark:text-slate-300">{a.job_owner_name || '—'}</td>
                            <td className="px-3 py-2.5 text-slate-500 dark:text-slate-400">{a.interview_result || '—'}</td>
                            <td className="px-3 py-2.5 whitespace-nowrap font-semibold text-[#405189]">{a.stage_name || '—'}</td>
                            <td className="px-3 py-2.5 text-slate-400 whitespace-nowrap">{formatDate(a.created_at)}</td>
                            <td className="px-3 py-2.5 text-right flex items-center justify-end gap-1">
                              <button
                                onClick={() => openEditModal(a)}
                                title="Edit job order details"
                                className="w-7 h-7 rounded-none inline-flex items-center justify-center text-slate-400 hover:text-[#405189] hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer">
                                <i className="fa-solid fa-pen-to-square text-[12px]"></i>
                              </button>
                              <button
                                onClick={() => removeApp(a)}
                                title="Remove from this job pipeline"
                                className="w-7 h-7 rounded-none inline-flex items-center justify-center text-slate-400 hover:text-rose-600 hover:bg-rose-50 dark:hover:bg-rose-950/30 transition cursor-pointer">
                                <i className="fa-solid fa-trash text-[12px]"></i>
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>

              {/* ===== Pipeline Activity Logs ===== */}
              <div className="bg-white dark:bg-slate-900 border border-vz-border dark:border-slate-800 rounded-none shadow-sm mt-5">
                <div className="px-5 py-3 border-b border-vz-border dark:border-slate-800 flex items-center justify-between gap-4 flex-wrap">
                  <div className="flex items-center gap-2">
                    <i className="fa-solid fa-clock-rotate-left text-[#405189]"></i>
                    <h3 className="text-sm font-semibold text-[#495057] dark:text-white">Pipeline Activity Logs</h3>
                    <span className="text-xs text-vz-muted">{pipelineLogs.length} log{pipelineLogs.length === 1 ? '' : 's'}</span>
                  </div>

                  <div className="flex items-center gap-3 flex-1 max-w-xs ml-auto">
                    <div className="relative w-full">
                      <i className="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
                      <input
                        type="text"
                        value={logSearch}
                        onChange={(e) => setLogSearch(e.target.value)}
                        placeholder="Search logs…"
                        className="w-full border border-vz-border dark:border-slate-700 dark:bg-slate-800 rounded-none pl-8 pr-3 py-1 text-xs focus:ring-2 focus:ring-[#405189]/25 focus:outline-none"
                      />
                    </div>
                    <button onClick={loadPipelineLogs} className="text-xs text-[#405189] hover:underline cursor-pointer flex items-center gap-1 whitespace-nowrap">
                      <i className="fa-solid fa-rotate-right text-[11px]"></i>Refresh
                    </button>
                  </div>
                </div>

                <div className="p-0">
                  {loadingLogs ? (
                    <div className="h-[320px] flex items-center justify-center text-xs text-slate-400">Loading logs…</div>
                  ) : (() => {
                    const filteredLogs = pipelineLogs.filter((log) => {
                      if (!logSearch.trim()) return true;
                      const q = logSearch.toLowerCase();
                      return (
                        (log.job_title || '').toLowerCase().includes(q) ||
                        (log.status_name || '').toLowerCase().includes(q) ||
                        (log.activity || '').toLowerCase().includes(q) ||
                        (log.performed_by_name || '').toLowerCase().includes(q) ||
                        (log.remark || '').toLowerCase().includes(q) ||
                        (log.changes_summary || '').toLowerCase().includes(q) ||
                        formatDateTime(log.created_at).toLowerCase().includes(q)
                      );
                    });

                    if (filteredLogs.length === 0) {
                      return (
                        <div className="py-10 flex flex-col items-center justify-center text-center text-slate-400 px-4">
                          <i className="fa-solid fa-list-check text-2xl block mb-2 opacity-30"></i>
                          <p className="text-xs">
                            {logSearch.trim() ? 'No matching logs found.' : 'No edit logs recorded yet. Changes made via the edit button will be displayed here.'}
                          </p>
                        </div>
                      );
                    }

                    return (
                      <div className="overflow-x-auto max-h-[260px] overflow-y-auto">
                        <table className="w-full text-xs">
                          <thead className="bg-slate-50 dark:bg-slate-950/90 backdrop-blur text-slate-400 text-left text-[10px] uppercase sticky top-0 z-10 border-b border-vz-border dark:border-slate-800">
                            <tr>
                              <th className="px-3 py-2.5 font-semibold text-center w-12">S. No.</th>
                              <th className="px-4 py-2.5 font-semibold">Date &amp; Time</th>
                              <th className="px-3 py-2.5 font-semibold">Status</th>
                              <th className="px-3 py-2.5 font-semibold">Activity</th>
                              <th className="px-3 py-2.5 font-semibold">Changed By</th>
                              <th className="px-3 py-2.5 font-semibold">Regarding (JD)</th>
                              <th className="px-3 py-2.5 font-semibold">Remarks</th>
                            </tr>
                          </thead>
                          <tbody>
                            {filteredLogs.map((log, index) => (
                              <tr key={log.id} className="border-b border-slate-100 dark:border-slate-800/60 hover:bg-slate-50/50 dark:hover:bg-slate-800/40 transition">
                                <td className="px-3 py-2.5 text-center font-bold text-slate-500 dark:text-slate-400">
                                  {index + 1}
                                </td>
                                <td className="px-4 py-2.5 whitespace-nowrap font-medium text-slate-500 dark:text-slate-400">
                                  {formatDateTime(log.created_at)}
                                </td>
                                <td className="px-3 py-2.5 whitespace-nowrap">
                                  {log.status_name ? (
                                    <span className="font-semibold text-[#405189] px-2 py-0.5 rounded-none bg-[#405189]/10">
                                      {log.status_name}
                                    </span>
                                  ) : <span className="text-slate-400">—</span>}
                                </td>
                                <td className="px-3 py-2.5 whitespace-nowrap">
                                  {log.activity ? (
                                    <span className="font-semibold text-[#0ab39c] px-2 py-0.5 rounded-none bg-[#0ab39c]/10">
                                      {log.activity}
                                    </span>
                                  ) : <span className="text-slate-400">—</span>}
                                </td>
                                <td className="px-3 py-2.5 whitespace-nowrap font-semibold text-slate-700 dark:text-slate-200">
                                  {log.performed_by_name || 'System'}
                                </td>
                                <td className="px-3 py-2.5 whitespace-nowrap font-bold text-[#405189]">
                                  {log.job_title || `Job #${log.job}`}
                                </td>
                                <td className="px-3 py-2.5 text-slate-600 dark:text-slate-300">
                                  <span className="max-w-xs truncate block" title={log.remark || log.changes_summary}>
                                    {log.remark || log.changes_summary || '—'}
                                  </span>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    );
                  })()}
                </div>
              </div>

              {/* Assign to Job Order modal */}
              {showAssign && (
                <div className="fixed inset-0 z-[80] bg-slate-950/50 flex items-center justify-center p-4" onClick={() => !assigning && setShowAssign(false)}>
                  <div className="bg-white dark:bg-slate-900 rounded-none w-full max-w-3xl p-6 space-y-4 flex flex-col max-h-[85vh]" onClick={(e) => e.stopPropagation()}>
                    <div className="flex items-center justify-between">
                      <h2 className="text-lg font-semibold text-[#495057] dark:text-slate-100">Assign to Job Order(s)</h2>
                      <span className="text-xs text-vz-muted">{assignJobs.length} selected</span>
                    </div>
                    {(() => {
                      const available = (jobs as any[]).filter((j) => !apps.some((a) => a.job === j.id));
                      const filtered = available.filter((j) =>
                        `${j.title} ${j.client_name || ''}`.toLowerCase().includes(jobSearch.toLowerCase()));
                      const allChecked = filtered.length > 0 && filtered.every((j) => assignJobs.includes(j.id));
                      return (
                        <>
                          <div className="relative">
                            <i className="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
                            <input value={jobSearch} onChange={(e) => setJobSearch(e.target.value)} placeholder="Search job orders..."
                              className="w-full border border-vz-border dark:border-slate-700 dark:bg-slate-800 rounded-none pl-9 pr-3 py-2 text-sm focus:ring-2 focus:ring-[#405189]/25 focus:outline-none" />
                          </div>
                          <div className="border border-vz-border dark:border-slate-800 rounded-none overflow-auto flex-1 min-h-[200px]">
                            <table className="w-full text-sm">
                              <thead className="bg-slate-50 dark:bg-slate-900/60 text-slate-500 text-left text-[11px] uppercase sticky top-0">
                                <tr>
                                  <th className="px-3 py-2 w-10">
                                    <input type="checkbox" checked={allChecked} className="accent-[#405189]"
                                      onChange={(e) => {
                                        const ids = filtered.map((j) => j.id);
                                        setAssignJobs((prev) => e.target.checked ? Array.from(new Set([...prev, ...ids])) : prev.filter((x) => !ids.includes(x)));
                                      }} />
                                  </th>
                                  <th className="px-3 py-2 font-semibold">Ref. #</th>
                                  <th className="px-3 py-2 font-semibold">Title</th>
                                  <th className="px-3 py-2 font-semibold">Company</th>
                                  <th className="px-3 py-2 font-semibold">Status</th>
                                  <th className="px-3 py-2 font-semibold">Owner</th>
                                  <th className="px-3 py-2 font-semibold">Modified</th>
                                </tr>
                              </thead>
                              <tbody>
                                {filtered.map((j) => {
                                  const checked = assignJobs.includes(j.id);
                                  return (
                                    <tr key={j.id} className="border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40 cursor-pointer"
                                      onClick={() => setAssignJobs((prev) => checked ? prev.filter((x) => x !== j.id) : [...prev, j.id])}>
                                      <td className="px-3 py-2"><input type="checkbox" checked={checked} readOnly className="accent-[#405189]" /></td>
                                      <td className="px-3 py-2 text-slate-500">#{j.id}</td>
                                      <td className="px-3 py-2 font-medium text-[#405189]">{j.title}</td>
                                      <td className="px-3 py-2 text-slate-500">{j.client_name || 'Internal'}</td>
                                      <td className="px-3 py-2">
                                        <span className={`text-[10px] font-semibold px-2 py-0.5 rounded-none ${j.status === 'Published' ? 'bg-emerald-500/10 text-emerald-600' : j.status === 'Closed' ? 'bg-slate-400/10 text-slate-500' : 'bg-amber-500/10 text-amber-600'}`}>{j.status}</span>
                                      </td>
                                      <td className="px-3 py-2 text-slate-500 truncate max-w-[140px]">{j.created_by_email || '—'}</td>
                                      <td className="px-3 py-2 text-slate-500 whitespace-nowrap">{formatDate(j.updated_at)}</td>
                                    </tr>
                                  );
                                })}
                                {filtered.length === 0 && (
                                  <tr><td colSpan={7} className="px-3 py-8 text-center text-slate-400">No available job orders.</td></tr>
                                )}
                              </tbody>
                            </table>
                          </div>
                          <span className="text-[11px] text-vz-muted">Candidate enters each selected pipeline at stage 1 (Contacted). Already-assigned jobs are hidden.</span>
                        </>
                      );
                    })()}
                    <div className="flex justify-end gap-2 pt-1">
                      <button onClick={() => setShowAssign(false)} disabled={assigning} className="px-4 py-2 rounded-none text-sm border border-vz-border text-slate-600 dark:text-slate-300">Cancel</button>
                      <button onClick={assignToJob} disabled={assigning || !assignJobs.length} className="px-4 py-2 rounded-none text-sm font-medium bg-[#405189] hover:bg-[#364574] text-white disabled:opacity-50">
                        {assigning ? 'Assigning…' : `Assign${assignJobs.length ? ` (${assignJobs.length})` : ''}`}
                      </button>
                    </div>
                  </div>
                </div>
              )}

              {/* JD viewer modal — opened from the Ref. # / title link */}
              {viewJob && (
                <JobDetailsModal
                  jobId={viewJob.id}
                  jobTitle={viewJob.title}
                  isOpen={!!viewJob}
                  onClose={() => setViewJob(null)}
                />
              )}

              {/* Edit Pipeline Entry modal */}
              {editApp && (
                <div className="fixed inset-0 z-[80] bg-slate-950/50 flex items-center justify-center p-4" onClick={() => !savingEdit && setEditApp(null)}>
                  <div className="bg-white dark:bg-slate-900 rounded-none w-full max-w-2xl max-h-[90vh] overflow-y-auto p-6 space-y-4 flex flex-col shadow-xl" onClick={(e) => e.stopPropagation()}>
                    <div className="flex items-center justify-between border-b border-vz-border dark:border-slate-800 pb-3">
                      <div>
                        <h2 className="text-base font-semibold text-[#495057] dark:text-slate-100">Edit Pipeline Details</h2>
                        <p className="text-xs text-vz-muted mt-0.5">{editApp.job_title} (#{editApp.job})</p>
                      </div>
                      <button onClick={() => setEditApp(null)} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-lg">
                        <i className="fa-solid fa-xmark"></i>
                      </button>
                    </div>

                    <div className="space-y-4 text-xs">
                      {/* Status + Activity — one row, two fields */}
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div>
                          <label className="block text-[11px] font-semibold text-slate-700 dark:text-slate-300 uppercase tracking-wider mb-1">
                            Status
                          </label>
                          <select
                            value={editStatus}
                            onChange={(e) => setEditStatus(e.target.value)}
                            className="w-full border border-vz-border dark:border-slate-700 dark:bg-slate-800 rounded-none px-3 py-2 text-xs focus:ring-2 focus:ring-[#405189]/25 focus:border-[#405189] focus:outline-none"
                          >
                            <option value="">Select Status…</option>
                            {stages.map((s) => (
                              <option key={s.id} value={s.id}>{s.name}</option>
                            ))}
                          </select>
                        </div>

                        <div>
                          <label className="block text-[11px] font-semibold text-slate-700 dark:text-slate-300 uppercase tracking-wider mb-1">
                            Activity
                          </label>
                          <select
                            value={editActivity}
                            onChange={(e) => setEditActivity(e.target.value)}
                            className="w-full border border-vz-border dark:border-slate-700 dark:bg-slate-800 rounded-none px-3 py-2 text-xs focus:ring-2 focus:ring-[#405189]/25 focus:border-[#405189] focus:outline-none"
                          >
                            <option value="">Select Activity…</option>
                            {ACTIVITY_OPTIONS.map((act) => (
                              <option key={act} value={act}>{act}</option>
                            ))}
                          </select>
                        </div>
                      </div>

                      {/* Remarks Textbox */}
                      <div>
                        <label className="block text-[11px] font-semibold text-slate-700 dark:text-slate-300 uppercase tracking-wider mb-1">
                          Remarks
                        </label>
                        <textarea
                          rows={3}
                          value={editRemark}
                          onChange={(e) => setEditRemark(e.target.value)}
                          placeholder="Add remarks for this candidate's job order entry…"
                          className="w-full border border-vz-border dark:border-slate-700 dark:bg-slate-800 rounded-none px-3 py-2 text-xs focus:ring-2 focus:ring-[#405189]/25 focus:border-[#405189] focus:outline-none"
                        />
                      </div>

                      {/* Notify candidate by email on this status change */}
                      <div className="border-t border-vz-border dark:border-slate-800 pt-3">
                        <label className="flex items-center gap-2 text-[11px] font-semibold text-slate-700 dark:text-slate-300 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={notifyOnSave}
                            onChange={(e) => setNotifyOnSave(e.target.checked)}
                            className="w-4 h-4 accent-[#405189]"
                          />
                          Send E-Mail Notification to Candidate
                        </label>

                        {notifyOnSave && (
                          <div className="mt-3 space-y-2">
                            <div>
                              <label className="block text-[10px] font-bold uppercase text-slate-400 mb-1">Subject</label>
                              <input
                                value={notifySubject}
                                onChange={(e) => setNotifySubject(e.target.value)}
                                className="w-full border border-vz-border dark:border-slate-700 dark:bg-slate-800 rounded-none px-3 py-2 text-xs focus:ring-2 focus:ring-[#405189]/25 focus:border-[#405189] focus:outline-none"
                              />
                            </div>
                            <div>
                              <label className="block text-[10px] font-bold uppercase text-slate-400 mb-1">Message (auto-generated — you can edit)</label>
                              <textarea
                                rows={11}
                                value={notifyMessage}
                                onChange={(e) => setNotifyMessage(e.target.value)}
                                className="w-full border border-vz-border dark:border-slate-700 dark:bg-slate-800 rounded-none px-3 py-2 text-xs font-mono leading-relaxed focus:ring-2 focus:ring-[#405189]/25 focus:border-[#405189] focus:outline-none resize-y"
                              />
                              <p className="text-[10px] text-slate-400 mt-1">Requires a valid email on the candidate record.</p>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>

                    <div className="flex justify-end gap-2 pt-3 border-t border-vz-border dark:border-slate-800">
                      <button
                        onClick={() => setEditApp(null)}
                        disabled={savingEdit}
                        className="px-4 py-2 rounded-none text-xs border border-vz-border text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800"
                      >
                        Cancel
                      </button>
                      <button
                        onClick={saveAppEdit}
                        disabled={savingEdit}
                        className="px-4 py-2 rounded-none text-xs font-medium bg-[#405189] hover:bg-[#364574] text-white disabled:opacity-50"
                      >
                        {savingEdit ? 'Saving…' : notifyOnSave ? 'Save & send email' : 'Save Changes'}
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
          {resumeView && (
            <ResumePreviewModal
              url={resumeView.url}
              name={resumeView.name}
              onClose={() => setResumeView(null)}
            />
          )}

          {c && (
            <NotifyCandidateModal
              open={notifyOpen}
              onClose={() => setNotifyOpen(false)}
              candidates={[c]}
            />
          )}
        </main>
  );
}
