---
import BaseLayout from '../layouts/BaseLayout.astro';
import { getToolsData } from '../utils/dataService.js';


const data = await getToolsData();

const hostedServices = data.tools.filter((tool: any) => {
  return tool.projectUrl !== undefined && 
         tool.projectUrl !== null && 
         tool.projectUrl !== "" && 
         tool.projectUrl.trim() !== "";
});
---

<BaseLayout title="Service Status">
  <section class="section-padding">
    <h1 class="content-center">Service Status</h1>
    <p class="text-muted" style="text-align: center; max-width: 600px; margin: 0 auto 3rem;">
      Live-Monitoring zum Onlinestatus der Dienste.
    </p>
    
    <div class="grid grid-cols-2 gap-4" style="margin-bottom: 3rem;">
      {hostedServices.map((service: any) => (
        <div class="card">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
            <h3 style="margin: 0;">{service.name}</h3>
            <div id={`status-${service.name.toLowerCase().replace(/\s+/g, '-')}`}>
              <span class="badge badge-warning">Loading...</span>
            </div>
          </div>
          <p class="text-muted" style="font-size: 0.875rem; margin-bottom: 1rem;">
            {service.description}
          </p>
          <a href={service.projectUrl} target="_blank" rel="noopener noreferrer" class="btn btn-secondary">
            Zugreifen →
          </a>
        </div>
      ))}
    </div>
    
  </section>
</BaseLayout>

<script define:vars={{ hostedServices }}>
  document.addEventListener('DOMContentLoaded', () => {
    hostedServices.forEach(service => {
      const statusElement = document.getElementById(`status-${service.name.toLowerCase().replace(/\s+/g, '-')}`);
      
      if (statusElement && service.statusUrl) {
        const img = document.createElement('img');
        img.src = service.statusUrl;
        img.alt = `Status for ${service.name}`;
        img.style.height = '20px';
        img.style.verticalAlign = 'middle';
        
        img.onerror = function() {
          statusElement.innerHTML = '<span class="badge badge-warning">Unknown</span>';
        };
        
        statusElement.innerHTML = '';
        statusElement.appendChild(img);
      } else if (statusElement) {
        statusElement.innerHTML = '<span class="badge badge-warning">No Status</span>';
      }
    });
  });
</script>