// Properties page JavaScript for KLEINS REAL ESTATE

// State management
let allProperties = [];
let filteredProperties = [];
let currentPage = 1;
const propertiesPerPage = 6;

// DOM Ready
document.addEventListener('DOMContentLoaded', function() {
  // Initialize properties page
  initPropertiesPage();
});

// Initialize properties page
async function initPropertiesPage() {
  try {
    // Load properties
    allProperties = await KleinsApp.loadProperties();
    filteredProperties = [...allProperties];
    
    // Render properties
    renderProperties();
    
    // Setup event listeners
    setupEventListeners();
    
    // Update pagination
    renderPagination();
  } catch (error) {
    console.error('Error initializing properties page:', error);
    showErrorMessage('Failed to load properties. Please try again later.');
  }
}

// Setup event listeners
function setupEventListeners() {
  // Filter form submission
  const filterForm = document.getElementById('property-filter-form');
  if (filterForm) {
    filterForm.addEventListener('submit', function(e) {
      e.preventDefault();
      applyFilters();
    });
  }
  
  // Sort select change
  const sortSelect = document.getElementById('sort-select');
  if (sortSelect) {
    sortSelect.addEventListener('change', function() {
      sortProperties(this.value);
      renderProperties();
    });
  }
}

// Apply filters
function applyFilters() {
  const locationFilter = document.getElementById('location-filter').value.toLowerCase();
  const typeFilter = document.getElementById('type-filter').value;
  const priceFilter = document.getElementById('price-filter').value;
  const bedroomsFilter = document.getElementById('bedrooms-filter').value;
  
  filteredProperties = allProperties.filter(property => {
    // Location filter
    if (locationFilter && 
        !property.city.toLowerCase().includes(locationFilter) && 
        !property.state.toLowerCase().includes(locationFilter)) {
      return false;
    }
    
    // Type filter
    if (typeFilter && property.type !== typeFilter) {
      return false;
    }
    
    // Price filter
    if (priceFilter) {
      const [min, max] = priceFilter.split('-').map(val => val === '' ? null : Number(val));
      if (min !== null && property.price < min) return false;
      if (max !== null && property.price > max) return false;
    }
    
    // Bedrooms filter
    if (bedroomsFilter && property.bedrooms < parseInt(bedroomsFilter)) {
      return false;
    }
    
    return true;
  });
  
  // Reset to first page
  currentPage = 1;
  
  // Render filtered properties
  renderProperties();
  
  // Update pagination
  renderPagination();
}

// Sort properties
function sortProperties(sortBy) {
  switch (sortBy) {
    case 'price-low':
      filteredProperties.sort((a, b) => a.price - b.price);
      break;
    case 'price-high':
      filteredProperties.sort((a, b) => b.price - a.price);
      break;
    case 'size':
      filteredProperties.sort((a, b) => b.area_sqft - a.area_sqft);
      break;
    case 'newest':
    default:
      // Keep original order
      break;
  }
}

