const API = 'api/ai.php';

const CATEGORIES = {
  science: 'Science',
  espace: 'Espace',
  geopo: 'Géopolitique',
  mythologie: 'Mythologie',
  history: 'Histoire',
  rap: 'Rap français',
  insolite: 'Insolite',
  christian: 'Culture chrétienne',
  etymologie: 'Étymologie',
  films_facile: 'Films (Facile)',
  films_difficile: 'Films (Difficile)',
  paris: 'Paris',
  alcool: 'Alcools',
  ortho_choix: 'Orthographe QCM',
  ortho_faute_f: 'Fautes faciles',
  ortho_faute_d: 'Fautes difficiles'
};

const GAME_TYPES = {
  memory: 'Memory Dates',
  timeline: 'Timeline Battle',
  popcorn: 'Popcorn Clash',
  geo: 'Géo-devinette',
  sondage: 'Sondage',
  juste_prix: 'Le Juste Prix',
  alcool_order: 'Degré Battle'
};

const $ = (id) => document.getElementById(id);

function setStatus(message, isError = false) {
  const el = $('adminStatus');
  if (!el) return;
  el.textContent = message || '';
  el.style.color = isError ? 'var(--bad)' : 'var(--muted)';
}

function getKey() {
  return $('adminKey').value.trim();
}

function escapeHtml(value) {
  return String(value ?? '')
    .replaceAll('&', '&amp;')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#039;');
}

function showResult(data) {
  $('aiResult').textContent = JSON.stringify(data, null, 2);
}

function digestFromResponse(data) {
  return data?.digest || data;
}

function renderPreview(data) {
  const digest = digestFromResponse(data);
  const title = digest?.title || 'Actu du jour';
  const date = digest?.date || data?.news_date || '';
  const summary = Array.isArray(digest?.summary) ? digest.summary : [];
  const items = Array.isArray(digest?.items) ? digest.items : [];

  $('previewWrap').innerHTML = `
    <article class="ai-news-preview">
      <div class="daily-header">
        <span class="daily-badge">Actu IA</span>
        <span class="tiny">${escapeHtml(date)}</span>
      </div>
      <h3>${escapeHtml(title)}</h3>
      ${summary.length ? `<ul>${summary.map(line => `<li>${escapeHtml(line)}</li>`).join('')}</ul>` : '<p class="muted">Aucun résumé disponible.</p>'}
      ${items.length ? `
        <div class="ai-news-list">
          ${items.map(item => `
            <section class="ai-news-item">
              <h4>${escapeHtml(item.title || 'Info')}</h4>
              <p>${escapeHtml(item.what_happened || '')}</p>
              ${item.why_it_matters ? `<p class="muted">${escapeHtml(item.why_it_matters)}</p>` : ''}
              ${item.source_hint ? `<span class="tiny">À vérifier : ${escapeHtml(item.source_hint)}</span>` : ''}
            </section>
          `).join('')}
        </div>` : ''}
    </article>
  `;
}

function fillSelects() {
  $('quizCategory').innerHTML = Object.entries(CATEGORIES)
    .map(([key, label]) => `<option value="${key}">${label}</option>`)
    .join('');
  $('gameType').innerHTML = Object.entries(GAME_TYPES)
    .map(([key, label]) => `<option value="${key}">${label}</option>`)
    .join('');
}

async function request(action, body = null, needsKey = true) {
  const key = needsKey ? `&key=${encodeURIComponent(getKey())}` : '';
  const res = await fetch(`${API}?action=${action}${key}`, {
    method: body ? 'POST' : 'GET',
    headers: { 'Content-Type': 'application/json' },
    body: body ? JSON.stringify(body) : undefined
  });
  const data = await res.json().catch(() => ({ message: 'Réponse serveur invalide' }));
  if (!res.ok) {
    const detail = data.details || data.raw_text || data.raw || data.endpoint || '';
    const err = new Error(detail ? `${data.message || 'Erreur serveur'} : ${detail}` : (data.message || 'Erreur serveur'));
    err.data = data;
    throw err;
  }
  return data;
}

