/* global React, PhotoCropper, TextField, TextArea, SelectField, RangeField, MonthYearField, LIMITS, MAX, LANG_LEVELS */

function RepeatList({ section, items, max, addLabel, onAdd, onRemove, sectionError, children }) {
  return (
    <div>
      <div className="repeat-head">
        <span className="repeat-count">Added <b>{items.length}</b> of {max}</span>
      </div>
      {sectionError ? <div className="field-error" style={{ marginBottom: 10 }}>{sectionError}</div> : null}
      {items.map((it, i) => (
        <div className="item-card" key={i}>
          <div className="item-bar">
            <span className="item-idx"><span className="dot">{i + 1}</span>{addLabel.replace(/^Add /, "")} {i + 1}</span>
            {items.length > 1 ? (
              <button type="button" className="icon-btn" onClick={() => onRemove(i)}>✕ Remove</button>
            ) : null}
          </div>
          {children(it, i)}
        </div>
      ))}
      <button type="button" className="add-btn" disabled={items.length >= max} onClick={onAdd}>
        + {addLabel}{items.length >= max ? " (limit reached)" : ""}
      </button>
    </div>
  );
}

// ---- step header ----
function Head({ eyebrow, title, sub }) {
  return (
    <div className="step-head">
      <p className="step-eyebrow">{eyebrow}</p>
      <h1 className="step-title">{title}</h1>
      <p className="step-sub">{sub}</p>
    </div>
  );
}

// ================= STEPS =================
function StepIdentity({ d, errors, h }) {
  const c = d.candidate;
  return (
    <div>
      <Head eyebrow="Step 1 · Candidate" title="Your identity & photo"
        sub="This appears in the header of your CV. Upload a clear headshot — you can zoom and drag to frame it." />
      <div className="field">
        <div className="field-label"><span className="lbl">Candidate photo<span className="req">*</span></span></div>
        <PhotoCropper value={c.photo} onChange={(v) => h.setCandidate("photo", v)} />
        {errors["candidate.photo"] ? <div className="field-error">{errors["candidate.photo"]}</div> : null}
      </div>
      <TextField label="Full name" required max={LIMITS.fullName}
        value={c.fullName} onChange={(v) => h.setCandidate("fullName", v)}
        error={errors["candidate.fullName"]} placeholder="e.g. María González Pérez" />
      <TextField label="Job title" required max={LIMITS.jobTitle}
        value={c.jobTitle} onChange={(v) => h.setCandidate("jobTitle", v)}
        error={errors["candidate.jobTitle"]} placeholder="e.g. Network Engineer" />
      <TextArea label="Professional summary" required max={LIMITS.professionalSummary} rows={7}
        value={c.professionalSummary} onChange={(v) => h.setCandidate("professionalSummary", v)}
        error={errors["candidate.professionalSummary"]}
        placeholder="A short profile summary — your experience, focus areas, and the value you bring to a team." />
    </div>
  );
}

function StepSkills({ d, errors, h }) {
  return (
    <div>
      <Head eyebrow="Step 2 · Technical Knowledge" title="Technical skills"
        sub="Up to 5 skills. Proficiency shows as a bar on the CV; years of experience is optional." />
      <RepeatList section="technicalKnowledge" items={d.technicalKnowledge} max={MAX.technicalKnowledge}
        addLabel="Add skill" onAdd={() => h.addItem("technicalKnowledge")} onRemove={(i) => h.removeItem("technicalKnowledge", i)}>
        {(it, i) => (
          <>
            <TextField label="Skill name" max={LIMITS.skillName} value={it.skillName}
              onChange={(v) => h.setItem("technicalKnowledge", i, "skillName", v)}
              error={errors[`technicalKnowledge.${i}.skillName`]} placeholder="e.g. Cisco Networking" />
            <div className="row-2">
              <RangeField label="Proficiency" value={it.proficiency}
                valueLabel={(it.proficiency || 0) <= 25 ? "Basic" : (it.proficiency || 0) <= 50 ? "Medium" : (it.proficiency || 0) <= 75 ? "Full" : "Expert"}
                onChange={(v) => h.setItem("technicalKnowledge", i, "proficiency", v)} />
              <TextField label="Years of experience" type="number" inputMode="numeric"
                value={it.yearsExperience} onChange={(v) => h.setItem("technicalKnowledge", i, "yearsExperience", v)}
                error={errors[`technicalKnowledge.${i}.yearsExperience`]} placeholder="1–30" />
            </div>
            <TextArea label="Description" max={LIMITS.skillDesc} rows={2} value={it.description}
              onChange={(v) => h.setItem("technicalKnowledge", i, "description", v)}
              error={errors[`technicalKnowledge.${i}.description`]} placeholder="A short note about this skill (optional)." />
          </>
        )}
      </RepeatList>
    </div>
  );
}

