/* The 8-tab candidate profile modal, split out of Candidates.jsx — it was the
single largest block in js/candidates.js and deserves its own file.
TWO DATA MODES, selected by whether the caller passes a `userId`:
SEED (Candidates.jsx) — every tab renders from the seed record, exactly as
the prototype did.
LIVE (TalentPool.jsx) — GET /candidate/fetch?user_id= switches the endpoint
into detail mode and returns the real record: résumé text, the agent's
match verdict, documents, and the four child collections (interviews,
notes, activity, feedback). The write tabs POST to their own endpoints
and invalidate this one query, so the whole modal repaints from a single
refetch.
Live collections are NEVER padded with the seed's demo rows. An empty tab gets
an empty state, because inventing three scorecards for a real applicant is
worse than showing none.
Scoping differs between the child tables and is not interchangeable: notes
hang off the candidate (users.id), while interviews, activity and feedback
hang off one application (inbox.id). */
import { useMemo, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import Modal from '../ui/Modal'
import { Tabs } from '../ui/Tabs'
import { Avatar, Badge, EmptyState, Icon, ScoreChip } from '../ui/primitives'
import { useToast } from '../ui/Toast'
import { seedQuery } from '../data/seedQueries'
import { qk } from '../lib/queryKeys'
import { friendlyAuthError } from '../lib/errors'
import * as candidatesApi from '../api/candidates'
import { companies, fmtDate, moneyK, pick } from '../data/seed'
const TABS = ['Overview', 'Resume', 'Timeline', 'Interview', 'Notes', 'Activity', 'Documents', 'Feedback']
const LABEL = { fontSize: 12, color: 'var(--text-3)', fontWeight: 600, textTransform: 'uppercase', marginBottom: 8 }
const REVIEWS = ['Strong Hire', 'Hire', 'Lean Hire', 'No Hire']
const INTERVIEW_TYPES = ['Phone Screen', 'Technical', 'System Design', 'Culture Fit', 'Final Round']
const INTERVIEW_STATES = ['Scheduled', 'Completed', 'Cancelled', 'No Show']
const ACTIVITY_TYPES = ['Call', 'Email', 'Meeting', 'Screening', 'Assessment', 'Note']
/** Seed timestamps are Date objects; the API sends ISO strings. */
function fmtWhen(value, fallback = '—') {
if (!value) return fallback
const d = value instanceof Date ? value : new Date(value)
return Number.isNaN(d.getTime()) ? String(value) : fmtDate(d)
}
function fmtClock(value) {
if (!value) return null
const d = new Date(value)
return Number.isNaN(d.getTime()) ? null : d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })
}
function stamp(value) {
const d = value instanceof Date ? value : new Date(value ?? NaN)
return Number.isNaN(d.getTime()) ? 0 : d.getTime()
}
/** + -> one ISO instant, or null. */
function toInstant(date, time) {
if (!date) return null
const d = new Date(`${date}T${time || '00:00'}`)
return Number.isNaN(d.getTime()) ? null : d.toISOString()
}
function Info({ label, val }) {
return (
{label}
{val === 0 || val ? val : '—'}
)
}
function useCandidateDetail(userId) {
return useQuery({
queryKey: qk.candidates.detail(userId),
queryFn: async () => candidatesApi.toRows(await candidatesApi.getByUserId(userId))[0] ?? null,
enabled: Boolean(userId),
})
}
/**
* A write against one of the child endpoints. Every one of them invalidates the
* single detail query the modal renders from, so a saved note and a submitted
* scorecard both land through the same refetch rather than through hand-patched
* cache entries that could drift from the server's view.
*/
function useProfileWrite({ userId, mutationFn, success, onDone }) {
const qc = useQueryClient()
const { toast } = useToast()
return useMutation({
mutationFn,
onSuccess: async (_data, vars) => {
await qc.invalidateQueries({ queryKey: qk.candidates.detail(userId) })
toast(typeof success === 'function' ? success(vars) : success, 'success')
onDone?.()
},
onError: (err) => toast(friendlyAuthError(err, 'Could not save. Please try again.'), 'error'),
})
}
export default function CandidateProfile({ candidate: c, onClose, onAdvance, onToggleFav, onAtsMatch }) {
const { toast } = useToast()
const [tab, setTab] = useState('Overview')
const { data: interviews = [] } = useQuery(seedQuery('interviews'))
const { data: recruiters = [] } = useQuery(seedQuery('recruiters'))
const isLive = Boolean(c.userId)
const detail = useCandidateDetail(c.userId)
const live = detail.data ?? null
// The prototype called DB.pick() inline while rendering, so the "previous
// employer" changed every repaint. Fixed per candidate.
const priorCompany = useMemo(() => pick(companies), [])
const candidateInterviews = interviews.filter((i) => i.candidateId === c.id)
// The application row interviews/activity/feedback attach to. Detail mode
// flattens every application the candidate owns; writes land on the first,
// which is the one the header is describing.
const inboxId = live?.inbox_id ?? null
const favorite = live ? Boolean(live.favorite) : c.favorite
const setFavorite = useProfileWrite({
userId: c.userId,
mutationFn: (next) => candidatesApi.update(c.userId, { favorite: next }),
success: (next) => (next ? `${c.name} added to favorites` : 'Removed from favorites'),
})
// Score the candidate's inbox CV against the assigned job with the ATS engine.
// Needs both an assigned job (what to score against) and a message (whose
// attachment to score); the refetch lands the new ai_score in this modal.
const canScoreAts = isLive && Boolean(live?.assigned_job_post_id && live?.message_id)
const scoreAts = useProfileWrite({
userId: c.userId,
mutationFn: () => candidatesApi.scoreInbox(live.assigned_job_post_id, [live.message_id]),
success: 'CV scored against the assigned job',
})
const title = live?.job_title || c.currentTitle
const company = live?.currentCompany || c.currentCompany
const counts = live && {
Interview: live.interviews?.length ?? 0,
Notes: live.notes?.length ?? 0,
Activity: live.activity?.length ?? 0,
Documents: live.documents?.length ?? 0,
Feedback: live.feedback?.length ?? 0,
}
// In live mode nothing below the hero can be trusted until the detail payload
// lands, so one guard replaces every tab body rather than each tab inventing
// its own half-loaded state.
const guard = !isLive ? null
: detail.isPending ? (
Fetching the full record.
) : detail.isError ? (
{friendlyAuthError(detail.error, 'Please try again.')}
) : !live ? (
This candidate is no longer in the pipeline.
) : null
return (
{canScoreAts && (
)}
>
}
>
Results-driven {c.currentTitle.toLowerCase()} with {c.experience} years of experience
across {c.department.toLowerCase()}. Passionate about building high-quality products
and collaborating with cross-functional teams.
{['Strong Hire', 'Hire', 'Lean Hire'].map((score, i) => {
const r = recruiters[i]
if (!r) return null
const notes = [
'Excellent technical depth and clear communication.',
'Good problem solving, would benefit from more system design exposure.',
'Solid candidate, positive team energy.',
]
return (
{r.name}
{notes[i]}
{score}
)
})}
>
)))}
)
}
/* ------------------------------------------------------------------
Live tabs. Each owns its own form state and its own write, so a half-typed
note is not held by the modal shell and does not survive a tab switch.
------------------------------------------------------------------ */
function ResumeTab({ live }) {
const source = live.documents?.[0]?.name
if (!live.resume_text) {
return (
{source
? `${source} is attached but has not been parsed yet — run the match to extract it.`
: 'This candidate applied without an attachment we could read.'}
)
}
return (
{live.name}
{source ? `Extracted from ${source}` : 'Extracted from the application email'}
{live.resume_text}
)
}
function TimelineTab({ live }) {
const events = useMemo(() => {
const out = []
if (live.applied) {
out.push({
icon: 'user-plus',
title: 'Application received',
at: live.applied,
desc: live.source ? `Applied via ${live.source}` : null,
})
}
if (live.matched_at) {
out.push({
icon: 'sparkles',
title: 'AI screening completed',
at: live.matched_at,
desc: live.match_error || live.match_summary || live.match_status,
})
}
for (const iv of live.interviews ?? []) {
out.push({
icon: 'calendar',
title: iv.interview_type || 'Interview',
at: iv.interview_date,
desc: iv.interview_status,
})
}
for (const a of live.activity ?? []) {
out.push({
icon: 'zap',
title: a.activity_type || 'Activity',
at: a.activity_date,
desc: a.description || a.activity_status,
})
}
for (const f of live.feedback ?? []) {
out.push({
icon: 'star',
title: f.review ? `Feedback: ${f.review}` : 'Feedback submitted',
at: f.created_at,
desc: f.reviewed_by_name ? `by ${f.reviewed_by_name}` : f.note,
})
}
return out.sort((a, b) => stamp(a.at) - stamp(b.at))
}, [live])
if (!events.length) {
return Activity appears here as the candidate moves.
}
return (
{events.map((e, i) => (
{e.title}
{fmtWhen(e.at)}
{e.desc &&
{e.desc}
}
))}
)
}
function InterviewTab({ userId, inboxId, rows }) {
const { toast } = useToast()
const [form, setForm] = useState({ type: INTERVIEW_TYPES[0], date: '', time: '', status: INTERVIEW_STATES[0] })
const set = (k, v) => setForm((f) => ({ ...f, [k]: v }))
const create = useProfileWrite({
userId,
// interviews.interview_date and .interview_time are BOTH datetime columns,
// so the same instant goes to each rather than inventing a second one.
mutationFn: (instant) => candidatesApi.createInterview({
inboxId, date: instant, time: instant, type: form.type, status: form.status,
}),
success: 'Interview scheduled',
onDone: () => setForm({ type: INTERVIEW_TYPES[0], date: '', time: '', status: INTERVIEW_STATES[0] }),
})
function submit() {
const instant = toInstant(form.date, form.time)
if (!instant) {
toast('Pick a date for the interview', 'warning')
return
}
create.mutate(instant)
}
return (
<>
{rows.length ? (