(() => {
  const root = document.documentElement;
  const themeButtons = document.querySelectorAll('.theme-button');
  const loginForm = document.getElementById('login-form');
  const emailInput = document.getElementById('email');
  const passwordInput = document.getElementById('password');
  const emailError = document.getElementById('email-error');
  const passwordError = document.getElementById('password-error');

  const STORAGE_KEY = 'signal-cyan-red-theme';

  function setTheme(theme) {
    root.setAttribute('data-theme', theme);
    themeButtons.forEach((button) => {
      const active = button.dataset.theme === theme;
      button.dataset.active = active ? 'true' : 'false';
      button.setAttribute('aria-checked', active ? 'true' : 'false');
    });
    try {
      localStorage.setItem(STORAGE_KEY, theme);
    } catch {
      // ignore storage errors
    }
  }

  function initTheme() {
    let theme = 'light';
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored === 'light' || stored === 'dark') {
        theme = stored;
      } else if (window.matchMedia &&
                 window.matchMedia('(prefers-color-scheme: dark)').matches) {
        theme = 'dark';
      }
    } catch {
      // keep default
    }
    setTheme(theme);
  }

  themeButtons.forEach((button) => {
    button.addEventListener('click', () => {
      const nextTheme = button.dataset.theme || 'light';
      setTheme(nextTheme);
    });
  });

  function validateEmail() {
    const invalid = !emailInput.validity.valid;
    emailInput.setAttribute('aria-invalid', String(invalid));
    emailError.classList.toggle('visible', invalid);
    return !invalid;
  }

  function validatePassword() {
    const invalid = !passwordInput.validity.valid;
    passwordInput.setAttribute('aria-invalid', String(invalid));
    passwordError.classList.toggle('visible', invalid);
    return !invalid;
  }

  loginForm.addEventListener('submit', (event) => {
    event.preventDefault();

    const okEmail = validateEmail();
    const okPassword = validatePassword();

    if (okEmail && okPassword) {
      // Demo only: no backend connection
      alert('Demo only – this login form is not connected to a backend.');
    }
  });

  emailInput.addEventListener('blur', validateEmail);
  passwordInput.addEventListener('blur', validatePassword);

  initTheme();
})();