/**
 * AKITRIPS FAIR FORM WIDGET
 *
 * Exposes global: AkiForm.open(), AkiForm.close(), AkiForm.next(),
 *                 AkiForm.prev(), AkiForm.clearCity(), AkiForm.clearCountry()
 *
 * Configuration:
 *   - CONFIG.eventName : Tag submissions with the fair/event name
 *   - CONFIG.endpoint  : POST URL for submissions (null = console.log only)
 */
const AkiForm = (() => {
  'use strict';

  // ==========================================
  // CONFIG — Edit per event / deployment
  // ==========================================
  const CONFIG = {
    eventName: 'Vitrina Turística de Anato 2025',
    endpoint: null, // e.g. '/api/form-submission'
  };

  // ==========================================
  // 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 COLOMBIAN_CITIES = [
    'Bogotá', 'Medellín', 'Cali', 'Barranquilla', 'Cartagena',
    'Bucaramanga', 'Pereira', 'Santa Marta', 'Manizales', 'Cúcuta',
    'Ibagué', 'Villavicencio', 'Pasto', 'Neiva', 'Armenia',
    'Montería', 'Popayán', 'Valledupar', 'Sincelejo', 'Tunja',
    'Florencia', 'Riohacha', 'Quibdó', 'Yopal', 'Mocoa',
    'Leticia', 'San Andrés', 'Buenaventura', 'Barichara', 'Girón',
    'Villa de Leyva', 'Salento', 'Guatapé', 'Filandia', 'Jardín',
    'Mompox', 'San Gil', 'Nuquí', 'Bahía Solano', 'Providencia',
    '— Otra ciudad de Colombia',
    '— Otro país',
  ];

  const COUNTRIES = [
    '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: [],
    city: null,
    otherCity: null,
    country: null,
    name: null,
    email: null,
    phone: null,
    org: null,
    comment: null,
  };

  // ==========================================
  // DOM HELPERS
  // ==========================================
  const $ = (sel) => document.querySelector(sel);
  const $$ = (sel) => document.querySelectorAll(sel);
  const norm = (s) => s.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');

  // ==========================================
  // 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: [], city: null, otherCity: null,
      country: null, name: null, email: null, phone: null, org: null, comment: null,
    };
    goToStep(1);
    $$('.akiform-role').forEach((r) => r.classList.remove('selected'));
    $('#akiform-success').classList.remove('active');
    $('#akiform-footer').style.display = 'flex';
    ['name', 'email', 'phone', 'org'].forEach((f) => {
      const el = $('#akiform-' + f);
      el.value = '';
      el.classList.remove('error');
    });
    $('#akiform-comment').value = '';
    ['name', 'email'].forEach((f) => {
      const err = $('#akiform-' + f + '-error');
      if (err) err.classList.remove('visible');
    });
    clearCity();
    clearCountry();
    $('#akiform-progress').style.display = '';
  }

  // ==========================================
  // NAVIGATION
  // ==========================================
  function goToStep(n) {
    state.step = n;
    $$('.akiform-step').forEach((s) => s.classList.remove('active'));
    const 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;

    if (state.step === 3 && state.city === '— Otra ciudad de Colombia') {
      state.otherCity = $('#akiform-other-city').value.trim();
    }

    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) {
      if (!state.city && !state.country) return false;
      if (state.city === '— Otro país' && !state.country) return false;
      return true;
    }
    return true;
  }

  function updateNextState() {
    $('#akiform-btn-next').disabled = !validateStep(state.step);
  }

  // ==========================================
  // STEP 1 — ROLES
  // ==========================================
  function initRoles() {
    $$('.akiform-role').forEach((el) => {
      el.addEventListener('click', () => {
        $$('.akiform-role').forEach((r) => r.classList.remove('selected'));
        el.classList.add('selected');
        state.role = el.dataset.role;
        state.interests = [];
        updateNextState();
      });
    });
  }

  // ==========================================
  // STEP 2 — INTERESTS
  // ==========================================
  function renderInterests() {
    const container = $('#akiform-interests');
    const items = INTERESTS[state.role] || [];
    container.innerHTML = '';
    state.interests = [];

    items.forEach((label) => {
      const 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', () => {
        el.classList.toggle('selected');
        const 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 — LOCATION
  // ==========================================
  function initCitySearch() {
    const input = $('#akiform-city-input');
    const dropdown = $('#akiform-city-dropdown');

    input.addEventListener('focus', () => {
      renderCityDropdown(input.value);
      dropdown.classList.add('open');
    });

    input.addEventListener('input', () => {
      renderCityDropdown(input.value);
      dropdown.classList.add('open');
    });

    document.addEventListener('click', (e) => {
      if (!e.target.closest('#akiform-city-search')) {
        dropdown.classList.remove('open');
      }
    });
  }

  function renderCityDropdown(query) {
    const dropdown = $('#akiform-city-dropdown');
    const filtered = COLOMBIAN_CITIES.filter((c) => norm(c).includes(norm(query)));

    if (!filtered.length) {
      dropdown.innerHTML = '<div class="akiform-dropdown-empty">Sin resultados</div>';
      return;
    }

    dropdown.innerHTML = filtered.map((c) =>
      '<div class="akiform-dropdown-item' + (state.city === c ? ' selected' : '') + '" data-value="' + c + '">' + c + '</div>'
    ).join('');

    dropdown.querySelectorAll('.akiform-dropdown-item').forEach((item) => {
      item.addEventListener('click', () => selectCity(item.dataset.value));
    });
  }

  function selectCity(value) {
    state.city = value;
    state.country = null;

    const input = $('#akiform-city-input');
    $('#akiform-city-dropdown').classList.remove('open');
    input.value = '';
    input.style.display = 'none';
    $('#akiform-city-tag').classList.add('visible');
    $('#akiform-city-tag-text').textContent = value;

    const isOtherCity = value === '— Otra ciudad de Colombia';
    const isOtherCountry = value === '— Otro país';

    $('#akiform-other-city-field').classList.toggle('visible', isOtherCity);
    $('#akiform-country-wrapper').classList.toggle('visible', isOtherCountry);

    if (isOtherCountry) state.city = null;
    updateNextState();
  }

  function clearCity() {
    state.city = null;
    state.otherCity = null;
    state.country = null;

    const input = $('#akiform-city-input');
    input.style.display = '';
    input.value = '';
    $('#akiform-city-tag').classList.remove('visible');
    $('#akiform-other-city-field').classList.remove('visible');
    $('#akiform-country-wrapper').classList.remove('visible');
    $('#akiform-other-city').value = '';
    clearCountry();
    updateNextState();
  }

  function initCountrySearch() {
    const input = $('#akiform-country-input');
    const dropdown = $('#akiform-country-dropdown');

    input.addEventListener('focus', () => {
      renderCountryDropdown(input.value);
      dropdown.classList.add('open');
    });

    input.addEventListener('input', () => {
      renderCountryDropdown(input.value);
      dropdown.classList.add('open');
    });

    document.addEventListener('click', (e) => {
      if (!e.target.closest('#akiform-country-wrapper')) {
        dropdown.classList.remove('open');
      }
    });
  }

  function renderCountryDropdown(query) {
    const dropdown = $('#akiform-country-dropdown');
    const filtered = COUNTRIES.filter((c) => norm(c).includes(norm(query)));

    if (!filtered.length) {
      dropdown.innerHTML = '<div class="akiform-dropdown-empty">Sin resultados</div>';
      return;
    }

    dropdown.innerHTML = filtered.map((c) =>
      '<div class="akiform-dropdown-item' + (state.country === c ? ' selected' : '') + '" data-value="' + c + '">' + c + '</div>'
    ).join('');

    dropdown.querySelectorAll('.akiform-dropdown-item').forEach((item) => {
      item.addEventListener('click', () => selectCountry(item.dataset.value));
    });
  }

  function selectCountry(value) {
    state.country = value;
    $('#akiform-country-dropdown').classList.remove('open');

    const 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;
    const input = $('#akiform-country-input');
    if (input) {
      input.style.display = '';
      input.value = '';
    }
    $('#akiform-country-tag').classList.remove('visible');
    updateNextState();
  }

  // ==========================================
  // STEP 4 — CONTACT VALIDATION
  // ==========================================
  function initContactValidation() {
    ['#akiform-name', '#akiform-email'].forEach((sel) => {
      $(sel).addEventListener('input', () => {
        $(sel).classList.remove('error');
        const err = $(sel + '-error');
        if (err) err.classList.remove('visible');
        updateNextState();
      });
    });
  }

  function validateStep4() {
    const name = $('#akiform-name').value.trim();
    const email = $('#akiform-email').value.trim();
    let 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;

    const payload = {
      event: CONFIG.eventName,
      role: state.role,
      interests: state.interests,
      location: {
        city: state.city === '— Otra ciudad de Colombia'
          ? (state.otherCity || 'Otra ciudad')
          : state.city,
        country: state.country || 'Colombia',
      },
      contact: {
        name: state.name,
        email: state.email,
        phone: state.phone,
        organization: state.org,
        comment: state.comment,
      },
      submitted_at: new Date().toISOString(),
    };

    const btn = $('#akiform-btn-next');
    btn.classList.add('loading');
    btn.disabled = true;

    try {
      if (CONFIG.endpoint) {
        const res = await fetch(CONFIG.endpoint, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        if (!res.ok) throw new Error('Server error: ' + res.status);
      } else {
        // DEV MODE — simulate network delay, log to console
        await new Promise((r) => setTimeout(r, 800));
        console.log('Form submission:', JSON.stringify(payload, null, 2));
      }
      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((s) => s.classList.remove('active'));
    $('#akiform-success').classList.add('active');
    $('#akiform-footer').style.display = 'none';
    $('#akiform-progress').style.display = 'none';
  }

  // ==========================================
  // INIT
  // ==========================================
  function init() {
    initRoles();
    initCitySearch();
    initCountrySearch();
    initContactValidation();

    // Keyboard shortcuts
    document.addEventListener('keydown', (e) => {
      if (!$('#akiform-overlay').classList.contains('active')) return;
      if (e.key === 'Escape') close();
      if (e.key === 'Enter' && !$('#akiform-btn-next').disabled) {
        e.preventDefault();
        next();
      }
    });

    // CTA card keyboard accessibility
    var ctaCard = $('.akitrips-cta-card');
    if (ctaCard) {
      ctaCard.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          open();
        }
      });
    }
  }

  // Auto-init when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

  // ==========================================
  // PUBLIC API
  // ==========================================
  return { open, close, next, prev, clearCity, clearCountry };
})();