//   Trigger Options

function after_add_trigger_update(){
	triggerListWinLoss_copy = [...triggerListWinLoss];
	
	display_alerts();

}
function after_radio_button_all_win_loss_update()
{
	selectTabAndUpdateContent(1, getTriggerList);
	display_alerts();
	console.log("triggerListItem: ",triggerListItem);
	console.log("triggerListWinLoss: ",triggerListWinLoss);
	console.log("triggerListWinLoss_copy: ",triggerListWinLoss_copy);
}

function triggerOptions() {

	let container_ = document.createElement('div');

    let section_title = panel_title();
    let section_outside_bets = outside_bet_section();
    let section_unique_bets = uniques_bet_section();
    let section_group_bets = group_bet_section();
    let section_pattern_bets = pattern_bet_section();
    let section_trigger_code = trigger_code_section();

    container_.appendChild(section_title);
    container_.appendChild(section_outside_bets);
    container_.appendChild(createDivider());
    container_.appendChild(section_group_bets);
    container_.appendChild(createDivider());
    container_.appendChild(section_unique_bets);
    container_.appendChild(createDivider());
    container_.appendChild(section_pattern_bets);
    container_.appendChild(createDivider());
    container_.appendChild(section_trigger_code);

	container_.appendChild(document.createElement('br'));

	return container_;

}

function createDivider() {
	const container_divider = document.createElement('div');
	const divider = document.createElement('hr');
	divider.classList.add('gradient');
	container_divider.append(divider);
	return container_divider;
}

function panel_title()
{
    let container = document.createElement('div');

	var sectionTitle = document.createElement('h2');
	sectionTitle.innerHTML = 'Triggers '+version;
	sectionTitle.style.textAlign = 'center';

    container.appendChild(sectionTitle);

    return container;
}

function outside_bet_section()
{
    let container = document.createElement('div');


    // Help message
    var title = 'Pre-defined';
	var msg = 'If x amount of (Evens, Rows, Dozens..) lose in a row, \nthen the tool will trigger to bet on those.';
	var evenNumbersTitle = createTitleWithHelp(title,msg);
    container.appendChild(evenNumbersTitle);

    // Input Box
    var evensSpins = document.createElement('input');
	evensSpins.type = 'text';
	evensSpins.id = "triggerEvensLosses";
	evensSpins.name = "triggerEvensLosses";
	evensSpins.placeholder = "";
	evensSpins.classList.add('textbox-container');
	evensSpins.classList.add('triggerGroups');
    container.appendChild(evensSpins);
	
	// Radio Selection
	//container.appendChild(createRadioButtonSelection('outside'));
	
	// DROP DOWN NODE: WINS / LOSSES
	var dropdown = document.createElement('select');
	dropdown.id = 'triggerEvensLossesDropDown'; // Add an ID for reference
	// Create "Losses" option
	var lossesOption = document.createElement('option');
	lossesOption.value = 'L';
	lossesOption.text = 'Losses';
	dropdown.appendChild(lossesOption);
	// Create "Wins" option
	var winsOption = document.createElement('option');
	winsOption.value = 'W';
	winsOption.text = 'Wins';
	dropdown.appendChild(winsOption);
	container.appendChild(dropdown);

    // Label
    var evenLabel = document.createElement('label');
	evenLabel.htmlFor = 'triggerEvensLosses';
	evenLabel.appendChild(document.createTextNode(' in a row '));
    container.appendChild(evenLabel);
	

    // Label
    var dropdownText = document.createElement('span');
	dropdownText.innerText = "on ";
    container.appendChild(dropdownText);

    // Drop Down
    var selectElement = document.createElement('select');
	selectElement.id = 'triggerOptionDropdown';
	var defaultValue = 'Even';

	triggerDropDown.forEach(function (option) {

		var optionElement = document.createElement('option');
		optionElement.value = option.value;
		optionElement.textContent = option.text;

		if (option.value === defaultValue) {
			optionElement.selected = true;
		}

		selectElement.appendChild(optionElement);
	});
    container.appendChild(selectElement);

    // Add Trigger Button
    const defined_trigger_button = document.createElement('button');
	defined_trigger_button.id = "triggerOptionsButtons";
	defined_trigger_button.innerText = "Add Trigger";
	defined_trigger_button.classList.add('triggerOptionsButtons');
	//defined_trigger_button.onclick = triggerPanelInsertDefinedTrigger;
	defined_trigger_button.addEventListener('click', function() {
		selectTabAndUpdateContent(1, outsideBetSelectionAddTrigger);
		after_add_trigger_update();
		
	});
    container.appendChild(defined_trigger_button);

    return container;
    
}

