// ====================== API INTEGRATION ======================
// Fetch & Display Users from JSONPlaceholder API

const API_URL = 'https://jsonplaceholder.typicode.com/users';
const apiContainer = document.getElementById('apiUsersContainer');

/**
 * Fetches users from JSONPlaceholder API
 * Parses response as JSON and renders to DOM
 * Includes error handling with catch()
 */
function fetchAndDisplayUsers() {
  if (!apiContainer) {
    console.log('API container not found on this page');
    return;
  }

  // Show loading state
  apiContainer.innerHTML = '<p class="loading">Daten werden geladen...</p>';

  fetch(API_URL)
    .then(response => {
      console.log('Response Status:', response.status);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.json();
    })
    .then(data => {
      console.log('Fetched Users Data:', data);

      // Clear container
      apiContainer.innerHTML = '';

      // Create list of users using createElement
      const userList = document.createElement('ul');
      userList.className = 'api-users-list';

      data.forEach(user => {
        const listItem = document.createElement('li');
        listItem.className = 'api-user-item';

        // Create user card with detailed information
        const userCard = document.createElement('div');
        userCard.className = 'api-user-card';

        userCard.innerHTML = `
          <div class="api-user-header">
            <h3 class="api-user-name">${user.name}</h3>
            <span class="api-user-id">ID: ${user.id}</span>
          </div>
          <div class="api-user-details">
            <p><strong>Username:</strong> ${user.username}</p>
            <p><strong>Email:</strong> <a href="mailto:${user.email}">${user.email}</a></p>
            <p><strong>Telefon:</strong> ${user.phone}</p>
            <p><strong>Website:</strong> <a href="https://${user.website}" target="_blank">${user.website}</a></p>
            <p><strong>Firma:</strong> ${user.company.name}</p>
          </div>
        `;

        listItem.appendChild(userCard);
        userList.appendChild(listItem);
      });

      apiContainer.appendChild(userList);
      console.log(`Successfully loaded and displayed ${data.length} users`);
    })
    .catch(error => {
      console.error('Error fetching users:', error);
      apiContainer.innerHTML = `
        <div class="error-message">
          <h3>⚠️ Fehler beim Laden der Daten</h3>
          <p>${error.message}</p>
          <p>Bitte versuchen Sie es später erneut oder kontaktieren Sie den Administrator.</p>
          <button onclick="fetchAndDisplayUsers()" class="retry-btn">Erneut versuchen</button>
        </div>
      `;
    });
}

// Execute on page load
document.addEventListener('DOMContentLoaded', fetchAndDisplayUsers);
