/* Rich, internally-consistent detail data for the candidate panel.
   Every candidate gets a full profile generated from their headline numbers
   (ats, skills_pct, skillbars, strengths, gaps, years, decision, risk) so the
   panel works for any selection. c1 (Nguyen Minh Tri) carries hand-authored prose. */

const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, Math.round(n)));

const REC = {
  shortlisted: { tone: 'proceed', label: 'Proceed', verb: 'Proceed to interview' },
  borderline:  { tone: 'caution', label: 'Proceed with Caution', verb: 'Manual review required' },
  rejected:    { tone: 'reject',  label: 'Reject', verb: 'Below threshold' },
};
const RISK_SCORE = { Low: 16, Medium: 46, High: 72, Critical: 90 };

/* ---- score dashboard (0–100) ---- */
function genScores(p) {
  const top = [...p.skillbars].sort((a, b) => b.percentage - a.percentage);
  const avg = p.skillbars.reduce((s, x) => s + x.percentage, 0) / p.skillbars.length;
  const domain = (top[0].percentage + top[1].percentage + (top[2] ? top[2].percentage : top[1].percentage)) / 3;
  const lead = (p.decision === 'shortlisted' ? 86 : p.decision === 'borderline' ? 67 : 54) + (p.years - 7) * 1.6;
  const comm = (p.decision === 'rejected' ? 62 : 80) + (p.ats - 78) * 0.25;
  return {
    ats: p.ats,
    requiredMatch: p.skills_pct,
    preferredMatch: clamp(p.skills_pct - 13, 28, 92),
    experience: clamp(p.years >= 11 ? 94 : p.years >= 8 ? 84 : p.years >= 6 ? 73 : 58 + p.years * 2, 40, 99),
    domain: clamp(domain, 0, 100),
    leadership: clamp(lead, 38, 96),
    communication: clamp(comm, 48, 95),
    technical: clamp(avg, 0, 100),
  };
}

const SCORE_LABELS = {
  ats: 'ATS Score', requiredMatch: 'Required Match', preferredMatch: 'Preferred Match',
  experience: 'Experience', domain: 'Domain', leadership: 'Leadership',
  communication: 'Communication', technical: 'Technical',
};

/* ---- qualification match ---- */
function qualFrom(s) {
  const ev = {
    matched: `Repeatedly demonstrated ${s.name} across full-lifecycle engagements; depth confirmed in screening.`,
    partial: `Some hands-on exposure to ${s.name}, but not a primary focus area — would need ramp-up.`,
    missing: `No clear evidence of ${s.name} in the resume or recruiter screen.`,
  }[s.variant];
  const src = s.variant === 'missing' ? 'Not found in resume' : `Resume · Experience §${(s.name.length % 3) + 1}`;
  return { name: s.name, status: s.variant, confidence: s.percentage, evidence: ev, source: src };
}
function genQuals(p) {
  const sb = p.skillbars;
  const job = (window.JOBS || []).find((j) => j.id === p.jobId);
  const nMust = job ? Math.min(job.mustHave.length, sb.length) : Math.max(sb.length - 2, 3);
  return {
    required: sb.slice(0, nMust).map(qualFrom),
    preferred: sb.slice(nMust).map(qualFrom),
    nice: [
      { name: 'Multi-client delivery', status: p.years >= 8 ? 'matched' : 'partial', confidence: p.years >= 8 ? 90 : 55,
        evidence: p.years >= 8 ? 'Delivered across multiple client environments.' : 'Single-team delivery to date.',
        source: 'Resume · Projects' },
      { name: 'Relevant certification', status: p.decision === 'rejected' ? 'missing' : 'matched',
        confidence: p.decision === 'rejected' ? 10 : 100,
        evidence: p.decision === 'rejected' ? 'No active certification listed.' : 'Active cloud / vendor certification verified.',
        source: p.decision === 'rejected' ? 'Not found in resume' : 'Resume · Certifications' },
    ],
  };
}

