<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <title>Agrégateur Multi-Source</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background: #1a1a1a; color: #e0e0e0; margin: 0; padding: 20px; font-size: 14px; }
    .container { max-width: 1200px; margin: auto; }
    h1 { color: #fff; text-align: center; }
    .searchbox { margin: 20px 0 30px; display: flex; justify-content: center; }
    input[type="text"] { font-size: 1.1em; width: clamp(200px, 60%, 500px); background: #2c2c2c; color: #fff; border: 1px solid #444; border-radius: 4px; padding: 10px 12px; }
    button { font-size: 1.1em; padding: 10px 18px; background: #007aff; color: #fff; border-radius: 4px; border: none; margin-left: 10px; cursor: pointer; transition: background-color 0.2s; }
    button:hover { background: #005bb5; }
    #films { margin-top: 20px; }
    .results-table { width: 100%; border-collapse: collapse; table-layout: fixed; }
    .results-table th, .results-table td { border: 1px solid #333; padding: 12px; text-align: left; vertical-align: top; }
    .results-table th { background-color: #252525; color: #ccc; font-weight: 600; }
    .results-table td:nth-child(1) { width: 25%; }
    .results-table td:nth-child(2) { width: 10%; }
    .results-table td:nth-child(3) { width: 65%; }
    .source-block { border: 1px solid #383838; border-radius: 4px; padding: 10px; margin-bottom: 10px; background-color: #222; }
    .source-block:last-child { margin-bottom: 0; }
    .source-name { font-weight: bold; color: #58a6ff; margin-bottom: 8px; font-size: 1.1em; }
    .source-block img { max-height: 100px; float: right; margin-left: 10px; border-radius: 3px; }
    .source-block p { margin: 4px 0; line-height: 1.5; }
    .source-block a { color: #79c0ff; text-decoration: none; }
    .source-block a:hover { text-decoration: underline; }
    .year { color: #aaa; }
    .loader { text-align: center; font-size: 1.2em; color: #888; }
    .no-results { text-align: center; font-size: 1.1em; color: #999; margin-top:30px;}
  </style>
</head>
<body>
  <div class="container">
    <img src="/logo.png" alt="Logo Cine Kids" style="display:block;margin:30px auto 10px;max-width:130px;height:auto;">
    <h1>Ciné-agrégateur Multi-Source</h1>
    <div class="searchbox">
      <input type="text" id="q" placeholder="Ex: Dune, Spider-Man, Oppenheimer..." />
      <button onclick="search()">Rechercher</button>
    </div>
    <div id="films"></div>
  </div>

  <script>
    async function search() {
      const query = document.getElementById('q').value.trim();
      if (!query) return;
      const filmsDiv = document.getElementById('films');
      filmsDiv.innerHTML = '<p class="loader">Recherche en cours...</p>';

      try {
        const response = await fetch(`http://localhost:3000/search?q=${encodeURIComponent(query)}`);
        if (!response.ok) {
          // Gilfoyle: "The network, or your server, is garbage."
          filmsDiv.innerHTML = `<p class="no-results">Erreur: ${response.status} ${response.statusText || 'Impossible de joindre le backend.'}</p>`;
          return;
        }
        const films = await response.json();

        if (!Array.isArray(films) || !films.length) {
          filmsDiv.innerHTML = '<p class="no-results">Aucun résultat trouvé. Essayez un autre terme.</p>';
          return;
        }

        let html = `<table class="results-table">
          <thead>
            <tr>
              <th>Titre</th>
              <th>Année</th>
              <th>Sources d'information</th>
            </tr>
          </thead>
          <tbody>`;

        films.forEach(film => {
          html += `<tr>
            <td>${film.title || 'Titre inconnu'}</td>
            <td class="year">${film.year || 'N/A'}</td>
            <td>`;

          film.results.forEach(r => {
            html += `<div class="source-block">
              <p class="source-name">${r.source.charAt(0).toUpperCase() + r.source.slice(1)}</p>`;
            if (r.img) {
              html += `<img src="${r.img}" alt="Affiche pour ${film.title}">`;
            }
            if (r.link) {
              html += `<p><a href="${r.link}" target="_blank">Voir la fiche détaillée</a></p>`;
            }

            // CommonSense Media specific
            if (r.source === 'commonsense') {
              html += `<p><b>Âge conseillé:</b> ${r.age || '-'}</p>`;
              html += `<p><b>Résumé (CSM):</b> ${r.summary || r.parentsNeedToKnow || '-'}</p>`;
              if (r.details && r.details.length) {
                html += `<p><b>Détails (CSM):</b></p><ul>`;
                r.details.forEach(d => {
                  html += `<li>${d.type}: ${d.score}/5 - ${d.description || ''}</li>`;
                });
                html += `</ul>`;
              }
            }
            // Cinecheck specific
            else if (r.source === 'cinecheck') {
              html += `<p><b>Âge(s) (Cinecheck):</b> ${r.marks && r.marks.length ? r.marks.join(', ') : '-'}</p>`;
              html += `<p><b>Résumé (Cinecheck):</b> ${r.summary || '-'}</p>`;
              if (r.details && r.details.length) {
                html += `<p><b>Pictogrammes (Cinecheck):</b> ${r.details.map(d => d.type).join(', ') || '-'}</p>`;
              }
            }
            // Filmages specific
            else if (r.source === 'filmages') {
              html += `<p><b>Titre original (Filmages):</b> ${r.details.titleOriginalPage || r.details.titleOriginal || '-'}</p>`;
              html += `<p><b>Âge légal (Filmages):</b> ${r.details.ageLegal || '-'}</p>`;
              html += `<p><b>Âge suggéré (Filmages):</b> ${r.details.ageSuggested || '-'}</p>`;
              html += `<p><b>Résumé (Filmages):</b> ${r.details.summary || '-'}</p>`;
              html += `<p><b>Synthèse (Filmages):</b> ${r.details.synthesis || '-'}</p>`;
              if (r.details.indications && r.details.indications.length) {
                html += `<p><b>Indications:</b> ${r.details.indications.join(', ')}</p>`;
              }
              if (r.details.counterIndications && r.details.counterIndications.length) {
                html += `<p><b>Contre-indications:</b> ${r.details.counterIndications.join(', ')}</p>`;
              }
            }
            // Fallback for any other or new source
            else {
                html += `<p><b>Résumé:</b> ${r.summary || '-'}</p>`;
                html += `<p><b>Âge:</b> ${r.age || '-'}</p>`;
            }
            html += `</div>`;
          });
          html += `</td></tr>`;
        });

        html += '</tbody></table>';
        filmsDiv.innerHTML = html;
      } catch (error) {
        // Mike: "Didn't go as planned."
        console.error('Search function error:', error);
        filmsDiv.innerHTML = `<p class="no-results">Une erreur s'est produite lors de la recherche. Vérifiez la console.</p>`;
      }
    }
    document.getElementById('q').addEventListener('keydown', e => { if (e.key === 'Enter') search(); });
  </script>
</body>
</html>