// PedScribe Mobile Launcher
// Handles configurable server URL and auto-redirect

(function() {
  var STORAGE_KEY = 'pedscribe_server_url';
  var DEFAULT_URL = 'https://app.pedshub.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');
  }

  // Connect button
  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...';
    haptic();

    localStorage.setItem(STORAGE_KEY, url);
    navigateToServer(url);
  });

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

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

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

  function showConnecting(url) {
    showScreen('connecting');
    setTimeout(function() { navigateToServer(url); }, 800);
  }

  function navigateToServer(url) {
    window.location.href = url;
  }

  function haptic() {
    try {
      if (window.Capacitor && window.Capacitor.Plugins && window.Capacitor.Plugins.Haptics) {
        window.Capacitor.Plugins.Haptics.impact({ style: 'medium' });
      }
    } catch(e) {}
  }
})();
