<div class="p-4 md:p-6">
  <h2 class="text-xl font-semibold text-gray-900 mb-6">Navigation Settings</h2>

  <%= form_with url: site_admin_website_update_links_path, method: :patch, local: true, data: { turbo: false }, id: 'navigation-form' do |f| %>
    <!-- Top Navigation Links -->
    <div class="mb-8">
      <h3 class="text-lg font-medium text-gray-900 mb-2">Top Navigation Links</h3>
      <p class="text-sm text-gray-500 mb-4">Drag to reorder. Edit titles in each supported language.</p>

      <% if @top_nav_links.any? %>
        <div id="top-nav-links" class="space-y-3">
          <% @top_nav_links.each_with_index do |link, index| %>
            <%
              english_title = Mobility.with_locale(:en) { link.link_title } || link.page_slug&.titleize || 'Untitled'
            %>
            <div class="bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden link-row"
                 data-link-id="<%= link.id %>"
                 draggable="true">

              <!-- Hidden fields -->
              <input type="hidden" name="links[][id]" value="<%= link.id %>">
              <input type="hidden" name="links[][sort_order]" value="<%= link.sort_order || index %>" class="sort-order-input">
              <input type="hidden" name="links[][link_path]" value="<%= link.link_path %>">

              <!-- Mobile Layout (stacked) -->
              <div class="md:hidden">
                <!-- Header row with controls -->
                <div class="flex items-center px-3 py-2 bg-gray-50 border-b border-gray-200">
                  <!-- Visibility Toggle -->
                  <div class="flex-shrink-0 mr-3">
                    <input type="hidden" name="links[][visible]" value="false" class="mobile-visible-hidden">
                    <label class="relative inline-flex items-center cursor-pointer" title="<%= link.visible? ? 'Visible - click to hide' : 'Hidden - click to show' %>">
                      <input type="checkbox" name="links[][visible]" value="true"
                             <%= 'checked' if link.visible? %>
                             class="sr-only peer mobile-visible-checkbox">
                      <div class="w-10 h-5 bg-gray-300 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-green-500"></div>
                    </label>
                  </div>

                  <!-- Drag Handle -->
                  <div class="flex-shrink-0 mr-3 cursor-move drag-handle p-1">
                    <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16"></path>
                    </svg>
                  </div>

                  <!-- Title -->
                  <h4 class="font-semibold text-gray-900 truncate flex-1"><%= english_title %></h4>
                </div>

                <!-- Language inputs (stacked) -->
                <div class="p-3 space-y-2">
                  <% @website_locales.each do |locale_info| %>
                    <%
                      locale_title = Mobility.with_locale(locale_info[:locale].to_sym) { link.link_title } || ''
                    %>
                    <div class="flex items-center">
                      <label class="text-xs text-gray-500 w-20 flex-shrink-0">
                        <%= locale_info[:label] %>:
                      </label>
                      <input type="text"
                             name="links[][titles][<%= locale_info[:locale] %>]"
                             value="<%= locale_title %>"
                             placeholder="<%= locale_info[:label] %>"
                             class="flex-1 px-2 py-1.5 border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm">
                    </div>
                  <% end %>
                </div>
              </div>

              <!-- Desktop Layout (horizontal row) -->
              <div class="hidden md:flex items-stretch">
                <!-- Visibility Toggle (prominent, at extreme left) -->
                <div class="flex-shrink-0 w-14 px-2 py-2 bg-gray-50 border-r border-gray-200 flex items-center justify-center">
                  <input type="hidden" name="links[][visible]" value="false" class="desktop-visible-hidden">
                  <label class="relative inline-flex items-center cursor-pointer" title="<%= link.visible? ? 'Visible - click to hide' : 'Hidden - click to show' %>">
                    <input type="checkbox" name="links[][visible]" value="true"
                           <%= 'checked' if link.visible? %>
                           class="sr-only peer desktop-visible-checkbox">
                    <div class="w-11 h-6 bg-gray-300 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-500"></div>
                  </label>
                </div>

                <!-- Drag Handle -->
                <div class="flex items-center justify-center w-10 bg-gray-50 border-r border-gray-200 cursor-move drag-handle">
                  <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16"></path>
                  </svg>
                </div>

                <!-- Link Title (English header) -->
                <div class="flex-shrink-0 w-40 px-4 py-3 bg-gray-50 border-r border-gray-200 flex items-center">
                  <h4 class="font-semibold text-gray-900 truncate"><%= english_title %></h4>
                </div>

                <!-- Multilingual Titles -->
                <div class="flex-1 flex items-center px-4 py-2 space-x-4">
                  <% @website_locales.each do |locale_info| %>
                    <div class="flex items-center space-x-2 flex-1">
                      <label class="text-xs text-gray-500 w-16 text-right flex-shrink-0">
                        <%= locale_info[:label] %>:
                      </label>
                      <%
                        locale_title = Mobility.with_locale(locale_info[:locale].to_sym) { link.link_title } || ''
                      %>
                      <input type="text"
                             name="links[][titles][<%= locale_info[:locale] %>]"
                             value="<%= locale_title %>"
                             placeholder="<%= locale_info[:label] %>"
                             class="flex-1 px-2 py-1.5 border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm">
                    </div>
                  <% end %>
                </div>
              </div>
            </div>
          <% end %>
        </div>
      <% else %>
        <div class="bg-gray-50 rounded-lg p-8 text-center text-gray-500">
          No top navigation links configured
        </div>
      <% end %>
    </div>

    <!-- Footer Links -->
    <div class="border-t border-gray-200 pt-6">
      <h3 class="text-lg font-medium text-gray-900 mb-2">Footer Links</h3>
      <p class="text-sm text-gray-500 mb-4">Drag to reorder. Edit titles in each supported language.</p>

      <% if @footer_links.any? %>
        <div id="footer-links" class="space-y-3">
          <% @footer_links.each_with_index do |link, index| %>
            <%
              english_title = Mobility.with_locale(:en) { link.link_title } || link.page_slug&.titleize || 'Untitled'
            %>
            <div class="bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden link-row"
                 data-link-id="<%= link.id %>"
                 draggable="true">

              <!-- Hidden fields -->
              <input type="hidden" name="links[][id]" value="<%= link.id %>">
              <input type="hidden" name="links[][sort_order]" value="<%= link.sort_order || index %>" class="sort-order-input">
              <input type="hidden" name="links[][link_path]" value="<%= link.link_path %>">

              <!-- Mobile Layout (stacked) -->
              <div class="md:hidden">
                <!-- Header row with controls -->
                <div class="flex items-center px-3 py-2 bg-gray-50 border-b border-gray-200">
                  <!-- Visibility Toggle -->
                  <div class="flex-shrink-0 mr-3">
                    <input type="hidden" name="links[][visible]" value="false" class="mobile-visible-hidden">
                    <label class="relative inline-flex items-center cursor-pointer" title="<%= link.visible? ? 'Visible - click to hide' : 'Hidden - click to show' %>">
                      <input type="checkbox" name="links[][visible]" value="true"
                             <%= 'checked' if link.visible? %>
                             class="sr-only peer mobile-visible-checkbox">
                      <div class="w-10 h-5 bg-gray-300 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-green-500"></div>
                    </label>
                  </div>

                  <!-- Drag Handle -->
                  <div class="flex-shrink-0 mr-3 cursor-move drag-handle p-1">
                    <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16"></path>
                    </svg>
                  </div>

                  <!-- Title -->
                  <h4 class="font-semibold text-gray-900 truncate flex-1"><%= english_title %></h4>
                </div>

                <!-- Language inputs (stacked) -->
                <div class="p-3 space-y-2">
                  <% @website_locales.each do |locale_info| %>
                    <%
                      locale_title = Mobility.with_locale(locale_info[:locale].to_sym) { link.link_title } || ''
                    %>
                    <div class="flex items-center">
                      <label class="text-xs text-gray-500 w-20 flex-shrink-0">
                        <%= locale_info[:label] %>:
                      </label>
                      <input type="text"
                             name="links[][titles][<%= locale_info[:locale] %>]"
                             value="<%= locale_title %>"
                             placeholder="<%= locale_info[:label] %>"
                             class="flex-1 px-2 py-1.5 border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm">
                    </div>
                  <% end %>
                </div>
              </div>

              <!-- Desktop Layout (horizontal row) -->
              <div class="hidden md:flex items-stretch">
                <!-- Visibility Toggle (prominent, at extreme left) -->
                <div class="flex-shrink-0 w-14 px-2 py-2 bg-gray-50 border-r border-gray-200 flex items-center justify-center">
                  <input type="hidden" name="links[][visible]" value="false" class="desktop-visible-hidden">
                  <label class="relative inline-flex items-center cursor-pointer" title="<%= link.visible? ? 'Visible - click to hide' : 'Hidden - click to show' %>">
                    <input type="checkbox" name="links[][visible]" value="true"
                           <%= 'checked' if link.visible? %>
                           class="sr-only peer desktop-visible-checkbox">
                    <div class="w-11 h-6 bg-gray-300 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-500"></div>
                  </label>
                </div>

                <!-- Drag Handle -->
                <div class="flex items-center justify-center w-10 bg-gray-50 border-r border-gray-200 cursor-move drag-handle">
                  <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16"></path>
                  </svg>
                </div>

                <!-- Link Title (English header) -->
                <div class="flex-shrink-0 w-40 px-4 py-3 bg-gray-50 border-r border-gray-200 flex items-center">
                  <h4 class="font-semibold text-gray-900 truncate"><%= english_title %></h4>
                </div>

                <!-- Multilingual Titles -->
                <div class="flex-1 flex items-center px-4 py-2 space-x-4">
                  <% @website_locales.each do |locale_info| %>
                    <div class="flex items-center space-x-2 flex-1">
                      <label class="text-xs text-gray-500 w-16 text-right flex-shrink-0">
                        <%= locale_info[:label] %>:
                      </label>
                      <%
                        locale_title = Mobility.with_locale(locale_info[:locale].to_sym) { link.link_title } || ''
                      %>
                      <input type="text"
                             name="links[][titles][<%= locale_info[:locale] %>]"
                             value="<%= locale_title %>"
                             placeholder="<%= locale_info[:label] %>"
                             class="flex-1 px-2 py-1.5 border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm">
                    </div>
                  <% end %>
                </div>
              </div>
            </div>
          <% end %>
        </div>
      <% else %>
        <div class="bg-gray-50 rounded-lg p-8 text-center text-gray-500">
          No footer links configured
        </div>
      <% end %>
    </div>

    <!-- Submit Button -->
    <div class="pt-6 border-t border-gray-200 mt-6">
      <%= f.submit "Save Navigation Settings",
          class: "w-full md:w-auto px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 cursor-pointer" %>
    </div>
  <% end %>
