// ====================== BEGRUESSUNG NACH TAGESZEIT ======================

document.addEventListener('DOMContentLoaded', function() {
  const stunde = new Date().getHours();
  const el = document.getElementById('begruessung');
  let text;

  if (el) {
    if (stunde < 10) {
      text = 'Guten Morgen!';
      el.classList.add('morgen');
    } else if (stunde < 18) {
      text = 'Hallo, schön dass du da bist!';
      el.classList.add('tag');
    } else {
      text = 'Guten Abend!';
      el.classList.add('abend');
    }

    el.textContent = text;
  }
});

// ====================== CONTACT FORM VALIDATION ======================

const contactForm = document.getElementById('contactForm');

if (contactForm) {
  contactForm.addEventListener('submit', (e) => {
    e.preventDefault();

    // Clear previous errors
    clearErrors();

    // Get form values
    const name = document.getElementById('name').value.trim();
    const email = document.getElementById('email').value.trim();
    const subject = document.getElementById('subject').value.trim();
    const message = document.getElementById('message').value.trim();
    const privacy = document.getElementById('privacy').checked;

    let isValid = true;

    // Validate name
    if (name === '') {
      showError('name', 'Bitte gib deinen Namen ein');
      isValid = false;
    } else if (name.length < 2) {
      showError('name', 'Der Name muss mindestens 2 Zeichen lang sein');
      isValid = false;
    }

    // Validate email
    if (email === '') {
      showError('email', 'Bitte gib deine E-Mail ein');
      isValid = false;
    } else if (!isValidEmail(email)) {
      showError('email', 'Bitte gib eine gültige E-Mail ein');
      isValid = false;
    }

    // Validate subject
    if (subject === '') {
      showError('subject', 'Bitte gib einen Betreff ein');
      isValid = false;
    } else if (subject.length < 3) {
      showError('subject', 'Der Betreff muss mindestens 3 Zeichen lang sein');
      isValid = false;
    }

    // Validate message
    if (message === '') {
      showError('message', 'Bitte gib eine Nachricht ein');
      isValid = false;
    } else if (message.length < 10) {
      showError('message', 'Die Nachricht muss mindestens 10 Zeichen lang sein');
      isValid = false;
    }

    // Validate privacy checkbox
    if (!privacy) {
      showError('privacy', 'Bitte akzeptiere die Datenschutzerklärung');
      isValid = false;
    }

    // Submit form if valid
    if (isValid) {
      submitForm();
    }
  });
}

function showError(fieldId, message) {
  const field = document.getElementById(fieldId);
  const errorElement = document.getElementById(fieldId + 'Error');

  if (field && errorElement) {
    field.parentElement.classList.add('error');
    errorElement.textContent = message;
  }
}

function clearErrors() {
  const formGroups = document.querySelectorAll('.form-group');
  formGroups.forEach(group => {
    group.classList.remove('error');
    const errorMessage = group.querySelector('.error-message');
    if (errorMessage) {
      errorMessage.textContent = '';
    }
  });
}

function isValidEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

function submitForm() {
  const form = document.getElementById('contactForm');
  const formMessage = document.getElementById('formMessage');

  // Show success message
  formMessage.classList.remove('error');
  formMessage.classList.add('success');
  formMessage.textContent = '✓ Deine Nachricht wurde erfolgreich versendet! Wir werden uns bald mit dir in Verbindung setzen.';

  // Reset form
  form.reset();

  // Hide message after 5 seconds
  setTimeout(() => {
    formMessage.classList.remove('success');
    formMessage.textContent = '';
  }, 5000);

  // Note: In a real application, you would send this data to a server
  console.log('Form submitted:', {
    name: document.getElementById('name').value,
    email: document.getElementById('email').value,
    phone: document.getElementById('phone').value,
    subject: document.getElementById('subject').value,
    message: document.getElementById('message').value
  });
}

// ====================== GALLERY LIGHTBOX ======================

