/* kariera.jsx, careers page; uses Header/Footer/Arrow from advant.jsx */
const { useState: useStateK, useEffect: useEffectK, useRef: useRefK, useMemo: useMemoK } = React;

/* ============ ROLE DATA ============ */

const ROLE = {
  id: "ADV-2026-01",
  title: "Specialist za vzdrževanje in zagon najsodobnejših hladilnih sistemov",
  team: "Tehnična podpora",
  loc: "Ljubljana, Cesta na Brdo 119A",
  type: "Polni delovni čas · pogodba za nedoločen čas",
  probation: "6-mesečno poskusno obdobje",
  start: "Možen takojšnji začetek",
  expect: [
    "Izkušnje z vzdrževanjem hladilnih sistemov",
    "Vsaj 3 leta dela na podobnem delovnem mestu",
    "Najmanj IV. stopnja tehnične izobrazbe",
    "Znanje angleškega jezika",
    "Vozniški izpit B-kategorije",
    "Pripravljenost za učenje novih tehnologij in delo s strankami",
  ],
  offer: [
    "Trajna zaposlitev s 6-mesečnim poskusnim obdobjem",
    "Delo v urejenem in sproščenem delovnem okolju",
    "Uporaba najsodobnejših orodij in opreme",
    "Možnost osebnega in strokovnega razvoja ter napredovanja",
    "Možen takojšnji začetek dela",
  ],
};

const WHY = [
  ["01", "Misijsko-kritični sistemi", "Delaš na opremi, ki ne sme odpovedati, banke, vlade, bolnišnice."],
  ["02", "Senior ekipa", "Inženirji s 15+ let izkušenj. Naučiš se hitro, ker te kdo nauči."],
  ["03", "Najsodobnejša orodja", "Uniflair, Schneider Electric, APC. Brez improvizacij."],
  ["04", "Brez politike", "Odgovorni vodja projekta odloča. Brez sestankov o sestankih."],
];

/* ============ UI TRANSLATIONS (static chrome + application form) ============
   Role/Why/Hero CONTENT comes from WP per language; these are the hardcoded
   labels and the whole apply form, which WP does not drive. */