async function runDailyGeneration() {
  try {
    setStatus('Génération du résumé en cours...');
    const instructions = $('dailyInstructions')?.value.trim() || '';
    localStorage.setItem('tq_daily_instructions', instructions);
    const data = await request('generate_daily', {
      date: $('dailyDate').value,
      topic: $('dailyTopic').value.trim() || 'general',
      instructions,
      use_web: $('dailyWeb').checked
    });
    showResult(data);
    renderPreview(data);
    setStatus("Résumé publié sur l'accueil.");
  } catch (err) {
    setStatus(err.message, true);
    showResult(err.data || { error: err.message });
  }
}

async function runGeneration(label, action, body) {
  try {
    setStatus(`${label} en cours...`);
    const data = await request(action, body);
    showResult(data);
    setStatus(data.imported ? `${label} terminé : ${data.imported} élément(s) ajouté(s).` : `${label} terminé.`);
  } catch (err) {
    setStatus(err.message, true);
    showResult(err.data || { error: err.message });
  }
}

async function loadPublicDaily() {
  try {
    setStatus('Chargement de l’actu publiée...');
    const date = $('dailyDate').value || new Date().toISOString().slice(0, 10);
    const topic = encodeURIComponent($('dailyTopic').value.trim() || 'general');
    const res = await fetch(`${API}?action=daily_cached&date=${encodeURIComponent(date)}&topic=${topic}`, { cache: 'no-store' });
    const data = await res.json().catch(() => ({ message: 'Réponse serveur invalide' }));
    if (!res.ok) throw new Error(data.message || 'Aucune actu publiée');
    showResult(data);
    renderPreview(data);
    setStatus('Actu publiée chargée.');
  } catch (err) {
    setStatus(err.message, true);
    showResult({ error: err.message });
  }
}

document.addEventListener('DOMContentLoaded', () => {
  fillSelects();
  $('adminKey').value = localStorage.getItem('tq_admin_key') || '';
  if ($('dailyInstructions')) {
    $('dailyInstructions').value = localStorage.getItem('tq_daily_instructions') || '';
  }
  $('dailyDate').value = new Date().toISOString().slice(0, 10);

  $('saveKeyBtn').addEventListener('click', () => {
    localStorage.setItem('tq_admin_key', getKey());
    setStatus('Clé admin enregistrée sur cet appareil.');
  });

  $('statusBtn').addEventListener('click', async () => {
    try {
      setStatus('Vérification...');
      const data = await request('test_ai');
      showResult(data);
      setStatus(`IA connectée (${data.provider} / ${data.model}).`);
    } catch (err) {
      setStatus(err.message, true);
      showResult(err.data || { error: err.message });
    }
  });

  $('dailyForm').addEventListener('submit', (event) => {
    event.preventDefault();
    runDailyGeneration();
  });

  $('quizForm').addEventListener('submit', (event) => {
    event.preventDefault();
    runGeneration('Génération quiz', 'generate_quiz', {
      category: $('quizCategory').value,
      count: Number($('quizCount').value || 10),
      difficulty: $('quizDifficulty').value,
      theme: $('quizTheme').value.trim(),
      import_questions: $('quizImport').checked
    });
  });

  $('gameForm').addEventListener('submit', (event) => {
    event.preventDefault();
    runGeneration('Génération jeux', 'generate_game', {
      game_type: $('gameType').value,
      count: Number($('gameCount').value || 10),
      theme: $('gameTheme').value.trim(),
      import_questions: $('gameImport').checked
    });
  });

  $('loadPublicBtn').addEventListener('click', loadPublicDaily);

  $('copyResultBtn').addEventListener('click', async () => {
    await navigator.clipboard.writeText($('aiResult').textContent || '{}');
    setStatus('JSON copié.');
  });
});
