(function() {
  'use strict';
  
  console.log('🔧 DataLayer universel chargé');
  
  // Arrêter sur les pages de confirmation
  if (window.location.href.includes('confirmation')) {
    console.log('⏭️ Page de confirmation - script ignoré');
    return;
  }

  // Attendre le formulaire avec plus de patience
  function waitForForm(maxAttempts = 100) {
    let attempts = 0;
    
    const checkInterval = setInterval(function() {
      attempts++;
      const form = document.getElementById('oscar_school_form');
      
      if (form) {
        clearInterval(checkInterval);
        console.log('✅ Formulaire trouvé après', attempts, 'tentatives');
        initializeDataLayer(form);
      } else if (attempts >= maxAttempts) {
        clearInterval(checkInterval);
        console.log('⏱️ Formulaire non trouvé après ' + (maxAttempts * 200 / 1000) + ' secondes');
      }
    }, 200);
  }

  function initializeDataLayer(form) {
    console.log('📊 Initialisation tracking DataLayer');
    
    // Fonction SHA-256
    async function sha256(value) {
      if (!value) return '';
      try {
        const encoder = new TextEncoder();
        const data = encoder.encode(value.trim().toLowerCase());
        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
      } catch (error) {
        console.error('❌ Erreur hashage:', error);
        return '';
      }
    }

    // Récupérer texte d'un select
    function getSelectText(selectId) {
      const select = document.getElementById(selectId);
      if (select && select.selectedIndex >= 0 && select.options[select.selectedIndex]) {
        return select.options[select.selectedIndex].text;
      }
      return '';
    }

    // Fonction principale de capture
    async function captureAndPushDataLayer() {
      console.log('📝 Capture des données formulaire');
      
      // Vérifier consentement CNIL
      const consentCheckbox = document.querySelector('input[name="cnil"]');
      if (!consentCheckbox || !consentCheckbox.checked) {
        console.warn('⚠️ Pas de consentement CNIL - dataLayer non envoyé');
        return;
      }

      // Récupération des champs (compatible tous formulaires)
      const typeRaw = (document.querySelector('input[name="type_formulaire"]') || {}).value || '';
      const emailRaw = (document.getElementById('email') || {}).value || '';
      const portableRaw = (document.getElementById('portable') || {}).value || '';
      const villeRaw = (document.getElementById('ville') || {}).value || '';
      const codePostalRaw = (document.getElementById('codepostal') || document.getElementById('code_postal') || {}).value || '';
      const campusRaw = (document.getElementById('campus_selection') || {}).value || '';
      
      // Selects (texte, pas value)
      const statusRaw = getSelectText('OscarContactJeSuisRefIdField');
      const formationRaw = getSelectText('formation');
      
      // Pays
      const paysSelect = document.getElementById('pays');
      let paysNom = '';
      if (paysSelect && paysSelect.selectedIndex > 0) {
        paysNom = paysSelect.options[paysSelect.selectedIndex].text;
      }

      console.log('📦 Données:', {
        type: typeRaw,
        status: statusRaw,
        campus: campusRaw,
        formation: formationRaw,
        hasEmail: !!emailRaw,
        hasPhone: !!portableRaw
      });

      // Hashage
      const emailHash = await sha256(emailRaw);
      const portableHash = await sha256(portableRaw);
      const codePostalHash = await sha256(codePostalRaw);

      // Construction dataLayer
      const dataLayerObject = {
        event: 'form_submit',
        type: typeRaw.trim().toLowerCase(),
        je_suis: statusRaw.trim(),
        sha256_email_address: emailHash,
        sha256_phone_number: portableHash,
        sha256_postal_code: codePostalHash,
        ville: villeRaw.trim(),
        pays: paysNom,
        campus: campusRaw.trim(),
        formation: formationRaw.trim()
      };

      // Push dataLayer
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push(dataLayerObject);
      
      console.log('🚀 DataLayer push réussi:', dataLayerObject);
    }

    // Attacher aux événements submit du FORMULAIRE
    form.addEventListener('submit', async function(event) {
      console.log('📝 Event: form submit');
      await captureAndPushDataLayer();
    });

    // Attacher AUSSI aux boutons (pour formulaire contact)
    const desktopBtn = document.getElementById('desktop-submit-btn');
    const mobileBtn = document.getElementById('mobile-submit-btn');
    
    if (desktopBtn) {
      desktopBtn.addEventListener('click', async function(e) {
        console.log('📝 Event: desktop button click');
        await captureAndPushDataLayer();
      });
    }
    
    if (mobileBtn) {
      mobileBtn.addEventListener('click', async function(e) {
        console.log('📝 Event: mobile button click');
        await captureAndPushDataLayer();
      });
    }

    // Boutons submit classiques (JPO, candidature)
    const submitButtons = form.querySelectorAll('button[type="submit"]');
    submitButtons.forEach(btn => {
      btn.addEventListener('click', async function(e) {
        console.log('📝 Event: submit button click');
        // Ne pas empêcher l'événement, juste capturer
        await captureAndPushDataLayer();
      });
    });
    
    console.log('✅ Tracking activé sur tous les événements');
  }

  // Démarrage
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
      waitForForm();
    });
  } else {
    waitForForm();
  }
})();
