<?php
require __DIR__ . '/lib.php';

$slug = slugify($_GET['form'] ?? '');
$form = $slug ? load_form($slug) : null;
if (!$form) {
    http_response_code(404);
    echo 'Sondage introuvable';
    exit;
}

$count = response_count($slug);
$closed = is_form_closed($form);
$publicUrl = survey_url($slug);
$background = trim((string)($form['meta']['background'] ?? ''));
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= h($form['meta']['name']) ?> — Sondage</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <main class="survey-shell" style="<?= $background ? '--survey-bg:url(' . h($background) . ');' : '' ?>">
    <div class="survey-overlay"></div>
    <section class="survey-card">
      <div class="survey-card-inner">
        <div class="survey-top">
          <div>
            <div class="badge">MyKollectOr® · Sondage</div>
          </div>
          <div class="counter"><strong id="responseCount"><?= $count ?></strong> réponse(s)</div>
        </div>
        <div class="progress-track"><div class="progress-bar" id="progressBar" style="width:0%"></div></div>
        <div id="app"></div>
      </div>
    </section>
  </main>

  <script>
    const SURVEY_DATA = <?= json_encode([
      'form' => $form,
      'closed' => $closed,
      'count' => $count,
      'publicUrl' => $publicUrl,
      'facebookUrl' => 'https://www.facebook.com/sharer/sharer.php?u=' . rawurlencode($publicUrl),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

    const app = document.getElementById('app');
    const progressBar = document.getElementById('progressBar');
    const responseCountEl = document.getElementById('responseCount');
    const answers = { prenom: '', nom: '' };
    const steps = SURVEY_DATA.form.steps;
    const renderedSteps = [];
    let questionIndex = 0;

    steps.forEach((step) => {
      if (step.type === 'intro' || step.type === 'identity' || step.type === 'multiple' || step.type === 'text') {
        renderedSteps.push({ ...step, key: step.type === 'multiple' || step.type === 'text' ? `Q${++questionIndex}` : step.type });
      }
    });

    let screenIndex = 0;
    const progressSteps = renderedSteps.filter(step => step.type !== 'intro').length;

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

    function setProgress() {
      const current = renderedSteps.slice(0, Math.min(screenIndex, renderedSteps.length)).filter(step => step.type !== 'intro').length;
      const pct = progressSteps ? Math.max(0, Math.min(100, (current / progressSteps) * 100)) : 0;
      progressBar.style.width = `${pct}%`;
    }

    function renderClosed() {
      app.innerHTML = `
        <div class="screen active">
          <div class="hero-title">Le sondage est fermé</div>
          <p class="hero-text">Le quota de réponses a été atteint ou la date de fin est dépassée.</p>
          <div class="copy-row">
            <a class="btn-secondary" href="${escapeHtml(SURVEY_DATA.facebookUrl)}" target="_blank" rel="noopener">Partager sur Facebook</a>
          </div>
        </div>
      `;
      setProgress();
    }

    function renderFinal(message = '') {
      app.innerHTML = `
        <div class="screen active">
          <div class="hero-title">Merci <?= '🙏' ?></div>
          <p class="final-text">Votre réponse a bien été enregistrée. Vous pouvez maintenant partager le sondage autour de vous.</p>
          ${message ? `<div class="success-box">${escapeHtml(message)}</div>` : ''}
          <div class="copy-row">
            <a class="btn-primary" href="${escapeHtml(SURVEY_DATA.facebookUrl)}" target="_blank" rel="noopener">Partager sur Facebook</a>
            <button class="btn-secondary" type="button" id="copyLinkBtn">Copier le lien</button>
          </div>
          <p class="hint" style="margin-top:16px">Texte suggéré : ${escapeHtml(SURVEY_DATA.form.meta.shareText || '')}</p>
        </div>
      `;
      const btn = document.getElementById('copyLinkBtn');
      if (btn) {
        btn.addEventListener('click', async () => {
          try {
            await navigator.clipboard.writeText(SURVEY_DATA.publicUrl);
            btn.textContent = 'Lien copié';
          } catch (e) {
            window.prompt('Copiez ce lien :', SURVEY_DATA.publicUrl);
          }
        });
      }
      screenIndex = renderedSteps.length + 1;
      setProgress();
    }

    function renderError(message) {
      const box = document.getElementById('errorBox');
      if (box) box.innerHTML = `<div class="error-box">${escapeHtml(message)}</div>`;
    }

    function goto(delta) {
      screenIndex += delta;
      renderScreen();
    }

    function submitSurvey() {
      fetch('submit.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          form: SURVEY_DATA.form.meta.slug,
          honeypot: document.getElementById('hpField')?.value || '',
          answers
        })
      })
      .then(r => r.json())
      .then((data) => {
        if (data.success) {
          responseCountEl.textContent = data.count ?? Number(responseCountEl.textContent || '0') + 1;
          renderFinal('Merci, votre participation a bien été prise en compte.');
          return;
        }
        if (data.alreadyAnswered) {
          renderFinal(data.message || 'Vous avez déjà participé à ce sondage.');
          return;
        }
        if (data.closed) {
          renderClosed();
          return;
        }
        renderError(data.message || 'Une erreur est survenue.');
      })
      .catch(() => renderError('Impossible d’envoyer votre réponse pour le moment.'));
    }

    function renderOptions(step) {
      const currentValue = answers[step.key];
      return `
        <div class="option-list">
          ${step.options.map((option) => {
            const isMulti = step.selection === 'multiple';
            const selected = isMulti
              ? Array.isArray(currentValue) && currentValue.includes(option)
              : currentValue === option;
            return `
              <button type="button" class="option-card ${selected ? 'is-active' : ''}" data-option="${escapeHtml(option)}">
                <span class="option-bullet ${isMulti ? 'option-checkbox' : ''}"></span>
                <span>${escapeHtml(option)}</span>
              </button>
            `;
          }).join('')}
        </div>
      `;
    }

    function renderScreen() {
      if (SURVEY_DATA.closed) {
        renderClosed();
        return;
      }
      if (screenIndex >= renderedSteps.length) {
        submitSurvey();
        return;
      }

      const step = renderedSteps[screenIndex];
      if (!step) return;

      if (step.type === 'intro') {
        app.innerHTML = `
          <div class="screen active">
            <div class="hero-title">${escapeHtml(step.title)}</div>
            <p class="hero-text">${escapeHtml(step.text || SURVEY_DATA.form.meta.description || '')}</p>
            <div class="copy-row" style="margin-top:24px">
              <button class="btn-primary" type="button" id="nextBtn">${escapeHtml(step.button || 'Commencer')}</button>
            </div>
            <input type="text" id="hpField" class="hp-field" autocomplete="off" tabindex="-1">
            <div id="errorBox"></div>
          </div>
        `;
        document.getElementById('nextBtn').addEventListener('click', () => goto(1));
        setProgress();
        return;
      }

      if (step.type === 'identity') {
        app.innerHTML = `
          <div class="screen active">
            <div class="question-title">Votre identité</div>
            <p class="question-text">Prénom et nom sont obligatoires avant de continuer.</p>
            <div class="form-grid" style="margin-top:20px">
              <div>
                <label class="lbl">Prénom</label>
                <input class="input" id="prenomInput" value="${escapeHtml(answers.prenom || '')}" placeholder="Votre prénom">
              </div>
              <div>
                <label class="lbl">Nom</label>
                <input class="input" id="nomInput" value="${escapeHtml(answers.nom || '')}" placeholder="Votre nom">
              </div>
            </div>
            <div class="question-actions">
              <button class="btn-secondary" type="button" id="backBtn">Retour</button>
              <button class="btn-primary" type="button" id="nextBtn">Continuer</button>
            </div>
            <div id="errorBox"></div>
          </div>
        `;
        document.getElementById('backBtn').addEventListener('click', () => goto(-1));
        document.getElementById('nextBtn').addEventListener('click', () => {
          answers.prenom = document.getElementById('prenomInput').value.trim();
          answers.nom = document.getElementById('nomInput').value.trim();
          if (!answers.prenom || !answers.nom) {
            renderError('Merci de renseigner votre prénom et votre nom.');
            return;
          }
          goto(1);
        });
        setProgress();
        return;
      }

      if (step.type === 'multiple') {
        app.innerHTML = `
          <div class="screen active">
            <div class="question-title">Question ${step.key.replace('Q','')}</div>
            <p class="question-text">${escapeHtml(step.question)}</p>
            <p class="hint">${step.selection === 'multiple' ? 'Plusieurs réponses possibles' : 'Une réponse'}.</p>
            ${renderOptions(step)}
            <div class="question-actions">
              <button class="btn-secondary" type="button" id="backBtn">Retour</button>
              <button class="btn-primary" type="button" id="nextBtn">Continuer</button>
            </div>
            <div id="errorBox"></div>
          </div>
        `;
        document.querySelectorAll('[data-option]').forEach((button) => {
          button.addEventListener('click', () => {
            const value = button.dataset.option;
            if (step.selection === 'multiple') {
              const current = Array.isArray(answers[step.key]) ? [...answers[step.key]] : [];
              const index = current.indexOf(value);
              if (index >= 0) current.splice(index, 1); else current.push(value);
              answers[step.key] = current;
            } else {
              answers[step.key] = value;
            }
            renderScreen();
          });
        });
        document.getElementById('backBtn').addEventListener('click', () => goto(-1));
        document.getElementById('nextBtn').addEventListener('click', () => {
          const value = answers[step.key];
          if (!value || (Array.isArray(value) && value.length === 0)) {
            renderError('Merci de sélectionner au moins une réponse.');
            return;
          }
          goto(1);
        });
        setProgress();
        return;
      }

      if (step.type === 'text') {
        app.innerHTML = `
          <div class="screen active">
            <div class="question-title">Question ${step.key.replace('Q','')}</div>
            <p class="question-text">${escapeHtml(step.question)}</p>
            <div style="margin-top:20px">
              <textarea class="textarea" id="textAnswer" placeholder="${escapeHtml(step.placeholder || 'Votre réponse...')}">${escapeHtml(answers[step.key] || '')}</textarea>
            </div>
            <div class="question-actions">
              <button class="btn-secondary" type="button" id="backBtn">Retour</button>
              <button class="btn-primary" type="button" id="nextBtn">Terminer</button>
            </div>
            <div id="errorBox"></div>
          </div>
        `;
        document.getElementById('backBtn').addEventListener('click', () => goto(-1));
        document.getElementById('nextBtn').addEventListener('click', () => {
          answers[step.key] = document.getElementById('textAnswer').value.trim();
          if (!answers[step.key]) {
            renderError('Merci de saisir une réponse avant de continuer.');
            return;
          }
          goto(1);
        });
        setProgress();
      }
    }

    renderScreen();
  </script>
</body>
</html>
