
<?php
$keyWordsData = $project->getKeyWords();
?>
<label for="palabras_claves" class="form-label"><?php echo __('Palabras claves') ?></label>
<div class="flex w-full sm:w-auto items-center space-x-1">
    <?php echo $this->Form->control('tag-input-'.$id, ['id'=> 'tag-input-'.$id,'class'=>'flex-1 form-input','label'=>false, 'templates' => ['inputContainer' => '{{content}}']]); ?>
    <button
        type="button"
        id="add-tag-<?php echo $id ?>"
        class="btn b-solid btn-primary-solid"
    >
        Agregar
    </button>
</div>
<?= $this->Form->error($id) ?>
<div id="tag-container-<?php echo $id ?>" class="mt-2 flex flex-wrap gap-2 p-2 border border-gray-300 rounded-md bg-white min-h-[48px]">
</div>

<?php echo $this->Form->hidden($id, ['id' => 'tags-hidden-'.$id, 'value' => $keyWordsData['str']]); ?>
<script>
$(document).ready(function () {
  let tags = <?php echo json_encode($keyWordsData['array']) ?>;
  let tagContainerStr = 'tag-container-' + '<?php echo $id ?>';
  let tagsHiddenStr = 'tags-hidden-' + '<?php echo $id ?>';
  let tagInputStr = 'tag-input-' + '<?php echo $id ?>';
  let addTagStr = 'add-tag-' + '<?php echo $id ?>';
  if(tags.length > 0)
  {
    renderTags();
  }
  function renderTags() {
    // Borra las etiquetas anteriores
    $('#' +  tagContainerStr).html('');
    tags.forEach((tag, index) => {
      const tagEl = $(`
        <span class="tag flex items-center bg-primary-200 text-primary-500 text-sm px-2 py-1 rounded-md">
          ${tag}
          <button type="button" class="ml-1 text-primary-500 hover:text-red-600" data-index="${index}">&times;</button>
        </span>
      `);
      $('#' + tagContainerStr).append(tagEl);
    });
    // Actualiza campo oculto
    $('#' + tagsHiddenStr).val(tags.join(','));
  }
  function addTag(value) {
    value = value.trim().replace(/,+$/, '');
    if (value && !tags.includes(value)) {
      tags.push(value);
      $('#' + tagInputStr).val('');
      renderTags();
    }
  }
  // Agrega al presionar Enter o coma
  $('#' + tagInputStr).on('keydown', function (e) {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault();
      addTag($(this).val());
    }
  });
  // Agrega al hacer clic en el botón
  $('#' + addTagStr).on('click', function () {
    addTag($('#' + tagInputStr).val());
  });
  // Eliminar una etiqueta
  $('#' + tagContainerStr).on('click', 'button[data-index]', function () {
    const index = $(this).data('index');
    tags.splice(index, 1);
    renderTags();
  });
});
</script>