const KT = {
  SI: {
    roleOpen: "Odprto delovno mesto", roleExpect: "Pričakujemo", roleOffer: "Nudimo",
    roleStatus: "Razpis odprt", roleDeadline: "prijave do 30.04.2026", roleApply: "Prijavi se na razpis",
    whyIdx: "Zakaj Advant",
    fbIdx: "Klasična pot", fbH3: "Raje po pošti ali e-pošti? Razumemo.",
    steps: ["Kontakt", "Izkušnje", "O tebi", "Potrditev"],
    skills: [
      ["cooling", "Vzdrževanje hladilnih sistemov", "CRAC / CRAH / chiller"],
      ["dc", "Delo v podatkovnih centrih", "Tier I–IV okolja"],
      ["bms", "Building Management Systems", "Schneider, Honeywell ipd."],
      ["ups", "UPS / napajalni sistemi", "APC, Eaton, Riello"],
      ["hvac", "HVAC inštalacije", "Hladilna sredstva, kategorija I/II"],
      ["fire", "Sistemi gašenja", "Novec 1230, Inergen"],
      ["cabling", "Računalniška omrežja", "Cat 6A, optika, certifikati"],
      ["en1047", "Standardi (EN1047, F90/120)", "Varne sobe, požarna varnost"],
    ],
    recap: [
      { q: "Katero mesto je v naslovu glavne pisarne Advanta? (namig: spodaj v nogi je naslov)", a: ["ljubljana", "lj"] },
      { q: "Kaj iščemo v naslovu? Specialist za vzdrževanje in zagon hladilnih ___ ?", a: ["sistemov", "sistemi", "sistem"] },
      { q: "Vpiši šifro razpisa, ki je prikazana zgoraj v hero sekciji (oblika ADV-YYYY-NN):", a: [ROLE.id.toLowerCase()] },
    ],
    headIdx: "Prijava", headH2a: "Prijavi se v ", headH2em: "4 minutah.",
    headDesc: "Ne želimo CV-jev, ki so jih napisali drugi. Štirje koraki, kontakt, izkušnje, par konkretnih vprašanj in potrditev. Brez registracije, brez priponk.",
    s0Title: "Kako se slišimo?", s0Sub: "Osnovni kontaktni podatki. Vse polja označena z * so obvezna.",
    lName: "Ime in priimek", lEmail: "E-pošta", lPhone: "Telefon", lLinkedin: "LinkedIn", optional: "neobvezno",
    phName: "Janez Novak", phEmail: "janez@example.si", phPhone: "+386 41 234 567", phLinkedin: "linkedin.com/in/...",
    honeypot: "Spletna stran (ne izpolnjuj)",
    s1Title: "Kaj že znaš?", s1Sub: "Označi vse, kar si že delal v praksi (ne samo brali o tem). Najmanj eno.",
    lYrs: "Leta izkušenj", lEdu: "Stopnja izobrazbe",
    s2Title: "Povej nam kaj konkretnega.", s2Sub: "Brez splošnih fraz. Dva odgovora, vsaj 80 znakov vsak. Tako vemo, da odgovarja človek.",
    q1: "Zakaj te zanima ta služba?", q1ph: "Kaj te v vzdrževanju hladilnih sistemov potegne? Kaj iščeš pri delodajalcu?",
    q2: "Opiši najbolj zahteven primer iz prakse, ki si ga rešil.", q2ph: "Kakšna okvara, kako si jo diagnosticiral, kako si jo rešil. Konkretno.",
    avail: "Razpoložljivost", availImm: "Takoj", avail1: "1 mesec", avail3: "3 mesece",
    reloc: "Selitev v Ljubljano (če potrebno)", relYes: "Da", relNo: "Ne", relNear: "Že tu / okolica",
    s3Title: "Potrditev", s3Sub: "Še zadnji korak: hitro varnostno vprašanje (ker ne maramo botov) in soglasje.",
    chHead: "Varnostno vprašanje", chSub: "brez captcha, brez piškotkov", chPh: "Tvoj odgovor",
    chHint: "Odgovor se obdela samo na tej strani. Nič ne pošljemo dalje.",
    consent: "Soglašam z obdelavo osebnih podatkov v okviru tega zaposlitvenega postopka.",
    consentD: "Podatki se hranijo do 6 mesecev po zaključku postopka. Pravica do izbrisa kadarkoli.",
    sumTitle: "Povzetek prijave", sumYrs: "let izkušenj", sumEdu: "stopnja izobrazbe", sumSkills: "izbranih spretnosti",
    sumApply: "Prijava na:", sumRole: "Specialist za hladilne sisteme",
    back: "← Nazaj", next: "Naprej", submit: "Oddaj prijavo", sending: "Pošiljanje…", progress: "NAPREDEK",
    errStep1: "Izpolnite ime, e-pošto in telefon.",
    errStep2: "Izberite vsaj eno spretnost in izpolnite izobrazbo + leta izkušenj.",
    errStep3: "Oba odgovora morata imeti vsaj 80 znakov, povej nam kaj konkretnega.",
    errHoney: "Zaznana je bila avtomatizirana prijava. Če ste človek, prosim osvežite stran.",
    errFast: "Zdi se, kot da ste obrazec izpolnili prehitro. Vzemite si trenutek in poskusite znova.",
    errFew: "Zaznali smo premalo interakcij. Prosim, izpolnite obrazec ročno.",
    errChallenge: "Odgovor na varnostno vprašanje ni pravilen. Poskusite znova.",
    errConsent: "Za oddajo vloge je potrebno soglasje za obdelavo podatkov.",
    errUnavail: "Oddaja trenutno ni na voljo. Poskusite kasneje.",
    errSubmit: "Napaka pri oddaji vloge. Poskusite znova.",
    okIdx: "Prejeli smo prijavo", okThanks: "Hvala, ", okThanksEnd: ".",
    okLead: "Tvoja prijava je v predalčniku Mojce iz kadrovske. Odzvali se bomo v 5 delovnih dneh.",
    okH3: "Vloga uspešno oddana",
    okBody: "Pregledamo jo ročno, ne strojno. Če bo tvoj profil ustrezal, te bomo povabili na prvi razgovor v Ljubljani na Cesti na Brdo.",
    okRef: "REF · ", submitMsg: "Prijava na razpis ",
  },
  EN: {
    roleOpen: "Open position", roleExpect: "We expect", roleOffer: "We offer",
    roleStatus: "Applications open", roleDeadline: "apply by 30.04.2026", roleApply: "Apply for this role",
    whyIdx: "Why Advant",
    fbIdx: "The classic way", fbH3: "Prefer post or email? We understand.",
    steps: ["Contact", "Experience", "About you", "Confirm"],
    skills: [
      ["cooling", "Cooling system maintenance", "CRAC / CRAH / chiller"],
      ["dc", "Work in data centers", "Tier I–IV environments"],
      ["bms", "Building Management Systems", "Schneider, Honeywell, etc."],
      ["ups", "UPS / power systems", "APC, Eaton, Riello"],
      ["hvac", "HVAC installations", "Refrigerants, category I/II"],
      ["fire", "Fire suppression systems", "Novec 1230, Inergen"],
      ["cabling", "Computer networks", "Cat 6A, fiber, certifications"],
      ["en1047", "Standards (EN1047, F90/120)", "Secure rooms, fire safety"],
    ],
    recap: [
      { q: "Which city is in the address of Advant's head office? (hint: the address is in the footer below)", a: ["ljubljana", "lj"] },
      { q: "What are we looking for in the job title? Specialist for the maintenance and commissioning of cooling ___ ?", a: ["systems", "system"] },
      { q: "Enter the job reference code shown above in the hero section (format ADV-YYYY-NN):", a: [ROLE.id.toLowerCase()] },
    ],
    headIdx: "Application", headH2a: "Apply in ", headH2em: "4 minutes.",
    headDesc: "We don't want CVs written by someone else. Four steps: contact, experience, a few concrete questions and confirmation. No registration, no attachments.",
    s0Title: "How do we reach you?", s0Sub: "Basic contact details. All fields marked with * are required.",
    lName: "Full name", lEmail: "Email", lPhone: "Phone", lLinkedin: "LinkedIn", optional: "optional",
    phName: "John Smith", phEmail: "john@example.com", phPhone: "+386 41 234 567", phLinkedin: "linkedin.com/in/...",
    honeypot: "Website (do not fill in)",
    s1Title: "What can you already do?", s1Sub: "Check everything you've actually done in practice (not just read about). At least one.",
    lYrs: "Years of experience", lEdu: "Level of education",
    s2Title: "Tell us something concrete.", s2Sub: "No generic phrases. Two answers, at least 80 characters each. That's how we know a human is answering.",
    q1: "Why does this job interest you?", q1ph: "What draws you to maintaining cooling systems? What are you looking for in an employer?",
    q2: "Describe the most demanding real-world case you've solved.", q2ph: "What failure, how you diagnosed it, how you fixed it. Be specific.",
    avail: "Availability", availImm: "Immediately", avail1: "1 month", avail3: "3 months",
    reloc: "Relocation to Ljubljana (if needed)", relYes: "Yes", relNo: "No", relNear: "Already here / nearby",
    s3Title: "Confirmation", s3Sub: "One last step: a quick security question (because we don't like bots) and consent.",
    chHead: "Security question", chSub: "no captcha, no cookies", chPh: "Your answer",
    chHint: "The answer is processed only on this page. We don't send anything on.",
    consent: "I agree to the processing of my personal data as part of this recruitment process.",
    consentD: "Data is kept for up to 6 months after the process ends. Right to erasure at any time.",
    sumTitle: "Application summary", sumYrs: "years of experience", sumEdu: "level of education", sumSkills: "skills selected",
    sumApply: "Applying for:", sumRole: "Cooling systems specialist",
    back: "← Back", next: "Next", submit: "Submit application", sending: "Sending…", progress: "PROGRESS",
    errStep1: "Please fill in your name, email and phone.",
    errStep2: "Select at least one skill and fill in education + years of experience.",
    errStep3: "Both answers must be at least 80 characters, tell us something concrete.",
    errHoney: "An automated submission was detected. If you are human, please refresh the page.",
    errFast: "It looks like you filled in the form too quickly. Take a moment and try again.",
    errFew: "We detected too few interactions. Please fill in the form manually.",
    errChallenge: "The answer to the security question is not correct. Please try again.",
    errConsent: "Consent to data processing is required to submit the application.",
    errUnavail: "Submission is currently unavailable. Please try later.",
    errSubmit: "Error submitting the application. Please try again.",
    okIdx: "We received your application", okThanks: "Thank you, ", okThanksEnd: ".",
    okLead: "Your application is in the inbox of Mojca from HR. We'll get back to you within 5 business days.",
    okH3: "Application submitted successfully",
    okBody: "We review it manually, not by machine. If your profile fits, we'll invite you to a first interview in Ljubljana at Cesta na Brdo.",
    okRef: "REF · ", submitMsg: "Application for role ",
  },
  DE: {
    roleOpen: "Offene Stelle", roleExpect: "Wir erwarten", roleOffer: "Wir bieten",
    roleStatus: "Bewerbungen offen", roleDeadline: "Bewerbung bis 30.04.2026", roleApply: "Jetzt bewerben",
    whyIdx: "Warum Advant",
    fbIdx: "Der klassische Weg", fbH3: "Lieber per Post oder E-Mail? Verstehen wir.",
    steps: ["Kontakt", "Erfahrung", "Über Sie", "Bestätigung"],
    skills: [
      ["cooling", "Wartung von Kühlsystemen", "CRAC / CRAH / Chiller"],
      ["dc", "Arbeit in Rechenzentren", "Tier-I–IV-Umgebungen"],
      ["bms", "Building Management Systems", "Schneider, Honeywell usw."],
      ["ups", "USV / Stromversorgungssysteme", "APC, Eaton, Riello"],
      ["hvac", "HLK-Installationen", "Kältemittel, Kategorie I/II"],
      ["fire", "Löschsysteme", "Novec 1230, Inergen"],
      ["cabling", "Computernetzwerke", "Cat 6A, Glasfaser, Zertifikate"],
      ["en1047", "Normen (EN1047, F90/120)", "Sicherheitsräume, Brandschutz"],
    ],
    recap: [
      { q: "Welche Stadt steht in der Adresse des Hauptsitzes von Advant? (Hinweis: die Adresse steht unten im Footer)", a: ["ljubljana", "lj"] },
      { q: "Wonach suchen wir im Stellentitel? Spezialist für Wartung und Inbetriebnahme von Kühl___ ?", a: ["systemen", "systeme", "system"] },
      { q: "Geben Sie den oben im Hero-Bereich angezeigten Ausschreibungscode ein (Format ADV-YYYY-NN):", a: [ROLE.id.toLowerCase()] },
    ],
    headIdx: "Bewerbung", headH2a: "Bewerben Sie sich in ", headH2em: "4 Minuten.",
    headDesc: "Wir wollen keine von anderen geschriebenen Lebensläufe. Vier Schritte: Kontakt, Erfahrung, ein paar konkrete Fragen und Bestätigung. Keine Registrierung, keine Anhänge.",
    s0Title: "Wie erreichen wir Sie?", s0Sub: "Grundlegende Kontaktdaten. Alle mit * markierten Felder sind erforderlich.",
    lName: "Vor- und Nachname", lEmail: "E-Mail", lPhone: "Telefon", lLinkedin: "LinkedIn", optional: "optional",
    phName: "Max Mustermann", phEmail: "max@example.com", phPhone: "+386 41 234 567", phLinkedin: "linkedin.com/in/...",
    honeypot: "Website (nicht ausfüllen)",
    s1Title: "Was können Sie bereits?", s1Sub: "Markieren Sie alles, was Sie in der Praxis gemacht haben (nicht nur darüber gelesen). Mindestens eines.",
    lYrs: "Jahre Erfahrung", lEdu: "Bildungsniveau",
    s2Title: "Erzählen Sie uns etwas Konkretes.", s2Sub: "Keine allgemeinen Floskeln. Zwei Antworten, jeweils mindestens 80 Zeichen. So wissen wir, dass ein Mensch antwortet.",
    q1: "Warum interessiert Sie diese Stelle?", q1ph: "Was reizt Sie an der Wartung von Kühlsystemen? Was suchen Sie bei einem Arbeitgeber?",
    q2: "Beschreiben Sie den anspruchsvollsten Praxisfall, den Sie gelöst haben.", q2ph: "Welcher Ausfall, wie Sie ihn diagnostiziert und behoben haben. Konkret.",
    avail: "Verfügbarkeit", availImm: "Sofort", avail1: "1 Monat", avail3: "3 Monate",
    reloc: "Umzug nach Ljubljana (falls nötig)", relYes: "Ja", relNo: "Nein", relNear: "Schon hier / in der Nähe",
    s3Title: "Bestätigung", s3Sub: "Ein letzter Schritt: eine kurze Sicherheitsfrage (weil wir keine Bots mögen) und Einwilligung.",
    chHead: "Sicherheitsfrage", chSub: "kein Captcha, keine Cookies", chPh: "Ihre Antwort",
    chHint: "Die Antwort wird nur auf dieser Seite verarbeitet. Wir senden nichts weiter.",
    consent: "Ich stimme der Verarbeitung meiner personenbezogenen Daten im Rahmen dieses Bewerbungsverfahrens zu.",
    consentD: "Die Daten werden bis zu 6 Monate nach Abschluss des Verfahrens aufbewahrt. Recht auf Löschung jederzeit.",
    sumTitle: "Zusammenfassung der Bewerbung", sumYrs: "Jahre Erfahrung", sumEdu: "Bildungsniveau", sumSkills: "ausgewählte Fähigkeiten",
    sumApply: "Bewerbung für:", sumRole: "Spezialist für Kühlsysteme",
    back: "← Zurück", next: "Weiter", submit: "Bewerbung absenden", sending: "Senden…", progress: "FORTSCHRITT",
    errStep1: "Bitte geben Sie Name, E-Mail und Telefon an.",
    errStep2: "Wählen Sie mindestens eine Fähigkeit und füllen Sie Ausbildung + Jahre Erfahrung aus.",
    errStep3: "Beide Antworten müssen mindestens 80 Zeichen haben, erzählen Sie uns etwas Konkretes.",
    errHoney: "Eine automatisierte Übermittlung wurde erkannt. Wenn Sie ein Mensch sind, aktualisieren Sie bitte die Seite.",
    errFast: "Es sieht so aus, als hätten Sie das Formular zu schnell ausgefüllt. Nehmen Sie sich einen Moment und versuchen Sie es erneut.",
    errFew: "Wir haben zu wenige Interaktionen erkannt. Bitte füllen Sie das Formular manuell aus.",
    errChallenge: "Die Antwort auf die Sicherheitsfrage ist nicht korrekt. Bitte versuchen Sie es erneut.",
    errConsent: "Für die Einreichung der Bewerbung ist die Einwilligung zur Datenverarbeitung erforderlich.",
    errUnavail: "Die Einreichung ist derzeit nicht verfügbar. Bitte versuchen Sie es später.",
    errSubmit: "Fehler beim Absenden der Bewerbung. Bitte versuchen Sie es erneut.",
    okIdx: "Wir haben Ihre Bewerbung erhalten", okThanks: "Danke, ", okThanksEnd: ".",
    okLead: "Ihre Bewerbung liegt im Postfach von Mojca aus der Personalabteilung. Wir melden uns innerhalb von 5 Werktagen.",
    okH3: "Bewerbung erfolgreich abgesendet",
    okBody: "Wir prüfen sie manuell, nicht maschinell. Wenn Ihr Profil passt, laden wir Sie zu einem ersten Gespräch in Ljubljana an der Cesta na Brdo ein.",
    okRef: "REF · ", submitMsg: "Bewerbung für die Stelle ",
  },
};

