<?php
/**
  * Ahead WebSoft Technologies Pvt Ltd.
  * @copyright  Copyright 2006-2026 Ahead WebSoft Technologies Pvt Ltd.
  * @license    https://www.socialengine.com/policies
*/
?>

<?php
  $collections = $this->collections;
  $hasCollections = !empty($collections) && count($collections) > 0;
?>

<!-- Save to Collection Sheet / Popover -->
<div id="savecollection_sheet_overlay" class="savecollection_sheet_overlay" style="display:none;" role="dialog" aria-modal="true" aria-labelledby="savecollection_sheet_title">
  <div class="savecollection_sheet_container">
    <!-- Header -->
    <div class="savecollection_sheet_header">
      <h4 id="savecollection_sheet_title" class="savecollection_sheet_prompt"><?php echo $this->translate("Add to Collection?"); ?></h4>
      <button type="button" class="savecollection_sheet_close" aria-label="<?php echo $this->translate('Close'); ?>">
        <i class="fi fi-rr-cross-small"></i>
      </button>
    </div>

    <!-- Collection Chips -->
    <div class="savecollection_sheet_body">
      <div id="savecollection_sheet_chips" class="savecollection_sheet_chips">
        <?php if ($hasCollections): ?>
          <?php foreach ($collections as $collection): ?>
            <button type="button"
                    class="savecollection_chip"
                    data-collection-id="<?php echo (int) $collection->collection_id; ?>"
                    aria-pressed="false">
              <?php echo $this->escape($collection->name); ?>
            </button>
          <?php endforeach; ?>
        <?php else: ?>
          <p class="savecollection_sheet_empty"><?php echo $this->translate("You don't have any collections yet."); ?></p>
        <?php endif; ?>
      </div>

      <!-- Inline Create Collection Form (hidden by default) -->
      <div id="savecollection_sheet_create_form" class="savecollection_sheet_create_form" style="display:none;">
        <div class="savecollection_sheet_create_header">
          <span class="savecollection_sheet_create_label"><?php echo $this->translate("New Collection"); ?></span>
        </div>
        <div class="savecollection_sheet_create_input_wrap">
          <input type="text"
                 id="savecollection_sheet_name_input"
                 class="savecollection_sheet_name_input"
                 placeholder="<?php echo $this->translate('Collection name'); ?>"
                 maxlength="50"
                 autocomplete="off" />
          <span id="savecollection_sheet_name_error" class="savecollection_sheet_name_error" style="display:none;"></span>
        </div>
        <div class="savecollection_sheet_create_actions">
          <button type="button" id="savecollection_sheet_create_cancel" class="savecollection_sheet_btn_secondary">
            <?php echo $this->translate("Cancel"); ?>
          </button>
          <button type="button" id="savecollection_sheet_create_submit" class="savecollection_sheet_btn_primary" disabled>
            <?php echo $this->translate("Create"); ?>
          </button>
        </div>
      </div>
    </div>

    <!-- Footer Actions -->
    <div class="savecollection_sheet_footer">
      <button type="button" id="savecollection_sheet_new_btn" class="savecollection_sheet_btn_secondary">
        <i class="fi fi-rr-plus"></i> <?php echo $this->translate("New Collection"); ?>
      </button>
      <button type="button" id="savecollection_sheet_done_btn" class="savecollection_sheet_btn_primary">
        <?php echo $this->translate("Done"); ?>
      </button>
    </div>
  </div>
</div>