// Render properties
function renderProperties() {
  const container = document.getElementById('properties-container');
  if (!container) return;
  
  // Calculate pagination
  const startIndex = (currentPage - 1) * propertiesPerPage;
  const endIndex = startIndex + propertiesPerPage;
  const paginatedProperties = filteredProperties.slice(startIndex, endIndex);
  
  if (paginatedProperties.length === 0) {
    container.innerHTML = '<p class="text-center text-gray-600 col-span-3">No properties match your search criteria.</p>';
    return;
  }
  
  let html = '';
  paginatedProperties.forEach(property => {
    html += `
      <div class="bg-white rounded-xl overflow-hidden shadow-lg property-card">
        <div class="relative">
          <img src="${property.images[0]}" alt="${property.title}" class="w-full h-64 object-cover">
          <div class="absolute top-4 right-4 bg-primary text-white px-3 py-1 rounded-full text-sm font-semibold">
            ${property.type === 'apartment' || property.type === 'condo' ? 'For Rent' : 'For Sale'}
          </div>
          ${property.is_featured ? `
            <div class="absolute top-4 left-4 bg-secondary text-primary px-3 py-1 rounded-full text-sm font-semibold">
              Featured
            </div>
          ` : ''}
        </div>
        <div class="p-6">
          <div class="flex justify-between items-start">
            <div>
              <h3 class="text-xl font-bold text-gray-800 mb-2">${property.title}</h3>
              <p class="text-gray-600 flex items-center">
                <i class="fas fa-map-marker-alt mr-2"></i> ${property.city}, ${property.state}
              </p>
            </div>
            <div class="text-right">
              <p class="text-2xl font-bold text-primary">
                ${property.type === 'apartment' || property.type === 'condo' ? `$${property.price.toLocaleString()}/mo` : `$${property.price.toLocaleString()}`}
              </p>
            </div>
          </div>
          <p class="text-gray-600 mt-3 line-clamp-2">${property.description}</p>
          <div class="flex justify-between mt-4 pt-4 border-t border-gray-200">
            <div class="flex space-x-4">
              <span class="text-gray-600"><i class="fas fa-bed mr-1"></i> ${property.bedrooms}</span>
              <span class="text-gray-600"><i class="fas fa-bath mr-1"></i> ${property.bathrooms}</span>
              <span class="text-gray-600"><i class="fas fa-ruler-combined mr-1"></i> ${property.area_sqft.toLocaleString()} sqft</span>
            </div>
          </div>
          <a href="property.html?id=${property.id}" class="block w-full mt-6 bg-primary hover:bg-blue-800 text-white font-medium py-3 rounded-lg text-center transition duration-300">
            View Details
          </a>
        </div>
      </div>
    `;
  });
  
  container.innerHTML = html;
}

// Render pagination
function renderPagination() {
  const container = document.getElementById('pagination-container');
  if (!container) return;
  
  const totalPages = Math.ceil(filteredProperties.length / propertiesPerPage);
  
  if (totalPages <= 1) {
    container.innerHTML = '';
    return;
  }
  
  let html = '<nav class="flex space-x-2">';
  
  // Previous button
  if (currentPage > 1) {
    html += `<a href="#" class="px-4 py-2 bg-gray-200 text-gray-700 hover:bg-gray-300 rounded-lg" data-page="${currentPage - 1}">Previous</a>`;
  }
  
  // Page numbers
  for (let i = 1; i <= totalPages; i++) {
    if (i === currentPage) {
      html += `<a href="#" class="px-4 py-2 bg-primary text-white rounded-lg" data-page="${i}">${i}</a>`;
    } else {
      html += `<a href="#" class="px-4 py-2 bg-gray-200 text-gray-700 hover:bg-gray-300 rounded-lg" data-page="${i}">${i}</a>`;
    }
  }
  
  // Next button
  if (currentPage < totalPages) {
    html += `<a href="#" class="px-4 py-2 bg-gray-200 text-gray-700 hover:bg-gray-300 rounded-lg" data-page="${currentPage + 1}">Next</a>`;
  }
  
  html += '</nav>';
  
  container.innerHTML = html;
  
  // Add event listeners to pagination links
  const paginationLinks = container.querySelectorAll('a[data-page]');
  paginationLinks.forEach(link => {
    link.addEventListener('click', function(e) {
      e.preventDefault();
      const page = parseInt(this.getAttribute('data-page'));
      goToPage(page);
    });
  });
}

// Go to specific page
function goToPage(page) {
  currentPage = page;
  renderProperties();
  renderPagination();
  
  // Scroll to top of properties section
  document.getElementById('properties-container').scrollIntoView({ behavior: 'smooth' });
}

// Show error message
function showErrorMessage(message) {
  const container = document.getElementById('properties-container');
  if (container) {
    container.innerHTML = `<p class="text-center text-red-600 col-span-3">${message}</p>`;
  }
}