const API = 'api/quiz_questions.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'
};

let page = 1;
let total = 0;
let lastQuestions = [];

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();
}

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

function fillCategorySelects() {
  const options = Object.entries(CATEGORIES)
    .map(([key, label]) => `<option value="${key}">${label}</option>`)
    .join('');
  $('categoryInput').innerHTML = options;
  $('filterCategory').innerHTML = `<option value="">Toutes les catégories</option>${options}`;
}

function formData() {
  const options = $('optionsInput').value
    .split(/\n+/)
    .map(v => v.trim())
    .filter(Boolean);
  return {
    id: Number($('questionId').value || 0),
    category: $('categoryInput').value,
    question: $('questionInput').value.trim(),
    options,
    answer: $('answerInput').value.trim(),
    explanation: $('explanationInput').value.trim(),
    difficulty: $('difficultyInput').value,
    active: $('activeInput').checked ? 1 : 0
  };
}

function resetForm() {
  $('questionForm').reset();
  $('questionId').value = '';
  $('activeInput').checked = true;
  $('difficultyInput').value = 'standard';
  $('formTitle').textContent = 'Nouvelle question';
}

function editQuestion(id) {
  const q = lastQuestions.find(item => item.id === id);
  if (!q) return;
  $('questionId').value = q.id;
  $('categoryInput').value = q.category;
  $('questionInput').value = q.question;
  $('optionsInput').value = (q.options || []).join('\n');
  $('answerInput').value = q.answer;
  $('explanationInput').value = q.explanation || '';
  $('difficultyInput').value = q.difficulty || 'standard';
  $('activeInput').checked = Number(q.active) === 1;
  $('formTitle').textContent = `Modifier #${q.id}`;
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

async function saveQuestion(e) {
  e.preventDefault();
  try {
    const payload = formData();
    if (!payload.question || !payload.answer) {
      setStatus('Question et réponse exacte sont obligatoires.', true);
      return;
    }
    const data = await request('save', { method: 'POST', body: payload });
    setStatus(data.message);
    resetForm();
    loadQuestions();
  } catch (err) {
    setStatus(err.message, true);
  }
}

async function toggleQuestion(id, active) {
  try {
    const data = await request('toggle', { method: 'POST', body: { id, active: active ? 1 : 0 } });
    setStatus(data.message);
    loadQuestions();
  } catch (err) {
    setStatus(err.message, true);
  }
}

async function deleteQuestion(id) {
  if (!confirm('Supprimer définitivement cette question ?')) return;
  try {
    const data = await request('delete', { method: 'POST', body: { id } });
    setStatus(data.message);
    loadQuestions();
  } catch (err) {
    setStatus(err.message, true);
  }
}

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

function renderQuestions(questions) {
  const list = $('questionList');
  if (!questions.length) {
    list.innerHTML = '<p class="muted">Aucune question trouvée.</p>';
    return;
  }
  list.innerHTML = questions.map(q => {
    const label = CATEGORIES[q.category] || q.category;
    const options = (q.options || []).length ? `${q.options.length} options` : 'réponse libre';
    const active = Number(q.active) === 1;
    return `
      <article class="question-row ${active ? '' : 'is-off'}">
        <div>
          <h3>${escapeHtml(q.question)}</h3>
          <div class="question-meta">
            <span>#${q.id}</span>
            <span>${escapeHtml(label)}</span>
            <span>${escapeHtml(q.difficulty || 'standard')}</span>
            <span>${options}</span>
            <span>${active ? 'active' : 'désactivée'}</span>
          </div>
          <p class="question-answer">Réponse : ${escapeHtml(q.answer)}</p>
          ${q.explanation ? `<p class="muted">${escapeHtml(q.explanation)}</p>` : ''}
        </div>
        <div class="question-actions">
          <button class="btn ghost" type="button" onclick="editQuestion(${q.id})">Modifier</button>
          <button class="btn ghost" type="button" onclick="toggleQuestion(${q.id}, ${active ? 0 : 1})">${active ? 'Désactiver' : 'Activer'}</button>
          <button class="btn ghost" type="button" onclick="deleteQuestion(${q.id})">Supprimer</button>
        </div>
      </article>`;
  }).join('');
}

async function loadQuestions() {
  try {
    const params = new URLSearchParams();
    const category = $('filterCategory').value;
    const active = $('filterActive').value;
    const q = $('searchInput').value.trim();
    if (category) params.set('category', category);
    if (active !== '') params.set('active', active);
    if (q) params.set('q', q);
    params.set('page', page);
    params.set('limit', 30);
    const data = await request('list', { query: `&${params.toString()}` });
    lastQuestions = data.questions || [];
    total = data.total || 0;
    renderQuestions(lastQuestions);
    const maxPage = Math.max(1, Math.ceil(total / 30));
    $('pageInfo').textContent = `Page ${page}/${maxPage} - ${total} question(s)`;
    $('prevPageBtn').disabled = page <= 1;
    $('nextPageBtn').disabled = page >= maxPage;
  } catch (err) {
    setStatus(err.message, true);
  }
}

function parseCsvLine(line, delimiter = ';') {
  const cells = [];
  let current = '';
  let quoted = false;
  for (let i = 0; i < line.length; i++) {
    const ch = line[i];
    if (ch === '"') {
      if (quoted && line[i + 1] === '"') {
        current += '"';
        i++;
      } else {
        quoted = !quoted;
      }
    } else if (ch === delimiter && !quoted) {
      cells.push(current);
      current = '';
    } else {
      current += ch;
    }
  }
  cells.push(current);
  return cells.map(v => v.trim());
}

function parseCsv(text) {
  const lines = text.replace(/\r/g, '').split('\n').filter(line => line.trim());
  if (lines.length < 2) return [];
  const delimiter = lines[0].includes(';') ? ';' : ',';
  const headers = parseCsvLine(lines[0], delimiter).map(h => h.toLowerCase().trim());
  return lines.slice(1).map(line => {
    const cells = parseCsvLine(line, delimiter);
    const row = {};
    headers.forEach((h, i) => row[h] = cells[i] || '');
    const options = row.options
      ? row.options.split('|').map(v => v.trim()).filter(Boolean)
      : [row.option_a, row.option_b, row.option_c, row.option_d].map(v => (v || '').trim()).filter(Boolean);
    return {
      category: row.category,
      question: row.question,
      options,
      answer: row.answer,
      explanation: row.explanation || '',
      difficulty: row.difficulty || 'standard',
      active: row.active === '0' ? 0 : 1
    };
  }).filter(q => q.category && q.question && q.answer);
}

async function importCsv() {
  try {
    const questions = parseCsv($('csvInput').value);
    if (!questions.length) {
      setStatus('CSV vide ou colonnes manquantes.', true);
      return;
    }
    const data = await request('bulk', { method: 'POST', body: { questions } });
    setStatus(`${data.message} : ${data.imported} importée(s), ${data.skipped} ignorée(s).`);
    $('csvInput').value = '';
    page = 1;
    loadQuestions();
  } catch (err) {
    setStatus(err.message, true);
  }
}

async function seedDefaults() {
  if (!confirm('Importer les questions actuelles du site dans la base ?')) return;
  try {
    const data = await request('seed_defaults', { method: 'POST', body: {} });
    setStatus(`${data.message} : ${data.imported} question(s).`);
    page = 1;
    loadQuestions();
  } catch (err) {
    setStatus(err.message, true);
  }
}

function loadTemplate() {
  $('csvInput').value = [
    'category;question;option_a;option_b;option_c;option_d;answer;explanation;difficulty',
    'science;Combien de planètes compte le système solaire ?;7;8;9;10;8;Depuis 2006, Pluton est classée planète naine.;facile',
    'rap;Quel rappeur a sorti Ipséité ?;Nekfeu;Damso;SCH;Orelsan;Damso;Ipséité est un album de Damso sorti en 2017.;standard'
  ].join('\n');
}

function init() {
  fillCategorySelects();
  $('adminKey').value = localStorage.getItem('tq_admin_key') || '';
  $('saveKeyBtn').addEventListener('click', () => {
    localStorage.setItem('tq_admin_key', getKey());
    setStatus('Clé enregistrée sur cet appareil.');
    loadQuestions();
  });
  $('questionForm').addEventListener('submit', saveQuestion);
  $('resetFormBtn').addEventListener('click', resetForm);
  $('refreshBtn').addEventListener('click', () => { page = 1; loadQuestions(); });
  $('seedBtn').addEventListener('click', seedDefaults);
  $('importCsvBtn').addEventListener('click', importCsv);
  $('loadTemplateBtn').addEventListener('click', loadTemplate);
  $('prevPageBtn').addEventListener('click', () => { if (page > 1) { page--; loadQuestions(); } });
  $('nextPageBtn').addEventListener('click', () => { page++; loadQuestions(); });
  ['filterCategory', 'filterActive'].forEach(id => $(id).addEventListener('change', () => { page = 1; loadQuestions(); }));
  $('searchInput').addEventListener('input', () => {
    clearTimeout(window.__adminSearchTimer);
    window.__adminSearchTimer = setTimeout(() => { page = 1; loadQuestions(); }, 250);
  });
  if (getKey()) loadQuestions();
}

window.editQuestion = editQuestion;
window.toggleQuestion = toggleQuestion;
window.deleteQuestion = deleteQuestion;
document.addEventListener('DOMContentLoaded', init);