<style type="text/css">
.savecollection_sheet_overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 10000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}
@media (min-width: 768px) {
  .savecollection_sheet_overlay {
    align-items: center;
  }
}
.savecollection_sheet_container {
  background: #fff;
  width: 100%;
  max-width: 420px;
  border-radius: 16px 16px 0 0;
  padding: 20px;
  max-height: 80vh;
  overflow-y: auto;
  animation: savecollection_sheet_slide_up 0.3s ease;
}
@media (min-width: 768px) {
  .savecollection_sheet_container {
    border-radius: 12px;
    animation: savecollection_sheet_fade_in 0.2s ease;
  }
}
@keyframes savecollection_sheet_slide_up {
  from { transform: translateY(100%); }
  to { transform: translateY(0); }
}
@keyframes savecollection_sheet_fade_in {
  from { opacity: 0; transform: scale(0.95); }
  to { opacity: 1; transform: scale(1); }
}
.savecollection_sheet_header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}
.savecollection_sheet_prompt {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}
.savecollection_sheet_close {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 20px;
  color: #666;
  padding: 4px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.savecollection_sheet_close:hover {
  background: #f0f0f0;
}
.savecollection_sheet_body {
  margin-bottom: 16px;
}
.savecollection_sheet_chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.savecollection_chip {
  display: inline-flex;
  align-items: center;
  padding: 8px 16px;
  border-radius: 20px;
  border: 1px solid #ddd;
  background: #f8f8f8;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  transition: all 0.2s ease;
  user-select: none;
}
.savecollection_chip:hover {
  border-color: #999;
}
.savecollection_chip[aria-pressed="true"] {
  background: var(--theme-primary-color, #4285f4);
  color: #fff;
  border-color: var(--theme-primary-color, #4285f4);
}
.savecollection_sheet_empty {
  color: #888;
  font-size: 14px;
  text-align: center;
  padding: 12px 0;
  margin: 0;
}
.savecollection_sheet_create_form {
  margin-top: 12px;
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 8px;
  background: #fafafa;
}
.savecollection_sheet_create_header {
  margin-bottom: 8px;
}
.savecollection_sheet_create_label {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}
.savecollection_sheet_create_input_wrap {
  margin-bottom: 10px;
}
.savecollection_sheet_name_input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  outline: none;
  box-sizing: border-box;
}
.savecollection_sheet_name_input:focus {
  border-color: var(--theme-primary-color, #4285f4);
}
.savecollection_sheet_name_error {
  display: block;
  color: #d93025;
  font-size: 12px;
  margin-top: 4px;
}
.savecollection_sheet_create_actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
.savecollection_sheet_footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}
.savecollection_sheet_btn_primary {
  padding: 10px 20px;
  background: var(--theme-primary-color, #4285f4);
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: opacity 0.2s;
}
.savecollection_sheet_btn_primary:hover {
  opacity: 0.9;
}
.savecollection_sheet_btn_primary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.savecollection_sheet_btn_secondary {
  padding: 10px 20px;
  background: transparent;
  color: var(--theme-primary-color, #4285f4);
  border: 1px solid var(--theme-primary-color, #4285f4);
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
.savecollection_sheet_btn_secondary:hover {
  background: rgba(66, 133, 244, 0.05);
}
</style>

<script type="application/javascript">
en4.core.runonce.add(function() {
  var overlay = document.getElementById('savecollection_sheet_overlay');
  var chipsContainer = document.getElementById('savecollection_sheet_chips');
  var createForm = document.getElementById('savecollection_sheet_create_form');
  var nameInput = document.getElementById('savecollection_sheet_name_input');
  var nameError = document.getElementById('savecollection_sheet_name_error');
  var createSubmitBtn = document.getElementById('savecollection_sheet_create_submit');
  var createCancelBtn = document.getElementById('savecollection_sheet_create_cancel');
  var newBtn = document.getElementById('savecollection_sheet_new_btn');
  var doneBtn = document.getElementById('savecollection_sheet_done_btn');
  var closeBtn = overlay.querySelector('.savecollection_sheet_close');

  var currentSaveditemId = null;
  var selectedCollectionIds = [];

  // ==========================================
  // Listen for the custom event from icon widget
  // ==========================================
  document.addEventListener('savecollection:showSheet', function(e) {
    if (e.detail && e.detail.saveditemId) {
      currentSaveditemId = e.detail.saveditemId;
      openSheet();
    }
  });

  // ==========================================
  // Sheet open/close
  // ==========================================
  function openSheet() {
    selectedCollectionIds = [];
    resetChipSelections();
    hideCreateForm();
    overlay.style.display = 'flex';
  }

  function closeSheet() {
    overlay.style.display = 'none';
    currentSaveditemId = null;
    selectedCollectionIds = [];
  }

  // ==========================================
  // Close handlers
  // ==========================================
  closeBtn.addEventListener('click', function() {
    closeSheet();
  });

  // Close on overlay background click (dismiss without action)
  overlay.addEventListener('click', function(e) {
    if (e.target === overlay) {
      closeSheet();
    }
  });

  // Close on Escape key
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && overlay.style.display === 'flex') {
      closeSheet();
    }
  });

  // ==========================================
  // Chip toggle (multi-select/deselect)
  // ==========================================
  chipsContainer.addEventListener('click', function(e) {
    var chip = e.target.closest('.savecollection_chip');
    if (!chip) return;

    var collectionId = parseInt(chip.getAttribute('data-collection-id'), 10);
    var isSelected = chip.getAttribute('aria-pressed') === 'true';

    if (isSelected) {
      // Deselect
      chip.setAttribute('aria-pressed', 'false');
      var idx = selectedCollectionIds.indexOf(collectionId);
      if (idx > -1) selectedCollectionIds.splice(idx, 1);
    } else {
      // Select
      chip.setAttribute('aria-pressed', 'true');
      selectedCollectionIds.push(collectionId);
    }
  });

  function resetChipSelections() {
    var chips = chipsContainer.querySelectorAll('.savecollection_chip');
    for (var i = 0; i < chips.length; i++) {
      chips[i].setAttribute('aria-pressed', 'false');
    }
  }

  // ==========================================
  // "Done" button
  // ==========================================
  doneBtn.addEventListener('click', function() {
    if (selectedCollectionIds.length === 0) {
      // No selections — just close the sheet
      closeSheet();
      return;
    }

    // POST to addToCollections API
    doneBtn.disabled = true;
    var formData = new FormData();
    formData.append('saveditem_id', currentSaveditemId);
    for (var i = 0; i < selectedCollectionIds.length; i++) {
      formData.append('collection_ids[]', selectedCollectionIds[i]);
    }

    fetch(en4.core.baseUrl + 'core/savecollection/add-to-collections', {
      method: 'POST',
      body: formData
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
      doneBtn.disabled = false;
      if (data.error == '0' || data.status === true) {
        var count = data.result && data.result.added_count ? data.result.added_count : selectedCollectionIds.length;
        closeSheet();
        showSheetToast('<?php echo addslashes($this->translate("Added to")); ?> ' + count + ' <?php echo addslashes($this->translate("collections")); ?>');
      } else {
        // Error: keep sheet open with selections preserved
        showSheetToast(data.error_message || '<?php echo addslashes($this->translate("Something went wrong. Please try again.")); ?>');
      }
    })
    .catch(function() {
      doneBtn.disabled = false;
      // Error: keep sheet open with selections preserved
      showSheetToast('<?php echo addslashes($this->translate("Something went wrong. Please try again.")); ?>');
    });
  });

  // ==========================================
  // "New Collection" button — show inline form
  // ==========================================
  newBtn.addEventListener('click', function() {
    showCreateForm();
  });

  function showCreateForm() {
    createForm.style.display = 'block';
    newBtn.style.display = 'none';
    nameInput.value = '';
    nameError.style.display = 'none';
    createSubmitBtn.disabled = true;
    nameInput.focus();
  }

  function hideCreateForm() {
    createForm.style.display = 'none';
    newBtn.style.display = '';
    nameInput.value = '';
    nameError.style.display = 'none';
  }

  // Cancel create form
  createCancelBtn.addEventListener('click', function() {
    hideCreateForm();
  });

  // Enable/disable Create button based on input
  nameInput.addEventListener('input', function() {
    var val = nameInput.value.trim();
    createSubmitBtn.disabled = (val.length === 0);
    nameError.style.display = 'none';
  });

  // Submit new collection
  createSubmitBtn.addEventListener('click', function() {
    var name = nameInput.value.trim();
    if (!name) return;

    createSubmitBtn.disabled = true;

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

    fetch(en4.core.baseUrl + 'core/savecollection/collection-create', {
      method: 'POST',
      body: formData
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
      if (data.error == '0' || data.status === true) {
        var newCollection = data.result || data.body;
        var newId = newCollection.collection_id;
        var newName = newCollection.name || name;

        // Add new chip to the list and auto-select it
        addChip(newId, newName, true);
        selectedCollectionIds.push(newId);

        // Remove empty state message if present
        var emptyMsg = chipsContainer.querySelector('.savecollection_sheet_empty');
        if (emptyMsg) emptyMsg.remove();

        hideCreateForm();
        showSheetToast('<?php echo addslashes($this->translate("Collection created")); ?>');
      } else {
        // Show validation error inline
        var errorMsg = data.error_message || data.error || '<?php echo addslashes($this->translate("Failed to create collection.")); ?>';
        nameError.textContent = errorMsg;
        nameError.style.display = 'block';
        createSubmitBtn.disabled = false;
      }
    })
    .catch(function() {
      nameError.textContent = '<?php echo addslashes($this->translate("Something went wrong. Please try again.")); ?>';
      nameError.style.display = 'block';
      createSubmitBtn.disabled = false;
    });
  });

  // Allow Enter key to submit the create form
  nameInput.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') {
      e.preventDefault();
      if (!createSubmitBtn.disabled) {
        createSubmitBtn.click();
      }
    }
  });

  // ==========================================
  // Helper: Add a new chip to the list
  // ==========================================
  function addChip(collectionId, name, isSelected) {
    var chip = document.createElement('button');
    chip.type = 'button';
    chip.className = 'savecollection_chip';
    chip.setAttribute('data-collection-id', collectionId);
    chip.setAttribute('aria-pressed', isSelected ? 'true' : 'false');
    chip.textContent = name;
    chipsContainer.appendChild(chip);
  }

  // ==========================================
  // Toast notification helper
  // ==========================================
  function showSheetToast(message) {
    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);
  }
});
</script>
