<%
  # Determine the public page URL for previews
  page_path = @page.slug == 'home' ? '/' : "/p/#{@page.slug}"
  public_page_url = "#{request.protocol}#{request.host_with_port}#{page_path}"
%>

<div class="max-w-6xl mx-auto">
  <!-- Header -->
  <div class="mb-6 flex items-center justify-between">
    <%= link_to '← Back to Pages', site_admin_pages_path, class: 'text-blue-600 hover:text-blue-800' %>
    <div class="flex items-center gap-3">
      <%= link_to public_page_url, target: '_blank', class: 'inline-flex items-center px-3 py-1.5 border border-gray-300 text-gray-700 text-sm rounded-lg hover:bg-gray-50' do %>
        <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="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path>
        </svg>
        View Live Page
      <% end %>
      <%= link_to settings_site_admin_page_path(@page), class: 'inline-flex items-center px-3 py-1.5 text-sm text-gray-600 hover:text-gray-900 border border-gray-300 rounded-lg hover:bg-gray-100' do %>
        <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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
        </svg>
        Page Settings
      <% end %>
    </div>
  </div>

  <!-- Page Title -->
  <div class="bg-white rounded-lg shadow overflow-hidden mb-6">
    <div class="px-6 py-5">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">Edit: <%= @page.slug.titleize %></h1>
          <p class="text-sm text-gray-500 mt-1">
            <span class="font-mono bg-gray-100 px-2 py-0.5 rounded">/<%= @page.slug %></span>
            <span class="mx-2">&middot;</span>
            <span><%= @page_parts.count %> content section<%= @page_parts.count == 1 ? '' : 's' %></span>
          </p>
        </div>
      </div>
    </div>
  </div>

  <!-- Page Parts List -->
  <div class="bg-white rounded-lg shadow overflow-hidden">
    <div class="px-6 py-4 border-b border-gray-200">
      <h2 class="text-lg font-semibold text-gray-900">Content Sections</h2>
      <p class="text-sm text-gray-500">Drag and drop to reorder sections. Changes are saved automatically.</p>
    </div>

    <% if @page_parts.any? %>
      <div id="page-parts-sortable" class="divide-y divide-gray-100" data-reorder-url="<%= reorder_parts_site_admin_page_path(@page) %>">
        <% @page_parts.each do |page_part| %>
          <% editor_setup = page_part.editor_setup || {} %>
          <% tab_title = editor_setup['tabTitleKey'] ? I18n.t(editor_setup['tabTitleKey'], default: page_part.page_part_key.titleize) : page_part.page_part_key.titleize %>
          <% page_content = @page.page_contents.find_by(page_part_key: page_part.page_part_key) %>
          <% is_visible = page_content&.visible_on_page %>
          <% preview_url = "#{request.protocol}#{request.host_with_port}/p/#{@page.slug}/#{page_part.page_part_key}" %>

          <div class="page-part-item" data-part-id="<%= page_part.id %>">
            <!-- Header Row -->
            <div class="px-6 py-4 flex items-center justify-between bg-white hover:bg-gray-50 transition-colors">
              <div class="flex items-center flex-1">
                <!-- Drag Handle -->
                <div class="drag-handle cursor-grab active:cursor-grabbing mr-4 p-1 text-gray-400 hover:text-gray-600">
                  <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M7 2a2 2 0 1 0 .001 4.001A2 2 0 0 0 7 2zm0 6a2 2 0 1 0 .001 4.001A2 2 0 0 0 7 8zm0 6a2 2 0 1 0 .001 4.001A2 2 0 0 0 7 14zm6-8a2 2 0 1 0-.001-4.001A2 2 0 0 0 13 6zm0 2a2 2 0 1 0 .001 4.001A2 2 0 0 0 13 8zm0 6a2 2 0 1 0 .001 4.001A2 2 0 0 0 13 14z"></path>
                  </svg>
                </div>

                <!-- Section Icon -->
                <div class="w-10 h-10 rounded-lg bg-blue-50 border border-blue-100 flex items-center justify-center mr-4">
                  <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z"></path>
                  </svg>
                </div>

                <!-- Section Info -->
                <div class="flex-1">
                  <p class="font-medium text-gray-900"><%= tab_title %></p>
                  <p class="text-sm text-gray-500"><%= page_part.page_part_key %></p>
                </div>
              </div>

              <div class="flex items-center gap-3">
                <!-- Preview Toggle -->
                <button type="button"
                        onclick="togglePreview('<%= page_part.id %>')"
                        id="preview-btn-<%= page_part.id %>"
                        class="inline-flex items-center px-2.5 py-1 text-xs rounded-lg border border-gray-300 text-gray-600 hover:bg-gray-100 transition-colors"
                        title="Toggle preview">
                  <svg class="w-3.5 h-3.5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"></path>
                  </svg>
                  <span class="btn-text">Hide</span>
                </button>

                <!-- Visibility Toggle -->
                <% if page_content %>
                  <%= button_to toggle_visibility_site_admin_page_page_part_path(@page, page_part),
                                method: :patch,
                                class: "inline-flex items-center px-2.5 py-1 text-xs rounded-full cursor-pointer transition-colors #{is_visible ? 'bg-green-100 text-green-700 hover:bg-green-200' : 'bg-gray-200 text-gray-600 hover:bg-gray-300'}",
                                title: is_visible ? 'Click to hide this section' : 'Click to show this section',
                                data: { turbo: false } do %>
                    <% if is_visible %>
                      <svg class="w-3.5 h-3.5 mr-1" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M10 12a2 2 0 100-4 2 2 0 000 4z"></path>
                        <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd"></path>
                      </svg>
                      Visible
                    <% else %>
                      <svg class="w-3.5 h-3.5 mr-1" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M3.707 2.293a1 1 0 00-1.414 1.414l14 14a1 1 0 001.414-1.414l-1.473-1.473A10.014 10.014 0 0019.542 10C18.268 5.943 14.478 3 10 3a9.958 9.958 0 00-4.512 1.074l-1.78-1.781zm4.261 4.26l1.514 1.515a2.003 2.003 0 012.45 2.45l1.514 1.514a4 4 0 00-5.478-5.478z" clip-rule="evenodd"></path>
                        <path d="M12.454 16.697L9.75 13.992a4 4 0 01-3.742-3.741L2.335 6.578A9.98 9.98 0 00.458 10c1.274 4.057 5.065 7 9.542 7 .847 0 1.669-.105 2.454-.303z"></path>
                      </svg>
                      Hidden
                    <% end %>
                  <% end %>
                <% else %>
                  <span class="px-2.5 py-1 text-xs rounded-full bg-yellow-100 text-yellow-700">Not configured</span>
                <% end %>

                <!-- Edit Button -->
                <%= link_to edit_site_admin_page_page_part_path(@page, page_part),
                            class: 'inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors shadow-sm' do %>
                  <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                  </svg>
                  Edit Content
                <% end %>
              </div>
            </div>

            <!-- Preview Panel (visible by default) -->
            <div id="preview-<%= page_part.id %>" class="bg-gray-100 border-t border-gray-200">
              <div class="p-4">
                <div class="flex items-center justify-between mb-3">
                  <span class="text-sm font-medium text-gray-700">Preview</span>
                  <a href="<%= preview_url %>" target="_blank" class="text-xs text-blue-600 hover:text-blue-800">
                    Open in new tab
                    <svg class="w-3 h-3 inline ml-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"></path>
                    </svg>
                  </a>
                </div>
                <div class="bg-white rounded-lg shadow-inner overflow-hidden" style="height: 300px;">
                  <iframe
                    src="<%= preview_url %>"
                    class="w-full h-full border-0"
                    title="Preview of <%= tab_title %>"
                    loading="lazy"
                    sandbox="allow-same-origin allow-scripts">
                  </iframe>
                </div>
              </div>
            </div>
          </div>
        <% end %>
      </div>
    <% else %>
      <div class="px-6 py-12 text-center text-gray-500">
        <svg class="mx-auto h-12 w-12 text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <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"></path>
        </svg>
        <p class="text-gray-600">No editable content sections configured for this page</p>
        <p class="text-sm text-gray-400 mt-1">Content sections are defined by the theme</p>
      </div>
    <% end %>
  </div>
