/* ================================================ */
/*  DESTINO PATAGONIA OPERATOR FORM - JS LOGIC      */
/* ================================================ */

const DpForm = (function() {

  const STORE_SLUG = 'destinopatagonia';
  const API_ENDPOINT = `https://${STORE_SLUG}.myvivirly.com/api/leads/submit`;

  const INTERESTS = [
    { id: 'visibility', label: 'Llegar a más viajeros y aumentar mis reservas' },
    { id: 'booking', label: 'Tener un sistema de reservas online integrado' },
    { id: 'payments', label: 'Cobrar online con pagos en moneda local e internacional' },
    { id: 'commission', label: 'Conocer las condiciones comerciales y comisiones' },
    { id: 'crosssell', label: 'Hacer paquetes y cross-selling con otros operadores' },
    { id: 'marketing', label: 'Aprovechar campañas de marketing conjuntas' },
    { id: 'other', label: 'Otro motivo' }
  ];

  const LOCATIONS = [
    // Argentina - Provincias patagónicas
    { code: 'AR-NQN', name: 'Neuquén', region: 'Argentina', type: 'province' },
    { code: 'AR-RNG', name: 'Río Negro', region: 'Argentina', type: 'province' },
    { code: 'AR-CHB', name: 'Chubut', region: 'Argentina', type: 'province' },
    { code: 'AR-SCZ', name: 'Santa Cruz', region: 'Argentina', type: 'province' },
    { code: 'AR-TDF', name: 'Tierra del Fuego', region: 'Argentina', type: 'province' },
    { code: 'AR-LPM', name: 'La Pampa', region: 'Argentina', type: 'province' },

    // Argentina - Localidades destacadas
    { code: 'AR-BAR', name: 'San Carlos de Bariloche', region: 'Río Negro', type: 'city' },
    { code: 'AR-VLA', name: 'Villa La Angostura', region: 'Neuquén', type: 'city' },
    { code: 'AR-SMA', name: 'San Martín de los Andes', region: 'Neuquén', type: 'city' },
    { code: 'AR-ESQ', name: 'Esquel', region: 'Chubut', type: 'city' },
    { code: 'AR-ELB', name: 'El Bolsón', region: 'Río Negro', type: 'city' },
    { code: 'AR-PMD', name: 'Puerto Madryn', region: 'Chubut', type: 'city' },
    { code: 'AR-TRL', name: 'Trelew', region: 'Chubut', type: 'city' },
    { code: 'AR-PPR', name: 'Puerto Pirámides', region: 'Chubut', type: 'city' },
    { code: 'AR-COM', name: 'Comodoro Rivadavia', region: 'Chubut', type: 'city' },
    { code: 'AR-ECH', name: 'El Chaltén', region: 'Santa Cruz', type: 'city' },
    { code: 'AR-ECL', name: 'El Calafate', region: 'Santa Cruz', type: 'city' },
    { code: 'AR-RGA', name: 'Río Gallegos', region: 'Santa Cruz', type: 'city' },
    { code: 'AR-USH', name: 'Ushuaia', region: 'Tierra del Fuego', type: 'city' },
    { code: 'AR-RGD', name: 'Río Grande', region: 'Tierra del Fuego', type: 'city' },
    { code: 'AR-PYM', name: 'Península Mitre', region: 'Tierra del Fuego', type: 'area' },
    { code: 'AR-ALU', name: 'Aluminé', region: 'Neuquén', type: 'city' },
    { code: 'AR-JUN', name: 'Junín de los Andes', region: 'Neuquén', type: 'city' },
    { code: 'AR-VIE', name: 'Viedma', region: 'Río Negro', type: 'city' },
    { code: 'AR-LAS', name: 'Las Grutas', region: 'Río Negro', type: 'city' },

    // Chile - Regiones patagónicas
    { code: 'CL-AR', name: 'Región de La Araucanía', region: 'Chile', type: 'province' },
    { code: 'CL-LR', name: 'Región de Los Ríos', region: 'Chile', type: 'province' },
    { code: 'CL-LL', name: 'Región de Los Lagos', region: 'Chile', type: 'province' },
    { code: 'CL-AI', name: 'Región de Aysén', region: 'Chile', type: 'province' },
    { code: 'CL-MA', name: 'Región de Magallanes', region: 'Chile', type: 'province' },

    // Chile - Localidades destacadas
    { code: 'CL-PUC', name: 'Pucón', region: 'La Araucanía', type: 'city' },
    { code: 'CL-VIL', name: 'Villarrica', region: 'La Araucanía', type: 'city' },
    { code: 'CL-VAL', name: 'Valdivia', region: 'Los Ríos', type: 'city' },
    { code: 'CL-PVA', name: 'Puerto Varas', region: 'Los Lagos', type: 'city' },
    { code: 'CL-PMO', name: 'Puerto Montt', region: 'Los Lagos', type: 'city' },
    { code: 'CL-FRU', name: 'Frutillar', region: 'Los Lagos', type: 'city' },
    { code: 'CL-CHL', name: 'Chiloé', region: 'Los Lagos', type: 'area' },
    { code: 'CL-COY', name: 'Coyhaique', region: 'Aysén', type: 'city' },
    { code: 'CL-PAY', name: 'Puerto Aysén', region: 'Aysén', type: 'city' },
    { code: 'CL-CAR', name: 'Carretera Austral', region: 'Aysén', type: 'area' },
    { code: 'CL-PUQ', name: 'Punta Arenas', region: 'Magallanes', type: 'city' },
    { code: 'CL-PNT', name: 'Puerto Natales', region: 'Magallanes', type: 'city' },
    { code: 'CL-TDP', name: 'Torres del Paine', region: 'Magallanes', type: 'area' },
    { code: 'CL-PWI', name: 'Puerto Williams', region: 'Magallanes', type: 'city' },

    // Catch-all
    { code: 'OTHER', name: 'Otra localidad patagónica', region: '—', type: 'other' }
  ];

  const state = {
    currentStep: 1,
    totalSteps: 4,
    role: null,
    interests: [],
    country: null,
    name: '',
    email: '',
    phone: '',
    org: '',
    comment: '',
    submitting: false
  };

  function $(id) { return document.getElementById(id); }

  function open() {
    $('dpform-overlay').classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  function close() {
    $('dpform-overlay').classList.remove('active');
    document.body.style.overflow = '';
  }

  function goToStep(step) {
    document.querySelectorAll('.dpform-step').forEach(el => el.classList.remove('active'));
    const stepEl = document.querySelector(`.dpform-step[data-step="${step}"]`);
    if (stepEl) stepEl.classList.add('active');

    state.currentStep = step;
    const pct = (step / state.totalSteps) * 100;
    $('dpform-progress-fill').style.width = pct + '%';
    $('dpform-progress-text').textContent = `Paso ${step} de ${state.totalSteps}`;

    $('dpform-btn-back').style.display = step > 1 ? 'block' : 'none';
    $('dpform-btn-next').querySelector('.btn-text').textContent =
      step === state.totalSteps ? 'Enviar' : 'Siguiente';

    updateNextButton();
  }

  function next() {
    if (state.currentStep < state.totalSteps) {
      goToStep(state.currentStep + 1);
    } else {
      submit();
    }
  }

  function prev() {
    if (state.currentStep > 1) {
      goToStep(state.currentStep - 1);
    }
  }

  function updateNextButton() {
    const btn = $('dpform-btn-next');
    let valid = false;

    if (state.currentStep === 1) valid = !!state.role;
    else if (state.currentStep === 2) valid = state.interests.length > 0;
    else if (state.currentStep === 3) valid = !!state.country;
    else if (state.currentStep === 4) valid = isValidEmail(state.email) && state.name.trim().length > 0;

    btn.disabled = !valid;
  }

  function isValidEmail(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  }

  /* --- Step 1: Roles --- */
  function initRoles() {
    document.querySelectorAll('.dpform-role').forEach(el => {
      el.addEventListener('click', () => {
        document.querySelectorAll('.dpform-role').forEach(r => r.classList.remove('selected'));
        el.classList.add('selected');
        state.role = el.dataset.role;
        updateNextButton();
      });
    });
  }

  /* --- Step 2: Interests --- */
  function initInterests() {
    const container = $('dpform-interests');
    container.innerHTML = '';
    INTERESTS.forEach(item => {
      const div = document.createElement('div');
      div.className = 'dpform-check';
      div.dataset.id = item.id;
      div.innerHTML = `
        <div class="dpform-checkbox">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
        </div>
        <div class="dpform-check-label">${item.label}</div>
      `;
      div.addEventListener('click', () => {
        const id = item.id;
        if (state.interests.includes(id)) {
          state.interests = state.interests.filter(i => i !== id);
          div.classList.remove('selected');
        } else {
          state.interests.push(id);
          div.classList.add('selected');
        }
        updateNextButton();
      });
      container.appendChild(div);
    });
  }

  /* --- Step 3: Location --- */
  function initCountry() {
    const input = $('dpform-country-input');
    const dropdown = $('dpform-country-dropdown');

    function renderList(filter = '') {
      dropdown.innerHTML = '';
      const f = filter.toLowerCase().trim();
      const filtered = LOCATIONS.filter(loc =>
        loc.name.toLowerCase().includes(f) ||
        loc.region.toLowerCase().includes(f)
      );
      if (filtered.length === 0) {
        dropdown.innerHTML = '<div class="dpform-dropdown-empty">Sin resultados</div>';
        return;
      }
      filtered.forEach(loc => {
        const item = document.createElement('div');
        item.className = 'dpform-dropdown-item';
        if (state.country && state.country.code === loc.code) item.classList.add('selected');
        item.innerHTML = `
          <div class="dpform-dropdown-item-name">${loc.name}</div>
          <div class="dpform-dropdown-item-region">${loc.region}</div>
        `;
        item.addEventListener('click', () => selectCountry(loc));
        dropdown.appendChild(item);
      });
    }

    input.addEventListener('focus', () => {
      renderList(input.value);
      dropdown.classList.add('open');
    });

    input.addEventListener('input', () => {
      renderList(input.value);
      dropdown.classList.add('open');
    });

    document.addEventListener('click', (e) => {
      if (!$('dpform-country-search').contains(e.target)) {
        dropdown.classList.remove('open');
      }
    });

    renderList();
  }

  function selectCountry(loc) {
    state.country = loc;
    $('dpform-country-input').value = '';
    $('dpform-country-input').style.display = 'none';
    $('dpform-country-tag-text').textContent = loc.name + (loc.region && loc.region !== '—' ? ` · ${loc.region}` : '');
    $('dpform-country-tag').classList.add('visible');
    $('dpform-country-dropdown').classList.remove('open');
    updateNextButton();
  }

  function clearCountry() {
    state.country = null;
    $('dpform-country-input').style.display = 'block';
    $('dpform-country-input').value = '';
    $('dpform-country-tag').classList.remove('visible');
    updateNextButton();
  }

  /* --- Step 4: Contact --- */
  function initContact() {
    $('dpform-name').addEventListener('input', e => {
      state.name = e.target.value;
      updateNextButton();
    });
    $('dpform-email').addEventListener('input', e => {
      state.email = e.target.value;
      updateNextButton();
    });
    $('dpform-phone').addEventListener('input', e => {
      state.phone = e.target.value;
    });
    $('dpform-org').addEventListener('input', e => {
      state.org = e.target.value;
    });
    $('dpform-comment').addEventListener('input', e => {
      state.comment = e.target.value;
    });

    $('dpform-email').addEventListener('blur', () => {
      const emailEl = $('dpform-email');
      const errEl = $('dpform-email-error');
      if (state.email && !isValidEmail(state.email)) {
        emailEl.classList.add('error');
        errEl.classList.add('visible');
      } else {
        emailEl.classList.remove('error');
        errEl.classList.remove('visible');
      }
    });

    $('dpform-name').addEventListener('blur', () => {
      const nameEl = $('dpform-name');
      const errEl = $('dpform-name-error');
      if (!state.name.trim()) {
        nameEl.classList.add('error');
        errEl.classList.add('visible');
      } else {
        nameEl.classList.remove('error');
        errEl.classList.remove('visible');
      }
    });
  }

  /* --- Submit --- */
  async function submit() {
    if (state.submitting) return;

    // Honeypot check
    const hp = $('dpform-hp');
    if (hp && hp.value.trim() !== '') {
      // Bot detected - silently show success
      showSuccess();
      return;
    }

    state.submitting = true;
    const btn = $('dpform-btn-next');
    btn.classList.add('loading');
    btn.disabled = true;

    const payload = {
      store: STORE_SLUG,
      role: state.role,
      interests: state.interests,
      location_code: state.country ? state.country.code : null,
      location_name: state.country ? state.country.name : null,
      location_region: state.country ? state.country.region : null,
      name: state.name.trim(),
      email: state.email.trim(),
      phone: state.phone.trim(),
      organization: state.org.trim(),
      comment: state.comment.trim(),
      source: 'operator_signup_widget',
      submitted_at: new Date().toISOString()
    };

    try {
      await fetch(API_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      showSuccess();
    } catch (err) {
      console.error('DpForm submission error:', err);
      // Still show success to user (graceful fallback)
      showSuccess();
    } finally {
      state.submitting = false;
      btn.classList.remove('loading');
    }
  }

  function showSuccess() {
    document.querySelectorAll('.dpform-step').forEach(el => el.classList.remove('active'));
    $('dpform-success').classList.add('active');
    $('dpform-progress').style.display = 'none';
    $('dpform-footer').style.display = 'none';
  }

  /* --- Init --- */
  function init() {
    initRoles();
    initInterests();
    initCountry();
    initContact();
  }

  document.addEventListener('DOMContentLoaded', init);

  return {
    open,
    close,
    next,
    prev,
    clearCountry
  };
})();