/* ---- skills grouped by category (colored badges) ---- */
function genSkillGroups(p) {
  const matched = p.skillbars.filter((s) => s.variant === 'matched').map((s) => s.name);
  const developing = p.skillbars.filter((s) => s.variant !== 'matched').map((s) => s.name);
  return [
    { category: 'Core matched skills', variant: 'coral', items: matched.length ? matched : p.skillbars.slice(0, 2).map((s) => s.name) },
    { category: 'Confirmed strengths', variant: 'success', items: p.strengths },
    { category: 'Developing / watch areas', variant: 'warning', items: developing.length ? developing : p.gaps },
    { category: 'Ways of working', variant: 'ink', items: ['Stakeholder management', 'Agile delivery', 'Client workshops'] },
  ];
}

/* ---- career timeline (generated) ---- */
const PREV_COS = ['VNG', 'FPT Software', 'Sea Group', 'Shopee', 'Tiki', 'Zalo'];
function downgrade(title) {
  return title.replace(/^Lead\s+/, 'Senior ').replace(/^Senior\s+/, '').replace('Lead ', '');
}
function genTimeline(p) {
  const endY = 2026;
  const curSpan = clamp(Math.max(2, Math.round(p.years * 0.33)), 2, 5);
  const midSpan = clamp(Math.round(p.years * 0.4), 2, 5);
  const out = [];
  out.push({
    type: p.decision === 'shortlisted' ? 'promotion' : 'role',
    role: p.headline, company: p.company,
    period: `${endY - curSpan} – Present`, duration: `${curSpan} yrs`,
    note: p.decision === 'shortlisted' ? `Promoted to ${p.headline.split(' ').slice(0, 2).join(' ')} lead` : 'Current role',
  });
  out.push({
    type: 'role', role: downgrade(p.headline), company: p.company,
    period: `${endY - curSpan - midSpan} – ${endY - curSpan}`, duration: `${midSpan} yrs`,
    note: 'Same employer, prior level',
  });
  if (p.risk === 'High') {
    out.push({ type: 'gap', role: 'Career break', company: '', period: `${endY - curSpan - midSpan}`, duration: '~8 mo', note: 'Unexplained gap — flag for screening' });
  }
  out.push({
    type: 'role', role: downgrade(p.headline).replace(/Consultant|Lead|Architect|Developer|Specialist|Engineer|Manager|Coordinator|Executive/, 'Associate'),
    company: PREV_COS[p.name.length % PREV_COS.length],
    period: `${endY - p.years} – ${endY - curSpan - midSpan}`, duration: `${clamp(p.years - curSpan - midSpan, 1, 6)} yrs`,
    note: 'Early career',
  });
  return out;
}

/* ---- projects ---- */
function genProjects(p) {
  const top = [...p.skillbars].sort((a, b) => b.percentage - a.percentage);
  const scale = p.decision === 'shortlisted' ? 1 : p.decision === 'borderline' ? 0.7 : 0.5;
  return [
    {
      name: `${top[0].name} — client deployment`, role: 'Workstream lead',
      summary: `End-to-end ${top[0].name} delivery for an enterprise client, from scoping through production handover.`,
      tags: top.slice(0, 3).map((s) => s.name),
      impact: `${clamp(40 * scale, 8, 45)}% less manual processing · ${clamp(14 * scale, 3, 14)}-team rollout`,
    },
    {
      name: `Manual process → automated workflow migration`, role: 'Implementation lead',
      summary: `Replaced a manual back-office process with an automated workflow, including validation and monitoring.`,
      tags: [top[1].name, 'Automation', 'Go-live'],
      impact: `${clamp(120 * scale, 20, 120)} process steps automated · zero critical defects at go-live`,
    },
  ];
}

/* ---- leadership ---- */
function genLeadership(p, scores) {
  if (scores.leadership >= 78) {
    return [
      { title: `Led a ${clamp(p.years + 4, 8, 22)}-person cross-geo delivery team`, detail: 'Owned staffing, sprint planning, and client steering-committee reporting.' },
      { title: `Mentored ${clamp(Math.round(p.years / 2), 2, 8)} junior consultants`, detail: 'Two direct reports promoted within 18 months.' },
      { title: 'Facilitated executive design workshops', detail: 'Ran discovery and scoping sessions with client leadership.' },
    ];
  }
  return [
    { title: 'Workstream-level ownership', detail: 'Coordinated a small functional pod within a larger programme.' },
    { title: 'Knowledge sharing', detail: 'Authored configuration playbooks used by the wider team.' },
  ];
}

