// Property details page JavaScript for KLEINS REAL ESTATE

// DOM Ready
document.addEventListener('DOMContentLoaded', function() {
  // Initialize property details page
  initPropertyPage();
});

// Initialize property details page
async function initPropertyPage() {
  try {
    // Get property ID from URL
    const urlParams = new URLSearchParams(window.location.search);
    const propertyId = urlParams.get('id');
    
    if (!propertyId) {
      showErrorMessage('No property specified.');
      return;
    }
    
    // Load properties
    const properties = await KleinsApp.loadProperties();
    
    // Find the specific property
    const property = properties.find(p => p.id === propertyId);
    
    if (!property) {
      showErrorMessage('Property not found.');
      return;
    }
    
    // Render property details
    renderPropertyDetails(property);
    
    // Setup event listeners
    setupEventListeners();
    
  } catch (error) {
    console.error('Error initializing property page:', error);
    showErrorMessage('Failed to load property details. Please try again later.');
  }
}

// Render property details
function renderPropertyDetails(property) {
  // Update page title
  document.title = `${property.title} - KLEINS REAL ESTATE`;
  
  // Update header details
  const pageTitle = document.querySelector('h1');
  if (pageTitle) pageTitle.textContent = property.title;
  
  const pageLocation = document.querySelector('p.flex.items-center');
  if (pageLocation) pageLocation.innerHTML = `<i class="fas fa-map-marker-alt mr-2"></i> ${property.address}, ${property.city}, ${property.state} ${property.zip_code}`;
  
  const pagePrice = document.querySelector('p.text-3xl.font-bold');
  if (pagePrice) {
    pagePrice.textContent = property.type === 'apartment' || property.type === 'condo' ? 
      `$${property.price.toLocaleString()}/mo` : 
      `$${property.price.toLocaleString()}`;
  }
  
  const propertyType = document.querySelector('span.inline-block.bg-primary');
  if (propertyType) propertyType.textContent = property.type === 'apartment' || property.type === 'condo' ? 'For Rent' : 'For Sale';
  
  // Update description
  const descriptionElement = document.querySelector('div.mb-8 > p:first-of-type');
  if (descriptionElement) descriptionElement.textContent = property.description.split('.')[0] + '.';
  
  const descriptionElement2 = document.querySelector('div.mb-8 > p:last-of-type');
  if (descriptionElement2) descriptionElement2.textContent = property.description.split('. ').slice(1).join('. ') + '.';
  
  // Update features
  const featuresList = document.querySelector('div.grid.grid-cols-1.md\\:grid-cols-2.gap-4 ul');
  if (featuresList) {
    featuresList.innerHTML = '';
    property.features.slice(0, 4).forEach(feature => {
      const li = document.createElement('li');
      li.className = 'flex items-center';
      li.innerHTML = `<i class="fas fa-check text-secondary mr-2"></i><span>${feature}</span>`;
      featuresList.appendChild(li);
    });
  }
  
  const featuresList2 = document.querySelector('div.grid.grid-cols-1.md\\:grid-cols-2.gap-4 ul:last-of-type');
  if (featuresList2) {
    featuresList2.innerHTML = '';
    property.features.slice(4).forEach(feature => {
      const li = document.createElement('li');
      li.className = 'flex items-center';
      li.innerHTML = `<i class="fas fa-check text-secondary mr-2"></i><span>${feature}</span>`;
      featuresList2.appendChild(li);
    });
  }
  
  // Update property details table
  const propertyDetails = document.querySelectorAll('div.flex.justify-between.border-b');
  if (propertyDetails.length >= 8) {
    propertyDetails[0].querySelector('span.font-medium').textContent = property.id;
    propertyDetails[1].querySelector('span.font-medium').textContent = property.type.charAt(0).toUpperCase() + property.type.slice(1);
    propertyDetails[2].querySelector('span.font-medium').textContent = property.bedrooms;
    propertyDetails[3].querySelector('span.font-medium').textContent = property.bathrooms;
    propertyDetails[4].querySelector('span.font-medium').textContent = `${property.area_sqft.toLocaleString()} sqft`;
    propertyDetails[5].querySelector('span.font-medium').textContent = '2025'; // Assuming current year
    propertyDetails[6].querySelector('span.font-medium').textContent = property.type === 'house' ? '2 cars' : 'N/A';
    propertyDetails[7].querySelector('span.font-medium').textContent = property.is_active ? 'Active' : 'Inactive';
  }
  
  // Update apply button with property ID
  const applyButton = document.querySelector('a[href^="contact.html"]');
  if (applyButton) {
    applyButton.href = `contact.html?property_id=${property.id}`;
  }
  
  // Update image placeholders with actual images
  const mainImage = document.querySelector('div.relative.rounded-xl.overflow-hidden.mb-4');
  if (mainImage) {
    mainImage.innerHTML = `<img src="${property.images[0]}" alt="${property.title}" class="w-full h-full object-cover">`;
  }
  
  // Update thumbnails
  const thumbnailContainer = document.querySelector('div.flex.space-x-4.overflow-x-auto');
  if (thumbnailContainer) {
    thumbnailContainer.innerHTML = '';
    property.images.forEach((image, index) => {
      const thumbDiv = document.createElement('div');
      thumbDiv.className = `w-24 h-24 rounded-lg overflow-hidden flex-shrink-0 ${index === 0 ? 'border-2 border-primary' : 'border border-gray-300'}`;
      thumbDiv.innerHTML = `<img src="${image}" alt="${property.title}" class="w-full h-full object-cover">`;
      thumbnailContainer.appendChild(thumbDiv);
    });
  }
}

// Setup event listeners
function setupEventListeners() {
  // Add any specific event listeners for the property page
  // For example, thumbnail click handlers, contact form prefilling, etc.
}

// Show error message
function showErrorMessage(message) {
  const mainSection = document.querySelector('section.py-12');
  if (mainSection) {
    mainSection.innerHTML = `
      <div class="container mx-auto px-4">
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
          <strong class="font-bold">Error: </strong>
          <span class="block sm:inline">${message}</span>
        </div>
      </div>
    `;
  }
}