jQuery(function($) {
  var $modal = $('#pdt-custom-menu-modal');
  var $rows = $modal.find('.pdt-custom-submenus__rows');
  var $iconModal = $('#pdt-custom-icon-modal');
  var $iconInput = $('#pdt_menu_icon');
  var $iconTrigger = $('.pdt-custom-icon-picker-trigger');
  var customMenuData = window.pdtCustomMenuData || null;
  function t(key) {
    if (!customMenuData) {
      return '';
    }
    return customMenuData[key] || '';
  }
  var $modalTitle = $('#pdt-custom-menu-modal-title');
  var $submitBtn = $('.pdt-custom-menu-submit-btn');
  var $editIdInput = $('#pdt_edit_menu_id');

  function openModal() {
    $modal.attr('aria-hidden', 'false').addClass('is-open');
    $('body').addClass('pdt-modal-open');
  }

  function closeModal() {
    $modal.attr('aria-hidden', 'true').removeClass('is-open');
    $('body').removeClass('pdt-modal-open');
  }

  function submenuRowTemplate(rowData) {
    var data = rowData || {};
    var menuTitle = data.menu_title || '';
    var target = data.target || '';
    var slug = data.menu_slug || '';
    var newTab = data.new_tab ? '1' : '0';

    return '' +
      '<div class="pdt-submenu-row">' +
      '  <div class="pdt-custom-menu-grid">' +
      '    <div class="pdt-custom-menu-field">' +
      '      <label>' + t('submenuTitleLabel') + '</label>' +
      '      <input type="text" name="submenu_menu_title[]" value="' + $('<div>').text(menuTitle).html() + '" />' +
      '      <p class="description">' + t('submenuTitleDescription') + '</p>' +
      '    </div>' +
      '    <div class="pdt-custom-menu-field">' +
      '      <label>' + t('submenuTargetLabel') + '</label>' +
      '      <input type="text" name="submenu_target[]" placeholder="' + t('submenuTargetPlaceholder') + '" value="' + $('<div>').text(target).html() + '" />' +
      '      <p class="description">' + t('submenuTargetDescription') + '</p>' +
      '    </div>' +
      '    <div class="pdt-custom-menu-field">' +
      '      <label>' + t('submenuSlugLabel') + '</label>' +
      '      <input type="text" name="submenu_slug[]" placeholder="' + t('submenuSlugPlaceholder') + '" value="' + $('<div>').text(slug).html() + '" />' +
      '      <p class="description">' + t('submenuSlugDescription') + '</p>' +
      '    </div>' +
      '    <div class="pdt-custom-menu-field">' +
      '      <label>' + t('submenuBehaviorLabel') + '</label>' +
      '      <select name="submenu_new_tab[]">' +
      '        <option value="0" ' + (newTab === '0' ? 'selected' : '') + '>' + t('openSameTabLabel') + '</option>' +
      '        <option value="1" ' + (newTab === '1' ? 'selected' : '') + '>' + t('openNewTabLabel') + '</option>' +
      '      </select>' +
      '      <p class="description">' + t('submenuBehaviorDescription') + '</p>' +
      '    </div>' +
      '  </div>' +
      '  <button type="button" class="button-link-delete pdt-remove-submenu-row">' + t('removeLabel') + '</button>' +
      '</div>';
  }

  function resetModalForCreate() {
    $modalTitle.text((customMenuData && customMenuData.addModalTitle) || '');
    $submitBtn.text((customMenuData && customMenuData.addSubmitLabel) || '');
    $editIdInput.val('');

    $('#pdt_menu_title').val('');
    $('#pdt_menu_target').val('');
    $('#pdt_menu_position').val('');
    $('#pdt_menu_icon').val('dashicons-admin-generic');
    $('input[name="menu_new_tab"]').prop('checked', false);
    $rows.empty();
    $iconTrigger.find('.dashicons').attr('class', 'dashicons dashicons-admin-generic');
  }

  function fillModalForEdit(menuId) {
    if (!customMenuData || !customMenuData.menuItems || !customMenuData.menuItems[menuId]) {
      return;
    }

    var item = customMenuData.menuItems[menuId];

    $modalTitle.text(customMenuData.editModalTitle || '');
    $submitBtn.text(customMenuData.editSubmitLabel || '');
    $editIdInput.val(menuId);

    $('#pdt_menu_title').val(item.menu_title || '');
    $('#pdt_menu_target').val(item.menu_target || '');
    $('#pdt_menu_position').val(item.position || '');
    $('#pdt_menu_icon').val(item.menu_icon || 'dashicons-admin-generic');
    $('input[name="menu_new_tab"]').prop('checked', !!item.new_tab);
    $iconTrigger.find('.dashicons').attr('class', 'dashicons ' + (item.menu_icon || 'dashicons-admin-generic'));

    $rows.empty();
    if (Array.isArray(item.submenus) && item.submenus.length) {
      item.submenus.forEach(function(submenu) {
        $rows.append(submenuRowTemplate(submenu));
      });
    }
  }

  $(document).on('click', '.pdt-open-custom-menu-modal', function() {
    resetModalForCreate();
    openModal();
  });

  $(document).on('click', '.pdt-close-custom-menu-modal', function() {
    closeModal();
  });

  $(document).on('click', '.pdt-custom-icon-picker-trigger', function() {
    $iconModal.attr('aria-hidden', 'false').addClass('is-open');
  });

  $(document).on('click', '.pdt-close-custom-icon-modal', function() {
    $iconModal.attr('aria-hidden', 'true').removeClass('is-open');
  });

  $(document).on('click', '.pdt-custom-icon-option', function() {
    var icon = $(this).data('icon');
    if (!icon) {
      return;
    }

    $iconInput.val(icon);
    $iconTrigger.find('.dashicons').attr('class', 'dashicons ' + icon);
    $iconModal.attr('aria-hidden', 'true').removeClass('is-open');
  });

  $(document).on('click', '.pdt-add-submenu-row', function() {
    $rows.append(submenuRowTemplate());
  });

  $(document).on('click', '.pdt-custom-menu-edit-btn', function() {
    var menuId = $(this).data('menu-id');
    if (!menuId) {
      return;
    }
    fillModalForEdit(menuId);
    openModal();
  });

  $(document).on('click', '.pdt-custom-menu-delete-btn', function() {
    var menuId = $(this).data('menu-id');
    if (!menuId || !customMenuData) {
      return;
    }

    if (!window.confirm(customMenuData.deleteConfirm || '')) {
      return;
    }

    var $form = $('<form>', {
      method: 'post',
      action: customMenuData.deleteUrl || ''
    });

    $form.append($('<input>', { type: 'hidden', name: 'action', value: customMenuData.deleteAction || 'pdt_custom_menu_delete' }));
    $form.append($('<input>', { type: 'hidden', name: 'menu_id', value: menuId }));
    $form.append($('<input>', { type: 'hidden', name: '_wpnonce', value: customMenuData.deleteNonce || '' }));

    $('body').append($form);
    $form.trigger('submit');
  });

  $(document).on('click', '.pdt-remove-submenu-row', function() {
    $(this).closest('.pdt-submenu-row').remove();
  });

  $(document).on('keydown', function(e) {
    if (e.key === 'Escape' && $modal.hasClass('is-open')) {
      closeModal();
    }
    if (e.key === 'Escape' && $iconModal.hasClass('is-open')) {
      $iconModal.attr('aria-hidden', 'true').removeClass('is-open');
    }
  });

  function appendDeleteButtonsToCustomMenus() {
    if (!customMenuData || !customMenuData.menuMap) {
      return;
    }

    Object.keys(customMenuData.menuMap).forEach(function(menuSlug) {
      var menuId = customMenuData.menuMap[menuSlug];
      var $row = $('.pdt-menu-row[data-slug="' + menuSlug + '"]');
      if (!$row.length || $row.find('.pdt-custom-menu-delete').length) {
        return;
      }

      var $label = $row.find('.pdt-menu-label').first();
      if (!$label.length) {
        return;
      }

      var $btn = $('<button>', {
        type: 'button',
        class: 'pdt-custom-menu-delete',
        text: '×',
        title: customMenuData.deleteAriaLabel || '',
        'aria-label': customMenuData.deleteAriaLabel || ''
      });

      $btn.on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();

        if (!window.confirm(customMenuData.deleteConfirm || '')) {
          return;
        }

        var $form = $('<form>', {
          method: 'post',
          action: customMenuData.deleteUrl || ''
        });

        $form.append($('<input>', { type: 'hidden', name: 'action', value: customMenuData.deleteAction || 'pdt_custom_menu_delete' }));
        $form.append($('<input>', { type: 'hidden', name: 'menu_id', value: menuId }));
        $form.append($('<input>', { type: 'hidden', name: '_wpnonce', value: customMenuData.deleteNonce || '' }));

        $('body').append($form);
        $form.trigger('submit');
      });

      $label.append($btn);
    });
  }

  appendDeleteButtonsToCustomMenus();
});