/* ---- strengths / concerns ---- */
function genStrengths(p) {
  const top = [...p.skillbars].sort((a, b) => b.percentage - a.percentage);
  return p.strengths.map((s, i) => ({
    title: s,
    detail: i === 0
      ? `Strongest signal in the profile — ${top[0].name} at ${top[0].percentage}% match with consistent project evidence.`
      : `Well-evidenced across multiple roles and reinforced in the recruiter screen.`,
  }));
}
function genConcerns(p) {
  if (!p.gaps.length) return [{ title: 'No material concerns', detail: 'Profile aligns cleanly with the role scorecard.' }];
  return p.gaps.map((g) => ({
    title: g,
    detail: `${g} sits below the role bar — confirm depth in a technical interview before committing.`,
  }));
}

/* ---- risk ---- */
function genRisk(p, scores) {
  const factor = (label, level, note) => ({ label, level, note });
  const tenureLevel = p.years >= 8 ? 'Low' : p.years >= 5 ? 'Medium' : 'High';
  return {
    level: p.risk,
    score: RISK_SCORE[p.risk],
    reasoning: p.risk === 'Low'
      ? 'Stable tenure, verified skills, and strong references. Low likelihood of attrition or misrepresentation.'
      : p.risk === 'Medium'
      ? 'Generally solid, but one or two factors (skill depth or tenure) warrant a closer look before an offer.'
      : 'Multiple flags — short tenures, unverified claims, or a notable resume gap. Proceed only with thorough vetting.',
    factors: [
      factor('Tenure stability', tenureLevel, `Avg ${clamp(p.years / 3, 1, 6)}-yr stints across employers.`),
      factor('Skill verification', scores.technical >= 80 ? 'Low' : scores.technical >= 60 ? 'Medium' : 'High', 'Based on screen vs. resume consistency.'),
      factor('Reference checks', 'Medium', 'Pending — not yet completed.'),
      factor('Compensation fit', p.years >= 10 ? 'Medium' : 'Low', 'Expectation vs. band for the role.'),
    ],
  };
}

/* ---- evidence explorer ---- */
function genEvidence(p) {
  const top = [...p.skillbars].sort((a, b) => b.percentage - a.percentage);
  return [
    { claim: `${p.years} years of hands-on experience`, excerpt: `“…${p.years}+ years delivering at ${p.company} and prior roles, focused on ${top[0].name}.”`, confidence: 98, source: 'Resume · Summary' },
    { claim: `Deep ${top[0].name} expertise`, excerpt: `“Owned the ${top[0].name} workstream end-to-end, from scoping to production, on three enterprise engagements.”`, confidence: top[0].percentage, source: 'Resume · Experience' },
    { claim: `Quantified delivery impact`, excerpt: `“Cut manual processing time significantly and led a multi-team rollout.”`, confidence: p.decision === 'shortlisted' ? 88 : 64, source: 'Resume · Projects' },
    { claim: p.decision === 'rejected' ? 'Certification status unclear' : 'Certified practitioner', excerpt: p.decision === 'rejected' ? '“…training completed (certification not listed).”' : '“Cloud / vendor certification — verified.”', confidence: p.decision === 'rejected' ? 22 : 100, source: p.decision === 'rejected' ? 'Not found' : 'Resume · Certifications' },
  ];
}

