// ========================================
// TICKET SELECTOR LOGIC
// ========================================
var selectedLocality = 0;
var selectedQty = 1;
var currentEvent = null;

function initSelector() {
  var params = new URLSearchParams(window.location.search);
  var eventId = params.get('idevento') || '9384';
  currentEvent = EVENTS_DB[eventId];
  if (!currentEvent) { currentEvent = EVENTS_DB['9384']; }

  // Fill event info
  document.getElementById('ev-name').textContent = currentEvent.name;
  document.getElementById('ev-date').textContent = currentEvent.date;
  document.getElementById('ev-venue').textContent = currentEvent.venue;
  document.getElementById('ev-location').textContent = currentEvent.location;
  var posterEl = document.getElementById('ev-poster');
  if (posterEl) posterEl.src = currentEvent.poster;
  var mapEl = document.getElementById('ev-map');
  if (mapEl) mapEl.src = currentEvent.mapImage;

  // Render dynamic interactive map if the event is 16966
  var mapContainer = document.getElementById('map-svg-container');
  var mapImg = document.getElementById('ev-map');
  if (eventId === '16966') {
    if (mapImg) mapImg.style.display = 'none';
    if (mapContainer) {
      mapContainer.style.display = 'block';
      setupInteractiveMap();
    }
  } else {
    if (mapImg) mapImg.style.display = 'block';
    if (mapContainer) mapContainer.style.display = 'none';
  }

  // Build locality options
  var container = document.getElementById('localities-list');
  container.innerHTML = '';
  var symbol = currentEvent.currencySymbol || '¢';
  currentEvent.localities.forEach(function(loc, i) {
    var div = document.createElement('div');
    div.className = 'locality-option' + (i === 0 ? ' selected' : '');
    div.setAttribute('data-index', i);
    div.onclick = function() { selectLocality(i); };
    var price = (loc.priceLocal !== undefined) ? loc.priceLocal : loc.priceCRC;
    var priceUSD = localToUSD(price, currentEvent);
    div.innerHTML =
      '<div class="flex items-center gap-3">' +
        '<div class="w-3 h-3 rounded-full flex-shrink-0" style="background:' + loc.color + '"></div>' +
        '<div><div class="font-medium text-on-surface text-sm">' + loc.name + '</div>' +
        '<div class="text-xs text-on-surface-variant">' + loc.type + '</div></div>' +
      '</div>' +
      '<div class="text-right"><div class="font-mono font-semibold text-on-surface text-sm">' + symbol + formatCurrency(price, currentEvent.currency) + '</div>' +
      '<div class="text-xs text-on-surface-variant">≈ $' + priceUSD + '</div></div>';
    container.appendChild(div);
  });

  selectedLocality = 0;
  selectedQty = 1;
  document.getElementById('qty-display').textContent = '1';
  updateTotals();
}

function selectLocality(index) {
  selectedLocality = index;
  document.querySelectorAll('.locality-option').forEach(function(el, i) {
    el.classList.toggle('selected', i === index);
  });
  updateTotals();
  
  // Highlight active SVG path if interactive map is enabled
  if (currentEvent && currentEvent.currency === 'COP') {
    highlightSvgMapSection(index);
  }
}

function changeQty(delta) {
  selectedQty = Math.max(1, Math.min(10, selectedQty + delta));
  document.getElementById('qty-display').textContent = selectedQty;
  updateTotals();
}

function updateTotals() {
  if (!currentEvent) return;
  var loc = currentEvent.localities[selectedLocality];
  var price = (loc.priceLocal !== undefined) ? loc.priceLocal : loc.priceCRC;
  var totalLocal = price * selectedQty;
  var totalUSD = localToUSD(totalLocal, currentEvent);
  var symbol = currentEvent.currencySymbol || '¢';

  document.getElementById('sel-total-crc').textContent = symbol + formatCurrency(totalLocal, currentEvent.currency);
  document.getElementById('sel-total-usd').textContent = '$' + totalUSD + ' USD';
  // Update summary panel
  document.getElementById('display-evento').textContent = currentEvent.name;
  document.getElementById('sum-locality').textContent = loc.name + ' x' + selectedQty;
  document.getElementById('display-subtotal').textContent = '$' + totalUSD;
  document.getElementById('display-total').textContent = '$' + totalUSD;

  var infoEl = document.getElementById('display-conversion-info');
  if (infoEl) {
    if (currentEvent.currency === 'COP') {
      infoEl.textContent = 'Precios en COP convertidos a USD (1 COP = ' + (currentEvent.exchangeRate || 0.00026) + ' USD)';
    } else {
      infoEl.textContent = 'Precios en CRC convertidos a USD (1 CRC = 0.0022 USD)';
    }
  }
}