function uniques_bet_section()
{
    let container = document.createElement('div');

	var title = 'Uniques';
	var msg = 'If x amount of unique numbers appear in a row, \nthen the tool will trigger to bet those numbers.';
	var uniquesTitle = createTitleWithHelp(title,msg);
    container.appendChild(uniquesTitle);

	var uniqueSpins = document.createElement('input');
	uniqueSpins.type = 'text';
	uniqueSpins.id = "triggerUniques";
	uniqueSpins.name = "triggerUniques";
	uniqueSpins.placeholder = "";
	uniqueSpins.classList.add('textbox-container');
	uniqueSpins.classList.add('triggerGroups');
    container.appendChild(uniqueSpins);

	// Group Label
	var uniqueLabel = document.createElement('label');
	uniqueLabel.htmlFor = 'triggerUniques';
	uniqueLabel.appendChild(document.createTextNode('Unique numbers in a row'));
    container.appendChild(uniqueLabel);

	// Apply Button
	const unique_trigger_button = document.createElement('button');
	unique_trigger_button.id = "triggerUniquesButtons";
	unique_trigger_button.innerText = "Add Trigger";
	unique_trigger_button.classList.add('triggerOptionsButtons');
	unique_trigger_button.addEventListener('click', function() {
		selectTabAndUpdateContent(1, uniqueBetSelectionAddTrigger);
		after_add_trigger_update();
		
	});
    container.appendChild(unique_trigger_button);

    return container;

}