function StepStrengths({ d, h }) {
  return (
    <div>
      <Head eyebrow="Step 3 · Strengths" title="Strengths & soft skills"
        sub="Up to 5 short soft-skill items. These appear as a bulleted list in the sidebar." />
      <RepeatList section="strengths" items={d.strengths} max={MAX.strengths}
        addLabel="Add strength" onAdd={() => h.addItem("strengths")} onRemove={(i) => h.removeItem("strengths", i)}>
        {(it, i) => (
          <TextField label={`Strength ${i + 1}`} max={LIMITS.strengthName} value={it.name}
            onChange={(v) => h.setItem("strengths", i, "name", v)} placeholder="e.g. Problem solving" />
        )}
      </RepeatList>
    </div>
  );
}

function StepLanguages({ d, h }) {
  return (
    <div>
      <Head eyebrow="Step 4 · Languages" title="Languages"
        sub="Up to 5 languages with a proficiency level." />
      <RepeatList section="languages" items={d.languages} max={MAX.languages}
        addLabel="Add language" onAdd={() => h.addItem("languages")} onRemove={(i) => h.removeItem("languages", i)}>
        {(it, i) => (
          <div className="row-2">
            <TextField label="Language" max={LIMITS.language} value={it.language}
              onChange={(v) => h.setItem("languages", i, "language", v)} placeholder="e.g. English" />
            <SelectField label="Proficiency" options={LANG_LEVELS} value={it.proficiency}
              onChange={(v) => h.setItem("languages", i, "proficiency", v)} placeholder="Select level…" />
          </div>
        )}
      </RepeatList>
    </div>
  );
}

function StepCourses({ d, errors, h }) {
  return (
    <div>
      <Head eyebrow="Step 5 · Courses / Certifications" title="Courses & certifications"
        sub="Up to 10. At least one with name, issuer and year is required." />
      <RepeatList section="courses" items={d.courses} max={MAX.courses}
        addLabel="Add certification" onAdd={() => h.addItem("courses")} onRemove={(i) => h.removeItem("courses", i)}
        sectionError={errors["courses._"]}>
        {(it, i) => (
          <>
            <TextField label="Course / certification name" required max={LIMITS.courseName} value={it.name}
              onChange={(v) => h.setItem("courses", i, "name", v)}
              error={errors[`courses.${i}.name`]} placeholder="e.g. CompTIA Network+" />
            <div className="row-2">
              <TextField label="Issuer / institution" required max={LIMITS.issuer} value={it.issuer}
                onChange={(v) => h.setItem("courses", i, "issuer", v)}
                error={errors[`courses.${i}.issuer`]} placeholder="e.g. CompTIA" />
              <TextField label="Completion year" required value={it.year} inputMode="numeric"
                onChange={(v) => h.setItem("courses", i, "year", v.replace(/\D/g, "").slice(0, 4))}
                error={errors[`courses.${i}.year`]} placeholder="e.g. 2023" />
            </div>
            <TextField label="Credential ID or URL" max={LIMITS.credential} value={it.credential}
              onChange={(v) => h.setItem("courses", i, "credential", v)} placeholder="e.g. ABC-12345 or https://…" />
          </>
        )}
      </RepeatList>
    </div>
  );
}

function StepEducation({ d, errors, h }) {
  return (
    <div>
      <Head eyebrow="Step 6 · Education" title="Education"
        sub="Up to 2 degrees or academic programs." />
      <RepeatList section="education" items={d.education} max={MAX.education}
        addLabel="Add program" onAdd={() => h.addItem("education")} onRemove={(i) => h.removeItem("education", i)}>
        {(it, i) => (
          <>
            <TextField label="Degree / program" max={LIMITS.degree} value={it.degree}
              onChange={(v) => h.setItem("education", i, "degree", v)} placeholder="e.g. B.Sc. Computer Science" />
            <div className="row-2">
              <TextField label="University / institution" max={LIMITS.university} value={it.university}
                onChange={(v) => h.setItem("education", i, "university", v)} placeholder="e.g. UNAM" />
              <TextField label="Graduation year" value={it.gradYear} inputMode="numeric"
                onChange={(v) => h.setItem("education", i, "gradYear", v.replace(/\D/g, "").slice(0, 4))}
                error={errors[`education.${i}.gradYear`]} placeholder="e.g. 2018" />
            </div>
          </>
        )}
      </RepeatList>
    </div>
  );
}