function proceedToPayment() {
  if (!currentEvent) return;
  var loc = currentEvent.localities[selectedLocality];
  var price = (loc.priceLocal !== undefined) ? loc.priceLocal : loc.priceCRC;
  var totalLocal = price * selectedQty;
  var totalUSD = localToUSD(totalLocal, currentEvent);

  // Update ORDER_DATA for PayPal
  ORDER_DATA.evento = currentEvent.name + ' | ' + loc.name + ' x' + selectedQty;
  ORDER_DATA.subtotal = totalUSD;
  ORDER_DATA.comision = "0.00";
  ORDER_DATA.impuesto = "0.00";
  ORDER_DATA.total = totalUSD;

  // Update summary
  document.getElementById('display-evento').textContent = ORDER_DATA.evento;
  document.getElementById('display-subtotal').textContent = '$' + totalUSD;
  document.getElementById('display-total').textContent = '$' + totalUSD;

  // Switch views
  document.getElementById('step-selector').style.display = 'none';
  document.getElementById('step-payment').style.display = 'block';
  document.getElementById('step-indicator-1').classList.remove('step-active');
  document.getElementById('step-indicator-1').classList.add('step-done');
  document.getElementById('step-indicator-2').classList.add('step-active');
}

function backToSelector() {
  document.getElementById('step-selector').style.display = 'block';
  document.getElementById('step-payment').style.display = 'none';
  document.getElementById('step-indicator-2').classList.remove('step-active');
  document.getElementById('step-indicator-1').classList.remove('step-done');
  document.getElementById('step-indicator-1').classList.add('step-active');
}

var SECTION_MAP = {
  'preferencial': 0,
  '117_124': 3,
  '125_132': 5,
  '111_113_115': 7,
  '112_114_116': 9,
  '107_109': 11,
  '108_110': 13,
  '101_103_105': 15,
  '102_104_106': 17,
  'platea_e': 19,
  'platea_d': 21,
  'platea_c': 23,
  'platea_b': 25,
  'platea_a': 27,
  'palcos_oro': 29,
  'palcos_diamante': 30
};

function setupInteractiveMap() {
  var svgEl = document.querySelector('#map-svg-container svg');
  if (!svgEl) return;
  
  var sections = svgEl.querySelectorAll('[data-section]');
  sections.forEach(function(sec) {
    sec.style.cursor = 'pointer';
    sec.onclick = function() {
      var secName = sec.getAttribute('data-section');
      var index = SECTION_MAP[secName];
      if (index !== undefined) {
        selectLocality(index);
        
        // Scroll the selected locality into view in the list if needed
        var locDiv = document.querySelector('.locality-option[data-index="' + index + '"]');
        if (locDiv) {
          locDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
      }
    };
  });
}

function highlightSvgMapSection(index) {
  var svgEl = document.querySelector('#map-svg-container svg');
  if (!svgEl) return;
  
  // Find which section name corresponds to this index
  var secName = null;
  for (var name in SECTION_MAP) {
    var baseIdx = SECTION_MAP[name];
    var nextBaseIdx = getNextBaseIndex(name);
    if (index >= baseIdx && index < nextBaseIdx) {
      secName = name;
      break;
    }
  }
  
  // Reset all section styles inside SVG
  svgEl.querySelectorAll('[data-section]').forEach(function(sec) {
    sec.classList.remove('svg-active');
    sec.setAttribute('fill-opacity', '0.25');
    sec.setAttribute('stroke-width', '1.5');
  });
  
  if (secName) {
    var activeSec = svgEl.querySelector('[data-section="' + secName + '"]');
    if (activeSec) {
      activeSec.classList.add('svg-active');
      activeSec.setAttribute('fill-opacity', '0.7');
      activeSec.setAttribute('stroke-width', '3.5');
    }
  }
}

function getNextBaseIndex(name) {
  var order = [
    'preferencial', '117_124', '125_132', '111_113_115', '112_114_116',
    '107_109', '108_110', '101_103_105', '102_104_106',
    'platea_e', 'platea_d', 'platea_c', 'platea_b', 'platea_a',
    'palcos_oro', 'palcos_diamante'
  ];
  var idx = order.indexOf(name);
  if (idx === -1 || idx === order.length - 1) return 999;
  return SECTION_MAP[order[idx + 1]];
}

document.addEventListener('DOMContentLoaded', initSelector);
