document.addEventListener('DOMContentLoaded', () => {

  // ===== Meklēšanas joslas mobilā versija =====
  const toggle = document.querySelector('.mobile-search-toggle'); 
  const search = document.querySelector('.search-container');

  if (toggle && search) {
    toggle.addEventListener('click', () => {
      search.classList.toggle('active'); 
    });
  }

  // ===== Rēgistrācijas forma =====
  const registerForm = document.getElementById('registerForm');
  if (registerForm) {
    const messageDiv = document.getElementById('message');
    const password = registerForm.querySelector('input[name="password"]');
    const confirmPassword = registerForm.querySelector('input[name="confirm_password"]');
    const emailInput = registerForm.querySelector('input[name="email"]');
    const passwordMatchMsg = document.getElementById('passwordMatchMsg');

    // Paroles paslēpšana, parādīšana
    registerForm.querySelectorAll('.toggle-password').forEach(icon => {
      icon.addEventListener('click', () => {
        const input = icon.previousElementSibling;
        input.type = input.type === 'password' ? 'text' : 'password';
      });
    });

    // Pārbauda, vai paroles sakrīt
    function checkPasswordMatch() {
      if (!confirmPassword.value) {
        passwordMatchMsg.textContent = '';
        return;
      }
      if (password.value === confirmPassword.value) {
        passwordMatchMsg.style.color = 'green';
        passwordMatchMsg.textContent = 'Paroles sakrīt';
      } else {
        passwordMatchMsg.style.color = 'red';
        passwordMatchMsg.textContent = 'Paroles nesakrīt';
      }
    }
    password.addEventListener('input', checkPasswordMatch);
    confirmPassword.addEventListener('input', checkPasswordMatch);

    // Pārbauda, vai sakrīt e-pasts
    let emailTimeout;
    emailInput.addEventListener('input', () => {
      clearTimeout(emailTimeout);
      messageDiv.textContent = '';

      const email = emailInput.value.trim();
      if (/^[a-zA-Z0-9][^\s@]*@[^\s@]+\.[^\s@]+$/.test(email)) return; // skip invalid format

      emailTimeout = setTimeout(async () => {
        try {
          const formData = new FormData();
          formData.append('email', email);

          const res = await fetch('check_email.php', {
            method: 'POST',
            body: formData
          });

          const result = await res.json();
          if (result.taken) {
            messageDiv.style.color = 'red';
            messageDiv.textContent = 'Šis e-pasts jau tiek izmantots!';
          } else {
            messageDiv.textContent = '';
          }
        } catch (err) {
          console.error(err);
        }
      }, 500);
    });

    // [Formas iesniegšana
    registerForm.addEventListener('submit', async (e) => {
      e.preventDefault();

const hasNumber = /[0-9]/.test(password.value);
const hasSymbol = /[\W]/.test(password.value);

     if (password.value.length < 10) {
      messageDiv.style.color = 'red';
      messageDiv.textContent = 'Parolei jābūt vismaz 10 simbolus garai!';
      return;
      }
      if (!hasNumber || !hasSymbol) {
        messageDiv.style.color = 'red';
        messageDiv.textContent = 'Parolei jābūt vismaz vienam ciparam un vienam simbolam!';
        return;
      }
      if (password.value !== confirmPassword.value) {
        messageDiv.style.color = 'red';
        messageDiv.textContent = 'Paroles nesakrīt!';
        return;
      }
      const email = emailInput.value.trim();
      if (!/^[a-zA-Z0-9][^\s@]*@[^\s@]+\.[^\s@]+$/.test(email)) {
        messageDiv.style.color = 'red';
        messageDiv.textContent = 'E-pasts nedrīkst sākties ar simbolu!';
        return;
      }
      if (messageDiv.textContent === 'Šis e-pasts jau tiek izmantots!') return;

      const formData = new FormData(registerForm);

      try {
        const response = await fetch('register.php', {
          method: 'POST',
          body: formData
        });
        const result = await response.json();

        if (result.success) {
          messageDiv.style.color = 'green';
          messageDiv.textContent = 'Reģistrācija veiksmīga! Pāradresācija..';
          // Novirza lietotāju uz sākumlapu
          setTimeout(() => window.location.href = 'login.html', 1500);
        } else {
          messageDiv.style.color = 'red';
          messageDiv.textContent = result.error;
        }
      } catch (err) {
        messageDiv.style.color = 'red';
        messageDiv.textContent = 'Servera kļūda, mēģiniet vēlreiz.';
        console.error(err);
      }
    });
  }

// ===== Pieslēgšanās forma =====
const loginForm = document.getElementById('loginForm');
if (loginForm) {
  const loginMessage = document.getElementById('loginMessage');
  const emailInput = loginForm.querySelector('input[name="email"]');
  const passwordInput = loginForm.querySelector('input[name="password"]');

  // Paroles parādīšana, paslēpšana
  loginForm.querySelectorAll('.toggle-password').forEach(icon => {
    icon.addEventListener('click', () => {
      const input = icon.previousElementSibling;
      input.type = input.type === 'password' ? 'text' : 'password';
    });
  });

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

    const email = emailInput.value.trim();
    const password = passwordInput.value;

    // Pārbaudes
    if (!email || !password) {
      loginMessage.style.color = 'red';
      loginMessage.textContent = 'Aizpildiet visus laukus!';
      return;
    }
    if (password.length < 10) {
      loginMessage.style.color = 'red';
      loginMessage.textContent = 'Parolei jābūt vismaz 10 simbolus garai!';
      return;
    }

    // Datu iesniegšana
    const formData = new FormData();
    formData.append('email', email);
    formData.append('password', password);

    try {
      const res = await fetch('login.php', {
        method: 'POST',
        body: formData
      });
      const result = await res.json();

      if (result.success) {
        loginMessage.style.color = 'green';
        loginMessage.textContent = 'Pieslēgšanās veiksmīga! Pāradresācija..';
        setTimeout(() => window.location.href = 'index.php', 1000);
      } else {
        loginMessage.style.color = 'red';
        loginMessage.textContent = result.error;
      }
    } catch (err) {
      loginMessage.style.color = 'red';
      loginMessage.textContent = 'Servera kļūda, mēģiniet vēlreiz.';
      console.error(err);
    }
  });
}
});