function group_bet_section()
{
    let container = document.createElement('div');

    var title = 'Group Numbers';
	var msg = 'Create your own number groups.';
	msg +='\nThe hyphen(-) separates the groups.';
	msg +='\nFor example, 1,2,3 - 4,5,6 becomes two groups [1,2,3] and [4,5,6].';
	msg += '\nIf x amount of losses happens for any group,';
	msg += '\nthen the tool will trigger to bet on that group.';
	var groupsTitle = createTitleWithHelp(title,msg);
    container.appendChild(groupsTitle);

	// Create losses textbox
	var groupSpins = document.createElement('input');
	groupSpins.type = 'text';
	groupSpins.id = "triggerGroupsLosses";
	groupSpins.name = "triggerGroupsLosses";
	groupSpins.placeholder = "";
	groupSpins.value = "5";
	groupSpins.classList.add('textbox-container');
	groupSpins.classList.add('triggerGroups');
    container.appendChild(groupSpins);

		// DROP DOWN NODE: WINS / LOSSES
		var dropdown = document.createElement('select');
		dropdown.id = 'triggerGroupsLossesDropDown'; // Add an ID for reference
		// Create "Losses" option
		var lossesOption = document.createElement('option');
		lossesOption.value = 'L';
		lossesOption.text = 'Losses';
		dropdown.appendChild(lossesOption);
		// Create "Wins" option
		var winsOption = document.createElement('option');
		winsOption.value = 'W';
		winsOption.text = 'Wins';
		dropdown.appendChild(winsOption);
		container.appendChild(dropdown);

	// Group Label
	var label = document.createElement('label');
	label.htmlFor = 'triggerGroupsLosses';
	label.appendChild(document.createTextNode(' in a row'));
    container.appendChild(label);

	// Add Trigger
	const apply_trigger_button = document.createElement('button');
	apply_trigger_button.innerText = "Add Trigger";
	apply_trigger_button.classList.add('triggerOptionsButton');
	apply_trigger_button.id = "addUserDefinedTriggerBtn";
	apply_trigger_button.addEventListener('click', function() {

		var textarea = document.getElementById('groupNumbers');

		var value = textarea.value;
	
		value = processValue(value);
	
		if(value.length==0)
		{
			showMessageAtCursor("Text Box needs a value.");
			return;
		}

		let good = selectTabAndUpdateContent(1, groupBetSelectionAddTrigger);
	
		after_add_trigger_update();
		
	});
    container.appendChild(apply_trigger_button);
    container.appendChild(document.createElement('br'));

	// Enter Text Area
	const groupNumbers = document.createElement('textarea');
	groupNumbers.id = "groupNumbers";
	groupNumbers.classList.add('enterOwnNumbers');
	groupNumbers.placeholder = "1,2,3 - 10,11,12 - 1,5,20 (separate groups with a -)";
	groupNumbers.value = "These are the group bets for everything, delete whatever you want, and this text <<  --- 3,6,9,12 - 15,18,21,24 - 27,30,33,36 - 2,5,8,11 - 14,17,20,23 - 26,29,32,35 - 1,4,7,10 - 13,16,19,22 - 25,28,31,34 - 0,1,2,3,4,5,6,7,8,9 - 10,11,12,13,14,15,16,17,18,19 - 20,21,22,23,24,25,26,26,27,28,29 - 30,31,32,33,34,35,36 - 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18 - 19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36 - 1,2,3,4,5,6,7,8,9,10,11,12 - 13,14,15,16,17,18,19,20,21,22,23,24 - 25,26,27,28,29,30,31,32,33,34,35,36 - 1,4,7,10,13,16,19,22,25,28,31,34 - 2,5,8,11,14,17,20,23,26,29,32,35 - 3,6,9,12,15,18,21,24,27,30,33,36 - 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35 - 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36 - 1,3,5,7,9,12,14,16,18,21,23,25,27,30,32,34,36 - 2,4,6,8,10,11,13,15,17,20,22,24,26,28,29,33,35 - 0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22-23-24-25-26-27-28-29-30-31-32-33-34-35-36 -  1,2,3,4,5,6 - 7,8,9,10,11,12 - 13,14,15,16,17,18 - 19,20,21,22,23,24 - 25,26,27,28,29,30 - 31,32,33,34,35,36 - 1,2,4,5 - 8,9,11,12 - 13,14,16,17 - 20,21,23,24 - 25,26,28,29 - 32,33,35,36 - 1,2-3,6-5,4-7,8-9,8-7,10-11,12-15,14-13,16-19,20-21,24-27,26-25,28-29,30-33,32-31,34-35,36 - 1,2,3 - 4,5,6 - 7,8,9 - 10,11,12 - 13,14,15 - 16,17,18 - 19,20,21 - 22,23,24 - 25,26,27 - 28,29,30 - 31,32,33 - 34,35,36 -  1,4 - 2,5 - 3,6 - 7,10 - 8,11 - 9,12 - 13,16 - 14,17 - 15,18 - 19,22 - 20,23 - 21,24 - 25,28 - 26,29 - 27,30 - 31,34 - 32,35 - 33,36";
    container.appendChild(groupNumbers);
    container.appendChild(document.createElement('br'));

    // Clear Button
	const clearGroupNumbersButton = document.createElement('button');
	clearGroupNumbersButton.innerText = "Clear Textbox";
	clearGroupNumbersButton.classList.add('triggerOptionsButtons');
	clearGroupNumbersButton.id = "clearUserDefinedOptionsBtn";
	clearGroupNumbersButton.onclick = function () {
        var textarea = document.getElementById('groupNumbers');
        textarea.value = '';
    };
    container.appendChild(clearGroupNumbersButton);



    return container;
}