/* ============ HERO + ROLE ============ */

function KHero({ heroImg, label, sublabel, h1, lede, ctaText }) {
  return (
    <section className="k-hero">
      <div className="k-hero__bg" style={{ backgroundImage: `url("${heroImg || '/images/data-center.jpeg'}")` }} />
      <div className="k-hero__scrim" />
      <div className="container">
        <div className="k-hero__simple">
          <div className="sec-head__index"><span className="num">{label || "KARIERA"}</span><span>{sublabel || "Advant · Ljubljana · 2026"}</span></div>
          <h1 dangerouslySetInnerHTML={{ __html: h1 || "Sistemi z <em>99.99&nbsp;%</em><br/>uptimea <em>ne pišejo</em><br/>sami sebe." }} />
          <p className="k-hero__lede">
            {lede || "Iščemo inženirja, ki razume razliko med N+1 in 2N in noč pred uvedbo v produkcijo raje preveri še enkrat."}
          </p>
          <a href="#role" className="btn btn--primary k-hero__cta">
            {ctaText || "Poglej odprto mesto"}
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
              <path d="M12 5v14M5 12l7 7 7-7"/>
            </svg>
          </a>
        </div>
      </div>
    </section>
  );
}

function RoleCard({ role }) {
  const lang = React.useContext(LangContext);
  const kt = KT[lang] || KT.SI;
  const r = role || ROLE;
  return (
    <section className="role" id="role">
      <div className="container">
        <div className="role__head">
          <div className="role__title">
            <div className="sec-head__index"><span className="num">01</span><span>{kt.roleOpen}</span></div>
            <h2 style={{ marginTop: 16 }}>{r.title}</h2>
          </div>
          <div className="role__meta">
            <span className="role__chip"><span className="dot"></span>{r.team}</span>
            <span className="role__chip">{r.loc}</span>
            <span className="role__chip">{r.type}</span>
          </div>
        </div>

        <div className="role__body">
          <div className="role__col">
            <h3>{kt.roleExpect} <span className="num">/ {String(r.expect.length).padStart(2,"0")}</span></h3>
            <ul className="role__list">
              {r.expect.map((t, i) => (
                <li key={i}>
                  <span className="mark">{String(i+1).padStart(2,"0")}</span>
                  <span>{t}</span>
                </li>
              ))}
            </ul>
          </div>
          <div className="role__col role__col--offer">
            <h3>{kt.roleOffer} <span className="num">/ {String(r.offer.length).padStart(2,"0")}</span></h3>
            <ul className="role__list">
              {r.offer.map((t, i) => (
                <li key={i}>
                  <span className="mark">+</span>
                  <span>{t}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>

        <div className="role__cta">
          <div className="role__cta-meta">
            <span className="mono">[ status ]</span>
            <strong>{kt.roleStatus}</strong>
            <span>{kt.roleDeadline}</span>
          </div>
          <a href="#apply" className="btn btn--primary role__cta-btn">
            {kt.roleApply}
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
              <path d="M5 12h14M13 5l7 7-7 7"/>
            </svg>
          </a>
        </div>
      </div>
    </section>
  );
}

function Why({ whyItems, h2, desc }) {
  const lang = React.useContext(LangContext);
  const kt = KT[lang] || KT.SI;
  const items = (whyItems && whyItems.length) ? whyItems : WHY;
  return (
    <section className="why">
      <div className="container">
        <div className="why__head">
          <div>
            <div className="sec-head__index"><span className="num">02</span><span>{kt.whyIdx}</span></div>
            <h2 style={{ marginTop: 16 }}>{h2 || "Inženirska kultura, ne korporativna."}</h2>
          </div>
          <p>
            {desc || "Smo manjše podjetje z velikimi projekti. Hierarhija je plitka, odločitve se sprejemajo na terenu, vsak član ekipe vidi svoje delo do konca, od koncepta do desetega leta vzdrževanja."}
          </p>
        </div>
        <div className="why__grid">
          {items.map(([n, t, d]) => (
            <div className="why__cell" key={n}>
              <span className="num">{n}</span>
              <div className="t">{t}</div>
              <p className="d">{d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============ APPLY FORM ============
   Steps, skills and the security questions are per-language in KT above. */

function ApplyForm() {
  const lang = React.useContext(LangContext);
  const kt = KT[lang] || KT.SI;
  const [step, setStep] = useStateK(0);
  const [data, setData] = useStateK({
    name: "",
    email: "",
    phone: "",
    linkedin: "",
    edu: "",
    yrs: "",
    skills: {},
    motivation: "",
    case: "",
    available: "immediately",
    relocation: "",
    honeypot: "",     // bot trap (hidden)
    challenge: "",    // human-readable challenge answer
    consent: false,
  });
  const [error, setError] = useStateK("");
  const [submitted, setSubmitted] = useStateK(false);
  const [appId, setAppId] = useStateK("");
  const [sending, setSending] = useStateK(false);

  // bot defenses
  const mountedAt = useRefK(Date.now());
  const interactions = useRefK(0);
  const recapIdx = useRefK(Math.floor(Math.random() * kt.recap.length));
  const recap = kt.recap[recapIdx.current];

  const set = (k, v) => {
    interactions.current += 1;
    setData(d => ({ ...d, [k]: v }));
  };
  const toggleSkill = (k) => {
    interactions.current += 1;
    setData(d => ({ ...d, skills: { ...d.skills, [k]: !d.skills[k] } }));
  };

  const motivationLen = data.motivation.length;
  const caseLen = data.case.length;

  const canStep1 =
    data.name.trim().length >= 2 &&
    /\S+@\S+\.\S+/.test(data.email) &&
    data.phone.trim().length >= 6;

  const skillsCount = Object.values(data.skills).filter(Boolean).length;
  const canStep2 = skillsCount >= 1 && data.yrs && data.edu;

  const canStep3 = motivationLen >= 80 && caseLen >= 80;

  const canSubmit = data.consent && data.challenge.trim().length > 0;

  const progress = useMemoK(() => {
    let p = 0;
    if (canStep1) p += 25;
    if (canStep2) p += 25;
    if (canStep3) p += 25;
    if (canSubmit) p += 25;
    return p;
  }, [canStep1, canStep2, canStep3, canSubmit]);

  const next = () => {
    setError("");
    if (step === 0 && !canStep1) { setError(kt.errStep1); return; }
    if (step === 1 && !canStep2) { setError(kt.errStep2); return; }
    if (step === 2 && !canStep3) { setError(kt.errStep3); return; }
    setStep(s => Math.min(s + 1, kt.steps.length - 1));
  };
  const back = () => { setError(""); setStep(s => Math.max(0, s - 1)); };

  const submit = (e) => {
    e.preventDefault();
    setError("");

    // Bot defense 1, honeypot must be empty
    if (data.honeypot.trim() !== "") {
      setError(kt.errHoney);
      return;
    }
    // Bot defense 2, minimum dwell time
    const elapsed = (Date.now() - mountedAt.current) / 1000;
    if (elapsed < 8) {
      setError(kt.errFast);
      return;
    }
    // Bot defense 3, interaction count
    if (interactions.current < 8) {
      setError(kt.errFew);
      return;
    }
    // Bot defense 4, human challenge
    const ans = data.challenge.trim().toLowerCase();
    if (!recap.a.some(a => ans.includes(a))) {
      setError(kt.errChallenge);
      return;
    }
    // Required: consent
    if (!data.consent) { setError(kt.errConsent); return; }

    if (sending) return;
    setSending(true);

    // Reference id
    const ref = "APP-" + new Date().toISOString().slice(2,10).replace(/-/g,"") + "-" +
                Math.random().toString(36).slice(2,6).toUpperCase();

    // Selected skill labels (human-readable) for the notification email
    const skillLabels = kt.skills.filter(([k]) => data.skills[k]).map(([, label]) => label);

    const submitFn = (window.AdvantWP && window.AdvantWP.wpSubmit)
      ? window.AdvantWP.wpSubmit("contact", {
          form: "career",
          role: ROLE.id + " — " + ROLE.title,
          name: data.name, email: data.email, phone: data.phone,
          linkedin: data.linkedin, edu: data.edu, yrs: data.yrs,
          skills: skillLabels, available: data.available, relocation: data.relocation,
          motivation: data.motivation, case: data.case,
          message: kt.submitMsg + ROLE.id + " (ref " + ref + ")",
          website: data.honeypot, t: mountedAt.current, lang: lang,
          source: typeof location !== "undefined" ? location.pathname : ""
        })
      : Promise.reject(new Error(kt.errUnavail));

    submitFn
      .then(() => { setSending(false); setAppId(ref); setSubmitted(true); })
      .catch((err) => { setSending(false); setError(err.message || kt.errSubmit); });
  };

  if (submitted) {
    return (
      <section className="apply">
        <div className="container">
          <div className="apply__head">
            <div>
              <div className="sec-head__index"><span className="num">03</span><span>{kt.okIdx}</span></div>
              <h2 style={{ marginTop: 16 }}>{kt.okThanks}{data.name.split(" ")[0] || ""}{kt.okThanksEnd}</h2>
            </div>
            <p>{kt.okLead}</p>
          </div>
          <div className="apply__success">
            <div className="apply__success-mark" aria-hidden="true"></div>
            <h3>{kt.okH3}</h3>
            <p>{kt.okBody}</p>
            <div className="apply__success-id">{kt.okRef}{appId}</div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="apply" id="apply">
      <div className="container">
        <div className="apply__head">
          <div>
            <div className="sec-head__index"><span className="num">03</span><span>{kt.headIdx}</span></div>
            <h2 style={{ marginTop: 16 }}>{kt.headH2a}<em>{kt.headH2em}</em></h2>
          </div>
          <p>{kt.headDesc}</p>
        </div>

        <form className="apply__form" onSubmit={submit} autoComplete="on" noValidate>
          {/* RAIL */}
          <aside className="apply__rail">
            {kt.steps.map((title, i) => (
              <div
                key={i}
                className={"apply__rail-step " +
                  (i === step ? "is-active " : "") +
                  (i < step ? "is-done " : "")}
              >
                <span className="n">{i < step ? "✓" : String(i + 1).padStart(2, "0")}</span>
                <span className="lbl">{title}</span>
              </div>
            ))}
          </aside>

          {/* PANEL */}
          <div className="apply__panel">
            {step === 0 && (
              <>
                <div className="apply__step-title">
                  <span className="num">/ 01</span>
                  <h3>{kt.s0Title}</h3>
                </div>
                <p className="apply__step-sub">{kt.s0Sub}</p>

                <div className="fld--row">
                  <div className="fld">
                    <label className="fld__label">{kt.lName} <span className="req">*</span></label>
                    <input type="text" autoComplete="name"
                      placeholder={kt.phName}
                      value={data.name}
                      onChange={e => set("name", e.target.value)} />
                  </div>
                  <div className="fld">
                    <label className="fld__label">{kt.lEmail} <span className="req">*</span></label>
                    <input type="email" autoComplete="email"
                      placeholder={kt.phEmail}
                      value={data.email}
                      onChange={e => set("email", e.target.value)} />
                  </div>
                </div>
                <div className="fld--row">
                  <div className="fld">
                    <label className="fld__label">{kt.lPhone} <span className="req">*</span></label>
                    <input type="tel" autoComplete="tel"
                      placeholder={kt.phPhone}
                      value={data.phone}
                      onChange={e => set("phone", e.target.value)} />
                  </div>
                  <div className="fld">
                    <label className="fld__label">{kt.lLinkedin} <span className="hint">{kt.optional}</span></label>
                    <input type="url" autoComplete="url"
                      placeholder={kt.phLinkedin}
                      value={data.linkedin}
                      onChange={e => set("linkedin", e.target.value)} />
                  </div>
                </div>

                {/* honeypot, invisible to humans */}
                <div className="fld fld--honeypot" aria-hidden="true">
                  <label>{kt.honeypot}</label>
                  <input type="text" tabIndex={-1} autoComplete="off"
                    value={data.honeypot}
                    onChange={e => setData(d => ({...d, honeypot: e.target.value}))} />
                </div>
              </>
            )}

            {step === 1 && (
              <>
                <div className="apply__step-title">
                  <span className="num">/ 02</span>
                  <h3>{kt.s1Title}</h3>
                </div>
                <p className="apply__step-sub">{kt.s1Sub}</p>

                <div className="chk-grid">
                  {kt.skills.map(([k, t, d]) => (
                    <label className="chk" key={k}>
                      <input type="checkbox" checked={!!data.skills[k]} onChange={() => toggleSkill(k)} />
                      <span className="chk__box"></span>
                      <span className="chk__text">
                        <span className="t">{t}</span>
                        <span className="d">{d}</span>
                      </span>
                    </label>
                  ))}
                </div>

                <div className="fld--row">
                  <div className="fld">
                    <label className="fld__label">{kt.lYrs} <span className="req">*</span></label>
                    <div className="radio-row">
                      {["0–1", "1–3", "3–5", "5–10", "10+"].map(v => (
                        <label key={v}>
                          <input type="radio" name="yrs" checked={data.yrs === v} onChange={() => set("yrs", v)} />
                          <span>{v}</span>
                        </label>
                      ))}
                    </div>
                  </div>
                  <div className="fld">
                    <label className="fld__label">{kt.lEdu} <span className="req">*</span></label>
                    <div className="radio-row">
                      {["IV.", "V.", "VI.", "VII.", "VIII.+"].map(v => (
                        <label key={v}>
                          <input type="radio" name="edu" checked={data.edu === v} onChange={() => set("edu", v)} />
                          <span>{v}</span>
                        </label>
                      ))}
                    </div>
                  </div>
                </div>
              </>
            )}

            {step === 2 && (
              <>
                <div className="apply__step-title">
                  <span className="num">/ 03</span>
                  <h3>{kt.s2Title}</h3>
                </div>
                <p className="apply__step-sub">{kt.s2Sub}</p>

                <div className="fld">
                  <label className="fld__label">
                    {kt.q1} <span className="req">*</span>
                    <span className={"fld__counter " + (motivationLen >= 80 ? "is-ready" : "")}>{motivationLen} / 80</span>
                  </label>
                  <textarea
                    placeholder={kt.q1ph}
                    value={data.motivation}
                    onChange={e => set("motivation", e.target.value)} />
                </div>

                <div className="fld">
                  <label className="fld__label">
                    {kt.q2} <span className="req">*</span>
                    <span className={"fld__counter " + (caseLen >= 80 ? "is-ready" : "")}>{caseLen} / 80</span>
                  </label>
                  <textarea
                    placeholder={kt.q2ph}
                    value={data.case}
                    onChange={e => set("case", e.target.value)} />
                </div>

                <div className="fld--row">
                  <div className="fld">
                    <label className="fld__label">{kt.avail}</label>
                    <div className="radio-row">
                      {[
                        ["immediately", kt.availImm],
                        ["1m", kt.avail1],
                        ["3m", kt.avail3],
                      ].map(([v, l]) => (
                        <label key={v}>
                          <input type="radio" name="available" checked={data.available === v} onChange={() => set("available", v)} />
                          <span>{l}</span>
                        </label>
                      ))}
                    </div>
                  </div>
                  <div className="fld">
                    <label className="fld__label">{kt.reloc}</label>
                    <div className="radio-row">
                      {[
                        ["yes", kt.relYes],
                        ["no", kt.relNo],
                        ["nearby", kt.relNear],
                      ].map(([v, l]) => (
                        <label key={v}>
                          <input type="radio" name="reloc" checked={data.relocation === v} onChange={() => set("relocation", v)} />
                          <span>{l}</span>
                        </label>
                      ))}
                    </div>
                  </div>
                </div>
              </>
            )}

            {step === 3 && (
              <>
                <div className="apply__step-title">
                  <span className="num">/ 04</span>
                  <h3>{kt.s3Title}</h3>
                </div>
                <p className="apply__step-sub">{kt.s3Sub}</p>

                <div className="challenge">
                  <div className="challenge__head">
                    <span className="mark">{kt.chHead}</span>
                    <span>{kt.chSub}</span>
                  </div>
                  <div className="challenge__q">{recap.q}</div>
                  <input type="text" autoComplete="off"
                    style={{
                      background: "transparent", border: "none",
                      borderBottom: "1px solid var(--line-2)",
                      padding: "10px 0", color: "var(--ink)",
                      fontFamily: "inherit", fontSize: 16, outline: "none", width: "100%",
                    }}
                    placeholder={kt.chPh}
                    value={data.challenge}
                    onChange={e => set("challenge", e.target.value)} />
                  <div className="challenge__hint">{kt.chHint}</div>
                </div>

                <label className="chk" style={{ marginTop: 24, padding: 0, background: "transparent" }}>
                  <input type="checkbox" checked={data.consent} onChange={e => set("consent", e.target.checked)} />
                  <span className="chk__box"></span>
                  <span className="chk__text">
                    <span className="t">{kt.consent}</span>
                    <span className="d">{kt.consentD}</span>
                  </span>
                </label>

                <div style={{ marginTop: 24, padding: "16px 20px", border: "1px solid var(--line)", background: "var(--bg-1)" }}>
                  <div style={{ fontFamily: "DM Mono, monospace", fontSize: 11, color: "var(--ink-3)", letterSpacing: ".06em", textTransform: "uppercase", marginBottom: 8 }}>
                    {kt.sumTitle}
                  </div>
                  <div style={{ fontSize: 14, color: "var(--ink-2)", lineHeight: 1.6 }}>
                    <strong style={{ color: "var(--ink)" }}>{data.name}</strong> · {data.email} · {data.phone}<br/>
                    {data.yrs} {kt.sumYrs} · {data.edu} {kt.sumEdu} · {skillsCount} {kt.sumSkills}<br/>
                    {kt.sumApply} <strong style={{ color: "var(--ink)" }}>{ROLE.id}</strong>, {kt.sumRole}
                  </div>
                </div>
              </>
            )}

            {error && <div className="apply__error">{error}</div>}

            <div className="apply__nav">
              <div className="gauge">
                <span>{kt.progress}</span>
                <div className="bar"><i style={{ width: progress + "%" }}></i></div>
                <span>{progress}%</span>
              </div>
              <div className="apply__btns">
                {step > 0 && (
                  <button type="button" className="apply__btn" onClick={back}>{kt.back}</button>
                )}
                {step < kt.steps.length - 1 ? (
                  <button type="button" className="apply__btn apply__btn--primary" onClick={next}>
                    {kt.next} <Arrow size={12} className="arrow" />
                  </button>
                ) : (
                  <button
                    type="submit"
                    className="apply__btn apply__btn--primary"
                    disabled={!canSubmit || sending}
                  >
                    {sending ? kt.sending : kt.submit} <Arrow size={12} className="arrow" />
                  </button>
                )}
              </div>
            </div>
          </div>
        </form>
      </div>
    </section>
  );
}

function Fallback() {
  const lang = React.useContext(LangContext);
  const kt = KT[lang] || KT.SI;
  return (
    <section className="k-fallback">
      <div className="container">
        <div className="k-fallback__inner">
          <div>
            <div className="sec-head__index"><span className="num">04</span><span>{kt.fbIdx}</span></div>
            <h3 style={{ marginTop: 12 }}>{kt.fbH3}</h3>
          </div>
          <div className="k-fallback__contacts">
            <div>Advant d.o.o.</div>
            <div>Cesta na Brdo 119A · 1000 Ljubljana</div>
            <div><a href="mailto:info@advant.si">info@advant.si</a></div>
            <div><a href="tel:+38614700000">+386 1 470 00 00</a></div>
          </div>
        </div>
      </div>
    </section>
  );
}

function CareersApp() {
  const [role, setRole] = React.useState(null);
  const [whyItems, setWhyItems] = React.useState(null);
  const [heroData, setHeroData] = React.useState(null);
  const [whyTexts, setWhyTexts] = React.useState(null);

  /* Fallback: hide preloader after 3 s even if WP never responds */
  React.useEffect(() => {
    const t = setTimeout(() => window.AdvantWP && window.AdvantWP.hidePreloader(), 3000);
    return () => clearTimeout(t);
  }, []);

  React.useEffect(() => {
    const { wpOptions, wpPosts, gs, rep, repF, decode } = window.AdvantWP || {};
    if (!wpOptions) { window.AdvantWP && window.AdvantWP.hidePreloader(); return; }

    /* Apply global contact/nav to T */
    wpOptions('global').then(g => {
      const set = (obj, key, val) => { if (val) obj[key] = decode(val); };
      ['SI','EN','DE'].forEach(LANG => {
        const l = LANG.toLowerCase();
        const tl = T[LANG];
        set(tl.contact.meta, 'emailVal',   gs(g, `g_contact_email_${l}`));
        set(tl.contact.meta, 'phoneVal',   gs(g, `g_contact_phone_${l}`));
        set(tl.contact.meta, 'addressVal', gs(g, `g_contact_address_${l}`));
        set(tl.contact.meta, 'mapsUrl',    gs(g, `g_contact_maps_${l}`));
        set(tl.footer, 'emailVal', gs(g, `g_contact_email_${l}`));
        set(tl.footer, 'phoneVal', gs(g, `g_contact_phone_${l}`));
      });
    }).catch(() => {});

    Promise.all([
      wpOptions('kariera-page'),
      wpPosts('kariera', { per_page: 50, orderby: 'menu_order', order: 'asc' }),
    ])
      .then(([kp, posts]) => {
        const l = (document.body.dataset.lang || 'SI').toLowerCase();

        /* ── Hero ── */
        setHeroData({
          heroImg: gs(kp, `kp_hero_image_${l}`) || null,
          label:   gs(kp, `kp_hero_eyebrow_${l}`) || null,
          sublabel: gs(kp, `kp_hero_sublabel_${l}`) || null,
          h1:      gs(kp, `kp_hero_h1_${l}`) || null,
          lede:    gs(kp, `kp_hero_sub_${l}`) || null,
          ctaText: gs(kp, `kp_hero_cta_${l}`) || null,
        });

        /* ── Why Advant ── */
        setWhyTexts({
          h2:   gs(kp, `kp_why_h2_${l}`) || null,
          desc: gs(kp, `kp_why_desc_${l}`) || null,
        });
        const whyRows = [];
        for (let i = 1; i <= 4; i++) {
          const n = gs(kp, `kp_why${i}_icon_${l}`);
          const t = gs(kp, `kp_why${i}_title_${l}`);
          const d = gs(kp, `kp_why${i}_desc_${l}`);
          if (t) whyRows.push([n || String(i).padStart(2,'0'), t, d]);
        }
        if (whyRows.length) setWhyItems(whyRows);

        /* ── Map kariera CPT posts → ROLE shape ── */
        if (!posts || !posts.length) return;
        /* Respect the "Oglas aktiven" (job_active) toggle per language */
        const isActive = v => v === true || v === 1 || v === '1';
        const activeRoles = posts.filter(p => p.acf && isActive(p.acf[`job_active_${l}`]));
        if (!activeRoles.length) return;
        const p = activeRoles[0]; /* display first open role */
        const a = p.acf || {};
        setRole({
          id:        p.slug || decode(gs(a, 'role_id') || String(p.id)),
          title:     decode(gs(a, `job_job_title_${l}`) || (p.title && p.title.rendered) || ''),
          team:      decode(gs(a, `job_team_${l}`) || ''),
          loc:       decode(gs(a, `job_location_${l}`) || ''),
          type:      decode(gs(a, `job_type_${l}`) || ''),
          probation: decode(gs(a, `job_probation_${l}`) || ''),
          start:     decode(gs(a, `job_start_${l}`) || ''),
          expect:    repF(a, `job_${l}_expect`, 'item').map(decode).filter(Boolean),
          offer:     repF(a, `job_${l}_offer`,  'item').map(decode).filter(Boolean),
        });
        window.AdvantWP && window.AdvantWP.hidePreloader();
      })
      .catch(e => {
        console.warn('[AdvantWP] kariera load failed, using fallback.', e);
        window.AdvantWP && window.AdvantWP.hidePreloader();
      });
  }, []);

  return (
    <LangContext.Provider value={document.body.dataset.lang || "SI"}>
      <AmbientOrb />
      <Header />
      <KHero
        heroImg={heroData && heroData.heroImg}
        label={heroData && heroData.label}
        sublabel={heroData && heroData.sublabel}
        h1={heroData && heroData.h1}
        lede={heroData && heroData.lede}
        ctaText={heroData && heroData.ctaText}
      />
      <RoleCard role={role} />
      <Why whyItems={whyItems} h2={whyTexts && whyTexts.h2} desc={whyTexts && whyTexts.desc} />
      <ApplyForm />
      <Fallback />
      <Footer />
    </LangContext.Provider>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<CareersApp />);