function StepExperience({ d, h }) {
  return (
    <div>
      <Head eyebrow="Step 7 · Professional Experience" title="Professional experience"
        sub="Up to 5 roles, most recent first. Keep each field concise — they print as short lines on the CV." />
      <RepeatList section="experience" items={d.experience} max={MAX.experience}
        addLabel="Add experience" onAdd={() => h.addItem("experience")} onRemove={(i) => h.removeItem("experience", i)}>
        {(it, i) => (
          <>
            <div className="row-2">
              <TextField label="Company name" max={LIMITS.company} value={it.company}
                onChange={(v) => h.setItem("experience", i, "company", v)} placeholder="e.g. Acme Corp" />
              <TextField label="Job title" max={LIMITS.expJobTitle} value={it.jobTitle}
                onChange={(v) => h.setItem("experience", i, "jobTitle", v)} placeholder="e.g. Systems Engineer" />
            </div>
            <div className="row-2">
              <MonthYearField label="Start date" value={it.startDate}
                onChange={(v) => h.setItem("experience", i, "startDate", v)} />
              <MonthYearField label="End date" value={it.endDate} disabled={it.isCurrent}
                onChange={(v) => h.setItem("experience", i, "endDate", v)} />
            </div>
            <label className="field" style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer", marginBottom: 14 }}>
              <input type="checkbox" checked={it.isCurrent}
                onChange={(e) => h.setItem("experience", i, "isCurrent", e.target.checked)} />
              <span style={{ fontSize: 13, fontWeight: 600 }}>This is my current role (show “Present”)</span>
            </label>
            <TextField label="Scope / role context" max={LIMITS.scope} value={it.scope}
              onChange={(v) => h.setItem("experience", i, "scope", v)} placeholder="e.g. 50-site enterprise network" />
            <TextField label="Key responsibilities" max={LIMITS.responsibilities} value={it.responsibilities}
              onChange={(v) => h.setItem("experience", i, "responsibilities", v)} placeholder="Concise — 30 chars" />
            <TextField label="Key achievements / impact" max={LIMITS.achievements} value={it.achievements}
              onChange={(v) => h.setItem("experience", i, "achievements", v)} placeholder="Concise — 30 chars" />
            <TextField label="Technologies & tools" max={LIMITS.technologies} value={it.technologies}
              onChange={(v) => h.setItem("experience", i, "technologies", v)} placeholder="e.g. Cisco, Azure, Linux" />
          </>
        )}
      </RepeatList>
    </div>
  );
}

function StepProjects({ d, h }) {
  return (
    <div>
      <Head eyebrow="Step 8 · Key Projects" title="Key projects"
        sub="Up to 2 standout projects with role, technologies and a measurable outcome." />
      <RepeatList section="projects" items={d.projects} max={MAX.projects}
        addLabel="Add project" onAdd={() => h.addItem("projects")} onRemove={(i) => h.removeItem("projects", i)}>
        {(it, i) => (
          <>
            <TextField label="Project title" max={LIMITS.projTitle} value={it.title}
              onChange={(v) => h.setItem("projects", i, "title", v)} placeholder="e.g. Datacenter Migration" />
            <TextArea label="Introduction" max={LIMITS.projIntro} rows={2} value={it.intro}
              onChange={(v) => h.setItem("projects", i, "intro", v)} placeholder="What the project was and its main objective." />
            <TextField label="Your role" max={LIMITS.projRole} value={it.role}
              onChange={(v) => h.setItem("projects", i, "role", v)} placeholder="e.g. Lead Engineer" />
            <TextArea label="Technologies" max={LIMITS.projTech} rows={2} value={it.technologies}
              onChange={(v) => h.setItem("projects", i, "technologies", v)} placeholder="Tools, software, systems involved." />
            <TextField label="Outcome" max={LIMITS.projOutcome} value={it.outcome}
              onChange={(v) => h.setItem("projects", i, "outcome", v)} placeholder="Measurable result / impact." />
          </>
        )}
      </RepeatList>
    </div>
  );
}

Object.assign(window, {
  StepIdentity, StepSkills, StepStrengths, StepLanguages,
  StepCourses, StepEducation, StepExperience, StepProjects, Head,
});