function pattern_bet_section()
{
    let container = document.createElement('div');

    var title = 'Pattern Break';
	var msg = 'Bet that a pattern does not repeat.';
	msg +='\n';
	msg +='\nFor example, group length 3 happens 2 times.';
	msg += '\n';
	msg += '\nThe tool then looks for a pattern of 3 such as [Red, Red, Black]';
	msg += '\nThen it looks for it to happen 2 times in a row [Red, Red, Black][Red, Red, Black]';
	msg += '\n';
	msg += '\nSince we do not want the pattern to come up again, the tool will alert to bet Black.';
	msg += '\n';
	var patternTitle = createTitleWithHelp(title,msg);
    container.appendChild(patternTitle);

	var patternLength = document.createElement('input');
	patternLength.type = 'text';
	patternLength.id = "patternLength";
	patternLength.name = "patternLength";
	patternLength.placeholder = "";
	patternLength.value = "3";
	patternLength.classList.add('textbox-container');
	patternLength.classList.add('triggerGroups');
    container.appendChild(patternLength);

	var label_patternLength = document.createElement('label');
	label_patternLength.htmlFor = 'patternLength';
	label_patternLength.appendChild(document.createTextNode('Pattern Length: '));
    container.appendChild(label_patternLength);

	var patternMultiplier = document.createElement('input');
	patternMultiplier.type = 'text';
	patternMultiplier.id = "patternMultiplier";
	patternMultiplier.name = "patternMultiplier";
	patternMultiplier.placeholder = "";
	patternMultiplier.value = "2";
	patternMultiplier.classList.add('textbox-container');
	patternMultiplier.classList.add('triggerGroups');
    container.appendChild(patternMultiplier);

	var label_patternMultiplier = document.createElement('label');
	label_patternMultiplier.htmlFor = 'patternMultiplier';
	label_patternMultiplier.appendChild(document.createTextNode('Pattern repeats: '));
    container.appendChild(label_patternMultiplier);

	// TRIGGER ADD CONTAINER
	const pattern_trigger_button = document.createElement('button');
	pattern_trigger_button.innerText = "Add Trigger";
	pattern_trigger_button.classList.add('triggerOptionsButton');
	pattern_trigger_button.id = "patternTriggerButton";
	pattern_trigger_button.addEventListener('click', function() {
		selectTabAndUpdateContent(1, patternBetSelectionAddTrigger);
		after_add_trigger_update();
		
	});	
    container.appendChild(pattern_trigger_button);

    return container;
}

function trigger_code_section(){

    let trigger_code_window = document.createElement('div');

    trigger_code_window.setAttribute('id', 'trigger-code-window');
	let userOption = userTriggerOptions();
	trigger_code_window.appendChild(userOption);

	// Dropdown Options
	var made_triggers = document.createElement('select');
	made_triggers.id = 'made_triggers_Dropdown';

	var defaultValue = 'Even';
	// Create and append options
	preMadeDropDown.forEach(function (option) {
		var optionElement = document.createElement('option');
		optionElement.value = option.value;
		optionElement.textContent = option.text;

		// Set the option as selected if it matches the defaultValue
		if (option.value === defaultValue) {
			optionElement.selected = true;
		}

		made_triggers.appendChild(optionElement);
	});
	trigger_code_window.appendChild(made_triggers);



	const made_button = document.createElement('button');
	made_button.innerText = "Insert Code";
	made_button.classList.add('triggerOptionsButton');
	made_button.id = "patternTriggerButton";
	made_button.onclick = addPremade;
	trigger_code_window.appendChild(made_button);

	const sendme = document.createElement('span');
	sendme.innerText = 'Email tollens@gmail.com to add a pre-made pattern.'
	trigger_code_window.appendChild(document.createElement('br'));
	trigger_code_window.appendChild(document.createElement('br'));
	trigger_code_window.appendChild(sendme);
	trigger_code_window.appendChild(document.createElement('br'));
	trigger_code_window.appendChild(document.createElement('br'));
	trigger_code_window.appendChild(document.createElement('br'));
	trigger_code_window.appendChild(document.createElement('br'));
	trigger_code_window.appendChild(document.createElement('br'));
	trigger_code_window.appendChild(document.createElement('br'));

    return trigger_code_window;

}



// Helper Functions
function createRadioButtonSelection(id) {
	// Create container div
	const container = document.createElement('div');
	container.id = 'container'+id;
	document.body.appendChild(container);

	// Unified name for radio button group
	const groupName = 'hitTypeSelection';

	// Misses
	const radioButtonMiss = document.createElement('input');
	radioButtonMiss.type = 'radio';
	radioButtonMiss.id = 'id_'+id+'_miss';
	radioButtonMiss.name = groupName; // Unified name
	radioButtonMiss.value = 'miss';
	radioButtonMiss.checked = true;
	const labelMiss = document.createElement('label');
	labelMiss.htmlFor = radioButtonMiss.id;
	labelMiss.textContent = 'Misses in a row (this works, the rest to come)';
	container.appendChild(radioButtonMiss);
	container.appendChild(labelMiss);
	container.appendChild(document.createElement('br'));

	// Hits
	const radioButtonHit = document.createElement('input');
	radioButtonHit.type = 'radio';
	radioButtonHit.id = 'id_'+id+'_hit';
	radioButtonHit.name = groupName; // Unified name
	radioButtonHit.value = 'hit';
	const labelHit = document.createElement('label');
	labelHit.htmlFor = radioButtonHit.id;
	labelHit.textContent = 'Hits in a row';
	container.appendChild(radioButtonHit);
	container.appendChild(labelHit);
	container.appendChild(document.createElement('br'));

	// Percent
	const radioButtonPercent = document.createElement('input');
	radioButtonPercent.type = 'radio';
	radioButtonPercent.id = 'id_'+id+'_percent';
	radioButtonPercent.name = groupName; // Unified name
	radioButtonPercent.value = 'percent';
	const labelPercent = document.createElement('label');
	labelPercent.htmlFor = radioButtonPercent.id;
	labelPercent.textContent = 'Percent hit rate';
	container.appendChild(radioButtonPercent);
	container.appendChild(labelPercent);

	// Additional Percent Spins Input
	var inputBox = document.createElement('input');
	inputBox.type = 'text';
	inputBox.id = 'extraInput_'+id;
	inputBox.style.width = '25px'; 
	let message = document.createTextNode(' out of the last ');
	let messageAfter = document.createTextNode(' spins.');
	container.appendChild(message);
	container.appendChild(inputBox);
	container.appendChild(messageAfter);
	return container;
}