</div>

<!-- SortableJS for drag and drop -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
  // Toggle preview visibility
  function togglePreview(partId) {
    const preview = document.getElementById(`preview-${partId}`);
    const btn = document.getElementById(`preview-btn-${partId}`);
    if (preview && btn) {
      preview.classList.toggle('hidden');
      const btnText = btn.querySelector('.btn-text');
      const isHidden = preview.classList.contains('hidden');
      if (btnText) {
        btnText.textContent = isHidden ? 'Show' : 'Hide';
      }
    }
  }

  // Initialize SortableJS
  document.addEventListener('DOMContentLoaded', function() {
    const sortableContainer = document.getElementById('page-parts-sortable');
    if (sortableContainer) {
      const reorderUrl = sortableContainer.dataset.reorderUrl;

      new Sortable(sortableContainer, {
        animation: 150,
        handle: '.drag-handle',
        ghostClass: 'bg-blue-50',
        dragClass: 'shadow-lg',
        onEnd: function(evt) {
          // Get new order of part IDs
          const items = sortableContainer.querySelectorAll('.page-part-item');
          const partIds = Array.from(items).map(item => item.dataset.partId);

          // Send reorder request
          fetch(reorderUrl, {
            method: 'PATCH',
            headers: {
              'Content-Type': 'application/json',
              'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
            },
            body: JSON.stringify({ part_ids: partIds })
          }).then(response => {
            if (response.ok) {
              // Optional: Show success feedback
              console.log('Order saved');
            } else {
              console.error('Failed to save order');
            }
          }).catch(error => {
            console.error('Error saving order:', error);
          });
        }
      });
    }
  });
</script>
