// Bootstrapper — runs last. Verifies the session, loads data from the backend,
// then mounts the app. Redirects to the login page when unauthenticated.
(async () => {
  const root = document.getElementById("root");
  const setStatus = (html) => {
    root.innerHTML =
      `<div style="height:100vh;display:grid;place-items:center;font-family:Manrope,sans-serif;color:#475569;text-align:center;padding:24px">${html}</div>`;
  };

  setStatus(`
    <div>
      <div style="width:34px;height:34px;border:3px solid #e2e8f0;border-top-color:#3a6df0;border-radius:50%;margin:0 auto 14px;animation:tl-spin .8s linear infinite"></div>
      <div style="font-weight:700">Memuat Talentir…</div>
    </div>
    <style>@keyframes tl-spin{to{transform:rotate(360deg)}}</style>
  `);

  try {
    await window.loadTalentirData();
  } catch (err) {
    if (err && err.code === 401) {
      // Unauthenticated visitors land on the marketing page (which has both
      // "Masuk" and "Daftar gratis" CTAs visible), instead of dumping them
      // straight on the login form. Users who actually want to log in click
      // "Masuk" in the nav; new users see signup options upfront.
      window.location.href = "landing.html";
      return;
    }
    console.error(err);
    setStatus(`
      <div>
        <div style="font-weight:800;font-size:18px;margin-bottom:6px">Tidak bisa terhubung ke server</div>
        <div style="font-size:13px;max-width:420px">Pastikan backend berjalan di <code>${window.TALENTIR_API || "http://localhost:3006"}</code>
        (jalankan <code>npm run dev</code> di folder <code>backend/</code>), lalu muat ulang halaman.</div>
        <div style="font-size:12px;color:#94a3b8;margin-top:10px">${(err && err.message) || ""}</div>
      </div>
    `);
    return;
  }

  ReactDOM.createRoot(root).render(<window.App />);
})();
