/**
 * Utility Functions for DatePress Template
 * Modern, optimized helper functions for better UX
 */

(function (window, $) {
  'use strict';

  // Namespace for utilities
  window.DatePressUtils = {
    
    /**
     * Lazy load images for better performance
     */
    lazyLoadImages: function() {
      if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
          entries.forEach(entry => {
            if (entry.isIntersecting) {
              const img = entry.target;
              if (img.dataset.src) {
                img.src = img.dataset.src;
                img.removeAttribute('data-src');
              }
              if (img.dataset.srcset) {
                img.srcset = img.dataset.srcset;
                img.removeAttribute('data-srcset');
              }
              img.classList.add('loaded');
              observer.unobserve(img);
            }
          });
        }, {
          rootMargin: '50px 0px',
          threshold: 0.01
        });

        document.querySelectorAll('img[data-src], img[data-srcset]').forEach(img => {
          imageObserver.observe(img);
        });
      }
    },

    /**
     * Smooth scroll to element
     */
    smoothScrollTo: function(element, duration = 600) {
      const targetPosition = element.getBoundingClientRect().top + window.pageYOffset;
      const startPosition = window.pageYOffset;
      const distance = targetPosition - startPosition;
      let startTime = null;

      function animation(currentTime) {
        if (startTime === null) startTime = currentTime;
        const timeElapsed = currentTime - startTime;
        const run = ease(timeElapsed, startPosition, distance, duration);
        window.scrollTo(0, run);
        if (timeElapsed < duration) requestAnimationFrame(animation);
      }

      function ease(t, b, c, d) {
        t /= d / 2;
        if (t < 1) return c / 2 * t * t + b;
        t--;
        return -c / 2 * (t * (t - 2) - 1) + b;
      }

      requestAnimationFrame(animation);
    },

    /**
     * Add loading state to button
     */
    setButtonLoading: function(button, isLoading) {
      const $btn = $(button);
      if (isLoading) {
        $btn.data('original-text', $btn.html());
        $btn.prop('disabled', true).addClass('loading');
      } else {
        $btn.prop('disabled', false).removeClass('loading');
        const originalText = $btn.data('original-text');
        if (originalText) {
          $btn.html(originalText);
        }
      }
    },

    /**
     * Show toast notification
     */
    showToast: function(message, type = 'info', duration = 3000) {
      const toast = $('<div>')
        .addClass('toast-notification toast-' + type)
        .html(message)
        .appendTo('body');

      setTimeout(() => toast.addClass('show'), 10);

      setTimeout(() => {
        toast.removeClass('show');
        setTimeout(() => toast.remove(), 300);
      }, duration);
    },

    /**
     * Validate form field
     */
    validateField: function(field) {
      const $field = $(field);
      const value = $field.val().trim();
      const type = $field.attr('type');
      let isValid = true;
      let message = '';

      // Required check
      if ($field.prop('required') && !value) {
        isValid = false;
        message = 'This field is required';
      }

      // Email validation
      if (type === 'email' && value) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(value)) {
          isValid = false;
          message = 'Please enter a valid email address';
        }
      }

      // Phone validation
      if (type === 'tel' && value) {
        const phoneRegex = /^[\d\s\-\+\(\)]+$/;
        if (!phoneRegex.test(value)) {
          isValid = false;
          message = 'Please enter a valid phone number';
        }
      }

      // Min length
      const minLength = $field.attr('minlength');
      if (minLength && value.length < minLength) {
        isValid = false;
        message = `Minimum ${minLength} characters required`;
      }

      // Update UI
      const $formGroup = $field.closest('.form-group');
      if (isValid) {
        $formGroup.removeClass('has-error').addClass('has-success');
        $formGroup.find('.error-message').remove();
      } else {
        $formGroup.removeClass('has-success').addClass('has-error');
        $formGroup.find('.error-message').remove();
        $formGroup.append(`<span class="error-message">${message}</span>`);
      }

      return isValid;
    },

    /**
     * Format date
     */
    formatDate: function(date, format = 'MMM DD, YYYY') {
      const d = new Date(date);
      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
      
      return format
        .replace('YYYY', d.getFullYear())
        .replace('MM', String(d.getMonth() + 1).padStart(2, '0'))
        .replace('MMM', months[d.getMonth()])
        .replace('DD', String(d.getDate()).padStart(2, '0'));
    },

    /**
     * Copy text to clipboard
     */
    copyToClipboard: function(text) {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
          this.showToast('Copied to clipboard!', 'success', 2000);
        });
      } else {
        // Fallback for older browsers
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        this.showToast('Copied to clipboard!', 'success', 2000);
      }
    },

    /**
     * Check if element is in viewport
     */
    isInViewport: function(element) {
      const rect = element.getBoundingClientRect();
      return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
      );
    },

    /**
     * Animate counter
     */
    animateCounter: function(element, start, end, duration = 2000) {
      const range = end - start;
      const increment = range / (duration / 16);
      let current = start;

      const timer = setInterval(() => {
        current += increment;
        if ((increment > 0 && current >= end) || (increment < 0 && current <= end)) {
          current = end;
          clearInterval(timer);
        }
        element.textContent = Math.round(current).toLocaleString();
      }, 16);
    },

    /**
     * Generate unique ID
     */
    generateId: function(prefix = 'id') {
      return prefix + '-' + Math.random().toString(36).substr(2, 9);
    },

    /**
     * Storage helpers
     */
    storage: {
      set: function(key, value) {
        try {
          localStorage.setItem(key, JSON.stringify(value));
          return true;
        } catch (e) {
          console.error('Storage error:', e);
          return false;
        }
      },
      get: function(key, defaultValue = null) {
        try {
          const item = localStorage.getItem(key);
          return item ? JSON.parse(item) : defaultValue;
        } catch (e) {
          console.error('Storage error:', e);
          return defaultValue;
        }
      },
      remove: function(key) {
        try {
          localStorage.removeItem(key);
          return true;
        } catch (e) {
          console.error('Storage error:', e);
          return false;
        }
      }
    }
  };

  // Auto-initialize on DOM ready
  $(document).ready(function() {
    // Initialize lazy loading
    DatePressUtils.lazyLoadImages();

    // Add smooth scroll to anchor links
    $('a[href^="#"]').on('click', function(e) {
      const href = $(this).attr('href');
      if (href !== '#' && $(href).length) {
        e.preventDefault();
        DatePressUtils.smoothScrollTo($(href)[0]);
      }
    });

    // Auto-validate forms on submit
    $('form[data-validate]').on('submit', function(e) {
      let isValid = true;
      $(this).find('input[required], textarea[required], select[required]').each(function() {
        if (!DatePressUtils.validateField(this)) {
          isValid = false;
        }
      });
      
      if (!isValid) {
        e.preventDefault();
        DatePressUtils.showToast('Please fix the errors in the form', 'error');
      }
    });

    // Add ripple effect to buttons
    $('.theme-btn, .theme-btn-secondary, .theme-btn-outline').on('click', function(e) {
      const $button = $(this);
      const $ripple = $('<span class="ripple"></span>');
      const diameter = Math.max($button.outerWidth(), $button.outerHeight());
      const radius = diameter / 2;

      $ripple.css({
        width: diameter,
        height: diameter,
        left: e.pageX - $button.offset().left - radius,
        top: e.pageY - $button.offset().top - radius
      });

      $button.find('.ripple').remove();
      $button.append($ripple);

      setTimeout(() => $ripple.remove(), 600);
    });
  });

})(window, jQuery);
