const DEFAULT_BASE_URL = 'http://localhost:3000';

function normalizeBaseUrl(rawBaseUrl) {
  if (typeof rawBaseUrl !== 'string' || rawBaseUrl.trim().length === 0) {
    return DEFAULT_BASE_URL;
  }

  return rawBaseUrl.trim().replace(/\/+$/, '');
}

function isValidHttpUrl(value) {
  try {
    const url = new URL(value);
    return url.protocol === 'http:' || url.protocol === 'https:';
  } catch {
    return false;
  }
}

const form = document.getElementById('settings-form');
const baseUrlInput = document.getElementById('base-url');
const statusNode = document.getElementById('status');

function showStatus(message, isError = false) {
  if (!statusNode) {
    return;
  }

  statusNode.textContent = message;
  statusNode.style.color = isError ? '#991b1b' : '#166534';
}

async function loadSettings() {
  const { recipeManagerBaseUrl } = await chrome.storage.sync.get({
    recipeManagerBaseUrl: DEFAULT_BASE_URL,
  });

  if (baseUrlInput) {
    baseUrlInput.value = normalizeBaseUrl(recipeManagerBaseUrl);
  }
}

form?.addEventListener('submit', async (event) => {
  event.preventDefault();

  const normalizedBaseUrl = normalizeBaseUrl(baseUrlInput?.value ?? '');

  if (!isValidHttpUrl(normalizedBaseUrl)) {
    showStatus('Please enter a valid http(s) URL.', true);
    baseUrlInput?.focus();
    return;
  }

  await chrome.storage.sync.set({ recipeManagerBaseUrl: normalizedBaseUrl });
  showStatus('Settings saved.');
});

loadSettings().catch((error) => {
  console.error('[Recipe Manager Extension] Failed to load settings', error);
  showStatus('Could not load settings.', true);
});
