// components/textinput.js
document.addEventListener('DOMContentLoaded', () => {
  fetch('components/textinput.html') // Make sure this path is correct
    .then(response => response.text())
    .then(html => {
      document.getElementById('textInputsContainer').innerHTML = html;
      initializeComponents();
    });

  function initializeComponents() {
    const textInputTemplate = document.getElementById('textInputTemplate').content;
    const container = document.getElementById('textInputsContainer');

    const textInputsData = [
      { placeholder: 'Enter your email' } // Example placeholder
    ];

    textInputsData.forEach(data => {
      const textInputClone = document.importNode(textInputTemplate, true);
      initializeComponent(textInputClone, data);
      container.appendChild(textInputClone);
    });

    function initializeComponent(component, { label, placeholder, description, suggestions = [], error = '' }) {
      const userInput = component.querySelector('.user-input');
      const clearButton = component.querySelector('.clear-button');
      const statusIcon = component.querySelector('.status-icon');
      const suggestionsList = component.querySelector('.suggestions-list');
      const errorMessage = component.querySelector('.error-message');
      const inputLabel = component.querySelector('.input-label');
      const inputDescription = component.querySelector('.input-description');

      if (label) {
        inputLabel.innerText = label;
        inputLabel.style.display = 'block';
      }

      if (placeholder) {
        userInput.placeholder = placeholder;
      }

      if (description) {
        inputDescription.innerText = description;
        inputDescription.style.display = 'block';
      }

      userInput.addEventListener('input', (e) => {
        const value = e.target.value;
        if (value) {
          clearButton.style.display = 'flex';
          validateInput(value);
          if (suggestions.length > 0) {
            showSuggestions(value);
          }
        } else {
          clearButton.style.display = 'none';
          suggestionsList.style.display = 'none';
          removeValidationStyles();
          inputDescription.style.display = description ? 'block' : 'none';
        }
      });

      clearButton.addEventListener('click', () => {
        userInput.value = '';
        clearButton.style.display = 'none';
        suggestionsList.style.display = 'none';
        removeValidationStyles();
        inputDescription.style.display = description ? 'block' : 'none';
      });

      const showSuggestions = (value) => {
        const filteredSuggestions = suggestions.filter(suggestion =>
          suggestion.toLowerCase().includes(value.toLowerCase())
        );

        if (filteredSuggestions.length > 0) {
          suggestionsList.innerHTML = '';
          filteredSuggestions.forEach(suggestion => {
            const listItem = document.createElement('li');
            listItem.textContent = suggestion;
            listItem.classList.add('px-4', 'py-2', 'cursor-pointer', 'hover:bg-gray-200');
            listItem.addEventListener('click', () => {
              userInput.value = suggestion;
              suggestionsList.style.display = 'none';
              clearButton.style.display = 'none';
              validateInput(suggestion);
            });
            suggestionsList.appendChild(listItem);
          });
          suggestionsList.style.display = 'block';
        } else {
          suggestionsList.innerHTML = '<li class="px-4 py-2">No results found</li>';
          suggestionsList.style.display = 'block';
        }
      };

      const validateInput = (value) => {
        removeValidationStyles();
        if (value.toLowerCase() === 'error') {
          setError('Error description lorem ipsum');
        } else {
          setValidated();
        }
      };

      const removeValidationStyles = () => {
        userInput.classList.remove('input-error', 'input-success');
        errorMessage.style.display = 'none';
        statusIcon.style.display = 'none';
      };

      const setError = (error) => {
        userInput.classList.add('input-error');
        errorMessage.textContent = error;
        errorMessage.style.display = 'block';
        statusIcon.innerHTML = `
          <svg class="h-5 w-5 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        `;
        statusIcon.style.display = 'flex';
      };

      const setValidated = () => {
        userInput.classList.add('input-success');
        errorMessage.style.display = 'none';
        statusIcon.innerHTML = `
          <svg class="h-5 w-5 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
          </svg>
        `;
        statusIcon.style.display = 'flex';
      };

      if (error) {
        setError(error);
      }
    }
  }
});
