// Functions called when user clicks add trigger 

// -------------------------------------------------------------------------------
//  Outside Bets
// -------------------------------------------------------------------------------
function outsideBetSelectionAddTrigger() {


	let container = createAndClearBlankDiv('alert-table-container');

	var triggerLoss = parseInt(document.getElementById('triggerEvensLosses').value);
	if (isNaN(triggerLoss) || triggerLoss < 1) {
		triggerLoss = 1;
		document.getElementById('triggerEvensLosses').value = 1;
	}

	var winLossIndicator = document.getElementById('triggerEvensLossesDropDown').value;

	var selectElement = document.getElementById('triggerOptionDropdown');
	var triggerOption = selectElement.value;
	var triggerText = selectElement.options[selectElement.selectedIndex].text;


	const indexFound = triggerListLoss.findIndex((value, index) => value === triggerLoss 
		&& triggerListItem[index] === triggerOption
		&& triggerListWinLoss[index] === winLossIndicator);

	const itemFound = indexFound !== -1;

	
	if (triggerOption === "AllOut") {

		var seletedItems = ["Even","Odd","Red","Black","High","Low","Dozen1","Dozen2","Dozen3","Row1","Row2","Row3"];
		triggerDropDown.forEach(group => {

			var indexFound = triggerListLoss.findIndex((value, index) => value === triggerLoss && triggerListItem[index] === group.value
			&& triggerListWinLoss[index] === winLossIndicator);

			var itemFound = indexFound !== -1;

			if (!itemFound && seletedItems.includes(group.value)) {
				addTriggerToTriggersList(triggerLoss, group.text, group.value, winLossIndicator,group.text);
			}

		});
	}

	if (triggerOption === "All") {

		var seletedItems = ["Even","Odd","Red","Black","High","Low","Dozen1","Dozen2","Dozen3","Row1","Row2","Row3","Quads","Splits","Streets","DoubleStreet"];
		triggerDropDown.forEach(group => {

			var indexFound = triggerListLoss.findIndex((value, index) => value === triggerLoss && triggerListItem[index] === group.value
			&& triggerListWinLoss[index] === winLossIndicator);

			var itemFound = indexFound !== -1;

			if (!itemFound && group.value !== "All" && group.value !=="StraightNumbers" && group.value !=="AllOut") {
				addTriggerToTriggersList(triggerLoss, group.text, group.value, winLossIndicator,group.value);
			}

		});
	}
	
	if (triggerOption !== "All" && triggerOption !== "AllOut") {

		if (!itemFound) {
			addTriggerToTriggersList(triggerLoss, triggerText, triggerOption, winLossIndicator,triggerOption);

		} else {
			showMessageAtCursor("Item already added.");

		}
		
	}

	let triggerList = getTriggerList();
	container.append(triggerList);
	return container;
	
}

// -------------------------------------------------------------------------------
//  Unique Bets
// -------------------------------------------------------------------------------

function uniqueBetSelectionAddTrigger() {

	let container = createAndClearBlankDiv('alert-table-container');
	
	var losses = parseInt(document.getElementById('triggerUniques').value);
	if (isNaN(losses) || losses < 1) {
		losses = 7;
		document.getElementById('triggerUniques').value = 7;
	}

	var triggerOption = "Uniques";

	const indexFound = triggerListLoss.findIndex((value, index) => value === losses && triggerListItem[index] === triggerOption);

	const itemFound = indexFound !== -1;

	if (!itemFound) {
		addTriggerToTriggersList(losses, 'Uniques', 'Uniques','-',"Unique","Unique");

	}else{
		showMessageAtCursor("Item already added.");
	}


	let triggerList = getTriggerList();
	container.append(triggerList);

	return container;
	
}

