// Main application JavaScript for KLEINS REAL ESTATE

// Configuration
const CONFIG = {
  FORM_SUBMIT_URL: '', // Empty by default, can be set for production
  PROPERTY_DATA_URL: 'data/properties.json'
};

// DOM Ready
document.addEventListener('DOMContentLoaded', function() {
  // Load header and footer
  loadHeaderFooter();
  
  // Initialize page-specific functionality
  initPage();
});

// Load header and footer partials
async function loadHeaderFooter() {
  try {
    // Load header
    const headerResponse = await fetch('partials/header.html');
    if (headerResponse.ok) {
      const headerHTML = await headerResponse.text();
      const headerPlaceholder = document.getElementById('header-placeholder');
      if (headerPlaceholder) {
        headerPlaceholder.innerHTML = headerHTML;
        setActiveNavLink();
      }
    }
    
    // Load footer
    const footerResponse = await fetch('partials/footer.html');
    if (footerResponse.ok) {
      const footerHTML = await footerResponse.text();
      const footerPlaceholder = document.getElementById('footer-placeholder');
      if (footerPlaceholder) {
        footerPlaceholder.innerHTML = footerHTML;
      }
    }
  } catch (error) {
    console.error('Error loading header/footer:', error);
  }
}

// Set active navigation link based on current page
function setActiveNavLink() {
  const currentPage = getCurrentPageName();
  const navLinks = document.querySelectorAll('.nav-link');
  
  navLinks.forEach(link => {
    // Remove active class from all links
    link.classList.remove('text-primary', 'font-bold');
    link.classList.add('text-gray-600');
    
    // Add active class to current page link
    const linkHref = link.getAttribute('href');
    if (linkHref && linkHref.includes(currentPage)) {
      link.classList.remove('text-gray-600');
      link.classList.add('text-primary', 'font-bold');
    }
  });
}

// Get current page name
function getCurrentPageName() {
  const path = window.location.pathname;
  const page = path.split('/').pop();
  return page || 'home.html';
}

// Initialize page-specific functionality
function initPage() {
  const page = getCurrentPageName();
  
  switch (page) {
    case 'home.html':
      initHomePage();
      break;
    case 'properties.html':
      // Properties page functionality is handled by properties.js
      break;
    case 'property.html':
      // Property details page functionality is handled by property.js
      break;
    case 'contact.html':
      // Contact form functionality is handled by form.js
      break;
    default:
      // Default initialization for other pages
      break;
  }
}

// Initialize home page
async function initHomePage() {
  try {
    // Load featured properties
    const properties = await loadProperties();
    const featuredProperties = properties.filter(property => property.is_featured);
    renderFeaturedProperties(featuredProperties);
  } catch (error) {
    console.error('Error initializing home page:', error);
    // Show error message or fallback content
    const container = document.getElementById('featured-properties');
    if (container) {
      container.innerHTML = '<p class="text-center text-gray-600">Failed to load featured properties. Please try again later.</p>';
    }
  }
}

// Load properties from JSON file
async function loadProperties() {
  try {
    const response = await fetch(CONFIG.PROPERTY_DATA_URL);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const properties = await response.json();
    return properties;
  } catch (error) {
    console.error('Error loading properties:', error);
    throw error;
  }
}

// Render featured properties on home page
function renderFeaturedProperties(properties) {
  const container = document.getElementById('featured-properties');
  if (!container) return;
  
  if (properties.length === 0) {
    container.innerHTML = '<p class="text-center text-gray-600">No featured properties available at this time.</p>';
    return;
  }
  
  let html = '';
  properties.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 === 'rent' ? 'For Rent' : 'For Sale'}
          </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 === 'rent' ? `$${property.price.toLocaleString()}/mo` : `$${property.price.toLocaleString()}`}
              </p>
            </div>
          </div>
          <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;
}

// Format currency
function formatCurrency(amount) {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  }).format(amount);
}

// Export functions for use in other modules
window.KleinsApp = {
  CONFIG,
  loadProperties,
  formatCurrency
};