<table class="table-address-add">
  <tr>
    <td style="text-align: left;">
      <div class="pagination">
        <%= paginate @address_books, :remote => true %>
      </div>
    </td>
    <td>
      <%= link_to image_tag('common/address_add.png', { :border => '0', :alt => 'add', :title => '新規登録'}), new_address_book_path, data: {turbo: false} %>
    </td>
  </tr>
</table>

<table class="table-address">
  <tr>
    <th>組織</th>
    <th>名前</th>
    <th>メールアドレス</th>
    <th></th>
    <th></th>
  </tr>

  <% @address_books.each do |address_book| %>
  <tr class="address_items" id="address_item_<%= address_book.id %>" data-id="<%= address_book.id %>">
    <td class="address_organization">
      <%= truncate(address_book.organization, {:length => 20}) %>
      <%= hidden_field_tag "address_book_organization_#{address_book.id}",address_book.organization, {:class => ""} %>
      <%= link_to '', address_book_path(address_book), :id => "show_address_book_#{address_book.id}", :class => 'show_address_book', :style => 'visibility:hidden;', data: {turbo: false} %>
    </td>
    <td class="address_name">
      <%= truncate(address_book.name, {:length => 20}) %>
      <%= hidden_field_tag "address_book_name_#{address_book.id}",address_book.name, {:class => ""} %>
    </td>
    <td class="address_email"><%= truncate(address_book.email,  {:length => 30}) %><%= hidden_field_tag "address_book_email_#{address_book.id}",address_book.email, {:class => ""} %></td>
    <td class="address_edit"><%= link_to image_tag('common/edit.png', { :border => '0', :alt => 'edit', :title => '編集'}), edit_address_book_path(address_book), data: {turbo: false} %></td>
    <td class="address_destroy" data-turbo="true">
      <%= link_to image_tag('common/trash.png', { border: '0', alt: 'destroy'}), address_book, data: { turbo_method: "delete", turbo_confirm: '削除してもよろしいでしょうか?' } %>
    </td>
  </tr>
  <% end %>

</table>

<table class="table-address-add">
  <tr>
    <td style="text-align: left;">
      <div class="pagination">
        <%= paginate @address_books, :remote => true %>
      </div>
    </td>
  </tr>
</table>

<script type="text/javascript">
// ページネーション差し替え後も動作するようdocumentレベルでイベント委譲
// 重複登録防止
if (!window._addressBookIndexResultClickBound) {
  window._addressBookIndexResultClickBound = true;
  document.addEventListener('click', function(e) {
    var resultEl = document.getElementById('result');
    if (!resultEl || !resultEl.contains(e.target)) return;
    var target = e.target.closest('.address_organization, .address_name, .address_email, .address_notes');
    if (target) {
      var id = target.parentElement.dataset.id;
      var link = document.querySelector("a#show_address_book_" + id);
      if (link) link.click();
    }
  });
}

</script>
