// script.js: client‑side logic for the guest view (index.html)

document.addEventListener('DOMContentLoaded', () => {
  const propertyListEl = document.getElementById('property-list');
  const searchInput = document.getElementById('search-input');
  let properties = [];

  // Fetch properties from the server
  fetch('/api/properties')
    .then((res) => res.json())
    .then((data) => {
      properties = data;
      renderProperties(properties);
    })
    .catch((err) => {
      console.error('Error fetching properties:', err);
      propertyListEl.innerHTML = '<p>Unable to load properties at this time.</p>';
    });

  // Filter properties based on search input
  searchInput.addEventListener('input', (e) => {
    const query = e.target.value.toLowerCase();
    const filtered = properties.filter(
      (p) =>
        p.location.toLowerCase().includes(query) ||
        p.name.toLowerCase().includes(query)
    );
    renderProperties(filtered);
  });

  /**
   * Render a list of properties into the page.
   * @param {Array} list
   */
  function renderProperties(list) {
    propertyListEl.innerHTML = '';
    if (!list || list.length === 0) {
      propertyListEl.innerHTML = '<p>No properties found.</p>';
      return;
    }
    list.forEach((prop) => {
      const card = document.createElement('div');
      card.className = 'property-card';
      card.innerHTML = `
        <h4>${prop.name}</h4>
        <p><strong>Location:</strong> ${prop.location}</p>
        <p><strong>Price:</strong> BWP ${prop.price} per night</p>
        <p><strong>Available:</strong> ${prop.availableRooms} rooms</p>
        <button class="btn-primary" data-id="${prop.id}">Book Now</button>
      `;
      const btn = card.querySelector('button');
      btn.addEventListener('click', () => openBookingModal(prop));
      propertyListEl.appendChild(card);
    });
  }

  /**
   * Opens a modal prompting the user to book the selected property.
   * @param {Object} prop
   */
  function openBookingModal(prop) {
    // Create modal if it doesn't exist
    let modal = document.getElementById('booking-modal');
    if (!modal) {
      modal = document.createElement('div');
      modal.id = 'booking-modal';
      modal.className = 'modal';
      modal.innerHTML = `
        <div class="modal-content">
          <span class="modal-close" title="Close">×</span>
          <h3 id="modal-title"></h3>
          <input type="text" id="guest-name" placeholder="Your name" required />
          <input type="number" id="rooms" min="1" placeholder="Rooms" required />
          <button class="btn-primary" id="confirm-booking">Confirm Booking</button>
        </div>
      `;
      document.body.appendChild(modal);
      // Attach close handler
      modal.querySelector('.modal-close').addEventListener('click', () => closeModal());
      // Clicking outside content closes modal
      modal.addEventListener('click', (e) => {
        if (e.target === modal) closeModal();
      });
    }
    // Populate modal with property data
    modal.style.display = 'flex';
    modal.querySelector('#modal-title').textContent = `Book ${prop.name}`;
    const roomsInput = modal.querySelector('#rooms');
    roomsInput.max = prop.availableRooms;
    roomsInput.value = 1;
    const confirmBtn = modal.querySelector('#confirm-booking');
    confirmBtn.onclick = () => {
      const guestName = modal.querySelector('#guest-name').value.trim();
      const roomsCount = parseInt(roomsInput.value, 10) || 1;
      if (!guestName) {
        alert('Please enter your name.');
        return;
      }
      if (roomsCount < 1 || roomsCount > prop.availableRooms) {
        alert(`Please enter a valid number of rooms (1–${prop.availableRooms}).`);
        return;
      }
      // Send booking request
      fetch('/api/bookings', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ propertyId: prop.id, rooms: roomsCount, guest: guestName })
      })
        .then((res) => {
          if (!res.ok) throw new Error('Booking failed');
          return res.json();
        })
        .then((data) => {
          alert('Booking successful! Enjoy your stay.');
          closeModal();
          // Refresh property list to show updated availability
          return fetch('/api/properties');
        })
        .then((res) => res.json())
        .then((data) => {
          properties = data;
          renderProperties(properties);
        })
        .catch((err) => {
          console.error(err);
          alert('An error occurred while booking. Please try again.');
        });
    };
  }

  function closeModal() {
    const modal = document.getElementById('booking-modal');
    if (modal) modal.style.display = 'none';
  }
});