/**
 * Save to Collection - Combined JS
 * AJAX & Language Switching Safe with Exact CSS Class Alignment
 */
(function() {
  'use strict';

  var busyIcons = {};

  function getBaseUrl() {
    return (typeof en4 !== 'undefined' && en4.core && en4.core.baseUrl) ? en4.core.baseUrl : '/';
  }

  function t(s) {
    return (typeof en4 !== 'undefined' && en4.core && en4.core.language) ? en4.core.language.translate(s) : s;
  }

  // =========================================================================
  // ENSURE MODAL HTML MATCHES YOUR EXACT CSS CLASSES
  // =========================================================================
  function ensureModalExists() {
    if (!document.body) return null;

    var overlay = document.getElementById('savecollection_sheet_overlay');
    if (!overlay) {
      var container = document.createElement('div');
      container.id = 'savecollection_dynamically_injected_modals';
      
      // Built using your exact CSS classes: savecollection_modal_overlay, savecollection_modal, etc.
      container.innerHTML = 
        '<div id="savecollection_sheet_overlay" class="savecollection_modal_overlay" style="display:none;">' +
          '<div class="savecollection_modal savecollection_modal_sheet">' +
            '<div class="savecollection_modal_header">' +
              '<h3>' + t('Add to Collection?') + '</h3>' +
              '<button class="savecollection_modal_close" type="button">&times;</button>' +
            '</div>' +
            '<div class="savecollection_modal_body">' +
              '<div id="savecollection_sheet_chips" class="savecollection_checkbox_list"></div>' +
            '</div>' +
            '<div class="savecollection_modal_footer">' +
              '<button type="button" class="btn btn-alt savecollection_create_btn" id="savecollection_sheet_new_btn"><i class="icon_add"></i> ' + t('New Collection') + '</button>' +
              '<button id="savecollection_sheet_done_btn" class="savecollection_sheet_btn_primary" type="button">' + t('Done') + '</button>' +
            '</div>' +
          '</div>' +
        '</div>' +

        '<div id="savecollection_create_modal" class="savecollection_modal_overlay savecollection_modal_overlay_high" style="display:none;">' +
          '<div class="savecollection_modal savecollection_modal_sm">' +
            '<div class="savecollection_modal_header">' +
              '<h3>' + t('Create New Collection') + '</h3>' +
              '<button class="savecollection_modal_close" type="button">&times;</button>' +
            '</div>' +
            '<div class="savecollection_modal_body">' +
              '<label class="savecollection_modal_label" for="savecollection_create_name">' + t('Collection Name') + '</label>' +
              '<input type="text" id="savecollection_create_name" class="savecollection_modal_input" placeholder="' + t('Enter collection name') + '" maxlength="50" />' +
              '<div id="savecollection_create_error" class="savecollection_modal_error"></div>' +
            '</div>' +
            '<div class="savecollection_modal_actions">' +
              '<button id="savecollection_create_cancel_btn" class="btn btn-secondary" type="button">' + t('Cancel') + '</button>' +
              '<button id="savecollection_create_submit_btn" class="btn btn-primary" type="button" disabled>' + t('Create') + '</button>' +
            '</div>' +
          '</div>' +
        '</div>';

			scriptJquery(container).appendTo('#append-script-data');
      // document.body.appendChild(container);
      overlay = document.getElementById('savecollection_sheet_overlay');
    }
    return overlay;
  }

  // =========================================================================
  // ICON CLICK HANDLER (Event Delegation)
  // =========================================================================
  document.addEventListener('click', function(e) {
    var el = e.target.closest('.savecollection_icon');
    if (!el) return;

    e.preventDefault();
    e.stopPropagation();

    ensureModalExists();

    var uniqueId = el.id || (el.getAttribute('data-content-type') + '_' + el.getAttribute('data-content-id'));
    if (busyIcons[uniqueId]) return;
    busyIcons[uniqueId] = true;

    var elementId = el.getAttribute('data-id');
    var contentType = el.getAttribute('data-content-type');
    var contentId = el.getAttribute('data-content-id');
    var saved = el.getAttribute('data-saved') === '1';

    var previousState = saved;
    saved = !saved;
    updateIconState(el, saved);

    var action = saved ? 'save' : 'unsave';
    var apiUrl = getBaseUrl() + 'core/savecollection/' + action;

    var timeoutId = setTimeout(function() {
      saved = previousState;
      updateIconState(el, saved);
      busyIcons[uniqueId] = false;
      showToast(t('Request timed out. Please try again.'));
    }, 10000);

    var formData = new FormData();
    formData.append('content_type', contentType);
    formData.append('content_id', contentId);

    fetch(apiUrl, { method: 'POST', body: formData })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        clearTimeout(timeoutId);
        if (data.error == '0') {
          if (saved) {
            showToast(t('Saved'));
            if (data.result && data.result.saveditem_id) {
              document.dispatchEvent(new CustomEvent('savecollection:showSheet', {
                detail: { saveditemId: data.result.saveditem_id, contentType: contentType, contentId: contentId }
              }));
            }
          } else {
            // if (elementId) {
            //   try {
            //     scriptJquery(el).parent().parent().parent().remove();
            //     if (scriptJquery('.savecollection_grid').find('li').length == 0) {
            //       scriptJquery('.savecollection_grid').after('<div class="no_result_tip"><i class="noicon center_item"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M2.849,23.55a2.954,2.954,0,0,0,3.266-.644L12,17.053l5.885,5.853a2.956,2.956,0,0,0,2.1.881,3.05,3.05,0,0,0,1.17-.237A2.953,2.953,0,0,0,23,20.779V5a5.006,5.006,0,0,0-5-5H6A5.006,5.006,0,0,0,1,5V20.779A2.953,2.953,0,0,0,2.849,23.55Z"></path></svg></i><p>'+t('You haven\'t saved any items yet.')+'</p><p>'+t('Tap the bookmark icon on any content to save it here.')+'</p></div>');
            //     }
            //   } catch(err) {}
            // }
            showToast(t('Remove from Saved'));
          }
        } else {
          saved = previousState;
          updateIconState(el, saved);
          showToast(data.error_message || t('Something went wrong. Please try again.'));
        }
        busyIcons[uniqueId] = false;
      })
      .catch(function() {
        clearTimeout(timeoutId);
        saved = previousState;
        updateIconState(el, saved);
        busyIcons[uniqueId] = false;
        showToast(t('Something went wrong. Please try again.'));
      });
  });

  function updateIconState(el, isSaved) {
    var icon = el.querySelector('i');
    var span = el.querySelector('span');
    var labelText = isSaved ? t('Remove from Saved') : t('Save');
    var labelTextButton = isSaved ? t('Saved') : t('Save');

    el.setAttribute('data-saved', isSaved ? '1' : '0');
    el.title = labelText;
    el.setAttribute('aria-label', labelText);

    if (isSaved) {
      el.classList.remove('savecollection_icon_unsaved');
      el.classList.add('savecollection_icon_saved');
    } else {
      el.classList.remove('savecollection_icon_saved');
      el.classList.add('savecollection_icon_unsaved');
    }

    if (span) {
      span.textContent = labelTextButton;
    }

    if (icon) {
      icon.className = 'fa-regular fa-bookmark';
      icon.setAttribute('title', labelText);
      icon.setAttribute('data-bs-original-title', labelText);

      try {
        if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
          var tooltip = bootstrap.Tooltip.getInstance(icon);
          if (tooltip) tooltip.dispose();
          new bootstrap.Tooltip(icon);
        } else if (typeof scriptJquery !== 'undefined' && scriptJquery(icon).data && scriptJquery(icon).data('bs.tooltip')) {
          scriptJquery(icon).attr('data-original-title', labelText);
        }
      } catch(err) {}
    }
  }

  // =========================================================================
  // ADD TO COLLECTION SHEET INTERACTIONS
  // =========================================================================
  var currentSavedItemId = null;

  document.addEventListener('savecollection:showSheet', function(e) {
    var overlay = ensureModalExists();
    currentSavedItemId = e.detail.saveditemId;
    loadCollections();
    
    if (overlay) {
      overlay.style.display = 'flex';
    }
  });

  document.addEventListener('click', function(e) {
    var overlay = document.getElementById('savecollection_sheet_overlay');
    var createModal = document.getElementById('savecollection_create_modal');

    // Close Modals
    if (e.target.closest('.savecollection_modal_close') || e.target === overlay) {
      closeSheet();
    }
    if (e.target.closest('#savecollection_sheet_done_btn')) {
      handleDone();
    }
    if (e.target.closest('#savecollection_sheet_new_btn')) {
      openCreateModal();
    }
    if (e.target.closest('#savecollection_create_cancel_btn') || e.target === createModal) {
      closeCreateModal();
    }
    if (e.target.closest('#savecollection_create_submit_btn')) {
      handleCreate();
    }
  });
	

	document.addEventListener('input', function(e) {
		if (e.target && e.target.id === 'savecollection_create_name') {
			var createSubmitBtn = document.getElementById('savecollection_create_submit_btn');
			var createError = document.getElementById('savecollection_create_error');
			var len = e.target.value.trim().length;
	
			if (createSubmitBtn) createSubmitBtn.disabled = len < 5;
			if (createError) {
				if (len > 0 && len < 5) {
					// Use en4.core.language.translate directly
					createError.textContent = en4.core.language.translate('Collection name must be at least 5 characters');
					createError.style.display = 'block';
				} else if (len > 50) {
					// Use en4.core.language.translate directly
					createError.textContent = en4.core.language.translate('Collection name must be 50 characters or less');
					createError.style.display = 'block';
				} else {
					createError.style.display = 'none';
				}
			}
		}
	});

  function closeSheet() {
    var overlay = document.getElementById('savecollection_sheet_overlay');
    if (overlay) overlay.style.display = 'none';
  }

  function openCreateModal() {
    ensureModalExists();
    var createModal = document.getElementById('savecollection_create_modal');
    var createNameInput = document.getElementById('savecollection_create_name');
    var createSubmitBtn = document.getElementById('savecollection_create_submit_btn');
    var createError = document.getElementById('savecollection_create_error');

    if (!createModal) return;
    if (createNameInput) createNameInput.value = '';
    if (createSubmitBtn) createSubmitBtn.disabled = true;
    if (createError) createError.style.display = 'none';

    createModal.style.display = 'flex';
    if (createNameInput) createNameInput.focus();
  }

  function closeCreateModal() {
    var createModal = document.getElementById('savecollection_create_modal');
    if (createModal) createModal.style.display = 'none';
  }

  function loadCollections() {
    var chipsContainer = document.getElementById('savecollection_sheet_chips');
    if (!chipsContainer) return;

    chipsContainer.innerHTML = '<div class="savecollection_sheet_msg">' + t('Loading collections...') + '</div>';
    fetch(getBaseUrl() + 'core/savecollection/get-collections-sheet')
      .then(function(r) { return r.json(); })
      .then(function(data) { renderCheckboxes(data.result || []); })
      .catch(function() {
        chipsContainer.innerHTML = '<div class="savecollection_sheet_msg">' + t('Unable to load collections.') + '</div>';
      });
  }

  function renderCheckboxes(collections) {
    var chipsContainer = document.getElementById('savecollection_sheet_chips');
    if (!chipsContainer) return;

    if (!collections.length) {
      chipsContainer.innerHTML = '<div class="savecollection_sheet_msg">' + en4.core.language.translate('No collections yet. Create one to get started!') + '</div>';
      return;
    }
    var html = '';
    collections.forEach(function(c) {
      var id = 'sc_check_' + c.collection_id;
      html += '<label for="' + id + '">';
      html += '<input type="checkbox" id="' + id + '" data-collection-id="' + c.collection_id + '" />';
      html += '<span>' + escapeHtml(c.name) + '</span>';
      html += '</label>';
    });
    chipsContainer.innerHTML = html;
  }

  function handleDone() {
    var chipsContainer = document.getElementById('savecollection_sheet_chips');
    if (!chipsContainer) return;

    var checked = chipsContainer.querySelectorAll('input[type=checkbox]:checked');
    var ids = [];
    checked.forEach(function(cb) { ids.push(cb.getAttribute('data-collection-id')); });

    if (ids.length === 0) { closeSheet(); return; }

    var fd = new FormData();
    fd.append('saveditem_id', currentSavedItemId);
    ids.forEach(function(id) { fd.append('collection_ids[]', id); });

    fetch(getBaseUrl() + 'core/savecollection/add-to-collections', { method: 'POST', body: fd })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        closeSheet();
        if (data.error == '0') showToast(t('Added to') + ' ' + ids.length + ' ' + t('collection(s)'));
      })
      .catch(function() { showToast(t('Something went wrong. Please try again.')); });
  }

  function handleCreate() {
    var createNameInput = document.getElementById('savecollection_create_name');
    var createSubmitBtn = document.getElementById('savecollection_create_submit_btn');
    var createError = document.getElementById('savecollection_create_error');

    if (!createNameInput) return;
    var name = createNameInput.value.trim();
    if (!name || name.length < 5 || name.length > 50) return;

    if (createSubmitBtn) createSubmitBtn.disabled = true;

    var fd = new FormData();
    fd.append('name', name);

    fetch(getBaseUrl() + 'core/savecollection/collection-create', { method: 'POST', body: fd })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data.error == '0') {
          closeCreateModal();
          showToast(t('Collection created'));
          loadCollections();
        } else {
          if (createError) {
            createError.textContent = data.error_message || t('Could not create collection.');
            createError.style.display = 'block';
          }
          if (createSubmitBtn) createSubmitBtn.disabled = false;
        }
      })
      .catch(function() {
        if (createError) {
          createError.textContent = t('Something went wrong. Please try again.');
          createError.style.display = 'block';
        }
        if (createSubmitBtn) createSubmitBtn.disabled = false;
      });
  }

  function escapeHtml(str) {
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
  }

  function showToast(message) {
    if (!document.body) return;
    var existing = document.querySelector('.savecollection_toast_notification');
    if (existing) existing.remove();
    var toast = document.createElement('div');
    toast.className = 'savecollection_toast_notification';
    toast.textContent = message;
    document.body.appendChild(toast);
    setTimeout(function() { toast.classList.add('visible'); }, 10);
    setTimeout(function() {
      toast.classList.remove('visible');
      setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
  }

  // =========================================================================
  // SOCIALENGINE AJAX TRIGGERS
  // =========================================================================
  
  // 1. SocialEngine core queue execution
  if (typeof en4 !== 'undefined' && en4.core && en4.core.runonce) {
    en4.core.runonce.add(ensureModalExists);
  }

  // 2. jQuery / scriptJquery AJAX Complete Trigger
  if (typeof scriptJquery !== 'undefined') {
    scriptJquery(document).ajaxComplete(function() {
      ensureModalExists();
    });
  } else if (typeof jQuery !== 'undefined') {
    jQuery(document).ajaxComplete(function() {
      ensureModalExists();
    });
  }

  // 3. Fallback Initial DOM Load
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', ensureModalExists);
  } else {
    ensureModalExists();
  }
})();