document.querySelectorAll('.galerie img').forEach(img => {
  img.addEventListener('click', () => {
    const overlay = document.createElement('div');
    overlay.style.cssText =
      'position:fixed;inset:0;background:rgba(0,0,0,.8);display:flex;' +
      'align-items:center;justify-content:center;cursor:pointer;z-index:999';

    const big = document.createElement('img');
    big.src = img.src;
    big.style.maxWidth = '90vw';
    big.style.maxHeight = '90vh';
    big.style.borderRadius = '8px';
    big.style.boxShadow = '0 20px 60px rgba(0,0,0,.3)';

    // Close button
    const closeBtn = document.createElement('button');
    closeBtn.innerHTML = '✕';
    closeBtn.style.cssText =
      'position:absolute;top:20px;right:20px;background:white;border:none;' +
      'width:40px;height:40px;border-radius:50%;font-size:24px;cursor:pointer;' +
      'font-weight:bold;color:#333;transition:all 0.3s ease;';

    closeBtn.addEventListener('mouseover', () => {
      closeBtn.style.background = '#f0f0f0';
      closeBtn.style.transform = 'scale(1.1)';
    });

    closeBtn.addEventListener('mouseout', () => {
      closeBtn.style.background = 'white';
      closeBtn.style.transform = 'scale(1)';
    });

    closeBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      overlay.remove();
    });

    overlay.appendChild(big);
    overlay.appendChild(closeBtn);

    overlay.addEventListener('click', () => overlay.remove());

    // Close on Escape key
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        overlay.remove();
      }
    });

    document.body.appendChild(overlay);
  });
});

// ====================== SMOOTH SCROLL FOR ANCHOR LINKS ======================

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
  anchor.addEventListener('click', function (e) {
    e.preventDefault();
    const target = document.querySelector(this.getAttribute('href'));
    if (target) {
      target.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      });
    }
  });
});

// ====================== ADD ACTIVE CLASS TO NAV ON SCROLL ======================

window.addEventListener('scroll', () => {
  const nav = document.querySelector('.navbar');
  if (window.scrollY > 100) {
    nav.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
  } else {
    nav.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.1)';
  }
});

// ====================== PHONE NUMBER FORMATTING (optional) ======================

const phoneInput = document.getElementById('phone');
if (phoneInput) {
  phoneInput.addEventListener('input', (e) => {
    let value = e.target.value.replace(/\D/g, '');
    if (value.length > 0) {
      if (value.length <= 4) {
        value = value;
      } else if (value.length <= 7) {
        value = value.slice(0, 4) + ' ' + value.slice(4);
      } else {
        value = value.slice(0, 4) + ' ' + value.slice(4, 7) + ' ' + value.slice(7, 11);
      }
    }
    e.target.value = value;
  });
}

// ====================== INTERSECTION OBSERVER FOR SMOOTH SCROLL REVEAL ======================

const observerOptions = {
  threshold: 0.1,
  rootMargin: '0px 0px -50px 0px'
};

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry, index) => {
    if (entry.isIntersecting) {
      setTimeout(() => {
        entry.target.style.opacity = '1';
        entry.target.style.transform = 'translateY(0) scale(1)';
        entry.target.classList.add('revealed');
      }, index * 50);
    }
  });
}, observerOptions);

// Observe content sections with staggered animation
document.querySelectorAll('.content-section, .feature-card, .kinetic-card, .team-member, .tech-card, .exercise-card').forEach((section, index) => {
  section.style.opacity = '0';
  section.style.transform = 'translateY(20px) scale(0.98)';
  section.style.transition = 'opacity 0.6s cubic-bezier(0.34, 1.56, 0.64, 1), transform 0.6s cubic-bezier(0.34, 1.56, 0.64, 1)';
  observer.observe(section);
});

// Reveal buttons with glow animation
document.querySelectorAll('.btn, .kinetic-btn').forEach(btn => {
  btn.style.transition = 'all 0.6s cubic-bezier(0.34, 1.56, 0.64, 1)';
  observer.observe(btn);
});

// ====================== UTILITY: CONSOLE MESSAGE ======================

console.log('%c🎉 Welcome to EIS Project!', 'color: #2563eb; font-size: 20px; font-weight: bold;');
console.log('%cThis website is a learning project for interactive software development at PH Weingarten.', 'color: #475569; font-size: 14px;');