// -------------------------------------------------------------------------------
//  Group Bets
// -------------------------------------------------------------------------------
function groupBetSelectionAddTrigger() {

	let container = createAndClearBlankDiv('alert-table-container');

	var losses = parseInt(document.getElementById('triggerGroupsLosses').value);

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

	var value = textarea.value;

	value = processValue(value);


	if(value.length==0 || !value)
	{
		showMessageAtCursor("Text Box needs a value.");
		return;
	}
	var winLossIndicator = document.getElementById('triggerGroupsLossesDropDown').value;

	value.forEach(group => {

		var joinedGroup = group.join(", ");

		const indexFound = triggerListLoss.findIndex((value, index) => value === losses && triggerListText[index] === joinedGroup
		&& triggerListWinLoss[index] === winLossIndicator);

		const itemFound = indexFound !== -1;


		if (!itemFound) {

			addTriggerToTriggersList(losses, joinedGroup, 'Groups', winLossIndicator,"Group");
	
		}else {
			showMessageAtCursor("Item already added.");

		}

	});

	let triggerList = getTriggerList();
	container.append(triggerList);

	return container;
}

// -------------------------------------------------------------------------------
//  Pattern Bets
// -------------------------------------------------------------------------------

function patternBetSelectionAddTrigger() {
	
	let container = createAndClearBlankDiv('alert-table-container');

	var losses = 'Pattern';

	var patternLength = parseInt(document.getElementById('patternLength').value);
	if (isNaN(patternLength) || patternLength < 1) {
		patternLength = 2;
		document.getElementById('patternLength').value = 2;
	}

	var patternMultiplier = parseInt(document.getElementById('patternMultiplier').value);
	if (isNaN(patternMultiplier) || patternMultiplier < 1) {
		patternMultiplier = 2;
		document.getElementById('patternMultiplier').value = 2;
	}

	var item = patternLength+" x "+patternMultiplier;

	const indexFound = triggerListLoss.findIndex((value, index) => value === losses && triggerListText[index] === item);


	const itemFound = indexFound !== -1;

	if (!itemFound) {
		addTriggerToTriggersList(losses, item, 'Pattern','-',"Pattern");
	}else{
		showMessageAtCursor("Item already added.");
	}

	let triggerList = getTriggerList();
	container.append(triggerList);

	return container;
}

// -------------------------------------------------------------------------------
//  Code Pre-Defined Bets
// -------------------------------------------------------------------------------

function codeBoxSelectionAddTrigger()
{
	let container = createAndClearBlankDiv('alert-table-container');
		var textareaValue = document.getElementById('trigger-code').value;

		
		var lines = textareaValue.split('\n');
	
		lines.forEach(function(line) {
		

			if (line.trim()) { 

				var items = line.split(':');
				var item_nameTag = items[0];
				items = items.slice(1);

	
				
				
			const indexFound = triggerListLoss.findIndex((value, index) => value === parseInt(items[1].trim()) && triggerListText[index] === items[2].trim()
			&& triggerListWinLoss[index] === items[0].trim());



			const itemFound = indexFound !== -1;
			if(!itemFound)
			{
			
		
				if(items[2].trim()=="Pattern")
				{

					
					const indexFound = triggerListLoss.findIndex((value, index) => value === 'Pattern' && triggerListText[index] === items[3].trim());
					
	

					const itemFound = indexFound !== -1;


					if (!itemFound) {

					
						addTriggerToTriggersList('Pattern', items[3].trim(), 'Pattern','-',item_nameTag);
					}else
					{
						triggerListName[indexFound] = item_nameTag;
					}
				}
				else
				{
					
					
					const indexFound = triggerListLoss.findIndex((value, index) => 
						value ===  parseInt(items[1].trim()) 
					    && triggerListWinLoss[index] === items[0].trim()
						&& triggerListItem[index] ==  items[2].trim()
						&& triggerListText[index] ==  items[3].trim()
						);

						

					const itemFound = indexFound !== -1;
				
					if (!itemFound) {
						
						addTriggerToTriggersList(parseInt(items[1].trim()),items[3].trim(),items[2].trim(),items[0].trim(),item_nameTag);
					}else {

							triggerListName[indexFound] = item_nameTag;
					
						showMessageAtCursor("Item already added. Tag Name updaed.");
			
					}

				}
				
			}	
			else
			{
				triggerListName[indexFound] = item_nameTag;
			}
				
			}
		});
		
		let triggerList = getTriggerList();
		container.append(triggerList);

		return container;
}

