/**
 * AKITRIPS CONTACT FORM WIDGET
 *
 * Exposes global: AkiForm.open(), AkiForm.close(), AkiForm.next(),
 *                 AkiForm.prev(), AkiForm.clearCountry()
 *
 * Configuration:
 *   - CONFIG.formName   : Identifier stored in form_submission.form_name
 *   - CONFIG.endpoint   : POST URL for submissions
 *   - CONFIG.tokenUrl   : GET URL to fetch a fresh CSRF token
 */
const AkiForm = (() => {
  'use strict';

  // ==========================================
  // CONFIG — Edit per deployment
  // ==========================================
  const CONFIG = {
    formName: 'contacto-akitrips',
    endpoint: '/api/form-submission',
    tokenUrl: '/api/form-submission/token',
  };

  // ==========================================
  // DATA
  // ==========================================
  const INTERESTS = {
    agencia: [
      'Revender experiencias de Akitrips',
      'Crear paquetes turísticos combinados',
      'Establecer una alianza comercial',
    ],
    gobierno: [
      'Promover experiencias turísticas de mi región',
      'Incluir emprendedores locales en la plataforma',
      'Conocer el modelo de turismo sostenible',
      'Explorar oportunidades de cooperación',
    ],
    operador: [
      'Publicar mis experiencias en Akitrips',
      'Llegar a nuevos mercados y viajeros',
      'Digitalizar la gestión de mis reservas',
    ],
    viajero: [
      'Conocer experiencias culturales auténticas',
      'Recibir ofertas y novedades',
      'Planear un próximo viaje a Colombia',
    ],
    otro: [
      'Alianza estratégica',
      'Cobertura de prensa o medios',
      'Investigación o academia',
      'Oportunidad de inversión',
    ],
  };

  const COUNTRIES = [
    'Colombia', 'Argentina', 'Bolivia', 'Brasil', 'Chile', 'Costa Rica',
    'Cuba', 'Ecuador', 'El Salvador', 'España', 'Estados Unidos',
    'Guatemala', 'Honduras', 'México', 'Nicaragua', 'Panamá',
    'Paraguay', 'Perú', 'Puerto Rico', 'República Dominicana',
    'Uruguay', 'Venezuela', 'Otro',
  ];

  // ==========================================
  // STATE
  // ==========================================
  let state = {
    step: 1,
    role: null,
    interests: [],
    country: null,
    name: null,
    email: null,
    phone: null,
    org: null,
    comment: null,
  };

  // ==========================================
  // DOM HELPERS
  // ==========================================
  const $ = function(sel) { return document.querySelector(sel); };
  const $$ = function(sel) { return document.querySelectorAll(sel); };
  const norm = function(s) { return s.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, ''); };

  /**
   * Fetch a fresh CSRF token from the server.
   * This avoids stale tokens when the page is cached.
   */
  async function fetchCsrfToken() {
    var res = await fetch(CONFIG.tokenUrl, {
      method: 'GET',
      credentials: 'same-origin',
    });
    if (!res.ok) throw new Error('Could not fetch CSRF token');
    var data = await res.json();
    return data.token;
  }

  // ==========================================
  // OPEN / CLOSE
  // ==========================================
  function open() {
    $('#akiform-overlay').classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  function close() {
    $('#akiform-overlay').classList.remove('active');
    document.body.style.overflow = '';
    setTimeout(resetForm, 400);
  }

  function resetForm() {
    state = {
      step: 1, role: null, interests: [], country: null,
      name: null, email: null, phone: null, org: null, comment: null,
    };
    goToStep(1);
    $$('.akiform-role').forEach(function(r) { r.classList.remove('selected'); });
    $('#akiform-success').classList.remove('active');
    $('#akiform-footer').style.display = 'flex';
    ['name', 'email', 'phone', 'org'].forEach(function(f) {
      var el = $('#akiform-' + f);
      el.value = '';
      el.classList.remove('error');
    });
    $('#akiform-comment').value = '';
    ['name', 'email'].forEach(function(f) {
      var err = $('#akiform-' + f + '-error');
      if (err) err.classList.remove('visible');
    });
    clearCountry();
    $('#akiform-progress').style.display = '';
  }

  // ==========================================
  // NAVIGATION
  // ==========================================
  function goToStep(n) {
    state.step = n;
    $$('.akiform-step').forEach(function(s) { s.classList.remove('active'); });
    var target = $('[data-step="' + n + '"]');
    if (target) target.classList.add('active');

    $('#akiform-progress-fill').style.width = (n / 4 * 100) + '%';
    $('#akiform-progress-text').textContent = 'Paso ' + n + ' de 4';
    $('#akiform-btn-back').style.display = n > 1 ? '' : 'none';
    $('#akiform-btn-next').querySelector('.btn-text').textContent = n === 4 ? 'Enviar' : 'Siguiente';

    updateNextState();
    $('#akiform-body').scrollTop = 0;
  }

  function next() {
    if (state.step === 4) { submit(); return; }
    if (!validateStep(state.step)) return;

    goToStep(state.step + 1);
    if (state.step === 2) renderInterests();
  }

  function prev() {
    if (state.step > 1) goToStep(state.step - 1);
  }

  function validateStep(n) {
    if (n === 1) return !!state.role;
    if (n === 2) return state.interests.length > 0;
    if (n === 3) return !!state.country;
    return true;
  }

  function updateNextState() {
    $('#akiform-btn-next').disabled = !validateStep(state.step);
  }

  // ==========================================
  // STEP 1 — ROLES
  // ==========================================
  function initRoles() {
    $$('.akiform-role').forEach(function(el) {
      el.addEventListener('click', function() {
        $$('.akiform-role').forEach(function(r) { r.classList.remove('selected'); });
        el.classList.add('selected');
        state.role = el.dataset.role;
        state.interests = [];
        updateNextState();
      });
    });
  }

  // ==========================================
  // STEP 2 — INTERESTS
  // ==========================================
  function renderInterests() {
    var container = $('#akiform-interests');
    var items = INTERESTS[state.role] || [];
    container.innerHTML = '';
    state.interests = [];

    items.forEach(function(label) {
      var el = document.createElement('div');
      el.className = 'akiform-check';
      el.innerHTML =
        '<div class="akiform-checkbox">' +
          '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round"><polyline points="20 6 9 17 4 12"/></svg>' +
        '</div>' +
        '<span class="akiform-check-label">' + label + '</span>';

      el.addEventListener('click', function() {
        el.classList.toggle('selected');
        var idx = state.interests.indexOf(label);
        if (idx === -1) state.interests.push(label);
        else state.interests.splice(idx, 1);
        updateNextState();
      });

      container.appendChild(el);
    });
    updateNextState();
  }

  // ==========================================
  // STEP 3 — COUNTRY
  // ==========================================
  function initCountrySearch() {
    var input = $('#akiform-country-input');
    var dropdown = $('#akiform-country-dropdown');

    input.addEventListener('focus', function() { renderCountryDropdown(input.value); dropdown.classList.add('open'); });
    input.addEventListener('input', function() { renderCountryDropdown(input.value); dropdown.classList.add('open'); });
    document.addEventListener('click', function(e) { if (!e.target.closest('#akiform-country-search')) dropdown.classList.remove('open'); });
  }

  function renderCountryDropdown(query) {
    var dropdown = $('#akiform-country-dropdown');
    var filtered = COUNTRIES.filter(function(c) { return norm(c).includes(norm(query)); });

    if (!filtered.length) {
      dropdown.innerHTML = '<div class="akiform-dropdown-empty">Sin resultados</div>';
      return;
    }
    dropdown.innerHTML = filtered.map(function(c) {
      return '<div class="akiform-dropdown-item' + (state.country === c ? ' selected' : '') + '" data-value="' + c + '">' + c + '</div>';
    }).join('');

    dropdown.querySelectorAll('.akiform-dropdown-item').forEach(function(item) {
      item.addEventListener('click', function() { selectCountry(item.dataset.value); });
    });
  }

  function selectCountry(value) {
    state.country = value;
    $('#akiform-country-dropdown').classList.remove('open');
    var input = $('#akiform-country-input');
    input.value = ''; input.style.display = 'none';
    $('#akiform-country-tag').classList.add('visible');
    $('#akiform-country-tag-text').textContent = value;
    updateNextState();
  }

  function clearCountry() {
    state.country = null;
    var input = $('#akiform-country-input');
    if (input) { input.style.display = ''; input.value = ''; }
    $('#akiform-country-tag').classList.remove('visible');
    updateNextState();
  }

  // ==========================================
  // STEP 4 — VALIDATION
  // ==========================================
  function initContactValidation() {
    ['#akiform-name', '#akiform-email'].forEach(function(sel) {
      $(sel).addEventListener('input', function() {
        $(sel).classList.remove('error');
        var err = $(sel + '-error');
        if (err) err.classList.remove('visible');
        updateNextState();
      });
    });
  }

  function validateStep4() {
    var name = $('#akiform-name').value.trim();
    var email = $('#akiform-email').value.trim();
    var valid = true;

    if (!name) {
      $('#akiform-name').classList.add('error');
      $('#akiform-name-error').classList.add('visible');
      valid = false;
    }
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      $('#akiform-email').classList.add('error');
      $('#akiform-email-error').classList.add('visible');
      valid = false;
    }
    return valid;
  }

  // ==========================================
  // SUBMIT
  // ==========================================
  async function submit() {
    if (!validateStep4()) return;

    state.name = $('#akiform-name').value.trim();
    state.email = $('#akiform-email').value.trim();
    state.phone = $('#akiform-phone').value.trim() || null;
    state.org = $('#akiform-org').value.trim() || null;
    state.comment = $('#akiform-comment').value.trim() || null;

    var payload = {
      formName: CONFIG.formName,
      email: state.email,
      website: $('#akiform-hp') ? $('#akiform-hp').value : '',
      data: {
        role: state.role,
        interests: state.interests,
        location: {
          country: state.country,
        },
        contact: {
          name: state.name,
          email: state.email,
          phone: state.phone,
          organization: state.org,
          comment: state.comment,
        }
      },
    };

    var btn = $('#akiform-btn-next');
    btn.classList.add('loading');
    btn.disabled = true;

    try {
      // 1) Fetch a fresh CSRF token (avoids stale cached tokens)
      var csrfToken = await fetchCsrfToken();

      // 2) Submit with the fresh token
      var res = await fetch(CONFIG.endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-Token': csrfToken,
        },
        credentials: 'same-origin',
        body: JSON.stringify(payload),
      });

      var result = await res.json();

      if (!res.ok) {
        throw new Error(result.message || 'Server error');
      }

      showSuccess();
    } catch (err) {
      console.error('Submit error:', err);
      btn.classList.remove('loading');
      btn.disabled = false;
      alert('Hubo un error al enviar. Por favor intenta de nuevo.');
    }
  }

  function showSuccess() {
    $$('.akiform-step').forEach(function(s) { s.classList.remove('active'); });
    $('#akiform-success').classList.add('active');
    $('#akiform-footer').style.display = 'none';
    $('#akiform-progress').style.display = 'none';
  }

  // ==========================================
  // INIT
  // ==========================================
  function init() {
    initRoles();
    initCountrySearch();
    initContactValidation();

    document.addEventListener('keydown', function(e) {
      if (!$('#akiform-overlay').classList.contains('active')) return;
      if (e.key === 'Escape') close();
      if (e.key === 'Enter' && !$('#akiform-btn-next').disabled) { e.preventDefault(); next(); }
    });

    var ctaCard = $('.akitrips-cta-card');
    if (ctaCard) {
      ctaCard.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(); }
      });
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

  return { open, close, next, prev, clearCountry };
})();