/* CA Automator — job application form, loaded only on a job posting's
   server-rendered detail page (see server/public_pages.py careers_detail_page).
   Deliberately separate from landing.js: this page carries none of the app
   shell or module JS, just this one small script. */
(function () {
  'use strict';
  const esc = s => String(s == null ? '' : s)
    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');

  function fileToBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(String(reader.result).split(',')[1] || '');
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  }

  document.addEventListener('DOMContentLoaded', () => {
    const root = document.getElementById('apply-root');
    if (!root) return;
    const slug = root.dataset.jobSlug;

    root.innerHTML =
      '<h2>Apply for this position</h2>' +
      '<form id="apply-form">' +
      '<label>Name<input id="ap-name" type="text" autocomplete="name" required></label>' +
      '<label>Email<input id="ap-email" type="email" autocomplete="email" required></label>' +
      '<label>Phone<input id="ap-phone" type="text" autocomplete="tel"></label>' +
      '<label>Address<input id="ap-address" type="text"></label>' +
      '<label>Education<input id="ap-education" type="text" placeholder="e.g. B.Com, Tribhuvan University"></label>' +
      '<label>Experience<input id="ap-experience" type="text" placeholder="e.g. 2 years articleship"></label>' +
      '<label>Portfolio / LinkedIn (optional)<input id="ap-portfolio" type="text"></label>' +
      '<label>Cover letter<textarea id="ap-cover" rows="4"></textarea></label>' +
      '<label>CV / resume (PDF or Word, up to 8MB)<input id="ap-cv" type="file" accept=".pdf,.doc,.docx"></label>' +
      '<label class="check"><input id="ap-consent" type="checkbox" required> I consent to this firm storing my application details for recruitment purposes.</label>' +
      '<button type="submit" class="btn btn-primary" id="ap-go">Submit application</button>' +
      '<p class="apply-msg" id="ap-msg"></p>' +
      '</form>';

    document.getElementById('apply-form').addEventListener('submit', async e => {
      e.preventDefault();
      const msgEl = document.getElementById('ap-msg');
      const goBtn = document.getElementById('ap-go');
      msgEl.textContent = '';
      const name = document.getElementById('ap-name').value.trim();
      const email = document.getElementById('ap-email').value.trim();
      const consent = document.getElementById('ap-consent').checked;
      if (!name || !email) { msgEl.textContent = 'Name and email are required.'; return; }
      if (!consent) { msgEl.textContent = 'Please confirm the consent checkbox to continue.'; return; }

      goBtn.disabled = true; goBtn.textContent = 'Submitting…';
      try {
        const body = {
          name, email, consent,
          phone: document.getElementById('ap-phone').value.trim(),
          address: document.getElementById('ap-address').value.trim(),
          education: document.getElementById('ap-education').value.trim(),
          experience: document.getElementById('ap-experience').value.trim(),
          portfolio_url: document.getElementById('ap-portfolio').value.trim(),
          cover_letter: document.getElementById('ap-cover').value.trim(),
        };
        const fileInput = document.getElementById('ap-cv');
        if (fileInput.files && fileInput.files[0]) {
          const file = fileInput.files[0];
          if (file.size > 8 * 1024 * 1024) throw new Error('The CV file is larger than 8MB.');
          body.cv_base64 = await fileToBase64(file);
          body.cv_filename = file.name;
        }
        const res = await fetch('/api/public/careers/' + encodeURIComponent(slug) + '/apply', {
          method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body)
        });
        const out = await res.json();
        if (!res.ok) throw new Error(out.error || 'Something went wrong — try again.');
        root.innerHTML = '<div class="apply-confirm"><b>Application received</b><br>' +
          'Thanks, ' + esc(name) + ' — we will be in touch as your application moves forward.</div>';
      } catch (err) {
        msgEl.textContent = err.message;
        goBtn.disabled = false; goBtn.textContent = 'Submit application';
      }
    });
  });
})();
