// screens-apply.jsx — Method choice, CV upload, Profile form

function formatRp(val) {
  const num = String(val).replace(/\D/g, "");
  if (!num) return "";
  return num.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
function parseRp(formatted) {
  return formatted.replace(/\./g, "");
}

function MethodScreen({ t, lang, state, onChoose }) {
  const name  = (state.reg && state.reg.name) || "";
  const first = name.split(" ")[0] || "";
  return (
    <div className="center-wrap">
      <div className="col-mid fadein">
        <div className="tcenter" style={{ marginBottom: 26 }}>
          <div className="eyebrow">{t.methodEyebrow}{first ? `, ${first}` : ""} 👋</div>
          <h1 className="title">{t.methodTitle}</h1>
          <p className="sub">{t.methodSub}</p>
        </div>
        <div className="method-grid">
          <button className="method" onClick={() => onChoose("upload")}>
            <span className="recommended"><Icon name="bolt" size={11} style={{ verticalAlign: -1 }} /> {t.recommended}</span>
            <div className="mi" style={{ background: "var(--brand-soft)", color: "var(--brand)" }}><Icon name="sparkle" size={26} /></div>
            <h3>{t.methodUploadT}</h3>
            <p>{t.methodUploadD}</p>
            <div className="go">{t.startNow} <Icon name="arrow" size={16} /></div>
          </button>
          <button className="method" onClick={() => onChoose("manual")}>
            <div className="mi" style={{ background: "color-mix(in oklab, var(--accent) 16%, white)", color: "var(--accent)" }}><Icon name="edit" size={24} /></div>
            <h3>{t.methodManualT}</h3>
            <p>{t.methodManualD}</p>
            <div className="go">{t.startNow} <Icon name="arrow" size={16} /></div>
          </button>
        </div>
      </div>
    </div>
  );
}

const CV_ACCEPT = ".pdf,.doc,.docx,.jpg,.jpeg,.png,.webp";

function CvPreviewRow({ icon, label, value }) {
  if (!value) return null;
  return (
    <div style={{ display: "flex", gap: 12, padding: "10px 0", borderBottom: "1px solid var(--line)", alignItems: "flex-start" }}>
      <span style={{ color: "var(--brand)", marginTop: 1, flex: "0 0 18px" }}><Icon name={icon} size={16} /></span>
      <span style={{ color: "var(--muted)", fontSize: 13, flex: "0 0 110px" }}>{label}</span>
      <span style={{ fontSize: 14, fontWeight: 500, flex: 1, wordBreak: "break-word" }}>{value}</span>
    </div>
  );
}

function CvPreview({ lang, data: d, fname, fsize, tag, color, onConfirm, onRescan }) {
  const id = lang === "id";
  const eduLabels = { SD:"SD", SMP:"SMP", SMA:"SMA", SMK:"SMK", D1:"D1", D2:"D2", D3:"D3", D4:"D4", S1:"S1/Sarjana", S2:"S2/Magister", S3:"S3/Doktor" };

  return (
    <div className="fadein">
      <FileChip name={fname} size={fsize} tag={tag} color={color} />

      {/* Header hasil */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "18px 0 4px" }}>
        <div style={{ width: 32, height: 32, borderRadius: 10, background: "var(--success-soft,#dcfce7)", color: "#16a34a", display: "grid", placeItems: "center" }}>
          <Icon name="check" size={18} />
        </div>
        <strong style={{ fontSize: 16 }}>{id ? "Hasil scan CV" : "CV scan result"}</strong>
      </div>
      <p className="sub" style={{ marginBottom: 16, fontSize: 13.5 }}>
        {id ? "Periksa data berikut sebelum melanjutkan. Anda bisa ubah di form profil." : "Check the data below before continuing. You can edit in the profile form."}
      </p>

      {/* Data diri */}
      <div style={{ background: "var(--surface)", borderRadius: "var(--radius-sm)", padding: "0 14px", marginBottom: 14 }}>
        <div style={{ padding: "10px 0 6px", fontWeight: 700, fontSize: 13, color: "var(--muted)", letterSpacing: ".05em" }}>
          {id ? "DATA DIRI" : "PERSONAL INFO"}
        </div>
        <CvPreviewRow icon="user"  label={id ? "Nama lengkap" : "Full name"}    value={d.fullName} />
        <CvPreviewRow icon="mail"  label="Email"                                 value={d.email} />
        <CvPreviewRow icon="phone" label={id ? "WhatsApp/HP" : "Phone"}          value={d.wa} />
        <CvPreviewRow icon="map"   label={id ? "Tempat lahir" : "Birth place"}   value={d.birthPlace} />
        <CvPreviewRow icon="cal"   label={id ? "Tanggal lahir" : "Birth date"}   value={d.birthDate} />
        <CvPreviewRow icon="home"  label={id ? "Alamat" : "Address"}             value={d.address} />
      </div>

      {/* Tentang saya */}
      {d.aboutMe && (
        <div style={{ background: "var(--surface)", borderRadius: "var(--radius-sm)", padding: "14px", marginBottom: 14 }}>
          <div style={{ fontWeight: 700, fontSize: 13, color: "var(--muted)", letterSpacing: ".05em", marginBottom: 8 }}>
            {id ? "TENTANG SAYA" : "ABOUT ME"}
          </div>
          <p style={{ fontSize: 14, lineHeight: 1.6, margin: 0 }}>{d.aboutMe}</p>
        </div>
      )}

      {/* Pendidikan */}
      {(d.edu || d.major) && (
        <div style={{ background: "var(--surface)", borderRadius: "var(--radius-sm)", padding: "0 14px", marginBottom: 14 }}>
          <div style={{ padding: "10px 0 6px", fontWeight: 700, fontSize: 13, color: "var(--muted)", letterSpacing: ".05em" }}>
            {id ? "PENDIDIKAN" : "EDUCATION"}
          </div>
          <CvPreviewRow icon="star" label={id ? "Jenjang" : "Level"}   value={eduLabels[d.edu] || d.edu} />
          <CvPreviewRow icon="file" label={id ? "Jurusan" : "Major"}   value={d.major} />
        </div>
      )}

      {/* Riwayat kerja */}
      {d.workHistory?.length > 0 && (
        <div style={{ background: "var(--surface)", borderRadius: "var(--radius-sm)", padding: "0 14px", marginBottom: 14 }}>
          <div style={{ padding: "10px 0 6px", fontWeight: 700, fontSize: 13, color: "var(--muted)", letterSpacing: ".05em" }}>
            {id ? "RIWAYAT KERJA" : "WORK HISTORY"}
          </div>
          {d.workHistory.map((w, i) => (
            <div key={i} style={{ padding: "10px 0", borderBottom: i < d.workHistory.length - 1 ? "1px solid var(--line)" : "none" }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{w.position || "—"}</div>
              <div style={{ color: "var(--muted)", fontSize: 13 }}>{w.company}{w.period ? ` · ${w.period}` : ""}</div>
            </div>
          ))}
        </div>
      )}

      {/* Sosial */}
      {(d.instagram || d.tiktok || d.linkedin) && (
        <div style={{ background: "var(--surface)", borderRadius: "var(--radius-sm)", padding: "0 14px", marginBottom: 14 }}>
          <div style={{ padding: "10px 0 6px", fontWeight: 700, fontSize: 13, color: "var(--muted)", letterSpacing: ".05em" }}>SOCIAL</div>
          <CvPreviewRow icon="star" label="Instagram" value={d.instagram ? `@${d.instagram}` : ""} />
          <CvPreviewRow icon="star" label="TikTok"    value={d.tiktok    ? `@${d.tiktok}`    : ""} />
          <CvPreviewRow icon="star" label="LinkedIn"  value={d.linkedin} />
        </div>
      )}

      {/* Tidak ada data */}
      {!d.fullName && !d.email && !d.wa && !d.edu && !d.workHistory?.length && (
        <div className="banner" style={{ background: "#fef9c3", borderColor: "#fbbf24", color: "#92400e", marginBottom: 14 }}>
          {id ? "Data yang berhasil diekstrak terbatas. Silakan isi form secara manual." : "Limited data extracted. Please fill the form manually."}
        </div>
      )}

      <Button block lg iconR="arrow" onClick={onConfirm} style={{ marginTop: 8 }}>
        {id ? "Lanjut isi form →" : "Continue to form →"}
      </Button>
      <button className="btn btn-ghost" onClick={onRescan} style={{ width: "100%", marginTop: 10 }}>
        {id ? "Upload file lain" : "Upload different file"}
      </button>
    </div>
  );
}

// options: [{ id, label }], value: [id, ...]
function MultiChipSelect({ options = [], value = [], onChange, invalid, placeholder }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    function handler(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  function toggle(id) {
    if (value.includes(id)) onChange(value.filter(x => x !== id));
    else onChange([...value, id]);
  }

  const labelOf = (id) => (options.find(o => o.id === id) || {}).label || id;

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <div
        className={`inp ${invalid ? "invalid" : ""}`}
        style={{ cursor: "pointer", minHeight: 44, height: "auto", display: "flex", flexWrap: "wrap", gap: 6, alignItems: "center", padding: "8px 14px" }}
        onClick={() => setOpen(o => !o)}
      >
        {value.length === 0 && <span style={{ color: "var(--muted)", fontSize: 14 }}>{placeholder}</span>}
        {value.map(id => (
          <span key={id} style={{ display: "inline-flex", alignItems: "center", gap: 4, background: "var(--brand-soft,#fce7f3)", color: "var(--brand)", borderRadius: 8, padding: "2px 8px", fontSize: 13, fontWeight: 500 }}>
            {labelOf(id)}
            <span style={{ cursor: "pointer", lineHeight: 1, marginLeft: 2 }} onClick={(e) => { e.stopPropagation(); toggle(id); }}>×</span>
          </span>
        ))}
        <span style={{ marginLeft: "auto", color: "var(--muted)" }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9l6 6 6-6"/></svg>
        </span>
      </div>
      {open && (
        <div style={{ position: "absolute", zIndex: 100, top: "calc(100% + 4px)", left: 0, right: 0, background: "var(--card,#fff)", border: "1.5px solid var(--line)", borderRadius: "var(--radius-sm)", boxShadow: "0 4px 24px rgba(0,0,0,.12)", maxHeight: 220, overflowY: "auto" }}>
          {options.length === 0 && (
            <div style={{ padding: "12px 14px", color: "var(--muted)", fontSize: 14 }}>Memuat data…</div>
          )}
          {options.map(opt => {
            const sel = value.includes(opt.id);
            return (
              <div key={opt.id} onClick={() => toggle(opt.id)}
                style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", cursor: "pointer", background: sel ? "var(--brand-soft,#fce7f3)" : "transparent", fontSize: 14 }}>
                <span style={{ width: 18, height: 18, borderRadius: 5, border: `2px solid ${sel ? "var(--brand)" : "var(--line)"}`, background: sel ? "var(--brand)" : "transparent", display: "grid", placeItems: "center", flexShrink: 0 }}>
                  {sel && <Icon name="check" size={11} style={{ color: "#fff" }} />}
                </span>
                {opt.label}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

function fileTag(name) {
  if (/\.docx?$/i.test(name)) return { tag: "DOC", color: "#2563eb" };
  if (/\.pdf$/i.test(name))   return { tag: "PDF", color: "#ef4444" };
  return { tag: "IMG", color: "#7c3aed" };
}

function CvUploadScreen({ t, lang, onParsed, onBack }) {
  const [file,    setFile]    = useState(null);
  const [phase,   setPhase]   = useState("idle"); // idle | reading | error | done
  const [steps,   setSteps]   = useState(0);
  const [errMsg,  setErrMsg]  = useState("");
  const [cvData,  setCvData]  = useState(null);
  const items = [t.px_name, t.px_edu, t.px_exp, t.px_skill];

  async function pick(f) {
    if (!f) return;
    setFile(f);
    setPhase("reading");
    setSteps(0);
    setErrMsg("");
    setCvData(null);

    try {
      const result = await window.API.parseCv(f);
      if (result.error) {
        setPhase("error");
        setErrMsg(result.error);
        return;
      }
      setCvData(result.data);
    } catch {
      setPhase("error");
      setErrMsg(lang === "id" ? "Gagal membaca file. Coba lagi." : "Failed to read file. Try again.");
    }
  }

  // Animasi step — lanjut terus sampai parse selesai (cvData ada)
  useEffect(() => {
    if (phase !== "reading") return;
    let i = 0;
    const iv = setInterval(() => {
      setSteps(s => {
        const next = Math.min(s + 1, items.length);
        return next;
      });
      i++;
      if (i >= items.length) clearInterval(iv);
    }, 700);
    return () => clearInterval(iv);
  }, [phase]);

  // Set done saat cvData sudah ada dan animasi sudah mulai
  useEffect(() => {
    if (cvData && phase === "reading") {
      setTimeout(() => setPhase("done"), steps >= items.length ? 300 : 800);
    }
  }, [cvData, steps]);

  const fname = file ? file.name : "";
  const fsize = file ? `${Math.max(1, Math.round(file.size / 1024))} KB` : "";
  const { tag, color } = fileTag(fname);

  function reset() { setFile(null); setPhase("idle"); setErrMsg(""); setSteps(0); }

  return (
    <div className="center-wrap">
      <div className="col-mid card card-pad fadein">
        <div className="eyebrow">{t.cvEyebrow}</div>
        <h1 className="title">{t.cvTitle}</h1>
        <p className="sub" style={{ marginBottom: 22 }}>{t.cvSub}</p>

        {phase === "idle" && (
          <>
            <FileDrop title={t.dropTitle}
              sub={lang === "id" ? "PDF, Word, atau foto CV (JPG/PNG)" : "PDF, Word, or CV photo (JPG/PNG)"}
              accept={CV_ACCEPT} onPick={pick} />
            <div className="tcenter" style={{ marginTop: 18 }}>
              <button className="btn btn-text" onClick={onBack}><Icon name="arrowL" size={16} /> {t.chooseOther}</button>
            </div>
          </>
        )}

        {phase === "error" && (
          <>
            <FileChip name={fname} size={fsize} tag={tag} color="#ef4444" />
            <div className="banner" style={{ background: "#fef2f2", borderColor: "#fca5a5", color: "#dc2626", marginTop: 16 }}>
              <b>{lang === "id" ? "File tidak valid" : "Invalid file"}</b><br />
              <span style={{ fontSize: 13.5 }}>{errMsg}</span>
            </div>
            <Button block onClick={reset} style={{ marginTop: 16 }}>
              {lang === "id" ? "Coba file lain" : "Try another file"}
            </Button>
          </>
        )}

        {phase === "reading" && (
          <>
            <FileChip name={fname} size={fsize} tag={tag} color={color} />
            <div className="scanwrap" style={{ marginTop: 16 }}>
              <div className="scan-beam" />
              <div className="scan-doc">
                {[88, 64, 96, 72, 80, 56].map((w, i) => (
                  <div className="scan-line" key={i} style={{ width: w + "%" }} />
                ))}
              </div>
            </div>
            <div style={{ marginTop: 18 }}>
              <strong style={{ fontSize: 16 }}>{t.cvReading}</strong>
            </div>
            <p className="sub" style={{ margin: "4px 0 0" }}>{t.cvReadingSub}</p>
            <div className="parse-list">
              {items.map((it, i) => (
                <div className={`parse-item ${i < steps ? "on" : ""}`} key={i}>
                  <span className="pc"><Icon name="check" size={13} /></span>{it}
                </div>
              ))}
            </div>
          </>
        )}

        {phase === "done" && cvData && (
          <CvPreview lang={lang} data={cvData} fname={fname} fsize={fsize} tag={tag} color={color}
            onConfirm={() => onParsed(cvData)} onRescan={reset} />
        )}
      </div>
    </div>
  );
}

function ProfileScreen({ t, lang, state, setState, onNext, onBack, autoFilled, editMode, profileReady = true, testsAllDone = false, masterPositions = [], masterLocations = [] }) {
  const D = window.APPDATA;
  const p = state.profile || {};
  const [errors,      setErrors]      = useState({});
  const [showErrBanner, setShowErrBanner] = useState(false);
  const [uploading,   setUploading]   = useState({});
  const [docUrls,     setDocUrls]     = useState({});
  const formRef = useRef(null);
  const [saveStatus, setSaveStatus] = useState(""); // "" | "saving" | "saved"
  const autoSaveTimer = useRef(null);
  const [appStatus, setAppStatus] = useState("");

  // Load server doc URLs on mount so previews work after refresh
  useEffect(() => {
    if (!window.API.getToken()) return;
    window.API.getMyDocs().then(d => { if (d && !d.error) setDocUrls(d); }).catch(() => {});
    window.API.getMyStatus().then(d => { if (d && !d.error) setAppStatus(d.status || ""); }).catch(() => {});
  }, []);

  // Auto-save dengan debounce 1.5 detik setiap kali profile berubah
  useEffect(() => {
    if (!window.API.getToken()) return;
    if (!state.profile) return;
    const p = state.profile;
    const hasData = p.fullName || p.birthPlace || p.address || p.positions?.length;
    if (!hasData) return;
    clearTimeout(autoSaveTimer.current);
    setSaveStatus("saving");
    autoSaveTimer.current = setTimeout(() => {
      window.API.saveStep("profile", { profile: p })
        .then(() => { setSaveStatus("saved"); setTimeout(() => setSaveStatus(""), 2000); })
        .catch(() => setSaveStatus(""));
    }, 1500);
    return () => clearTimeout(autoSaveTimer.current);
  }, [state.profile]);

  function resolveDocUrl(type, stateVal) {
    return docUrls[type] || (typeof stateVal === "string" && stateVal.startsWith("blob:") ? stateVal : (stateVal ? true : false));
  }

  function set(k, v) { setState((s) => ({ ...s, profile: { ...s.profile, [k]: v } })); }

  const work = (p.workHistory && p.workHistory.length) ? p.workHistory : [{ company: "", position: "", period: "", salary: "" }];
  function setWork(i, key, val) { set("workHistory", work.map((x, j) => j === i ? { ...x, [key]: val } : x)); }
  function addWork()    { set("workHistory", [...work, { company: "", position: "", period: "", salary: "" }]); }
  function removeWork(i){ set("workHistory", work.filter((_, j) => j !== i)); }

  async function uploadDoc(file, type, flag) {
    if (!file) return;
    setUploading((u) => ({ ...u, [type]: true }));
    // Store local preview URL immediately so user sees the image
    const previewUrl = URL.createObjectURL(file);
    set(flag, previewUrl);
    if (window.API.getToken()) {
      window.API.upload(file, type).catch(console.error);
    }
    setUploading((u) => ({ ...u, [type]: false }));
  }

  function submit() {
    const e = {};
    ["birthPlace", "address", "major", "salary"].forEach((k) => { if (!p[k]) e[k] = t.required; });
    if (!p.positions?.length) e.position = t.required;
    if (!p.locations?.length) e.location = t.required;
    if (!resolveDocUrl("ktp",   p.ktp))   e.ktp   = t.required;
    if (!resolveDocUrl("photo", p.photo)) e.photo = t.required;
    if (appStatus === "diterima") {
      if (!p.famName)     e.famName    = t.required;
      if (!p.famRelation) e.famRelation = t.required;
      if (!p.famPhone)    e.famPhone   = t.required;
    }
    setErrors(e);
    if (Object.keys(e).length === 0) { setShowErrBanner(false); onNext(); }
    else {
      setShowErrBanner(true);
      setTimeout(() => {
        const root = formRef.current;
        if (!root) return;
        const bad    = root.querySelector(".inp.invalid, .ta.invalid, .field .err");
        const target = bad ? (bad.closest(".field") || bad) : null;
        if (target) window.scrollTo({ top: target.getBoundingClientRect().top + window.scrollY - 110, behavior: "smooth" });
      }, 30);
    }
  }

  return (
    <div className="center-wrap">
      <div className="col-mid card card-pad fadein" ref={formRef}>
        <div className="eyebrow">{t.profEyebrow}</div>
        <h1 className="title">{t.profTitle}</h1>
        <p className="sub">{t.profSub}</p>

        {autoFilled && (
          <div className="banner ok" style={{ marginTop: 18 }}>
            <span className="bi"><Icon name="sparkle" size={18} /></span>
            <span><b>{t.autoFilled}</b> {t.autoFilledSub}</span>
          </div>
        )}

        {/* Data diri */}
        <div className="fsec"><span className="n">1</span><h3>{t.secPersonal}</h3></div>
        <Field label={t.fullName}>
          <Input lead="user" value={p.fullName || (state.reg && state.reg.name) || ""} onChange={(e) => set("fullName", e.target.value)} />
        </Field>
        <div className="row2">
          <Field label={t.waNumber}>
            <div style={{ position: "relative" }}>
              <Input leadText="+62" value={state.reg?.wa || p.wa || ""} readOnly verified />
              <span style={{
                position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)",
                display: "flex", alignItems: "center", gap: 4,
                background: "#ecfdf5", color: "#059669", borderRadius: 20,
                padding: "2px 8px", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap",
              }}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12l5 5L20 6"/></svg>
                {lang === "id" ? "Terverifikasi WA & SMS" : "WA & SMS Verified"}
              </span>
            </div>
          </Field>
          <Field label={t.email}>
            <Input lead="mail" value={p.email || (state.reg && state.reg.email) || ""} readOnly verified />
          </Field>
        </div>

        {/* Nomor kontak lain dari CV */}
        {((p.otherPhones || []).length > 0 || null) && (
          <Field label={lang === "id" ? "Nomor Kontak Lainnya" : "Other Contact Numbers"}
            hint={lang === "id" ? "Nomor HP lain yang ditemukan dari CV Anda." : "Other phone numbers found from your CV."}>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {(p.otherPhones || []).map((num, i) => (
                <div key={i} style={{ display: "flex", gap: 8, alignItems: "center" }}>
                  <Input leadText="+62" value={num}
                    onChange={e => {
                      const arr = [...(p.otherPhones || [])];
                      arr[i] = e.target.value;
                      set("otherPhones", arr);
                    }} />
                  <button type="button" onClick={() => {
                    const arr = (p.otherPhones || []).filter((_, j) => j !== i);
                    set("otherPhones", arr);
                  }} style={{ flexShrink: 0, background: "none", border: "1.5px solid var(--line)", borderRadius: 10, padding: "8px 10px", cursor: "pointer", color: "var(--muted)" }}>
                    <Icon name="x" size={15} />
                  </button>
                </div>
              ))}
              <button type="button" className="addbtn" onClick={() => set("otherPhones", [...(p.otherPhones || []), ""])}>
                <Icon name="plus" size={14} /> {lang === "id" ? "Tambah nomor lain" : "Add another number"}
              </button>
            </div>
          </Field>
        )}
        <div className="row2">
          <Field label={t.birthPlace} error={errors.birthPlace} required>
            <Input value={p.birthPlace || ""} invalid={!!errors.birthPlace} onChange={(e) => set("birthPlace", e.target.value)} />
          </Field>
          <Field label={t.birthDate}>
            <Input type="date" value={p.birthDate || ""} onChange={(e) => set("birthDate", e.target.value)} />
          </Field>
        </div>
        <Field label={t.address} error={errors.address} required>
          <textarea className={`ta ${errors.address ? "invalid" : ""}`} placeholder={t.addressPh} value={p.address || ""} onChange={(e) => set("address", e.target.value)} />
        </Field>
        <div className="row2">
          <Field label={t.lastEdu}>
            <Select value={p.edu ?? ""} onChange={(e) => set("edu", e.target.value)}>
              <option value="" disabled>—</option>
              {D.eduLevels[lang].map((x, i) => <option key={i} value={i}>{x}</option>)}
            </Select>
          </Field>
          <Field label={t.major} error={errors.major} required>
            <Input placeholder={t.majorPh} value={p.major || ""} invalid={!!errors.major} onChange={(e) => set("major", e.target.value)} />
          </Field>
        </div>

        {/* Tentang Saya */}
        <div className="fsec"><span className="n">2</span><h3>{t.secAbout} <span className="muted" style={{ fontWeight:500, fontSize:12.5 }}>· {t.optional}</span></h3></div>
        <Field label={t.aboutMe} hint={t.aboutMeHint}>
          <textarea className="ta" placeholder={t.aboutMePh} rows={5}
            value={p.aboutMe || ""} onChange={(e) => set("aboutMe", e.target.value)} />
        </Field>

        {/* Riwayat kerja */}
        <div className="fsec"><span className="n">3</span><h3>{t.secWork} <span className="muted" style={{ fontWeight:500, fontSize:12.5 }}>· {t.optional}</span></h3></div>
        <p className="sub" style={{ margin: "-6px 0 14px", fontSize: 13 }}>{t.workHint}</p>
        {work.map((w, i) => (
          <div className="subcard" key={i}>
            <div className="subcard-head">
              <span className="t">#{i + 1}</span>
              {work.length > 1 && <button className="rm" onClick={() => removeWork(i)}><Icon name="x" size={13} /> {lang === "id" ? "Hapus" : "Remove"}</button>}
            </div>
            <Field label={t.company}>
              <Input lead="briefcase" placeholder={t.company} value={w.company || ""} onChange={(e) => setWork(i, "company", e.target.value)} />
            </Field>
            <div className="row2">
              <Field label={t.jobTitle}>
                <Input placeholder={t.jobTitle} value={w.position || ""} onChange={(e) => setWork(i, "position", e.target.value)} />
              </Field>
              <Field label={t.period}>
                <Input placeholder={t.periodPh} value={w.period || ""} onChange={(e) => setWork(i, "period", e.target.value)} />
              </Field>
            </div>
            <Field label={t.lastSalary}>
              <Input leadText="Rp" inputMode="numeric" placeholder={t.salaryPh} value={formatRp(w.salary)} onChange={(e) => setWork(i, "salary", parseRp(e.target.value))} />
            </Field>
          </div>
        ))}
        <button className="addbtn" onClick={addWork}><Icon name="plus" size={16} /> {t.addWork}</button>

        {/* Keahlian */}
        <div className="fsec"><span className="n">4</span><h3>{t.secSkills} <span className="muted" style={{ fontWeight:500, fontSize:12.5 }}>· {t.optional}</span></h3></div>
        {(p.skills || []).map((sk, i) => (
          <div className="subcard" key={i} style={{ display:"flex", gap:10, alignItems:"center" }}>
            <div style={{ flex:2 }}>
              <Input placeholder={t.skillNamePh} value={sk.name || ""} onChange={(e) => {
                const arr = [...(p.skills||[])]; arr[i] = {...arr[i], name: e.target.value}; set("skills", arr);
              }} />
            </div>
            <div style={{ flex:1 }}>
              <Input placeholder={t.skillLevel} value={sk.level || ""} onChange={(e) => {
                const arr = [...(p.skills||[])]; arr[i] = {...arr[i], level: e.target.value}; set("skills", arr);
              }} />
            </div>
            <button className="rm" style={{ marginTop:0, flexShrink:0 }} onClick={() => {
              const arr = (p.skills||[]).filter((_,j)=>j!==i); set("skills", arr);
            }}><Icon name="x" size={14} /></button>
          </div>
        ))}
        <button className="addbtn" onClick={() => set("skills", [...(p.skills||[]), {name:"", level:""}])}>
          <Icon name="plus" size={16} /> {t.addSkill}
        </button>

        {/* Referensi */}
        <div className="fsec"><span className="n">5</span><h3>{t.secRefs} <span className="muted" style={{ fontWeight:500, fontSize:12.5 }}>· {t.optional}</span></h3></div>
        {(p.references || []).map((rf, i) => (
          <div className="subcard" key={i}>
            <div className="subcard-head">
              <span className="t">#{i+1}</span>
              <button className="rm" onClick={() => set("references", (p.references||[]).filter((_,j)=>j!==i))}>
                <Icon name="x" size={13} /> {lang==="id"?"Hapus":"Remove"}
              </button>
            </div>
            <div className="row2">
              <Field label={t.refName}>
                <Input lead="user" value={rf.name||""} onChange={(e)=>{const a=[...(p.references||[])];a[i]={...a[i],name:e.target.value};set("references",a);}} />
              </Field>
              <Field label={t.refCompany}>
                <Input value={rf.company||""} onChange={(e)=>{const a=[...(p.references||[])];a[i]={...a[i],company:e.target.value};set("references",a);}} />
              </Field>
            </div>
            <div className="row2">
              <Field label={t.refPhone}>
                <Input lead="phone" inputMode="tel" value={rf.phone||""} onChange={(e)=>{const a=[...(p.references||[])];a[i]={...a[i],phone:e.target.value};set("references",a);}} />
              </Field>
              <Field label={t.refEmail}>
                <Input lead="mail" value={rf.email||""} onChange={(e)=>{const a=[...(p.references||[])];a[i]={...a[i],email:e.target.value};set("references",a);}} />
              </Field>
            </div>
          </div>
        ))}
        <button className="addbtn" onClick={() => set("references", [...(p.references||[]), {name:"",company:"",phone:"",email:""}])}>
          <Icon name="plus" size={16} /> {t.addRef}
        </button>

        {/* Dokumen */}
        <div className="fsec"><span className="n">6</span><h3>{t.secDocs}</h3></div>
        <div className="row2">
          <Field label={t.uploadKtp} hint={t.uploadKtpSub} error={errors.ktp} required>
            <ImageTile wide label={t.uploadKtp} sub={t.uploadKtpSub} filled={resolveDocUrl("ktp", p.ktp)}
              capLabel="KTP.jpg" onPick={(file) => uploadDoc(file, "ktp", "ktp")} />
          </Field>
          <Field label={t.uploadPhoto} hint={t.uploadPhotoSub} error={errors.photo} required>
            <ImageTile label={t.uploadPhoto} sub={t.uploadPhotoSub} filled={resolveDocUrl("photo", p.photo)}
              capLabel="foto.jpg" onPick={(file) => uploadDoc(file, "photo", "photo")} />
          </Field>
        </div>
        <div className="note-line"><span className="ni"><Icon name="shield" size={15} /></span><span>{t.kkNote}</span></div>

        {/* Posisi */}
        <div className="fsec"><span className="n">7</span><h3>{t.secPosition}</h3></div>
        <Field label={t.position} error={errors.position} required>
          <MultiChipSelect
            options={masterPositions.map(p => ({ id: p.id, label: lang === "en" ? p.name_en : p.name_id }))}
            value={p.positions || []}
            onChange={(v) => set("positions", v)}
            invalid={!!errors.position}
            placeholder={t.selectPosition}
          />
        </Field>
        <Field label={t.location} error={errors.location} required>
          <MultiChipSelect
            options={masterLocations.map(l => ({ id: l.id, label: l.name }))}
            value={p.locations || []}
            onChange={(v) => set("locations", v)}
            invalid={!!errors.location}
            placeholder={t.selectLocation}
          />
        </Field>
        <Field label={t.salary} error={errors.salary} required>
          <Input leadText="Rp" placeholder={t.salaryPh} inputMode="numeric" value={formatRp(p.salary)} invalid={!!errors.salary} onChange={(e) => set("salary", parseRp(e.target.value))} />
        </Field>

        {/* Kontak keluarga */}
        <div className="fsec"><span className="n">8</span><h3>{t.secFamily} {appStatus !== "diterima" && <span className="muted" style={{ fontWeight:500, fontSize:12.5 }}>· {t.optional}</span>}{appStatus === "diterima" && <span style={{ fontWeight:500, fontSize:12.5, color:"var(--brand)" }}>· {lang==="id"?"Wajib diisi":"Required"}</span>}</h3></div>
        {appStatus !== "diterima" && (
          <p className="sub" style={{ margin: "-6px 0 14px", fontSize: 13, color: "var(--muted)" }}>
            {lang === "id" ? "Akan wajib diisi jika lamaran Anda diterima." : "Required if your application is accepted."}
          </p>
        )}
        <p className="sub" style={{ margin: "-6px 0 14px", fontSize: 13 }}>{t.familyHint}</p>
        <div className="row2">
          <Field label={t.famName} error={errors.famName} required={appStatus === "diterima"}>
            <Input lead="user" placeholder={t.famNamePh} value={p.famName || ""} invalid={!!errors.famName} onChange={(e) => set("famName", e.target.value)} />
          </Field>
          <Field label={t.relation} error={errors.famRelation} required={appStatus === "diterima"}>
            <Select value={p.famRelation ?? ""} invalid={!!errors.famRelation} onChange={(e) => set("famRelation", e.target.value)}>
              <option value="" disabled>—</option>
              <option value="relParent">{t.relParent}</option>
              <option value="relSpouse">{t.relSpouse}</option>
              <option value="relSibling">{t.relSibling}</option>
              <option value="relOther">{t.relOther}</option>
            </Select>
          </Field>
        </div>
        <Field label={t.famPhone} error={errors.famPhone} required={appStatus === "diterima"}>
          <Input leadText="+62" placeholder="8xx xxxx xxxx" value={p.famPhone || ""} invalid={!!errors.famPhone} onChange={(e) => set("famPhone", e.target.value)} />
        </Field>

        {/* Media sosial */}
        <div className="fsec"><span className="n">9</span><h3>{t.secSocial} <span className="muted" style={{ fontWeight: 500, fontSize: 12.5 }}>· {t.optional}</span></h3></div>
        <p className="sub" style={{ margin: "-6px 0 14px", fontSize: 13 }}>{t.socialHint}</p>
        <Field label={t.instagram}>
          <Input leadText="@" placeholder="username" value={p.instagram || ""} onChange={(e) => set("instagram", e.target.value)} />
        </Field>
        <div className="row2">
          <Field label={t.tiktok}>
            <Input leadText="@" placeholder="username" value={p.tiktok || ""} onChange={(e) => set("tiktok", e.target.value)} />
          </Field>
          <Field label={t.linkedin}>
            <Input lead="linkedin" placeholder="linkedin.com/in/…" value={p.linkedin || ""} onChange={(e) => set("linkedin", e.target.value)} />
          </Field>
        </div>

        {showErrBanner && Object.keys(errors).length > 0 && (
          <div className="banner err-banner" style={{ marginTop: 24, marginBottom: 0 }}>
            <span className="bi"><Icon name="x" size={18} /></span>
            <span>{t.fixErrors}</span>
          </div>
        )}

        <div className="flexbtns">
          <Button variant="ghost" icon="arrowL" onClick={onBack}>{t.back}</Button>
          <span className="grow" />
          {!profileReady && (
            <span style={{ fontSize: 13, color: "var(--muted)", alignSelf: "center", marginRight: 8 }}>
              ⏳ {lang === "id" ? "Memuat data…" : "Loading data…"}
            </span>
          )}
          {profileReady && saveStatus === "saving" && (
            <span style={{ fontSize: 13, color: "var(--muted)", alignSelf: "center", marginRight: 8 }}>
              ⏳ {lang === "id" ? "Menyimpan…" : "Saving…"}
            </span>
          )}
          {profileReady && saveStatus === "saved" && (
            <span style={{ fontSize: 13, color: "var(--ok,#16a34a)", alignSelf: "center", marginRight: 8 }}>
              ✓ {lang === "id" ? "Tersimpan" : "Saved"}
            </span>
          )}
          <Button lg iconR={editMode ? "check" : "arrow"} onClick={submit} disabled={!profileReady}>
            {editMode ? t.saveProfile : testsAllDone ? (lang === "id" ? "Simpan & lanjut ke status" : "Save & go to status") : t.saveContinue}
          </Button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MethodScreen, CvUploadScreen, ProfileScreen });
