// api.jsx — Frontend API client
// Loaded sebelum app.jsx, tersedia global via window.API

window.API = (function () {
  const BASE = '';  // same origin — Express serve semua dari root
  const TOKEN_KEY = 'rabbani_token';
  const STATE_KEY  = 'rabbani_karier_state_v1';

  function getToken()      { return localStorage.getItem(TOKEN_KEY); }
  function setToken(t)     { localStorage.setItem(TOKEN_KEY, t); }
  function clearSession()  { localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(STATE_KEY); }

  function authHeaders(json = true) {
    const h = { Authorization: `Bearer ${getToken()}` };
    if (json) h['Content-Type'] = 'application/json';
    return h;
  }

  const ADMIN_TOKEN_KEY = 'rabbani_admin_token';
  function getAdminToken() { return localStorage.getItem(ADMIN_TOKEN_KEY); }
  function adminAuthHeaders(json = true) {
    const h = { Authorization: `Bearer ${getAdminToken()}` };
    if (json) h['Content-Type'] = 'application/json';
    return h;
  }

  async function post(path, body) {
    const r = await fetch(BASE + path, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    return r.json();
  }

  async function postAuth(path, body) {
    const r = await fetch(BASE + path, {
      method: 'POST',
      headers: authHeaders(),
      body: JSON.stringify(body),
    });
    return r.json();
  }

  async function putAuth(path, body) {
    const r = await fetch(BASE + path, {
      method: 'PUT',
      headers: authHeaders(),
      body: JSON.stringify(body),
    });
    return r.json();
  }

  return {
    getToken,
    setToken,
    clearSession,

    // ── Auth ────────────────────────────────────────────────────────────────
    register(name, wa, email, lang) {
      return post('/api/auth/register', { name, wa, email, lang });
    },
    sendOtp(email, channel) {
      return post('/api/auth/send-otp', { email, channel });
    },
    login(identifier, password) {
      return post('/api/auth/login', { identifier, password });
    },
    forgot(identifier) {
      return post('/api/auth/forgot', { identifier });
    },
    forgotOtp(identifier, channel) {
      return post('/api/auth/forgot-otp', { identifier, channel });
    },
    resetPassword(email, otp, newPassword) {
      return post('/api/auth/reset-password', { email, otp, newPassword });
    },
    setPassword(password) {
      return postAuth('/api/auth/set-password', { password });
    },
    verify(email, otp) {
      return post('/api/auth/verify', { email, otp });
    },
    resend(email) {
      return post('/api/auth/resend', { email });
    },

    // ── Application ─────────────────────────────────────────────────────────
    saveStep(step, data) {
      return postAuth('/api/application/save', { step, data });
    },
    getMyApplication() {
      return fetch(BASE + '/api/application/me', { headers: authHeaders() }).then(r => r.json());
    },
    getMyDocs() {
      return fetch(BASE + '/api/application/docs', { headers: authHeaders() }).then(r => r.json());
    },
    getMyStatus() {
      return fetch(BASE + '/api/application/status', { headers: authHeaders() }).then(r => r.json());
    },
    confirmInterview(confirm) {
      return postAuth('/api/application/interview-confirm', { confirm });
    },
    updateLocation(locations) {
      return putAuth('/api/application/location', { locations });
    },

    // ── Parse CV ────────────────────────────────────────────────────────────
    async parseCv(file) {
      const fd = new FormData();
      fd.append('file', file);
      const r = await fetch('/api/parse-cv', { method: 'POST', headers: authHeaders(false), body: fd });
      return r.json();
    },

    // ── Master data ─────────────────────────────────────────────────────────
    getPositions() {
      return fetch(BASE + '/api/positions').then(r => r.json());
    },
    getLocations() {
      return fetch(BASE + '/api/locations').then(r => r.json());
    },

    // Admin CRUD
    adminGetPositions()          { return fetch(BASE + '/api/admin/positions', { headers: adminAuthHeaders() }).then(r => r.json()); },
    adminAddPosition(data)       { return fetch(BASE + '/api/admin/positions', { method:'POST', headers: adminAuthHeaders(), body:JSON.stringify(data) }).then(r=>r.json()); },
    adminUpdatePosition(id,data) { return fetch(BASE + `/api/admin/positions/${id}`, { method:'PUT', headers: adminAuthHeaders(), body:JSON.stringify(data) }).then(r=>r.json()); },
    adminDeletePosition(id)      { return fetch(BASE + `/api/admin/positions/${id}`, { method:'DELETE', headers: adminAuthHeaders() }).then(r=>r.json()); },

    adminGetApplicants()         { return fetch(BASE + '/api/admin/applicants', { headers: adminAuthHeaders() }).then(r => r.json()); },
    adminGetDocs(applicantId)    { return fetch(BASE + `/api/admin/applicants/${applicantId}/docs`, { headers: adminAuthHeaders() }).then(r => r.json()); },
    adminSetStatus(id, status, extra = {}) { return fetch(BASE + `/api/admin/applicants/${id}/status`, { method:'PATCH', headers: adminAuthHeaders(), body:JSON.stringify({ status, ...extra }) }).then(r=>r.json()); },
    adminSaveRecommendation(id, recommendation) { return fetch(BASE + `/api/admin/applicants/${id}/recommendation`, { method:'PATCH', headers: adminAuthHeaders(), body:JSON.stringify({ recommendation }) }).then(r=>r.json()); },

    // Contract
    getContract()               { return fetch(BASE + '/api/application/contract', { headers: authHeaders() }).then(r => r.json()); },
    async signContract(file) {
      const fd = new FormData(); fd.append('file', file);
      const r = await fetch(BASE + '/api/application/sign-contract', { method:'POST', headers:{ Authorization:`Bearer ${getToken()}` }, body:fd });
      return r.json();
    },
    adminGetContract(id)        { return fetch(BASE + `/api/admin/applicants/${id}/contract`, { headers: adminAuthHeaders() }).then(r => r.json()); },
    adminGetContractTemplate()  { return fetch(BASE + '/api/admin/contract-template', { headers: adminAuthHeaders() }).then(r => r.json()); },
    adminSaveContractTemplate(content) { return fetch(BASE + '/api/admin/contract-template', { method:'PUT', headers: adminAuthHeaders(), body:JSON.stringify({ content }) }).then(r=>r.json()); },
    adminResetContractTemplate() { return fetch(BASE + '/api/admin/contract-template/reset', { method:'POST', headers: adminAuthHeaders() }).then(r=>r.json()); },


    adminGetLocations()          { return fetch(BASE + '/api/admin/locations', { headers: adminAuthHeaders() }).then(r => r.json()); },
    adminAddLocation(data)       { return fetch(BASE + '/api/admin/locations', { method:'POST', headers: adminAuthHeaders(), body:JSON.stringify(data) }).then(r=>r.json()); },
    adminUpdateLocation(id,data) { return fetch(BASE + `/api/admin/locations/${id}`, { method:'PUT', headers: adminAuthHeaders(), body:JSON.stringify(data) }).then(r=>r.json()); },
    adminDeleteLocation(id)      { return fetch(BASE + `/api/admin/locations/${id}`, { method:'DELETE', headers: adminAuthHeaders() }).then(r=>r.json()); },

    // ── Upload ──────────────────────────────────────────────────────────────
    async upload(file, type) {
      const fd = new FormData();
      fd.append('file', file);
      fd.append('type', type);
      const r = await fetch(BASE + '/api/upload', {
        method: 'POST',
        headers: { Authorization: `Bearer ${getToken()}` },
        body: fd,
      });
      return r.json();
    },
  };
})();
