const API_URL = 'https://fb.srv.medeba-media.de/api';
const LOGIN_BROADCAST_KEY = 'fb-login-broadcast';

function getRedirectTarget() {
  try {
    const params = new URLSearchParams(window.location.search);
    const redirect = params.get('redirect');
    if (redirect) {
      return decodeURIComponent(redirect);
    }
  } catch (error) {
    console.warn('Konnte Redirect-Parameter nicht lesen:', error);
  }
  return 'index.html';
}

function updateStatus(message, isError = false) {
  const statusEl = document.getElementById('status');
  if (!statusEl) {
    return;
  }
  statusEl.textContent = message || '';
  statusEl.style.color = isError ? '#b91c1c' : '#15803d';
}

async function checkExistingSession() {
  try {
    const response = await fetch(`${API_URL}/session`, { credentials: 'include' });
    if (response.ok) {
      const data = await response.json();
      if (data && data.authenticated) {
        window.location.href = getRedirectTarget();
        return true;
      }
    }
  } catch (error) {
    console.warn('Konnte Session nicht prüfen:', error);
  }
  return false;
}

async function handleLogin(event) {
  event.preventDefault();
  const usernameInput = document.getElementById('username');
  const passwordInput = document.getElementById('password');

  const username = usernameInput ? usernameInput.value.trim() : '';
  const password = passwordInput ? passwordInput.value : '';

  if (!username || !password) {
    updateStatus('Bitte Benutzername und Passwort eingeben.', true);
    return;
  }

  updateStatus('Anmeldung läuft…', false);

  try {
    const response = await fetch(`${API_URL}/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ username, password })
    });

    if (!response.ok) {
      const payload = await response.json().catch(() => ({}));
      const message = payload && payload.error ? payload.error : 'Anmeldung fehlgeschlagen';
      updateStatus(message, true);
      return;
    }

    updateStatus('Erfolgreich angemeldet. Weiterleitung…', false);
    broadcastLogin();
    window.location.href = getRedirectTarget();
  } catch (error) {
    console.error('Login fehlgeschlagen:', error);
    updateStatus('Netzwerkfehler – bitte erneut versuchen.', true);
  }
}

document.addEventListener('DOMContentLoaded', async () => {
  const alreadyLoggedIn = await checkExistingSession();
  if (alreadyLoggedIn) {
    return;
  }

  setupCrossTabLoginSync();

  const form = document.getElementById('loginForm');
  if (form) {
    form.addEventListener('submit', handleLogin);
  }
});

function broadcastLogin() {
  try {
    localStorage.setItem(LOGIN_BROADCAST_KEY, String(Date.now()));
  } catch (error) {
    // ignore storage errors (private mode, blocked)
  }
  if ('BroadcastChannel' in window) {
    try {
      const channel = new BroadcastChannel('fb-login');
      channel.postMessage({ type: 'login', at: Date.now() });
      channel.close();
    } catch (error) {
      // ignore
    }
  }
}

function setupCrossTabLoginSync() {
  window.addEventListener('storage', (event) => {
    if (event.key !== LOGIN_BROADCAST_KEY) return;
    checkExistingSession();
  });

  if ('BroadcastChannel' in window) {
    const channel = new BroadcastChannel('fb-login');
    channel.addEventListener('message', (event) => {
      if (!event || !event.data || event.data.type !== 'login') return;
      checkExistingSession();
    });
  }
}