</div>

<style>
  .link-row.dragging {
    opacity: 0.5;
    border: 2px dashed #3b82f6;
  }
  .link-row.drag-over {
    border-top: 3px solid #3b82f6;
  }
  .drag-handle:hover svg {
    color: #3b82f6;
  }
</style>

<script>
  document.addEventListener('DOMContentLoaded', function() {
    initDragAndDrop('top-nav-links');
    initDragAndDrop('footer-links');
    syncVisibilityCheckboxes();
  });

  // Sync visibility checkboxes between mobile and desktop views
  function syncVisibilityCheckboxes() {
    document.querySelectorAll('.link-row').forEach(row => {
      const mobileCheckbox = row.querySelector('.mobile-visible-checkbox');
      const desktopCheckbox = row.querySelector('.desktop-visible-checkbox');

      if (mobileCheckbox && desktopCheckbox) {
        mobileCheckbox.addEventListener('change', () => {
          desktopCheckbox.checked = mobileCheckbox.checked;
        });
        desktopCheckbox.addEventListener('change', () => {
          mobileCheckbox.checked = desktopCheckbox.checked;
        });
      }
    });
  }

  function initDragAndDrop(containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;

    const rows = container.querySelectorAll('.link-row');
    let draggedItem = null;

    rows.forEach(row => {
      // Only allow dragging from the handle
      const handles = row.querySelectorAll('.drag-handle');

      handles.forEach(handle => {
        handle.addEventListener('mousedown', () => {
          row.setAttribute('draggable', 'true');
        });

        // Touch support for mobile
        handle.addEventListener('touchstart', (e) => {
          row.setAttribute('draggable', 'true');
        }, { passive: true });
      });

      row.addEventListener('dragstart', (e) => {
        draggedItem = row;
        row.classList.add('dragging');
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/plain', row.dataset.linkId);
      });

      row.addEventListener('dragend', () => {
        row.classList.remove('dragging');
        row.setAttribute('draggable', 'false');
        draggedItem = null;
        // Remove all drag-over classes
        container.querySelectorAll('.drag-over').forEach(el => el.classList.remove('drag-over'));
        // Update sort order values
        updateSortOrder(containerId);
      });

      row.addEventListener('dragover', (e) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';

        if (draggedItem && draggedItem !== row) {
          row.classList.add('drag-over');
        }
      });

      row.addEventListener('dragleave', () => {
        row.classList.remove('drag-over');
      });

      row.addEventListener('drop', (e) => {
        e.preventDefault();
        row.classList.remove('drag-over');

        if (draggedItem && draggedItem !== row) {
          // Determine position based on mouse position
          const rect = row.getBoundingClientRect();
          const midpoint = rect.top + rect.height / 2;

          if (e.clientY < midpoint) {
            container.insertBefore(draggedItem, row);
          } else {
            container.insertBefore(draggedItem, row.nextSibling);
          }
        }
      });
    });
  }

  function updateSortOrder(containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;

    const rows = container.querySelectorAll('.link-row');
    rows.forEach((row, index) => {
      const sortInput = row.querySelector('.sort-order-input');
      if (sortInput) {
        sortInput.value = index;
      }
    });
  }
</script>
