// ============================================
// Script.js - SSR La Aguada
// Funcionalidades JavaScript para mejorar UX
// ============================================

document.addEventListener('DOMContentLoaded', function() {
  
  // ============================================
  // 1. Smooth Scroll para enlaces internos
  // ============================================
  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'
        });
      }
    });
  });
  
  // ============================================
  // 2. Resaltar enlace activo en navegación
  // ============================================
  const currentLocation = window.location.pathname.split('/').pop() || 'index.php';
  document.querySelectorAll('nav a').forEach(link => {
    const href = link.getAttribute('href');
    if (href === currentLocation || (currentLocation === '' && href === 'index.php')) {
      link.style.color = 'var(--color-primario, #1976d2)';
      link.style.background = 'var(--color-fondo, #f5f9fc)';
      link.style.fontWeight = '700';
    }
  });
  
  // ============================================
  // 3. Validación de formularios mejorada
  // ============================================
  const forms = document.querySelectorAll('form');
  forms.forEach(form => {
    form.addEventListener('submit', function(e) {
      const inputs = form.querySelectorAll('input[required], textarea[required], select[required]');
      let valid = true;
      
      inputs.forEach(input => {
        if (!input.value.trim()) {
          valid = false;
          input.style.borderColor = '#f44336';
          
          // Remover borde rojo al escribir
          input.addEventListener('input', function() {
            this.style.borderColor = '';
          });
        }
      });
      
      if (!valid) {
        e.preventDefault();
        alert('Por favor, complete todos los campos obligatorios.');
      }
    });
  });
  
  // ============================================
  // 4. Validación de email en tiempo real
  // ============================================
  const emailInputs = document.querySelectorAll('input[type="email"]');
  emailInputs.forEach(input => {
    input.addEventListener('blur', function() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (this.value && !emailRegex.test(this.value)) {
        this.style.borderColor = '#f44336';
        
        // Crear mensaje de error si no existe
        if (!this.nextElementSibling || !this.nextElementSibling.classList.contains('email-error')) {
          const errorMsg = document.createElement('span');
          errorMsg.className = 'email-error';
          errorMsg.style.color = '#f44336';
          errorMsg.style.fontSize = '0.85em';
          errorMsg.style.marginTop = '5px';
          errorMsg.style.display = 'block';
          errorMsg.textContent = 'Por favor, ingrese un correo válido';
          this.parentNode.insertBefore(errorMsg, this.nextSibling);
        }
      } else {
        this.style.borderColor = '';
        // Remover mensaje de error si existe
        if (this.nextElementSibling && this.nextElementSibling.classList.contains('email-error')) {
          this.nextElementSibling.remove();
        }
      }
    });
  });
  
  // ============================================
  // 5. Contador de caracteres para textarea
  // ============================================
  const textareas = document.querySelectorAll('textarea');
  textareas.forEach(textarea => {
    // Crear contador
    const counter = document.createElement('div');
    counter.style.textAlign = 'right';
    counter.style.fontSize = '0.85em';
    counter.style.color = '#666';
    counter.style.marginTop = '5px';
    textarea.parentNode.insertBefore(counter, textarea.nextSibling);
    
    // Actualizar contador
    const updateCounter = () => {
      const length = textarea.value.length;
      counter.textContent = `${length} caracteres`;
      
      if (length > 500) {
        counter.style.color = '#f44336';
      } else {
        counter.style.color = '#666';
      }
    };
    
    textarea.addEventListener('input', updateCounter);
    updateCounter(); // Inicializar
  });
  
  // ============================================
  // 6. Botón "Volver arriba"
  // ============================================
  const backToTopButton = document.createElement('button');
  backToTopButton.innerHTML = '↑';
  backToTopButton.className = 'back-to-top';
  backToTopButton.style.cssText = `
    position: fixed;
    bottom: 30px;
    right: 30px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: linear-gradient(135deg, #1976d2 0%, #0288d1 100%);
    color: white;
    border: none;
    font-size: 1.5em;
    cursor: pointer;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    opacity: 0;
    transition: opacity 0.3s, transform 0.3s;
    z-index: 1000;
    display: none;
  `;
  document.body.appendChild(backToTopButton);
  
  // Mostrar/ocultar botón según scroll
  window.addEventListener('scroll', () => {
    if (window.pageYOffset > 300) {
      backToTopButton.style.display = 'block';
      setTimeout(() => {
        backToTopButton.style.opacity = '1';
      }, 10);
    } else {
      backToTopButton.style.opacity = '0';
      setTimeout(() => {
        backToTopButton.style.display = 'none';
      }, 300);
    }
  });
  
  // Funcionalidad del botón
  backToTopButton.addEventListener('click', () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  });
  
  backToTopButton.addEventListener('mouseenter', () => {
    backToTopButton.style.transform = 'scale(1.1)';
  });
  
  backToTopButton.addEventListener('mouseleave', () => {
    backToTopButton.style.transform = 'scale(1)';
  });
  
  // ============================================
  // 7. Animación de entrada para elementos
  // ============================================
  const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
  };
  
  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.style.opacity = '1';
        entry.target.style.transform = 'translateY(0)';
        observer.unobserve(entry.target);
      }
    });
  }, observerOptions);
  
  // Aplicar animación a secciones y cards
  document.querySelectorAll('section, .card, .comunicacion-item').forEach(element => {
    element.style.opacity = '0';
    element.style.transform = 'translateY(20px)';
    element.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
    observer.observe(element);
  });
  
  // ============================================
  // 8. Confirmación antes de eliminar
  // ============================================
  document.querySelectorAll('button[type="submit"]').forEach(button => {
    if (button.textContent.toLowerCase().includes('eliminar') || 
        button.textContent.toLowerCase().includes('borrar')) {
      button.addEventListener('click', function(e) {
        if (!button.form.hasAttribute('data-confirmed')) {
          e.preventDefault();
          if (confirm('¿Está seguro de que desea eliminar este elemento?')) {
            button.form.setAttribute('data-confirmed', 'true');
            button.form.submit();
          }
        }
      });
    }
  });
  
  // ============================================
  // 9. Auto-guardar en localStorage (borrador)
  // ============================================
  const formInputs = document.querySelectorAll('form input[type="text"], form textarea');
  formInputs.forEach(input => {
    const storageKey = `ssr_draft_${input.name}`;
    
    // Cargar borrador si existe
    const savedValue = localStorage.getItem(storageKey);
    if (savedValue && !input.value) {
      input.value = savedValue;
      input.style.background = '#fff8e1';
      
      // Mostrar mensaje de borrador recuperado
      const draftMsg = document.createElement('span');
      draftMsg.textContent = '📝 Borrador recuperado';
      draftMsg.style.cssText = 'color: #f57c00; font-size: 0.85em; margin-left: 10px;';
      input.parentNode.insertBefore(draftMsg, input.nextSibling);
      
      setTimeout(() => {
        input.style.background = '';
        draftMsg.remove();
      }, 3000);
    }
    
    // Guardar borrador mientras escribe
    input.addEventListener('input', () => {
      localStorage.setItem(storageKey, input.value);
    });
    
    // Limpiar borrador al enviar el formulario
    if (input.form) {
      input.form.addEventListener('submit', () => {
        localStorage.removeItem(storageKey);
      });
    }
  });
  
  // ============================================
  // 10. Mejorar accesibilidad de enlaces externos
  // ============================================
  document.querySelectorAll('a[target="_blank"]').forEach(link => {
    if (!link.getAttribute('rel')) {
      link.setAttribute('rel', 'noopener noreferrer');
    }
    
    // Añadir icono visual de enlace externo
    if (!link.querySelector('.external-icon')) {
      const icon = document.createElement('span');
      icon.className = 'external-icon';
      icon.innerHTML = ' ↗';
      icon.style.fontSize = '0.8em';
      link.appendChild(icon);
    }
  });
  
  console.log('✅ SSR La Aguada - Scripts cargados correctamente');
});

// ============================================
// 11. Utilidad: Formatear números de teléfono
// ============================================
function formatPhoneNumber(input) {
  let value = input.value.replace(/\D/g, '');
  
  if (value.startsWith('569')) {
    // Formato chileno: +569 XXXX XXXX
    value = value.replace(/^569(\d{4})(\d{4})/, '+569 $1 $2');
  }
  
  input.value = value;
}

// Aplicar formateo a inputs de teléfono
document.querySelectorAll('input[type="tel"]').forEach(input => {
  input.addEventListener('blur', () => formatPhoneNumber(input));
});
