import { FormConfig, DEFAULT_FORM_CONFIG } from '../types';

export function getStandaloneFormHtml(config: FormConfig = DEFAULT_FORM_CONFIG): string {
  const activeStepsCount =
    (config.enableQuestion1 ? 1 : 0) + (config.enableQuestion2 ? 1 : 0) + 1;

  const bName = config.businessName || 'Apex English Academy';

  return `<!DOCTYPE html>
<html lang="fr" class="h-full">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>${bName} | Évaluation d'Anglais Gratuite</title>
  <!-- Tailwind CSS CDN -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- jQuery 3.7.1 -->
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
  <style>
    body { font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif; -webkit-tap-highlight-color: transparent; }
    .step-view { display: none; }
    .step-view.active { display: block; }
  </style>
</head>
<body class="bg-slate-950 text-slate-100 min-h-full flex flex-col justify-between antialiased selection:bg-indigo-500 selection:text-white">

  <!-- En-tête mobile avec Nom de l'entreprise en haut à gauche -->
  <header class="w-full max-w-md mx-auto pt-6 px-5 flex items-center justify-between">
    <div class="flex items-center gap-2">
      <div class="w-2.5 h-2.5 rounded-full bg-indigo-500"></div>
      <span class="text-xs font-bold tracking-tight text-white uppercase">${bName}</span>
    </div>
    <div class="flex items-center gap-1.5">
      <div class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></div>
      <span id="stepCounter" class="text-xs font-mono text-slate-400 font-semibold">1 / ${activeStepsCount}</span>
    </div>
  </header>

  <!-- Segmented Progress Bar Dynamique -->
  <div class="w-full max-w-md mx-auto px-5 pt-3 pb-4">
    <div id="progressBarContainer" class="grid gap-1.5" style="grid-template-columns: repeat(${activeStepsCount}, minmax(0, 1fr));">
      ${Array.from({ length: activeStepsCount })
        .map(
          (_, i) =>
            `<div id="bar-${i + 1}" class="h-1.5 rounded-full ${i === 0 ? 'bg-indigo-500' : 'bg-slate-800'} transition-all duration-300"></div>`
        )
        .join('\n      ')}
    </div>
  </div>

  <!-- Formulaire Mobile-First -->
  <main class="w-full max-w-md mx-auto flex-1 px-5 pb-8 flex flex-col justify-center">
    <form id="metaEnglishForm" novalidate class="flex flex-col h-full justify-between">

      ${config.enableQuestion1 ? `
      <!-- QUESTION 1 : OBJECTIF -->
      <div class="step-view" data-step-name="goal">
        <div class="mb-5">
          <h1 class="text-xl sm:text-2xl font-bold text-white tracking-tight leading-snug">
            Quel est votre objectif prioritaire ?
          </h1>
          <p class="text-slate-400 text-xs mt-1">
            Permet de calibrer les questions de votre test gratuit.
          </p>
        </div>

        <div class="space-y-2.5 mb-6">
          <label class="option-card block cursor-pointer p-4 rounded-xl border border-indigo-500 bg-indigo-950/20 active:scale-[0.99] transition">
            <input type="radio" name="goal" value="business_career" class="sr-only" checked>
            <div class="flex items-center justify-between">
              <div>
                <div class="text-sm font-semibold text-white">Carrière & Réunions pro</div>
                <div class="text-xs text-slate-400 mt-0.5">S'exprimer avec assurance au travail</div>
              </div>
              <div class="radio-indicator w-4 h-4 rounded-full border-2 border-indigo-500 bg-indigo-500 flex items-center justify-center">
                <div class="w-1.5 h-1.5 rounded-full bg-white"></div>
              </div>
            </div>
          </label>

          <label class="option-card block cursor-pointer p-4 rounded-xl border border-slate-800 bg-slate-900/60 active:scale-[0.99] transition">
            <input type="radio" name="goal" value="oral_fluency" class="sr-only">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-sm font-semibold text-white">Fluidité & Spontanéité</div>
                <div class="text-xs text-slate-400 mt-0.5">Supprimer la traduction mentale</div>
              </div>
              <div class="radio-indicator w-4 h-4 rounded-full border border-slate-600 flex items-center justify-center"></div>
            </div>
          </label>

          <label class="option-card block cursor-pointer p-4 rounded-xl border border-slate-800 bg-slate-900/60 active:scale-[0.99] transition">
            <input type="radio" name="goal" value="toeic_ielts" class="sr-only">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-sm font-semibold text-white">Certification (TOEIC / IELTS)</div>
                <div class="text-xs text-slate-400 mt-0.5">Pour promotion, diplôme ou visa</div>
              </div>
              <div class="radio-indicator w-4 h-4 rounded-full border border-slate-600 flex items-center justify-center"></div>
            </div>
          </label>
        </div>

        <button type="button" class="btn-step-next w-full h-13 rounded-xl bg-white hover:bg-slate-100 text-slate-950 font-bold text-sm transition active:scale-[0.98] flex items-center justify-center gap-2 cursor-pointer shadow-sm">
          <span>Continuer</span>
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"/></svg>
        </button>
      </div>` : ''}

      ${config.enableQuestion2 ? `
      <!-- QUESTION 2 : FREIN COGNITIF & NIVEAU -->
      <div class="step-view" data-step-name="blocker">
        <div class="mb-5">
          <h2 class="text-xl sm:text-2xl font-bold text-white tracking-tight leading-snug">
            Votre principal frein aujourd'hui ?
          </h2>
          <p class="text-slate-400 text-xs mt-1">
            Analyse vos blocages neuronaux réflexes.
          </p>
        </div>

        <div class="space-y-2 mb-4">
          <label class="option-blocker block cursor-pointer p-3.5 rounded-xl border border-indigo-500 bg-indigo-950/20 active:scale-[0.99] transition">
            <input type="radio" name="blocker" value="traduction_mentale" class="sr-only" checked>
            <div class="flex items-center justify-between">
              <span class="text-xs font-medium text-slate-200">Je traduis mot à mot dans ma tête</span>
              <div class="radio-indicator w-3.5 h-3.5 rounded-full border border-indigo-500 bg-indigo-500 flex items-center justify-center">
                <div class="w-1 h-1 rounded-full bg-white"></div>
              </div>
            </div>
          </label>

          <label class="option-blocker block cursor-pointer p-3.5 rounded-xl border border-slate-800 bg-slate-900/60 active:scale-[0.99] transition">
            <input type="radio" name="blocker" value="peur_faute" class="sr-only">
            <div class="flex items-center justify-between">
              <span class="text-xs font-medium text-slate-200">Peur de faire une faute ou de l'accent</span>
              <div class="radio-indicator w-3.5 h-3.5 rounded-full border border-slate-600 flex items-center justify-center"></div>
            </div>
          </label>

          <label class="option-blocker block cursor-pointer p-3.5 rounded-xl border border-slate-800 bg-slate-900/60 active:scale-[0.99] transition">
            <input type="radio" name="blocker" value="vocabulaire_fige" class="sr-only">
            <div class="flex items-center justify-between">
              <span class="text-xs font-medium text-slate-200">Le vocabulaire met trop de temps à venir</span>
              <div class="radio-indicator w-3.5 h-3.5 rounded-full border border-slate-600 flex items-center justify-center"></div>
            </div>
          </label>

          <label class="option-blocker block cursor-pointer p-3.5 rounded-xl border border-slate-800 bg-slate-900/60 active:scale-[0.99] transition">
            <input type="radio" name="blocker" value="debit_rapide" class="sr-only">
            <div class="flex items-center justify-between">
              <span class="text-xs font-medium text-slate-200">Perte de fil dès que le débit est rapide</span>
              <div class="radio-indicator w-3.5 h-3.5 rounded-full border border-slate-600 flex items-center justify-center"></div>
            </div>
          </label>
        </div>

        <div class="mb-5">
          <label class="block text-[11px] font-semibold uppercase tracking-wider text-slate-400 mb-1.5">Niveau estimé</label>
          <select name="current_level" class="w-full h-11 bg-slate-900 border border-slate-800 rounded-xl px-3 text-xs text-white focus:outline-none focus:border-indigo-500">
            <option value="A1_debutant">Débutant (A1)</option>
            <option value="A2_faux_debutant">Éléments de base (A2)</option>
            <option value="B1_intermediaire" selected>Intermédiaire (B1) - Comprends mais bloque à l'oral</option>
            <option value="B2_autonome">Intermédiaire confirmé (B2) - Manque d'aisance</option>
            <option value="C1_avance">Avancé (C1) - En quête de finesse pro</option>
          </select>
        </div>

        <div class="flex items-center gap-2">
          <button type="button" class="btn-step-prev w-1/3 h-12 rounded-xl border border-slate-800 text-slate-400 hover:text-white text-xs font-medium transition cursor-pointer">
            Retour
          </button>
          <button type="button" class="btn-step-next w-2/3 h-12 rounded-xl bg-white hover:bg-slate-100 text-slate-950 font-semibold text-sm transition active:scale-[0.98] flex items-center justify-center gap-1.5 cursor-pointer shadow-sm">
            <span>Dernière étape</span>
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"/></svg>
          </button>
        </div>
      </div>` : ''}

      <!-- DERNIÈRE ÉTAPE : COORDONNÉES (CHAMPS MODULABLES) -->
      <div class="step-view" data-step-name="contact">
        <div class="mb-5">
          <h2 class="text-xl sm:text-2xl font-bold text-white tracking-tight leading-snug">
            Accéder à votre test gratuit
          </h2>
          <p class="text-slate-400 text-xs mt-1">
            Recevez immédiatement vos accès sécurisés.
          </p>
        </div>

        <div class="space-y-3.5 mb-5">
          ${config.fields.firstName.visible ? `
          <div>
            <label class="block text-[11px] font-semibold uppercase tracking-wider text-slate-400 mb-1">
              ${config.fields.firstName.label} ${config.fields.firstName.required ? '*' : '(optionnel)'}
            </label>
            <input type="text" id="inputFirstName" placeholder="${config.fields.firstName.placeholder}" ${config.fields.firstName.required ? 'required' : ''} class="w-full h-11 bg-slate-900 border border-slate-800 rounded-xl px-3.5 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:border-indigo-500">
          </div>` : ''}

          ${config.fields.lastName.visible ? `
          <div>
            <label class="block text-[11px] font-semibold uppercase tracking-wider text-slate-400 mb-1">
              ${config.fields.lastName.label} ${config.fields.lastName.required ? '*' : '(optionnel)'}
            </label>
            <input type="text" id="inputLastName" placeholder="${config.fields.lastName.placeholder}" ${config.fields.lastName.required ? 'required' : ''} class="w-full h-11 bg-slate-900 border border-slate-800 rounded-xl px-3.5 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:border-indigo-500">
          </div>` : ''}

          ${config.fields.email.visible ? `
          <div>
            <label class="block text-[11px] font-semibold uppercase tracking-wider text-slate-400 mb-1">
              ${config.fields.email.label} ${config.fields.email.required ? '*' : '(optionnel)'}
            </label>
            <input type="email" id="inputEmail" placeholder="${config.fields.email.placeholder}" ${config.fields.email.required ? 'required' : ''} class="w-full h-11 bg-slate-900 border border-slate-800 rounded-xl px-3.5 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:border-indigo-500">
          </div>` : ''}

          ${config.fields.phone.visible ? `
          <div>
            <label class="block text-[11px] font-semibold uppercase tracking-wider text-slate-400 mb-1">
              ${config.fields.phone.label} ${config.fields.phone.required ? '*' : '(optionnel)'}
            </label>
            <input type="tel" id="inputPhone" placeholder="${config.fields.phone.placeholder}" ${config.fields.phone.required ? 'required' : ''} class="w-full h-11 bg-slate-900 border border-slate-800 rounded-xl px-3.5 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:border-indigo-500">
          </div>` : ''}
        </div>

        <div id="statusMessage" class="hidden text-xs text-rose-400 bg-rose-950/40 border border-rose-900/50 rounded-xl p-3 mb-3"></div>

        <div class="flex items-center gap-2 mb-4">
          <button type="button" class="btn-step-prev btn-back-contact w-1/3 h-12 rounded-xl border border-slate-800 text-slate-400 hover:text-white text-xs font-medium transition cursor-pointer">
            Retour
          </button>
          <button type="submit" id="btnSubmit" class="btn-submit-main flex-1 h-12 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white font-semibold text-sm transition active:scale-[0.98] flex items-center justify-center gap-2 cursor-pointer shadow-md shadow-indigo-600/20">
            <svg id="loader" class="hidden w-4 h-4 animate-spin text-white" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
            <span id="btnText">Démarrer le test</span>
          </button>
        </div>

        <p class="text-[11px] text-slate-500 text-center flex items-center justify-center gap-1">
          <svg class="w-3.5 h-3.5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
          <span>Chiffré SHA-256 Meta CAPI & SQLite. 100% gratuit.</span>
        </p>
      </div>
    </form>

    <!-- Écran de Confirmation / Succès -->
    <div id="successView" class="hidden text-center py-6 animate-in fade-in">
      <div class="w-12 h-12 rounded-full bg-emerald-950/60 border border-emerald-500/30 text-emerald-400 flex items-center justify-center mx-auto mb-3">
        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
      </div>
      <h2 class="text-xl font-bold text-white mb-1">Accès réservé</h2>
      <p class="text-slate-400 text-xs mb-5 max-w-xs mx-auto">
        Votre test calibré a été transmis. Vos données brutes ont été enregistrées en base SQLite.
      </p>
      <div class="bg-slate-900 border border-slate-800 rounded-xl p-3.5 text-left text-xs font-mono text-slate-300 space-y-1 mb-5" id="capiStatusBox"></div>
      <button type="button" onclick="location.reload()" class="text-xs text-indigo-400 hover:text-indigo-300 font-medium py-2 px-4 transition">
        Refaire le test
      </button>
    </div>
  </main>

  <!-- JQUERY & META CAPI SCRIPT -->
  <script>
    (function($) {
      'use strict';

      // 1. Détection des paramètres Meta & UTMs
      function getQueryParam(param) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
      }
      function getCookie(name) {
        const value = '; ' + document.cookie;
        const parts = value.split('; ' + name + '=');
        if (parts.length === 2) return parts.pop().split(';').shift();
        return null;
      }
      function setCookie(name, value, days) {
        const d = new Date();
        d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
        document.cookie = name + '=' + value + ';path=/;SameSite=Lax;expires=' + d.toUTCString();
      }

      const fbclid = getQueryParam('fbclid');
      let fbc = getCookie('_fbc');
      if (fbclid) {
        fbc = 'fb.1.' + Date.now() + '.' + fbclid;
        setCookie('_fbc', fbc, 90);
      }
      let fbp = getCookie('_fbp');
      if (!fbp) {
        fbp = 'fb.1.' + Date.now() + '.' + (Math.floor(Math.random() * 9e9) + 1e9);
        setCookie('_fbp', fbp, 90);
      }

      // 2. Gestion des étapes dynamiques
      const steps = [];
      $('.step-view').each(function() {
        steps.push($(this).data('step-name'));
      });

      let currentStepIndex = 0;
      function updateView() {
        $('.step-view').removeClass('active');
        $('.step-view[data-step-name="' + steps[currentStepIndex] + '"]').addClass('active');
        $('#stepCounter').text((currentStepIndex + 1) + ' / ' + steps.length);

        // Progress bar segments
        for (let i = 0; i < steps.length; i++) {
          const $b = $('#bar-' + (i + 1));
          if (currentStepIndex >= i) {
            $b.removeClass('bg-slate-800').addClass('bg-indigo-500');
          } else {
            $b.removeClass('bg-indigo-500').addClass('bg-slate-800');
          }
        }

        // Hide back button if on first step
        if (currentStepIndex === 0) {
          $('.btn-back-contact').addClass('hidden');
          $('.btn-submit-main').removeClass('w-2/3').addClass('w-full');
        } else {
          $('.btn-back-contact').removeClass('hidden');
          $('.btn-submit-main').removeClass('w-full').addClass('w-2/3');
        }
      }

      // Initialiser la première étape
      updateView();

      // Sélecteurs d'options
      $(document).on('click', '.option-card, .option-blocker', function() {
        const $this = $(this);
        const $group = $this.parent().find('.option-card, .option-blocker');
        $group.removeClass('border-indigo-500 bg-indigo-950/20').addClass('border-slate-800 bg-slate-900/60');
        $group.find('.radio-indicator').removeClass('border-indigo-500 bg-indigo-500').addClass('border-slate-600').html('');

        $this.removeClass('border-slate-800 bg-slate-900/60').addClass('border-indigo-500 bg-indigo-950/20');
        $this.find('.radio-indicator').removeClass('border-slate-600').addClass('border-indigo-500 bg-indigo-500').html('<div class="w-1.5 h-1.5 rounded-full bg-white"></div>');
        $this.find('input[type="radio"]').prop('checked', true);
      });

      $(document).on('click', '.btn-step-next', function() {
        if (currentStepIndex < steps.length - 1) {
          currentStepIndex++;
          updateView();
        }
      });
      $(document).on('click', '.btn-step-prev', function() {
        if (currentStepIndex > 0) {
          currentStepIndex--;
          updateView();
        }
      });

      // 3. Soumission et enregistrement SQLite + CAPI
      $('#metaEnglishForm').on('submit', function(e) {
        e.preventDefault();
        $('#statusMessage').addClass('hidden');

        const firstName = $('#inputFirstName').length ? $('#inputFirstName').val().trim() : '';
        const lastName  = $('#inputLastName').length ? $('#inputLastName').val().trim() : '';
        const email      = $('#inputEmail').length ? $('#inputEmail').val().trim() : '';
        const phone      = $('#inputPhone').length ? $('#inputPhone').val().trim() : '';

        // Validation selon les champs requis
        ${config.fields.firstName.visible && config.fields.firstName.required ? `
        if (!firstName) {
          $('#statusMessage').removeClass('hidden').text('Veuillez renseigner votre prénom.');
          return;
        }` : ''}
        ${config.fields.lastName.visible && config.fields.lastName.required ? `
        if (!lastName) {
          $('#statusMessage').removeClass('hidden').text('Veuillez renseigner votre nom.');
          return;
        }` : ''}
        ${config.fields.email.visible && config.fields.email.required ? `
        if (!email) {
          $('#statusMessage').removeClass('hidden').text('Veuillez renseigner une adresse email valide.');
          return;
        }` : ''}
        ${config.fields.phone.visible && config.fields.phone.required ? `
        if (!phone) {
          $('#statusMessage').removeClass('hidden').text('Veuillez renseigner votre numéro de téléphone.');
          return;
        }` : ''}

        const eventId = 'lead_' + Date.now() + '_' + Math.random().toString(36).substring(2, 8);
        $('#btnSubmit').prop('disabled', true).addClass('opacity-70');
        $('#btnText').text('Envoi sécurisé...');
        $('#loader').removeClass('hidden');

        if (typeof window.fbq === 'function') {
          window.fbq('track', 'Lead', { content_name: 'Test Anglais Gratuit' }, { eventID: eventId });
        }

        const endpointUrl = window.location.pathname.endsWith('.php') ? './capi.php' : '/api/meta-capi';

        $.ajax({
          url: endpointUrl,
          method: 'POST',
          contentType: 'application/json',
          data: JSON.stringify({
            eventName: 'Lead',
            eventId: eventId,
            userData: { firstName, lastName, email, phone },
            assessmentData: {
              goal: $('input[name="goal"]:checked').val() || 'direct_lead',
              blocker: $('input[name="blocker"]:checked').val() || 'direct_lead',
              currentLevel: $('select[name="current_level"]').val() || 'non_specifie'
            },
            trackingData: {
              fbclid: fbclid,
              fbc: fbc,
              fbp: fbp,
              utm_source: getQueryParam('utm_source'),
              utm_medium: getQueryParam('utm_medium'),
              utm_campaign: getQueryParam('utm_campaign'),
              utm_content: getQueryParam('utm_content'),
              utm_term: getQueryParam('utm_term'),
              pageUrl: window.location.href,
              referrer: document.referrer
            }
          }),
          success: function(res) {
            $('#metaEnglishForm').addClass('hidden');
            $('#successView').removeClass('hidden');
            $('#capiStatusBox').html(
              '<div><span class="text-indigo-400">Meta CAPI :</span> ' + (res.status || 'OK') + '</div>' +
              '<div><span class="text-indigo-400">Event ID :</span> ' + eventId + '</div>' +
              '<div><span class="text-indigo-400">Score EMQ :</span> ' + (res.emqScore || '9.0') + '/10</div>' +
              '<div><span class="text-emerald-400">Base SQLite :</span> ID #' + (res.sqliteId || 'Enregistré') + '</div>' +
              '<div><span class="text-indigo-400">_fbc :</span> ' + (fbc || 'Non fourni') + '</div>' +
              '<div><span class="text-indigo-400">_fbp :</span> ' + fbp + '</div>'
            );
          },
          error: function(err) {
            $('#btnSubmit').prop('disabled', false).removeClass('opacity-70');
            $('#btnText').text('Démarrer le test');
            $('#loader').addClass('hidden');
            $('#statusMessage').removeClass('hidden').text('Erreur de transmission : ' + (err.responseJSON?.error || 'Vérifiez votre connexion'));
          }
        });
      });

    })(jQuery);
  </script>
</body>
</html>`;
}

export const STANDALONE_FORM_HTML = getStandaloneFormHtml(DEFAULT_FORM_CONFIG);
