const profileSelect = document.getElementById('profileSelect');
const statusEl = document.getElementById('status');
const debugToggle = document.getElementById('debugLoggingToggle');

function isValidProfileNumber(value) {
  return Number.isInteger(value) && value >= 1 && value <= 5;
}

function apiFetch(url, options = {}) {
  const config = {
    ...options,
    credentials: 'include'
  };

  if (options && options.headers) {
    config.headers = { ...options.headers };
  }

  return fetch(url, config);
}

async function fetchProfileState() {
  try {
    const response = await apiFetch(`${API_BASE_URL}/api/profile-state`);
    if (!response.ok) {
      return null;
    }

    const data = await response.json();
    if (data && typeof data.profile_number !== 'undefined') {
      const parsed = parseInt(data.profile_number, 10);
      if (!Number.isNaN(parsed)) {
        return parsed;
      }
    }
    return null;
  } catch (error) {
    console.warn('Profile state fetch failed:', error);
    return null;
  }
}

async function updateProfileState(profileNumber) {
  try {
    const response = await apiFetch(`${API_BASE_URL}/api/profile-state`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ profile_number: profileNumber })
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
  } catch (error) {
    console.error('Failed to update profile state:', error);
  }
}

function updateStatus(message, saved = false) {
  statusEl.textContent = message;
  statusEl.className = saved ? 'status saved' : 'status';
}

async function initProfileSelect() {
  const backendProfile = await fetchProfileState();
  if (isValidProfileNumber(backendProfile)) {
    profileSelect.value = String(backendProfile);
    chrome.storage.sync.set({ profileNumber: backendProfile });
    updateStatus(`Profil ${backendProfile} ausgewählt`);
    return;
  }

  chrome.storage.sync.get(['profileNumber'], (result) => {
    const profileNumber = result.profileNumber;
    if (isValidProfileNumber(profileNumber)) {
      profileSelect.value = String(profileNumber);
      updateStatus(`Profil ${profileNumber} ausgewählt (lokal)`);
      return;
    }
    profileSelect.value = '';
    updateStatus('Bitte zuerst ein Profil auswählen.');
  });
}

initProfileSelect();

if (debugToggle) {
  chrome.storage.sync.get(['debugLoggingEnabled'], (result) => {
    const enabled = Boolean(result && result.debugLoggingEnabled);
    debugToggle.checked = enabled;
  });

  debugToggle.addEventListener('change', () => {
    const enabled = debugToggle.checked;
    chrome.storage.sync.set({ debugLoggingEnabled: enabled }, () => {
      updateStatus(`Debug-Logging ${enabled ? 'aktiviert' : 'deaktiviert'} (wirksam ohne Reload)`, true);
    });
  });
}

function reloadFacebookTabs() {
  chrome.tabs.query({ url: ['https://www.facebook.com/*', 'https://facebook.com/*'] }, (tabs) => {
    tabs.forEach(tab => {
      chrome.tabs.reload(tab.id);
    });
  });
}

document.getElementById('saveBtn').addEventListener('click', async () => {
  const profileNumber = parseInt(profileSelect.value, 10);
  if (!isValidProfileNumber(profileNumber)) {
    updateStatus('Bitte zuerst ein Profil auswählen.');
    return;
  }

  chrome.storage.sync.set({ profileNumber }, async () => {
    updateStatus(`Profil ${profileNumber} gespeichert!`, true);
    await updateProfileState(profileNumber);
    reloadFacebookTabs();
  });
});

document.getElementById('webInterfaceBtn').addEventListener('click', () => {
  chrome.tabs.create({ url: API_BASE_URL });
});
