// Boot — orchestrates password gate, data load, and app mount.
// Owns the React root. Sets window.TOOLS / window.STATS before mounting App so the
// existing view components can keep reading from globals.

const rootEl = document.getElementById("root");
const reactRoot = ReactDOM.createRoot(rootEl);

const state = {
  unlocked: window.isUnlocked(),
  tools: null,
  stats: null,
  loadInfo: null,
  loading: false,
};

function renderGate() {
  reactRoot.render(
    <PasswordGate onUnlock={() => { state.unlocked = true; bootMain(); }} />
  );
}

function renderLoading(msg) {
  reactRoot.render(
    <div className="boot-loading">
      <div className="boot-spinner" />
      <div className="boot-msg">{msg || "Loading tech stack…"}</div>
    </div>
  );
}

function renderApp() {
  // App is a global from app.jsx
  reactRoot.render(<App loadInfo={state.loadInfo} onReload={refresh} onLock={window.lockSession} />);
}

async function loadAndUpdate() {
  const cfg = window.CONFIG || {};
  state.loading = true;
  const info = await window.loadTools(cfg.sheetUrl);
  window.TOOLS = info.tools;
  window.STATS = window.buildStats(info.tools);
  state.tools = info.tools;
  state.stats = window.STATS;
  state.loadInfo = info;
  state.loading = false;
}

async function bootMain() {
  renderLoading("Fetching latest data…");
  await loadAndUpdate();
  renderApp();

  // Periodic refresh
  const cfg = window.CONFIG || {};
  const mins = Number(cfg.refreshMinutes) || 0;
  if (mins > 0 && !window.__zintexRefreshTimer) {
    window.__zintexRefreshTimer = setInterval(async () => {
      await loadAndUpdate();
      renderApp();
    }, mins * 60 * 1000);
  }
}

async function refresh() {
  await loadAndUpdate();
  renderApp();
}

// Entry
if (!state.unlocked) {
  renderGate();
} else {
  bootMain();
}
