// Options-page glue. Reads existing values, saves on click.

const $host = document.getElementById('admin-host')
const $key = document.getElementById('session-key')
const $btn = document.getElementById('save')
const $status = document.getElementById('status')

function setStatus(text, isError) {
  $status.textContent = text
  $status.classList.toggle('error', !!isError)
}

async function load() {
  const stored = await chrome.storage.local.get(['adminHost', 'sessionKey'])
  if (typeof stored.adminHost === 'string') $host.value = stored.adminHost
  if (typeof stored.sessionKey === 'string') $key.value = stored.sessionKey
}

async function save() {
  const adminHost = $host.value.trim()
  const sessionKey = $key.value.trim()
  if (!adminHost) return setStatus('Admin host is required.', true)
  if (!/^https?:\/\//.test(adminHost)) return setStatus('Admin host must start with http(s)://.', true)
  if (!sessionKey) return setStatus('Session key is required.', true)
  await chrome.storage.local.set({ adminHost: adminHost, sessionKey: sessionKey })
  setStatus('Saved.', false)
}

$btn.addEventListener('click', save)
load()
