/**
 * Address Management Module
 * Handles saving and loading delivery addresses from localStorage
 */

class AddressManager {
  constructor() {
    this.storageKey = 'guarulhos_saved_addresses';
    this.initializeAddresses();
    this.setupEventListeners();
  }

  /**
   * Initialize address management
   */
  initializeAddresses() {
    this.loadAddresses();
    this.displaySavedAddresses();
  }

  /**
   * Setup event listeners
   */
  setupEventListeners() {
    const checkoutForm = document.getElementById('checkout-form');
    if (checkoutForm) {
      checkoutForm.addEventListener('submit', (e) => {
        // Save address BEFORE form processing
        const saveCheckbox = document.getElementById('save-address');
        if (saveCheckbox && saveCheckbox.checked) {
          const fullName = document.getElementById('fullName')?.value.trim();
          const email = document.getElementById('email')?.value.trim();
          const phone = document.getElementById('phone')?.value.trim();
          const deliveryLocation = document.getElementById('deliveryLocation')?.value.trim();
          
          if (fullName && email && phone && deliveryLocation) {
            this.saveAddress(fullName, email, phone, deliveryLocation);
          }
        }
      });
    }

    // Show/hide saved addresses when user interacts with form
    const addressInputs = ['fullName', 'email', 'phone', 'deliveryLocation', 'address'];
    addressInputs.forEach(id => {
      const input = document.getElementById(id);
      if (input) {
        input.addEventListener('focus', () => {
          this.displaySavedAddresses();
        });
      }
    });
  }

  /**
   * Get all saved addresses
   * @returns {Array} Array of saved addresses
   */
  loadAddresses() {
    try {
      const stored = localStorage.getItem(this.storageKey);
      this.addresses = stored ? JSON.parse(stored) : [];
      
      // Filter out any corrupt entries (entries with undefined values)
      this.addresses = this.addresses.filter(addr => 
        addr && addr.fullName && addr.email && addr.phone && addr.location
      );
      
      console.log('Loaded addresses:', this.addresses);
      return this.addresses;
    } catch (error) {
      console.error('Error loading addresses:', error);
      this.addresses = [];
      return [];
    }
  }

  /**
   * Save address with all customer information
   * @param {string} fullName - Full name
   * @param {string} email - Email address
   * @param {string} phone - Phone number
   * @param {string} location - Delivery location
   */
  saveAddress(fullName, email, phone, location) {
    console.log('saveAddress called with:', { fullName, email, phone, location });
    
    if (!fullName || !email || !phone || !location) {
      console.warn('Missing required fields:', { fullName, email, phone, location });
      return false;
    }

    const addressObj = {
      fullName: fullName || '',
      email: email || '',
      phone: phone || '',
      location: location || '',
      id: Date.now()
    };

    console.log('Created address object:', addressObj);

    // Check if this exact information already exists
    const exists = this.addresses.some(
      addr => addr.fullName === fullName && addr.email === email && addr.phone === phone && addr.location === location
    );

    if (!exists) {
      this.addresses.push(addressObj);
      this.addresses = this.addresses.slice(-10); // Keep only last 10 saved profiles
      try {
        localStorage.setItem(this.storageKey, JSON.stringify(this.addresses));
        console.log('Address saved. Current addresses:', this.addresses);
        this.displaySavedAddresses();
        return true;
      } catch (error) {
        console.error('Error saving profile:', error);
        return false;
      }
    }
    return false;
  }

  /**
   * Save current address
   */
  saveCurrentAddress() {
    const deliveryLocation = document.getElementById('deliveryLocation')?.value.trim();
    const address = document.getElementById('address')?.value.trim();

    if (!deliveryLocation) {
      showNotification('Please enter a delivery location', 'error');
      return;
    }

    // Check if address already exists
    const addressObj = {
      location: deliveryLocation,
      details: address,
      id: Date.now()
    };

    const exists = this.addresses.some(
      addr => addr.location === deliveryLocation && addr.details === address
    );

    if (!exists) {
      this.addresses.push(addressObj);
      this.addresses = this.addresses.slice(-10); // Keep only last 10 addresses
      localStorage.setItem(this.storageKey, JSON.stringify(this.addresses));
      showNotification('Address saved! ✓', 'success');
      this.displaySavedAddresses();
    }
  }

