<%# External Listings Search Results %>
<div class="external-listings-page">
  <%# Search Header %>
  <div class="bg-gray-50 border-b">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
      <h1 class="text-2xl font-bold text-gray-900">
        <%= t("external_feed.search.title", default: "Property Search") %>
      </h1>
      <p class="mt-1 text-sm text-gray-600">
        <%= t("external_feed.search.subtitle", default: "Browse available properties from our partner network") %>
      </p>
    </div>
  </div>

  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="lg:grid lg:grid-cols-4 lg:gap-8">
      <%# Filters Sidebar %>
      <aside class="lg:col-span-1 mb-8 lg:mb-0">
        <%= render "search_form", filter_options: @filter_options, search_params: @search_params %>
      </aside>

      <%# Results %>
      <main class="lg:col-span-3">
        <%# Results Header %>
        <div class="flex items-center justify-between mb-6">
          <div>
            <% if @result.any? %>
              <p class="text-sm text-gray-700">
                <%= t("external_feed.search.showing",
                      range: @result.results_range,
                      default: "Showing %{range} properties") %>
              </p>
            <% else %>
              <p class="text-sm text-gray-700">
                <%= t("external_feed.search.no_results", default: "No properties found") %>
              </p>
            <% end %>
          </div>

          <%# Sort Dropdown and Save Search Button %>
          <div class="flex items-center gap-4">
            <%# Save Search Button %>
            <button type="button"
                    onclick="openSaveSearchModal()"
                    class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-blue-600 hover:text-blue-800 border border-blue-300 rounded-md hover:bg-blue-50">
              <svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
              </svg>
              Save Search
            </button>

            <div class="flex items-center gap-2">
              <label for="sort" class="text-sm text-gray-600">
                <%= t("external_feed.search.sort_by", default: "Sort by:") %>
              </label>
              <select id="sort" name="sort"
                      class="text-sm border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
                      onchange="updateSort(this.value)">
                <% @filter_options[:sort_options].each do |opt| %>
                  <option value="<%= opt[:value] %>" <%= 'selected' if @search_params[:sort].to_s == opt[:value] %>>
                    <%= opt[:label] %>
                  </option>
                <% end %>
              </select>
            </div>
          </div>
        </div>

        <% if @result.error? %>
          <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-6">
            <div class="flex">
              <div class="flex-shrink-0">
                <svg class="h-5 w-5 text-yellow-400" fill="currentColor" viewBox="0 0 20 20">
                  <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
                </svg>
              </div>
              <div class="ml-3">
                <p class="text-sm text-yellow-700">
                  <%= t("external_feed.search.error", default: "Unable to load properties at this time. Please try again later.") %>
                </p>
              </div>
            </div>
          </div>
        <% end %>

        <%# Property Grid %>
        <% if @result.any? %>
          <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
            <% @result.properties.each do |property| %>
              <%= render "property_card", property: property %>
            <% end %>
          </div>

          <%# Pagination %>
          <% if @result.total_pages > 1 %>
            <%= render "pagination", result: @result %>
          <% end %>
        <% else %>
          <div class="text-center py-12">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/>
            </svg>
            <h3 class="mt-2 text-sm font-medium text-gray-900">
              <%= t("external_feed.search.no_properties", default: "No properties found") %>
            </h3>
            <p class="mt-1 text-sm text-gray-500">
              <%= t("external_feed.search.try_different", default: "Try adjusting your search filters") %>
            </p>
          </div>
        <% end %>
      </main>
    </div>
  </div>
</div>

