(function() {
  var STORAGE_KEY = 'pedshub_server_url';
  var DEFAULT_URL = 'https://quiz.danvics.com';

  var setupScreen = document.getElementById('setup-screen');
  var connectingScreen = document.getElementById('connecting-screen');
  var urlInput = document.getElementById('server-url');
  var connectBtn = document.getElementById('btn-connect');
  var changeBtn = document.getElementById('btn-change-server');

  var savedUrl = localStorage.getItem(STORAGE_KEY);

  if (savedUrl) {
    showConnecting(savedUrl);
  } else {
    urlInput.value = DEFAULT_URL;
    showScreen('setup');
  }

  connectBtn.addEventListener('click', function() {
    var url = (urlInput.value || DEFAULT_URL).trim().replace(/\/+$/, '');
    if (!url.startsWith('http')) url = 'https://' + url;
    connectBtn.disabled = true;
    connectBtn.textContent = 'Connecting...';
    localStorage.setItem(STORAGE_KEY, url);
    window.location.href = url;
  });

  urlInput.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') connectBtn.click();
  });

  changeBtn.addEventListener('click', function() {
    localStorage.removeItem(STORAGE_KEY);
    urlInput.value = savedUrl || DEFAULT_URL;
    showScreen('setup');
    urlInput.focus();
  });

  function showScreen(which) {
    setupScreen.style.display = which === 'setup' ? '' : 'none';
    connectingScreen.style.display = which === 'connecting' ? '' : 'none';
  }

  function showConnecting(url) {
    showScreen('connecting');
    setTimeout(function() { window.location.href = url; }, 800);
  }
})();