  /**
   * Display saved addresses
   */
  displaySavedAddresses() {
    const section = document.getElementById('saved-addresses-section');
    const list = document.getElementById('saved-addresses-list');

    if (!section || !list) return;

    this.addresses = this.loadAddresses();

    if (this.addresses.length === 0) {
      section.style.display = 'none';
      return;
    }

    section.style.display = 'block';

    // Clear and populate the list
    list.innerHTML = '';
    this.addresses.forEach((profile, index) => {
      const profileDiv = document.createElement('div');
      profileDiv.style.cssText = `
        padding: 10px;
        margin-bottom: 8px;
        background-color: var(--primary-dark);
        border: 1px solid var(--border-color);
        border-radius: 5px;
        cursor: pointer;
        transition: all 0.3s ease;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
      `;

      profileDiv.innerHTML = `
        <div style="flex: 1;">
          <p style="color: var(--accent-gold); margin: 0 0 5px 0; font-weight: bold;">${profile.fullName}</p>
          <p style="color: var(--text-muted); margin: 0 0 3px 0; font-size: 0.9rem;">📧 ${profile.email}</p>
          <p style="color: var(--text-muted); margin: 0 0 3px 0; font-size: 0.9rem;">📱 ${profile.phone}</p>
          <p style="color: var(--text-muted); margin: 0; font-size: 0.9rem;">📍 ${profile.location}</p>
        </div>
        <button type="button" class="delete-address-btn" data-id="${profile.id}" onclick="addressManager.deleteAddress(${profile.id}, event)" style="
          padding: 5px 10px;
          background-color: #ff6b6b;
          color: white;
          border: none;
          border-radius: 3px;
          cursor: pointer;
          font-size: 0.8rem;
          margin-left: 10px;
          white-space: nowrap;
        ">Delete</button>
      `;

      // Click to use this profile
      profileDiv.addEventListener('click', (e) => {
        if (!e.target.classList.contains('delete-address-btn') && e.target.tagName !== 'BUTTON') {
          this.selectAddress(profile);
        }
      });

      list.appendChild(profileDiv);
    });
  }

  /**
   * Select a saved profile
   * @param {Object} profile - Profile object
   */
  selectAddress(profile) {
    document.getElementById('fullName').value = profile.fullName;
    document.getElementById('email').value = profile.email;
    document.getElementById('phone').value = profile.phone;
    document.getElementById('deliveryLocation').value = profile.location;
    document.getElementById('save-address').checked = false;
    showNotification('Profile loaded! 👤', 'success');
  }

  /**
   * Delete a saved address
   * @param {number} id - Address ID
   * @param {Event} event - Click event
   */
  deleteAddress(id, event) {
    event.stopPropagation();
    this.addresses = this.addresses.filter(addr => addr.id !== id);
    localStorage.setItem(this.storageKey, JSON.stringify(this.addresses));
    this.displaySavedAddresses();
    showNotification('Address deleted', 'info');
  }
}

/**
 * Clear all saved addresses
 */
function clearAllAddresses() {
  if (confirm('Are you sure you want to delete all saved addresses?')) {
    addressManager.addresses = [];
    localStorage.setItem(addressManager.storageKey, JSON.stringify([]));
    addressManager.displaySavedAddresses();
    showNotification('All addresses cleared', 'info');
  }
}

/**
 * Clear corrupt saved addresses data
 */
function clearCorruptAddresses() {
  if (confirm('Clear all saved addresses and start fresh?')) {
    localStorage.removeItem('guarulhos_saved_addresses');
    location.reload();
  }
}

// Initialize address manager when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
  window.addressManager = new AddressManager();
  
  // Check for corrupt data and warn user
  try {
    const stored = localStorage.getItem('guarulhos_saved_addresses');
    if (stored) {
      const data = JSON.parse(stored);
      if (Array.isArray(data)) {
        const hasCorrupt = data.some(addr => !addr.fullName || !addr.email || !addr.phone || !addr.location);
        if (hasCorrupt) {
          console.warn('Corrupt addresses detected. Run clearCorruptAddresses() to fix.');
        }
      }
    }
  } catch (error) {
    console.warn('Could not check for corrupt data:', error);
  }
});
