import './demo.css';
const container = document.getElementById('workspace')!;
const status = document.getElementById('demo-status')!;
let cleanup: (() => void) | undefined;
let current = '';
let version = 0;
document.querySelectorAll<HTMLButtonElement>('[data-tool]').forEach(button => button.addEventListener('click', async () => {
  if (current && !confirm('Switch tools? Download JSON first if you want to keep the open draft.')) return;
  const requested = ++version;
  cleanup?.(); cleanup = undefined;
  current = button.dataset.tool!;
  status.textContent = 'Loading the local tool…';
  try {
    const tool = current === 'document' ? await import('./src/tools/document/index') : current === 'planner' ? await import('./src/tools/planner/index') : await import('./src/tools/mapper/index');
    if (requested !== version) return;
    cleanup = tool.mount(container);
    status.textContent = 'Tool ready. Save JSON to keep an editable copy.';
  } catch { status.textContent = 'The tool could not load. Check the build instructions and try again.'; }
}));
window.addEventListener('pagehide', () => cleanup?.());
