<div class="max-w-6xl mx-auto">
  <%= render 'header' %>
  <div class="bg-white rounded-lg shadow overflow-hidden">
    <%= render 'navigation', current_tab: 'labels' %>
    <div class="p-6">
      <%= form_with url: site_admin_prop_path(@prop), method: :patch, local: true do |f| %>
        <div class="mb-6">
          <p class="text-sm text-gray-600">
            Select labels to categorize this property. Categories match those defined in
            <%= link_to 'Properties Settings', site_admin_properties_settings_path, class: 'text-blue-600 hover:underline' %>.
          </p>
        </div>

        <%
          # Create a human-readable label from key using FieldKey with Mobility
          label_text = ->(key) {
            return key.to_s if key.blank?
            field_key = Pwb::FieldKey.find_by(global_key: key)
            field_key&.display_label || key.to_s.split('.').last&.humanize&.titleize || key
          }
        %>

        <div class="space-y-8">
          <% @label_categories.each do |tag, info| %>
            <% labels = @labels_by_category[tag] || [] %>
            <% next if labels.empty? %>

            <div class="border rounded-lg p-4">
              <div class="mb-4">
                <h3 class="text-lg font-semibold text-gray-900"><%= info[:title] %></h3>
                <p class="text-sm text-gray-500"><%= info[:description] %></p>
              </div>

              <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                <% labels.each do |label_key| %>
                  <label class="flex items-center p-2 rounded hover:bg-gray-50">
                    <input type="checkbox"
                           name="features[]"
                           value="<%= label_key %>"
                           <%= 'checked' if @current_features.include?(label_key) %>
                           class="rounded text-blue-600 focus:ring-blue-500">
                    <span class="ml-2 text-sm text-gray-700"><%= label_text.call(label_key) %></span>
                  </label>
                <% end %>
              </div>
            </div>
          <% end %>
        </div>

        <!-- Hidden field to ensure empty features array is submitted when nothing is checked -->
        <input type="hidden" name="features[]" value="">

        <!-- Form Actions -->
        <div class="flex justify-end items-center mt-8 pt-6 border-t border-gray-200">
          <div class="flex space-x-3">
            <%= link_to 'Cancel', site_admin_prop_path(@prop), class: 'px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50' %>
            <%= f.submit 'Save Changes', class: 'px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 cursor-pointer' %>
          </div>
        </div>
      <% end %>
    </div>
  </div>
</div>