// -------------------------------------------------------------------------------
//  Helper Code
// -------------------------------------------------------------------------------

function addTriggerToTriggersList(triggerLoss, triggerText, triggerOption, triggerWinLoss,triggerNameTag){

	triggerListLoss.push(triggerLoss);
	triggerListItem.push(triggerOption);
	triggerListText.push(triggerText);
	triggerListWinLoss.push(triggerWinLoss);

	triggerListName.push(triggerNameTag);


}


function triggerPanelRemoveRow(row) {

	var winLoss = row.cells[1].textContent;
	var triggerLoss = row.cells[2].textContent;
	const triggerOption = row.cells[3].textContent;
	
	if(triggerLoss!=="Pattern")
	{
		triggerLoss = parseInt(triggerLoss);
	}

	const index = triggerListLoss.findIndex((value, idx) => value === triggerLoss && triggerListText[idx] === triggerOption &&
	triggerListWinLoss[idx] === winLoss);


	if (index !== -1) {

		triggerListWinLoss.splice(index, 1);
		triggerListLoss.splice(index, 1);
		triggerListItem.splice(index, 1);
		triggerListText.splice(index, 1);
		triggerListName.splice(index, 1);
	}

	row.parentNode.removeChild(row);

}


function getTriggerList() {


	let container = createAndClearBlankDiv('trigger-results-triggers-container');

	let table = document.getElementById('triggerItems');

	if (!table) {
	
// Create the header title
const headerTitle = document.createElement('h2');
headerTitle.textContent = 'Triggers List';
headerTitle.classList.add('rwd-table-title');

// Create a container div for the title and radio buttons
const titleContainer = document.createElement('div');
titleContainer.style.display = 'flex';
titleContainer.style.alignItems = 'center';
titleContainer.style.gap = '10px';

// Append the title to the container
titleContainer.appendChild(headerTitle);

// Create the radio buttons
const radioOptions = [
    { id: 'reset', value: 'default', label: 'Default' },
    { id: 'all-loss', value: 'allLoss', label: 'All Loss' },
    { id: 'all-win', value: 'allWin', label: 'All Win' }
];

radioOptions.forEach(option => {
    const label = document.createElement('label');
    label.textContent = option.label;
    label.style.marginLeft = '5px';
    
    const radio = document.createElement('input');
    radio.type = 'radio';
    radio.name = 'triggerOptions';
    radio.id = option.id;
    radio.value = option.value;

    // Set the radio button as selected based on the global variable
    if (selectedTriggerRadioButton === option.value) {
        radio.checked = true;
    }

    // Add an on-select event listener
    radio.addEventListener('change', (event) => {
        selectedTriggerRadioButton = event.target.value; // Update the global variable
        handleRadioSelection(event.target.value);
    });

    label.prepend(radio);
    titleContainer.appendChild(label);
});

// Append the titleContainer to the main container
container.appendChild(titleContainer);

// Create the trigger display
let trigger_display_simple = triggerPanelCreateTriggerTable();
container.appendChild(trigger_display_simple);

// Function to handle radio selection
function handleRadioSelection(selectedValue) {
    if (selectedValue === 'default') {
        console.log('Reset option selected');
        triggerListWinLoss = [...triggerListWinLoss_copy];
        after_radio_button_all_win_loss_update();
    } else if (selectedValue === 'allLoss') {
        console.log('All Loss option selected');
        triggerListWinLoss = triggerListWinLoss.map(item => item === 'W' ? 'L' : item);
        after_radio_button_all_win_loss_update();
    } else if (selectedValue === 'allWin') {
        console.log('All Win option selected');
        triggerListWinLoss = triggerListWinLoss.map(item => item === 'L' ? 'W' : item);
        after_radio_button_all_win_loss_update();
    }
}


		
	
		table = trigger_display_simple;
	}
	

	for (let i = 0; i < triggerListLoss.length; i++) {

		const newRow = table.insertRow(-1); 
		const cellName = newRow.insertCell(0); 
		const cell0 = newRow.insertCell(1); 
		const cell1 = newRow.insertCell(2); 
		const cell2 = newRow.insertCell(3); 
		const cell3 = newRow.insertCell(4); 

		cellName.textContent = triggerListName[i];
		cell0.textContent = triggerListWinLoss[i];
		cell1.textContent = triggerListLoss[i];
		cell2.textContent = triggerListText[i];

		const removeBtn = document.createElement('button');
		removeBtn.textContent = 'Remove';
		removeBtn.addEventListener('click', () => {
			triggerPanelRemoveRow(newRow);
			setTriggerCode(); 
			selectTabAndUpdateContent(1, getTriggerList);
			
		});
		cell3.appendChild(removeBtn);
	}


	if(triggerListLoss.length>0)
	{
		setTriggerCode();	
	}


	if(triggerListLoss.length == 0)
	{
		container.innerHTML = '';
	}
	return container;
}

