var envSelectedDatasets = [];
var fileSelectedLayers = [];

// Mirror R's make.names(): replace chars that are invalid in R names with '.'
function makeNames(name) {
  return name.replace(/[^a-zA-Z0-9._]/g, '.');
}

function updateImportButton() {
  const src = $('input[name="import_source"]:checked').val();
  const hasSelection = src === 'env'
    ? envSelectedDatasets.length > 0
    : fileSelectedLayers.length > 0;
  const btn = document.getElementById('confirm_import');
  if (btn) btn.disabled = !hasSelection;
}

function envRowToggle(name) {
  const row = document.getElementById('env_row_' + name);
  const idx = envSelectedDatasets.indexOf(name);
  if (idx === -1) {
    envSelectedDatasets.push(name);
    if (row) row.classList.add('selected');
  } else {
    envSelectedDatasets.splice(idx, 1);
    if (row) row.classList.remove('selected');
  }
  Shiny.setInputValue('env_selected_datasets', envSelectedDatasets.slice(), {priority: 'event'});
  updateImportButton();
}

function fileRowToggle(name) {
  const row = document.getElementById('file_row_' + makeNames(name));
  const idx = fileSelectedLayers.indexOf(name);
  if (idx === -1) {
    fileSelectedLayers.push(name);
    if (row) row.classList.add('selected');
  } else {
    fileSelectedLayers.splice(idx, 1);
    if (row) row.classList.remove('selected');
  }
  Shiny.setInputValue('file_selected_layers', fileSelectedLayers.slice(), {priority: 'event'});
  updateImportButton();
}

function envPreviewRequest(name) {
  Shiny.setInputValue('env_preview_request', name, {priority: 'event'});
}

function envClosePreview() {
  Shiny.setInputValue('env_preview_request', null, {priority: 'event'});
  const panel = document.getElementById('env-preview-panel');
  if (panel) panel.style.display = 'none';
}

function filePreviewRequest(name) {
  Shiny.setInputValue('file_preview_request', name, {priority: 'event'});
}

function fileClosePreview() {
  Shiny.setInputValue('file_preview_request', null, {priority: 'event'});
  const panel = document.getElementById('file-preview-panel');
  if (panel) panel.style.display = 'none';
}

// Reset selection state when the modal opens (fresh start each time)
$(document).on('shown.bs.modal', function() {
  envSelectedDatasets = [];
  Shiny.setInputValue('env_selected_datasets', [], {priority: 'event'});
  fileSelectedLayers = [];
  Shiny.setInputValue('file_selected_layers', [], {priority: 'event'});
  updateImportButton();
});

// Update button state when the source radio changes
$(document).on('change', 'input[name="import_source"]', function() {
  updateImportButton();
});

// Reset file layer selection when a new file is uploaded
$(document).on('shiny:inputchanged', function(e) {
  if (e.name === 'upload_file') {
    fileSelectedLayers = [];
    Shiny.setInputValue('file_selected_layers', [], {priority: 'event'});
    const panel = document.getElementById('file-preview-panel');
    if (panel) panel.style.display = 'none';
    updateImportButton();
  }
});

// Custom message from server: show the preview panel and set its title
Shiny.addCustomMessageHandler('showEnvPreview', function(name) {
  const panel = document.getElementById('env-preview-panel');
  const title = document.getElementById('env-preview-title');
  if (panel) panel.style.display = 'block';
  if (title) title.textContent = name;
  // Trigger resize so Shiny recomputes plot dimensions after panel reveal
  // (otherwise the plot have not the appropriate dimensions on first render)
  setTimeout(function() { $(window).trigger('resize'); }, 50);
});

Shiny.addCustomMessageHandler('showFilePreview', function(name) {
  const panel = document.getElementById('file-preview-panel');
  const title = document.getElementById('file-preview-title');
  if (panel) panel.style.display = 'block';
  if (title) title.textContent = name;
  // Trigger resize so Shiny recomputes plot dimensions after panel reveal
  // (otherwise the plot have not the appropriate dimensions on first render)
  setTimeout(function() { $(window).trigger('resize'); }, 50);
});
