const DEFAULT_CONFIG = {
  server: 'http://localhost:4242',
  user_id: 1,
  token: '',
  enabled: true,
};

async function load() {
  const cfg = await chrome.storage.sync.get(DEFAULT_CONFIG);
  document.getElementById('server').value = cfg.server;
  document.getElementById('user_id').value = cfg.user_id;
  document.getElementById('token').value = cfg.token;
  document.getElementById('enabled').checked = cfg.enabled;

  const lc = await chrome.storage.local.get({ last_capture: null });
  if (lc.last_capture) {
    const { title, time } = lc.last_capture;
    const ago = Math.round((Date.now() - time) / 60000);
    const agoText = ago < 1 ? 'just now' : `${ago}m ago`;
    const short = title.length > 42 ? title.slice(0, 42) + '…' : title;
    document.getElementById('last-capture').textContent =
      `Last: "${short}" (${agoText})`;
  }
}

document.getElementById('save').addEventListener('click', async () => {
  const server = document.getElementById('server').value.trim();
  const user_id = parseInt(document.getElementById('user_id').value, 10);
  const cfg = {
    server: server || DEFAULT_CONFIG.server,
    user_id: user_id > 0 ? user_id : 1,
    token: document.getElementById('token').value.trim(),
    enabled: document.getElementById('enabled').checked,
  };
  await chrome.storage.sync.set(cfg);
  const status = document.getElementById('save-status');
  status.textContent = 'Saved ✓';
  setTimeout(() => { status.textContent = ''; }, 2000);
});

load();
