/* global React */
// Field limits & validation — mirrors the spec table + Limitations.
// LIMITS/MAX son objetos MUTABLES: main.jsx llama applyLimits() tras leer
// /api/settings para que el admin pueda cambiarlos sin redeploy.

const LIMITS = {
  fullName: 50, jobTitle: 30, professionalSummary: 1000,
  skillName: 30, skillDesc: 200,
  strengthName: 30,
  language: 30,
  courseName: 30, issuer: 30, credential: 30,
  degree: 30, university: 30,
  company: 30, expJobTitle: 30, scope: 30, responsibilities: 30, achievements: 30, technologies: 30,
  projTitle: 30, projIntro: 100, projRole: 30, projTech: 100, projOutcome: 30,
};

const MAX = {
  technicalKnowledge: 5, strengths: 5, languages: 5,
  courses: 10, education: 2, experience: 5, projects: 2,
};

// Aplica límites venidos del backend (mutando los objetos in-place para que
// todos los componentes que ya referencian LIMITS/MAX vean los nuevos valores).
function applyLimits(fetched) {
  if (fetched && fetched.limits) for (const k of Object.keys(LIMITS)) {
    const v = Number(fetched.limits[k]);
    if (Number.isFinite(v) && v > 0) LIMITS[k] = Math.round(v);
  }
  if (fetched && fetched.max) for (const k of Object.keys(MAX)) {
    const v = Number(fetched.max[k]);
    if (Number.isFinite(v) && v > 0) MAX[k] = Math.round(v);
  }
}

const LANG_LEVELS = ["Native", "Fluent", "Professional", "Intermediate", "Basic"];

const blank = {
  skill: () => ({ skillName: "", proficiency: 70, yearsExperience: "", description: "" }),
  strength: () => ({ name: "" }),
  language: () => ({ language: "", proficiency: "" }),
  course: () => ({ name: "", issuer: "", year: "", credential: "" }),
  education: () => ({ degree: "", university: "", gradYear: "" }),
  experience: () => ({ company: "", jobTitle: "", startDate: "", endDate: "", isCurrent: false, scope: "", responsibilities: "", achievements: "", technologies: "" }),
  project: () => ({ title: "", intro: "", role: "", technologies: "", outcome: "" }),
};

function emptyData() {
  return {
    candidate: { fullName: "", jobTitle: "", professionalSummary: "", photo: null },
    technicalKnowledge: [blank.skill()],
    strengths: [blank.strength()],
    languages: [blank.language()],
    courses: [blank.course()],
    education: [blank.education()],
    experience: [blank.experience()],
    projects: [blank.project()],
  };
}

const yr4 = (v) => /^\d{4}$/.test(String(v || "").trim());
const over = (v, m) => (v || "").length > m;

// Returns { errors: {path: msg}, count } for a given step id.
function validateStep(stepId, d) {
  const e = {};
  if (stepId === "identity") {
    const c = d.candidate;
    if (!c.fullName.trim()) e["candidate.fullName"] = "Full name is required.";
    else if (over(c.fullName, LIMITS.fullName)) e["candidate.fullName"] = `Max ${LIMITS.fullName} characters.`;
    if (!c.jobTitle.trim()) e["candidate.jobTitle"] = "Job title is required.";
    else if (over(c.jobTitle, LIMITS.jobTitle)) e["candidate.jobTitle"] = `Max ${LIMITS.jobTitle} characters.`;
    if (!c.professionalSummary.trim()) e["candidate.professionalSummary"] = "A professional summary is required.";
    else if (over(c.professionalSummary, LIMITS.professionalSummary)) e["candidate.professionalSummary"] = `Max ${LIMITS.professionalSummary} characters.`;
    if (!c.photo) e["candidate.photo"] = "A candidate photo is required.";
  }
  if (stepId === "skills") {
    d.technicalKnowledge.forEach((s, i) => {
      if (s.skillName && over(s.skillName, LIMITS.skillName)) e[`technicalKnowledge.${i}.skillName`] = `Max ${LIMITS.skillName} characters.`;
      if (s.description && over(s.description, LIMITS.skillDesc)) e[`technicalKnowledge.${i}.description`] = `Max ${LIMITS.skillDesc} characters.`;
      if (s.yearsExperience && (Number(s.yearsExperience) < 1 || Number(s.yearsExperience) > 30)) e[`technicalKnowledge.${i}.yearsExperience`] = "1 to 30 years.";
    });
  }
  if (stepId === "courses") {
    const complete = d.courses.filter(c => c.name.trim() && c.issuer.trim() && yr4(c.year));
    if (!complete.length) e["courses._"] = "At least one certification with name, issuer and a 4-digit year is required.";
    d.courses.forEach((c, i) => {
      const touched = c.name || c.issuer || c.year || c.credential;
      if (!touched) return;
      if (!c.name.trim()) e[`courses.${i}.name`] = "Name is required.";
      else if (over(c.name, LIMITS.courseName)) e[`courses.${i}.name`] = `Max ${LIMITS.courseName} characters.`;
      if (!c.issuer.trim()) e[`courses.${i}.issuer`] = "Issuer is required.";
      if (c.year && !yr4(c.year)) e[`courses.${i}.year`] = "4-digit year.";
      else if (!c.year) e[`courses.${i}.year`] = "Year is required.";
    });
  }
  if (stepId === "education") {
    d.education.forEach((ed, i) => {
      if (ed.gradYear && !yr4(ed.gradYear)) e[`education.${i}.gradYear`] = "4-digit year.";
    });
  }
  return e;
}

Object.assign(window, { LIMITS, MAX, LANG_LEVELS, blank, emptyData, validateStep, yr4, applyLimits });