function getPatternList(triggerLoss, triggerText, triggerOption, triggerWinLoss, name="system") {

	let container = createAndClearBlankDiv('trigger-results-triggers-container');

	triggerListName.push(name);
	triggerListLoss.push(triggerLoss);
	triggerListItem.push(triggerOption);
	triggerListText.push(triggerText);
	triggerListWinLoss.push(triggerWinLoss);

	let table = document.getElementById('triggerItems');

	if (!table) {

		const headerTitle = document.createElement('h2');
		headerTitle.textContent = 'Triggers List';
		headerTitle.classList.add('rwd-table-title');
		let trigger_display_simple = triggerPanelCreateTriggerTable();
		container.appendChild(headerTitle);
		container.appendChild(trigger_display_simple);

		table = trigger_display_simple;
	}

	const newRow = table.insertRow();
	const cellNamme = newRow.insertCell();
	const cell1 = newRow.insertCell();
	const cell2 = newRow.insertCell();
	const cell3 = newRow.insertCell();

	cellNamme.textContent = name;
	cell1.textContent = triggerLoss;
	cell2.textContent = triggerText;

	const removeBtn = document.createElement('button');
	removeBtn.textContent = 'Remove';
	removeBtn.addEventListener('click', () =>
	{
		patternPanelRemoveRow(newRow);
		setTriggerCode();
		selectTabAndUpdateContent(1, getPatternList);
	} );
	cell3.appendChild(removeBtn);

	if(triggerListLoss.length>0)
	{
		setTriggerCode();
	}
	
	return container;

}


function triggerPanelCreateTriggerTable() {

	
	const table = document.createElement('table');
	table.setAttribute('id', 'triggerItems');
	table.classList.add('rwd-table');

	
	const headerRow = table.insertRow();
	const headers = ['Tag','W/L','Count', 'Item', 'Action'];
	headers.forEach(headerText => {
		let headerCell = document.createElement('th');
		headerCell.textContent = headerText;
		headerRow.appendChild(headerCell);
	});


	return table;


}


function getTriggers() {

	let array1 = [];
	let array2 = [];


	const table = document.getElementById('triggerItems');


	if (table) {

		for (let i = 0; i < table.rows.length; i++) {

			let row = table.rows[i];

			if (row.cells.length >= 2) {
				array1.push(row.cells[0].textContent || row.cells[0].innerText);
				array2.push(row.cells[1].textContent || row.cells[1].innerText);
			}
		}
	}

}
