import { navigate } from '../router.js';

function escapeHtml(text) {
  return String(text || '')
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}

export function openAuthRequiredModal({
  title = 'Нужен вход',
  text = 'Эта часть доступна после входа в систему.',
  startRoute = 'start-view',
} = {}) {
  const root = document.getElementById('modal-root');
  if (!(root instanceof HTMLElement)) {
    window.alert(`${title}\n\n${text}`);
    return;
  }
  root.innerHTML = `
    <div class="modal" id="auth-required-modal">
      <div class="modal-card stack">
        <h3 class="modal-title">${escapeHtml(title)}</h3>
        <p class="meta-muted" style="white-space: pre-wrap; line-height: 1.45;">${escapeHtml(text)}</p>
        <div class="form-actions-grid">
          <button class="secondary-btn" type="button" id="auth-required-close">Закрыть</button>
          <button class="primary-btn" type="button" id="auth-required-start">На старт</button>
        </div>
      </div>
    </div>
  `;

  const close = () => { root.innerHTML = ''; };
  root.querySelector('#auth-required-close')?.addEventListener('click', close);
  root.querySelector('#auth-required-start')?.addEventListener('click', () => {
    close();
    navigate(startRoute);
  });
  root.querySelector('#auth-required-modal')?.addEventListener('click', (event) => {
    if (event.target?.id === 'auth-required-modal') close();
  });
}