function userTriggerOptions_old() {


	// Paste Tab Container
	let panelPasteNumbers = document.createElement('div');
	panelPasteNumbers.setAttribute('id', 'trigger-code-container');
	panelPasteNumbers.class = 'enterOwnNumbers';
	panelPasteNumbers.innerHTML = '';

	// Message to users
	let textMessage = document.createElement('h2');
	textMessage.innerText = "Trigger Insert Code";
	textMessage.setAttribute('id', 'paste-pasteNumbersMessage');

	const buttonGroupContainer = document.createElement('div');
	buttonGroupContainer.setAttribute('id', 'trigger-options-user-button-container');


	// Apply Button
	const addNumbersButton = document.createElement('button');
	addNumbersButton.innerText = "Insert Triggers";
	addNumbersButton.classList.add('triggerOptionsButtons');
	//addNumbersButton.setAttribute('id', 'paste-applyButton');
	addNumbersButton.addEventListener('click', function(){
				

		selectTabAndUpdateContent(1, codeBoxSelectionAddTrigger);
		after_add_trigger_update();
		
	});

	// Clear Button
	const clearButton = document.createElement('button');
	clearButton.innerText = "Clear";
	clearButton.classList.add('triggerOptionsButtons');
	//clearButton.setAttribute('id', 'paste-clearButton');
	clearButton.addEventListener('click', function () {
		var textarea = document.getElementById('trigger-code');
		textarea.value = '';
	});

	// Create button
	var copyButton = document.createElement('button');
	copyButton.innerText = 'Clipboard';
	copyButton.classList.add('triggerOptionsButtons');

	// Event listener for the button
	copyButton.addEventListener('click', function () {
		// Select the text
		let data = document.getElementById('trigger-code').value;
		// Copy the text inside the text field
		navigator.clipboard.writeText(data)
			.then(() => {
				// Success message
				showMessageAtCursor("Copied to clipboard.");
			})
			.catch(err => {
				// If the user denies clipboard permissions or another error occurs
				console.error('Failed to copy: ', err);
			});
	});
	
	
	// Create the "Play How to Video" button
const playHowToVideoButton = document.createElement('button');
playHowToVideoButton.textContent = 'Play How to Video';
playHowToVideoButton.classList.add('play-video-button'); // Optional, for styling

// Create the modal container
const videoModal = document.createElement('div');
videoModal.id = 'videoModal';
videoModal.style.display = 'none'; // Hidden by default
videoModal.style.position = 'fixed';
videoModal.style.zIndex = '1';
videoModal.style.left = '0';
videoModal.style.top = '0';
videoModal.style.width = '100%';
videoModal.style.height = '100%';
videoModal.style.backgroundColor = 'rgba(0, 0, 0, 0.8)'; // Semi-transparent background
videoModal.style.justifyContent = 'center';
videoModal.style.alignItems = 'center';

// Create the video element
const video = document.createElement('video');
video.id = 'howToVideo';
video.setAttribute('controls', 'true');
video.innerHTML = '<source src="items/test.mp4" type="video/mp4">Your browser does not support the video tag.';

// Append the video to the modal
videoModal.appendChild(video);

// Create the close button
const closeButton = document.createElement('span');
closeButton.textContent = '×';
closeButton.style.position = 'absolute';
closeButton.style.top = '20px';
closeButton.style.right = '30px';
closeButton.style.color = 'white';
closeButton.style.fontSize = '40px';
closeButton.style.fontWeight = 'bold';
closeButton.style.cursor = 'pointer';

// Append the close button to the modal
videoModal.appendChild(closeButton);

// Add the video modal to the body (or a specific container)
document.body.appendChild(videoModal);

// Event listener for the "Play How to Video" button
playHowToVideoButton.addEventListener('click', function () {
	videoModal.style.display = 'flex'; // Show the modal
	video.play(); // Play video
});

// Event listener for the close button
closeButton.addEventListener('click', function () {
	videoModal.style.display = 'none'; // Hide the modal
	video.pause(); // Pause video when modal is closed
});

// Append the "Play How to Video" button to the container (assuming buttonGroupContainer exists)
buttonGroupContainer.appendChild(playHowToVideoButton);
	

	buttonGroupContainer.appendChild(addNumbersButton);
	buttonGroupContainer.appendChild(clearButton);
	buttonGroupContainer.appendChild(copyButton);

	// Enter Text Area
	const textarea = document.createElement('textarea');
	textarea.setAttribute('id', 'trigger-code');
	textarea.placeholder = 'Pick a pre-made from the dropdown below then press INSERT TRIGGERS buttom above. You can send your own trigger combo in to the email below, or comment it below and we will add it to the list below';

	// Add items to Paste Tab Container
	panelPasteNumbers.appendChild(textMessage);
	panelPasteNumbers.appendChild(buttonGroupContainer);
	panelPasteNumbers.appendChild(textarea);

	return panelPasteNumbers;
}