<%# Save Search Modal %>
<div id="save-search-modal" class="fixed inset-0 z-50 hidden overflow-y-auto">
  <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:p-0">
    <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onclick="closeSaveSearchModal()"></div>

    <div class="relative inline-block bg-white rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:max-w-lg sm:w-full sm:p-6">
      <div class="absolute top-0 right-0 pt-4 pr-4">
        <button type="button" onclick="closeSaveSearchModal()" class="text-gray-400 hover:text-gray-500">
          <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <div class="sm:flex sm:items-start">
        <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-blue-100 sm:mx-0 sm:h-10 sm:w-10">
          <svg class="h-6 w-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
          </svg>
        </div>
        <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left flex-1">
          <h3 class="text-lg leading-6 font-medium text-gray-900">
            Save This Search
          </h3>
          <p class="mt-2 text-sm text-gray-500">
            Get email alerts when new properties match your search criteria.
          </p>
        </div>
      </div>

      <%= form_with url: my_saved_searches_path, method: :post, local: true, id: "save-search-form", class: "mt-5" do |f| %>
        <input type="hidden" name="saved_search[search_criteria]" value="<%= @search_params.to_json %>">

        <div class="space-y-4">
          <div>
            <label for="save_search_email" class="block text-sm font-medium text-gray-700">
              Email Address
            </label>
            <input type="email" name="saved_search[email]" id="save_search_email" required
                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                   placeholder="your@email.com">
          </div>

          <div>
            <label for="save_search_name" class="block text-sm font-medium text-gray-700">
              Search Name (optional)
            </label>
            <input type="text" name="saved_search[name]" id="save_search_name"
                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                   placeholder="e.g., My Dream Home Search">
          </div>

          <div>
            <label for="save_search_frequency" class="block text-sm font-medium text-gray-700">
              Alert Frequency
            </label>
            <select name="saved_search[alert_frequency]" id="save_search_frequency"
                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm">
              <option value="daily">Daily - Get notified once per day</option>
              <option value="weekly">Weekly - Get notified once per week</option>
              <option value="none">No alerts - Just save the search</option>
            </select>
          </div>
        </div>

        <div class="mt-5 sm:mt-6 sm:flex sm:flex-row-reverse gap-3">
          <button type="submit"
                  class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm">
            Save Search
          </button>
          <button type="button" onclick="closeSaveSearchModal()"
                  class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:w-auto sm:text-sm">
            Cancel
          </button>
        </div>
      <% end %>
    </div>
  </div>
</div>

<%# Favorite Property Modal %>
<div id="favorite-modal" class="fixed inset-0 z-50 hidden overflow-y-auto">
  <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:p-0">
    <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onclick="closeFavoriteModal()"></div>

    <div class="relative inline-block bg-white rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:max-w-lg sm:w-full sm:p-6">
      <div class="absolute top-0 right-0 pt-4 pr-4">
        <button type="button" onclick="closeFavoriteModal()" class="text-gray-400 hover:text-gray-500">
          <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <div class="sm:flex sm:items-start">
        <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
          <svg class="h-6 w-6 text-red-600" fill="currentColor" viewBox="0 0 24 24">
            <path d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
          </svg>
        </div>
        <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left flex-1">
          <h3 class="text-lg leading-6 font-medium text-gray-900">
            Save to Favorites
          </h3>
          <p class="mt-2 text-sm text-gray-500" id="favorite-property-name">
            Enter your email to save this property.
          </p>
        </div>
      </div>

      <%= form_with url: my_favorites_path, method: :post, local: true, id: "favorite-form", class: "mt-5" do |f| %>
        <input type="hidden" name="saved_property[external_reference]" id="favorite-reference">
        <input type="hidden" name="saved_property[provider]" value="<%= current_website.external_feed_provider %>">
        <input type="hidden" name="saved_property[property_data]" id="favorite-property-data" value="{}">

        <div class="space-y-4">
          <div>
            <label for="favorite_email" class="block text-sm font-medium text-gray-700">
              Email Address
            </label>
            <input type="email" name="saved_property[email]" id="favorite_email" required
                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                   placeholder="your@email.com">
          </div>

          <div>
            <label for="favorite_notes" class="block text-sm font-medium text-gray-700">
              Notes (optional)
            </label>
            <textarea name="saved_property[notes]" id="favorite_notes" rows="2"
                      class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
                      placeholder="e.g., Great location, needs to visit..."></textarea>
          </div>
        </div>

        <div class="mt-5 sm:mt-6 sm:flex sm:flex-row-reverse gap-3">
          <button type="submit"
                  class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:w-auto sm:text-sm">
            Save to Favorites
          </button>
          <button type="button" onclick="closeFavoriteModal()"
                  class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:w-auto sm:text-sm">
            Cancel
          </button>
        </div>
      <% end %>
    </div>
  </div>
</div>

<script>
  function updateSort(value) {
    const url = new URL(window.location.href);
    url.searchParams.set('sort', value);
    window.location.href = url.toString();
  }

  function openSaveSearchModal() {
    document.getElementById('save-search-modal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
  }

  function closeSaveSearchModal() {
    document.getElementById('save-search-modal').classList.add('hidden');
    document.body.style.overflow = '';
  }

  function toggleFavorite(event, reference, title) {
    event.preventDefault();
    event.stopPropagation();

    document.getElementById('favorite-reference').value = reference;
    document.getElementById('favorite-property-name').textContent = title;
    document.getElementById('favorite-modal').classList.remove('hidden');
    document.body.style.overflow = 'hidden';
  }

  function closeFavoriteModal() {
    document.getElementById('favorite-modal').classList.add('hidden');
    document.body.style.overflow = '';
  }

  // Close modals on escape key
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
      closeSaveSearchModal();
      closeFavoriteModal();
    }
  });
</script>