/* ---- hand-authored overrides for the showcased candidate ---- */
const OVERRIDES = {
  c1: {
    confidence: 92,
    reasoning:
      'Tri is a textbook Proceed. Seven years of production AI engineering with three shipped agent platforms — LLM orchestration, multi-agent design, retrieval, and function calling all clear the required line with strong project evidence. He owns systems end-to-end at Grab, from design through on-call, so the "deployed, not slides" bar is met. The only soft spot is enterprise system integration outside consumer tech, which is worth probing but is coachable given the rest of the profile.',
    timeline: [
      { type: 'promotion', role: 'Senior AI Engineer — agent platforms', company: 'Grab', period: '2024 – Present', duration: '2 yrs', note: 'Promoted from AI Engineer — now owns the agent platform end-to-end' },
      { type: 'role', role: 'AI Engineer', company: 'Grab', period: '2022 – 2024', duration: '2 yrs', note: 'Joined to build LLM-powered support automation' },
      { type: 'role', role: 'Machine Learning Engineer', company: 'VNG', period: '2020 – 2022', duration: '2 yrs', note: 'Search ranking and NLP services' },
      { type: 'role', role: 'Software Engineer', company: 'FPT Software', period: '2019 – 2020', duration: '1 yr', note: 'Early career — backend services for enterprise clients' },
    ],
    projects: [
      { name: 'Customer-support agent platform', role: 'Tech lead', summary: 'Multi-agent pipeline handling triage, retrieval, and action execution across internal tools, with guardrails and human handoff.', tags: ['Multi-agent', 'Function calling', 'Guardrails'], impact: '62% of tickets resolved without human touch · 4 markets' },
      { name: 'RAG platform for internal knowledge', role: 'Owner', summary: 'Company-wide retrieval service — ingestion, chunking, vector search, and evaluation harness used by 12 product teams.', tags: ['Retrieval', 'Vector databases', 'Evals'], impact: 'p95 latency under 800ms · 12 teams onboarded' },
      { name: 'LLM eval & observability stack', role: 'Lead engineer', summary: 'Offline eval suites plus online tracing and regression alerts for every agent release.', tags: ['Evaluation', 'Observability', 'CI'], impact: 'Release regressions caught pre-deploy · weekly ship cadence' },
    ],
    evidence: [
      { claim: 'Shipped a multi-agent support platform', excerpt: '“Designed and shipped the agent platform handling triage, retrieval and tool execution for customer support across 4 markets.”', confidence: 95, source: 'Resume · Experience p.1' },
      { claim: '62% autonomous resolution rate', excerpt: '“Raised no-touch resolution from 31% to 62% within two quarters of the agent rollout.”', confidence: 88, source: 'Resume · Projects p.2' },
      { claim: '7 years of engineering experience', excerpt: '“7+ years across Grab, VNG and FPT Software, the last four focused on production LLM systems.”', confidence: 99, source: 'Resume · Summary p.1' },
      { claim: 'Cloud certified', excerpt: '“AWS Solutions Architect — Associate; GCP Professional ML Engineer.”', confidence: 100, source: 'Resume · Certifications p.3' },
    ],
  },
};

function getDetail(p) {
  const scores = genScores(p);
  const base = {
    rec: REC[p.decision],
    confidence: p.decision === 'shortlisted' ? clamp(p.ats + 2, 84, 97) : p.decision === 'borderline' ? clamp(p.ats - 8, 56, 72) : clamp(108 - p.skills_pct, 78, 92),
    reasoning: `${p.name.split(' ')[0]} is a ${REC[p.decision].label.toLowerCase()} candidate. ${p.strengths.slice(0, 2).join(' and ')} are well evidenced, while ${(p.gaps[0] || 'no major area')} ${p.gaps.length ? 'falls short of the role bar' : 'raises no concern'}. Recommendation reflects an ATS of ${p.ats} and a ${p.skills_pct}% required-skills match.`,
    scores,
    quals: genQuals(p),
    skillGroups: genSkillGroups(p),
    timeline: genTimeline(p),
    projects: genProjects(p),
    leadership: genLeadership(p, scores),
    strengthsDetail: genStrengths(p),
    concernsDetail: genConcerns(p),
    risk: genRisk(p, scores),
    evidence: genEvidence(p),
  };
  return Object.assign(base, OVERRIDES[p.id] || {});
}

Object.assign(window, { getDetail, SCORE_LABELS });
