

// src/setup.js
import { setConfig } from './state.js';
import { getLinks } from './api.js';
import { startLauncher } from './starter.js';
import { loadAppOrder } from './order.js';
import { renderApps } from './render.js';

export async function showSetupPage(Storage) {
  const cfg = await Storage.loadConfig();
  if (cfg) {
    document.getElementById('cfg-url').value = cfg.url;
    document.getElementById('cfg-user').value = cfg.user;
    document.getElementById('cfg-pass').value = cfg.password;
    document.getElementById('cfg-refresh').style.display = 'block';
  } else {
    document.getElementById('cfg-refresh').style.display = 'none';
  }
  document.getElementById('setup-page').classList.remove('hidden');

  // Bottone "Aggiorna ora"
  document.getElementById('cfg-refresh').onclick = async () => {
    const cfg = await Storage.loadConfig();
    if (!cfg) {
      alert('Config mancante. Inserisci URL, user e password.');
      return;
    }
    setConfig({ url: cfg.url, user: cfg.user, password: cfg.password });
    const ok = await getLinks(Storage, renderApps, loadAppOrder);
    if (ok) {
      hideSetupPage();
      await startLauncher(Storage);
    } else {
      alert('Impossibile aggiornare le app dal server.');
    }
  };

  // Bottone "Salva"
  document.getElementById('cfg-save').onclick = async () => {
    const url = document.getElementById('cfg-url').value;
    const user = document.getElementById('cfg-user').value;
    const pass = document.getElementById('cfg-pass').value;
    await Storage.saveConfig({ url, user, password: pass });
    setConfig({ url, user, password: pass });
    const ok = await getLinks(Storage, renderApps, loadAppOrder);
    if (ok) {
      hideSetupPage();
      await startLauncher(Storage);
    }
  };
}

export function hideSetupPage() {
  document.getElementById('setup-page').classList.add('hidden');
}
