<div class="max-w-6xl mx-auto">
  <%= render 'header' %>
  <div class="bg-white rounded-lg shadow overflow-hidden">
    <%= render 'navigation', current_tab: 'text' %>
    <div class="p-6">
      <div class="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-md">
        <p class="text-sm text-blue-700">
          <strong>Note:</strong> Title and description are marketing text that belongs to each listing.
          <% if @sale_listing.nil? && @rental_listing.nil? %>
            <br><span class="text-amber-700"><strong>Warning:</strong> No listings exist yet. Create a Sale or Rental listing first in the Sale/Rental tab.</span>
          <% end %>
        </p>
      </div>

      <% if @sale_listing.present? %>
        <div class="mb-8">
          <h3 class="text-xl font-bold text-gray-900 mb-4 flex items-center">
            <span class="bg-green-100 text-green-800 text-xs font-semibold px-2.5 py-0.5 rounded mr-2">FOR SALE</span>
            Sale Listing Text
          </h3>
          <%= form_with model: @sale_listing, url: site_admin_prop_path(@prop), method: :patch, local: true, scope: :sale_listing do |f| %>
            <% %w[en es].each do |locale| %>
              <div class="mb-6 pb-6 border-b border-gray-200 last:border-0">
                <h4 class="text-md font-semibold text-gray-700 mb-3">
                  <%= locale.upcase %>
                </h4>
                <div class="grid grid-cols-1 gap-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                      Title (<%= locale %>)
                    </label>
                    <%= f.text_field "title_#{locale}",
                        value: @sale_listing.send("title_#{locale}"),
                        class: "block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm",
                        placeholder: "Property title in #{locale}..." %>
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                      Description (<%= locale %>)
                    </label>
                    <%= f.text_area "description_#{locale}",
                        value: @sale_listing.send("description_#{locale}"),
                        rows: 4,
                        class: "block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm",
                        placeholder: "Property description in #{locale}..." %>
                  </div>
                  <!-- SEO Fields for this locale -->
                  <details class="group mt-2">
                    <summary class="flex items-center cursor-pointer list-none text-sm text-gray-600 hover:text-gray-800">
                      <svg class="w-4 h-4 mr-1 group-open:rotate-90 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                      </svg>
                      SEO Settings (<%= locale %>)
                    </summary>
                    <div class="mt-3 ml-5 space-y-4 p-4 bg-gray-50 rounded-md">
                      <p class="text-xs text-gray-500">
                        Customize how this listing appears in search engines. Leave blank to use title/description above.
                      </p>

                      <!-- Google Preview -->
                      <div class="p-3 bg-white rounded border border-gray-200">
                        <p class="text-xs font-medium text-gray-500 mb-2">Google Preview</p>
                        <div class="google-preview" data-locale="<%= locale %>" data-listing="sale">
                          <p class="text-blue-800 text-lg font-normal hover:underline cursor-pointer truncate preview-title">
                            <%= @sale_listing.send("seo_title_#{locale}").presence || @sale_listing.send("title_#{locale}").presence || "Property Title" %>
                          </p>
                          <p class="text-green-700 text-sm preview-url">
                            <%= request.host %>/properties/for-sale/...
                          </p>
                          <p class="text-gray-600 text-sm line-clamp-2 preview-description">
                            <%= @sale_listing.send("meta_description_#{locale}").presence || @sale_listing.send("description_#{locale}").to_s.truncate(160) %>
                          </p>
                        </div>
                      </div>

                      <div>
                        <label class="block text-xs font-medium text-gray-600 mb-1">
                          SEO Title <span class="text-gray-400">(50-60 chars recommended)</span>
                        </label>
                        <%= f.text_field "seo_title_#{locale}",
                            value: @sale_listing.send("seo_title_#{locale}"),
                            class: "seo-field block w-full px-2 py-1.5 text-sm border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500",
                            placeholder: "Custom SEO title...",
                            maxlength: 70,
                            id: "sale_seo_title_#{locale}",
                            data: { max_length: 70, optimal_max: 60, preview_target: "title", listing: "sale", locale: locale } %>
                        <p class="mt-1 text-xs text-gray-500 char-counter" data-for="sale_listing_seo_title_<%= locale %>">0 / 70 characters</p>
                      </div>
                      <div>
                        <label class="block text-xs font-medium text-gray-600 mb-1">
                          Meta Description <span class="text-gray-400">(150-160 chars recommended)</span>
                        </label>
                        <%= f.text_area "meta_description_#{locale}",
                            value: @sale_listing.send("meta_description_#{locale}"),
                            rows: 2,
                            class: "seo-field block w-full px-2 py-1.5 text-sm border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500",
                            placeholder: "Custom meta description...",
                            maxlength: 200,
                            id: "sale_meta_description_#{locale}",
                            data: { max_length: 200, optimal_max: 160, preview_target: "description", listing: "sale", locale: locale } %>
                        <p class="mt-1 text-xs text-gray-500 char-counter" data-for="sale_listing_meta_description_<%= locale %>">0 / 200 characters</p>
                      </div>
                    </div>
                  </details>
                </div>
              </div>
            <% end %>

            <div class="flex justify-end mt-6">
              <%= f.submit 'Save Sale Listing Text', class: 'px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 cursor-pointer' %>
            </div>
          <% end %>
        </div>
      <% end %>

      <% if @rental_listing.present? %>
        <div class="mb-8">
          <h3 class="text-xl font-bold text-gray-900 mb-4 flex items-center">
            <span class="bg-purple-100 text-purple-800 text-xs font-semibold px-2.5 py-0.5 rounded mr-2">FOR RENT</span>
            Rental Listing Text
          </h3>
          <%= form_with model: @rental_listing, url: site_admin_prop_path(@prop), method: :patch, local: true, scope: :rental_listing do |f| %>
            <% %w[en es].each do |locale| %>
              <div class="mb-6 pb-6 border-b border-gray-200 last:border-0">
                <h4 class="text-md font-semibold text-gray-700 mb-3">
                  <%= locale.upcase %>
                </h4>
                <div class="grid grid-cols-1 gap-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                      Title (<%= locale %>)
                    </label>
                    <%= f.text_field "title_#{locale}",
                        value: @rental_listing.send("title_#{locale}"),
                        class: "block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm",
                        placeholder: "Property title in #{locale}..." %>
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                      Description (<%= locale %>)
                    </label>
                    <%= f.text_area "description_#{locale}",
                        value: @rental_listing.send("description_#{locale}"),
                        rows: 4,
                        class: "block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm",
                        placeholder: "Property description in #{locale}..." %>
                  </div>
                  <!-- SEO Fields for this locale -->
                  <details class="group mt-2">
                    <summary class="flex items-center cursor-pointer list-none text-sm text-gray-600 hover:text-gray-800">
                      <svg class="w-4 h-4 mr-1 group-open:rotate-90 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                      </svg>
                      SEO Settings (<%= locale %>)
                    </summary>
                    <div class="mt-3 ml-5 space-y-4 p-4 bg-gray-50 rounded-md">
                      <p class="text-xs text-gray-500">
                        Customize how this listing appears in search engines. Leave blank to use title/description above.
                      </p>

                      <!-- Google Preview -->
                      <div class="p-3 bg-white rounded border border-gray-200">
                        <p class="text-xs font-medium text-gray-500 mb-2">Google Preview</p>
                        <div class="google-preview" data-locale="<%= locale %>" data-listing="rental">
                          <p class="text-blue-800 text-lg font-normal hover:underline cursor-pointer truncate preview-title">
                            <%= @rental_listing.send("seo_title_#{locale}").presence || @rental_listing.send("title_#{locale}").presence || "Property Title" %>
                          </p>
                          <p class="text-green-700 text-sm preview-url">
                            <%= request.host %>/properties/for-rent/...
                          </p>
                          <p class="text-gray-600 text-sm line-clamp-2 preview-description">
                            <%= @rental_listing.send("meta_description_#{locale}").presence || @rental_listing.send("description_#{locale}").to_s.truncate(160) %>
                          </p>
                        </div>
                      </div>

                      <div>
                        <label class="block text-xs font-medium text-gray-600 mb-1">
                          SEO Title <span class="text-gray-400">(50-60 chars recommended)</span>
                        </label>
                        <%= f.text_field "seo_title_#{locale}",
                            value: @rental_listing.send("seo_title_#{locale}"),
                            class: "seo-field block w-full px-2 py-1.5 text-sm border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500",
                            placeholder: "Custom SEO title...",
                            maxlength: 70,
                            id: "rental_seo_title_#{locale}",
                            data: { max_length: 70, optimal_max: 60, preview_target: "title", listing: "rental", locale: locale } %>
                        <p class="mt-1 text-xs text-gray-500 char-counter" data-for="rental_listing_seo_title_<%= locale %>">0 / 70 characters</p>
                      </div>
                      <div>
                        <label class="block text-xs font-medium text-gray-600 mb-1">
                          Meta Description <span class="text-gray-400">(150-160 chars recommended)</span>
                        </label>
                        <%= f.text_area "meta_description_#{locale}",
                            value: @rental_listing.send("meta_description_#{locale}"),
                            rows: 2,
                            class: "seo-field block w-full px-2 py-1.5 text-sm border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500",
                            placeholder: "Custom meta description...",
                            maxlength: 200,
                            id: "rental_meta_description_#{locale}",
                            data: { max_length: 200, optimal_max: 160, preview_target: "description", listing: "rental", locale: locale } %>
                        <p class="mt-1 text-xs text-gray-500 char-counter" data-for="rental_listing_meta_description_<%= locale %>">0 / 200 characters</p>
                      </div>
                    </div>
                  </details>
                </div>
              </div>
            <% end %>

            <div class="flex justify-end mt-6">
              <%= f.submit 'Save Rental Listing Text', class: 'px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-purple-600 hover:bg-purple-700 cursor-pointer' %>
            </div>
          <% end %>
        </div>
      <% end %>

      <% if @sale_listing.nil? && @rental_listing.nil? %>
        <div class="text-center py-12">
          <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          <h3 class="mt-2 text-sm font-medium text-gray-900">No listings yet</h3>
          <p class="mt-1 text-sm text-gray-500">Create a sale or rental listing first to add marketing text.</p>
          <div class="mt-6">
            <%= link_to 'Go to Sale/Rental Tab', edit_sale_rental_site_admin_prop_path(@prop), class: 'inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700' %>
          </div>
        </div>
      <% end %>

      <!-- Back Link -->
      <div class="flex justify-start items-center mt-8 pt-6 border-t border-gray-200">
        <%= link_to '&larr; Back to Properties'.html_safe, site_admin_props_path, class: 'text-blue-600 hover:text-blue-800' %>
      </div>
    </div>
  </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function() {
    // Initialize character counters for SEO fields
    const seoFields = document.querySelectorAll('.seo-field');

    seoFields.forEach(function(field) {
      const maxLength = parseInt(field.dataset.maxLength) || 200;
      const optimalMax = parseInt(field.dataset.optimalMax) || maxLength;
      const counter = field.parentElement.querySelector('.char-counter');

      function updateCounter() {
        const length = field.value.length;
        counter.textContent = length + ' / ' + maxLength + ' characters';

        // Color coding based on length
        counter.classList.remove('text-gray-500', 'text-yellow-600', 'text-red-600', 'text-green-600');

        if (length === 0) {
          counter.classList.add('text-gray-500');
        } else if (length <= optimalMax) {
          counter.classList.add('text-green-600');
        } else if (length <= maxLength) {
          counter.classList.add('text-yellow-600');
        } else {
          counter.classList.add('text-red-600');
        }
      }

      // Initial update
      updateCounter();

      // Update on input
      field.addEventListener('input', updateCounter);

      // Update Google preview if this field affects it
      const previewTarget = field.dataset.previewTarget;
      const listing = field.dataset.listing;
      const locale = field.dataset.locale;

      if (previewTarget && listing && locale) {
        field.addEventListener('input', function() {
          const preview = document.querySelector(`.google-preview[data-listing="${listing}"][data-locale="${locale}"]`);
          if (preview) {
            const targetEl = preview.querySelector(`.preview-${previewTarget}`);
            if (targetEl && this.value.trim()) {
              targetEl.textContent = this.value.trim();
            }
          }
        });
      }
    });

    // Also update preview when title/description (non-SEO fields) change
    const titleFields = document.querySelectorAll('input[name*="title_"]');
    const descFields = document.querySelectorAll('textarea[name*="description_"]');

    titleFields.forEach(function(field) {
      field.addEventListener('input', function() {
        // Extract locale from field name (e.g., sale_listing[title_en])
        const nameMatch = this.name.match(/(sale|rental)_listing\[title_(\w+)\]/);
        if (nameMatch) {
          const listing = nameMatch[1];
          const locale = nameMatch[2];
          const seoField = document.getElementById(`${listing}_seo_title_${locale}`);
          // Only update preview if SEO field is empty
          if (!seoField || !seoField.value.trim()) {
            const preview = document.querySelector(`.google-preview[data-listing="${listing}"][data-locale="${locale}"]`);
            if (preview) {
              const titleEl = preview.querySelector('.preview-title');
              if (titleEl) {
                titleEl.textContent = this.value.trim() || 'Property Title';
              }
            }
          }
        }
      });
    });

    descFields.forEach(function(field) {
      field.addEventListener('input', function() {
        const nameMatch = this.name.match(/(sale|rental)_listing\[description_(\w+)\]/);
        if (nameMatch) {
          const listing = nameMatch[1];
          const locale = nameMatch[2];
          const seoField = document.getElementById(`${listing}_meta_description_${locale}`);
          // Only update preview if SEO field is empty
          if (!seoField || !seoField.value.trim()) {
            const preview = document.querySelector(`.google-preview[data-listing="${listing}"][data-locale="${locale}"]`);
            if (preview) {
              const descEl = preview.querySelector('.preview-description');
              if (descEl) {
                const truncated = this.value.trim().substring(0, 160);
                descEl.textContent = truncated || 'Property description...';
              }
            }
          }
        }
      });
    });
  });
</script>