function userTriggerOptions() {

  // Paste Tab Container
  let panelPasteNumbers = document.createElement('div');
  panelPasteNumbers.setAttribute('id', 'trigger-code-container');
  panelPasteNumbers.class = 'enterOwnNumbers';
  panelPasteNumbers.innerHTML = '';

  // Message to users
  let textMessage = document.createElement('h2');
  textMessage.innerText = "Trigger Insert Code";
  textMessage.setAttribute('id', 'paste-pasteNumbersMessage');

  const buttonGroupContainer = document.createElement('div');
  buttonGroupContainer.setAttribute('id', 'trigger-options-user-button-container');

  // Insert Triggers
  const addNumbersButton = document.createElement('button');
  addNumbersButton.innerText = "Insert Triggers";
  addNumbersButton.classList.add('triggerOptionsButtons');
  addNumbersButton.addEventListener('click', function () {
    selectTabAndUpdateContent(1, codeBoxSelectionAddTrigger);
    after_add_trigger_update();
  });

  // --- NEW: Import button (after Insert Triggers) ---
  const importButton = document.createElement('button');
  importButton.innerText = "Import";
  importButton.classList.add('triggerOptionsButtons');

  // Hidden file input for Import
  const fileInput = document.createElement('input');
  fileInput.type = 'file';
  fileInput.accept = 'application/json,.json';
  fileInput.style.display = 'none';

  importButton.addEventListener('click', () => {
    fileInput.click();
  });

  fileInput.addEventListener('change', async (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;

    try {
      const text = await file.text();
      let valueToSet = text;

      // Try to parse as JSON; support either a raw string or { trigger_code: "..."}
      try {
        const parsed = JSON.parse(text);
        if (typeof parsed === 'string') {
          valueToSet = parsed;
        } else if (parsed && typeof parsed === 'object') {
          if ('trigger_code' in parsed && typeof parsed.trigger_code === 'string') {
            valueToSet = parsed.trigger_code;
          } else {
            // If it's some other object, keep original text but still allow
            // user to see it. You could stringify nicely if desired.
            valueToSet = text;
          }
        }
      } catch (_) {
        // Not JSON? Just load raw text.
        valueToSet = text;
      }

      const textarea = document.getElementById('trigger-code');
      if (textarea) {
        textarea.value = valueToSet;
        showMessageAtCursor("Imported trigger code.");
      }
    } catch (err) {
      console.error('Import failed:', err);
      showMessageAtCursor("Import failed. See console.");
    } finally {
      // Reset input so the same file can be chosen again later if needed
      fileInput.value = '';
    }
  });

  // --- NEW: Export button ---
  const exportButton = document.createElement('button');
  exportButton.innerText = "Export";
  exportButton.classList.add('triggerOptionsButtons');

  exportButton.addEventListener('click', () => {
    const textarea = document.getElementById('trigger-code');
    const raw = (textarea && textarea.value) ? textarea.value : "";

    // If raw is valid JSON, save as-is; else wrap it.
    let payload = raw;
    let isJson = false;
    try {
      JSON.parse(raw);
      isJson = true;
    } catch (_) { /* not JSON */ }

    if (!isJson) {
      payload = JSON.stringify({ trigger_code: raw }, null, 2);
    }

    //const blob = new Blob([payload], { type: 'application/json' });
    const blob = new Blob([raw], { type: 'application/json' });
	const url = URL.createObjectURL(blob);
    const a = document.createElement('a');

    const date = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
    a.href = url;
    a.download = `triggers-${date}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    showMessageAtCursor("Exported trigger code.");
  });

  // Clear Button
  const clearButton = document.createElement('button');
  clearButton.innerText = "Clear";
  clearButton.classList.add('triggerOptionsButtons');
  clearButton.addEventListener('click', function () {
    var textarea = document.getElementById('trigger-code');
    textarea.value = '';
  });

  // Clipboard Button (existing)
  var copyButton = document.createElement('button');
  copyButton.innerText = 'Clipboard';
  copyButton.classList.add('triggerOptionsButtons');
  copyButton.addEventListener('click', function () {
    let data = document.getElementById('trigger-code').value;
    navigator.clipboard.writeText(data)
      .then(() => {
        showMessageAtCursor("Copied to clipboard.");
      })
      .catch(err => {
        console.error('Failed to copy: ', err);
      });
  });

  // Play How-to Video (existing)
  const playHowToVideoButton = document.createElement('button');
  playHowToVideoButton.textContent = 'Play How to Video';
  playHowToVideoButton.classList.add('play-video-button');

  const videoModal = document.createElement('div');
  videoModal.id = 'videoModal';
  videoModal.style.display = 'none';
  videoModal.style.position = 'fixed';
  videoModal.style.zIndex = '1';
  videoModal.style.left = '0';
  videoModal.style.top = '0';
  videoModal.style.width = '100%';
  videoModal.style.height = '100%';
  videoModal.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
  videoModal.style.justifyContent = 'center';
  videoModal.style.alignItems = 'center';

  const video = document.createElement('video');
  video.id = 'howToVideo';
  video.setAttribute('controls', 'true');
  video.innerHTML = '<source src="items/test.mp4" type="video/mp4">Your browser does not support the video tag.';

  videoModal.appendChild(video);

  const closeButton = document.createElement('span');
  closeButton.textContent = '×';
  closeButton.style.position = 'absolute';
  closeButton.style.top = '20px';
  closeButton.style.right = '30px';
  closeButton.style.color = 'white';
  closeButton.style.fontSize = '40px';
  closeButton.style.fontWeight = 'bold';
  closeButton.style.cursor = 'pointer';

  videoModal.appendChild(closeButton);
  document.body.appendChild(videoModal);

  playHowToVideoButton.addEventListener('click', function () {
    videoModal.style.display = 'flex';
    video.play();
  });

  closeButton.addEventListener('click', function () {
    videoModal.style.display = 'none';
    video.pause();
  });

  // Append buttons in desired order
  buttonGroupContainer.appendChild(playHowToVideoButton);
  buttonGroupContainer.appendChild(addNumbersButton);

  buttonGroupContainer.appendChild(clearButton);
  buttonGroupContainer.appendChild(copyButton);
  buttonGroupContainer.appendChild(fileInput);      // hidden input for Import

  // Enter Text Area
  const textarea = document.createElement('textarea');
  textarea.setAttribute('id', 'trigger-code');
  textarea.placeholder = 'Pick a pre-made from the dropdown below then press INSERT TRIGGERS buttom above. You can send your own trigger combo in to the email below, or comment it below and we will add it to the list below';

  // Add items to Paste Tab Container
  panelPasteNumbers.appendChild(textMessage);
  panelPasteNumbers.appendChild(buttonGroupContainer);
  panelPasteNumbers.appendChild(textarea);
    panelPasteNumbers.appendChild(importButton);   // <— after Insert Triggers
  panelPasteNumbers.appendChild(exportButton);   // <— after Import

  return panelPasteNumbers;
}
