// This is the yellow alerts table
function normalizeTag(tag) {
  // Handle singular vs plural special cases
  if (tag === "Split") return "Splits";
  if (tag === "Street") return "Streets";
  if (tag === "Quad") return "Quads";
  if (tag === "Unique") return "Uniques";
  if (tag === "Groups") return "Group";
  if (tag === "Row 1 (1,4,7...)") return "Row1";
  if (tag === "Row 2 (2,5,8...)") return "Row2";
  if (tag === "Row 3 (3,6,9...)") return "Row3";
  if (tag === "Dozen 1 (1-12)") return "Dozen1";
  if (tag === "Dozen 2 (13-24)") return "Dozen2";
  if (tag === "Dozen 3 (25-36)") return "Dozen3";
  if(tag === "Corner") return "Quads";
  if(tag === "Lines") return "DoubleStreet";
  return tag;
}


function trigger_alert_display() {

   
	let container = createAndClearBlankDiv('trigger-alert-title-container');
	let innerContainer = createAndClearBlankDiv('trigger-watch-title-inner-container');

	let indexedMap = alertCounter.map((value, index) => ({ value, index }));
	indexedMap.sort((a, b) => b.value - a.value);
	let sortedIndexes = indexedMap.map(item => item.index);
    

	sortedIndexes.forEach((value, index) => {


		let table = innerContainer.querySelector(`#watch-${CSS.escape(alertId[index])}`);
			
			if (!table) {
				table = createAlertTable(alertId[index],alertId[index]);
               if(!(alertId[index]==="Splits 17:1"))
				{
					if(isButtonOn())
						{	
							makeElementDraggable(table);
						}
				}
				innerContainer.appendChild(table);
			}
			

		const newRow = table.insertRow();

			// Cells

			const nameTag = newRow.insertCell();
			const cellButton = newRow.insertCell();
			cellButton.style.verticalAlign = "bottom";
			//const cell0 = newRow.insertCell();
			//cell0.style.verticalAlign = "bottom";
			const cell1 = newRow.insertCell();
			cell1.style.verticalAlign = "bottom";
			const cell2 = newRow.insertCell();
			cell2.style.whiteSpace = "pre-line"; 
			const cell3 = newRow.insertCell();
			cell3.style.verticalAlign = "bottom";

			
			const button = document.createElement('button');
			button.textContent = alertWinLoss[index];
			button.onclick = () => { 
				setChips(alertItemDetail[index],alert_nameTag[index]);
			 };
			cellButton.appendChild(button);

			nameTag.textContent = alert_nameTag[index];
			//cell0.textContent = alertWinLoss[index];
			cell1.textContent = alertCounter[index];
			cell2.textContent = alertItem[index];
			cell3.textContent = alertItemDetail[index];
        });
    container.appendChild(innerContainer);
	return container;
}

function createAlertTable(id, tableTitle="FIX") {

    // Create table
    const table = document.createElement('table');
    table.setAttribute('id', `watch-` + id);
    table.classList.add('trigger-watch-table');
    table.classList.add('trigger-alert-table');

    // Table Title Row
    const headerTitle = table.insertRow();
    const headerCell = document.createElement('th');
    headerCell.colSpan = 3; 
    headerCell.style.textAlign = 'center';
    headerCell.style.color = 'brown';
    headerCell.style.position = 'relative';

    // Title text
    const titleSpan = document.createElement('span');
    titleSpan.textContent = `Alert  -   ` + tableTitle;
    headerCell.appendChild(titleSpan);

    // Place Bets button (top-right)
    const placeBtn = document.createElement('button');
  placeBtn.textContent = "Place Bets";
    placeBtn.style.position = "absolute";
    placeBtn.style.top = "-1px";
    placeBtn.style.left = "180px";
    placeBtn.style.padding = "4px 8px";
    placeBtn.style.fontSize = "13px";
	placeBtn.style.whiteSpace = "nowrap";
    placeBtn.addEventListener("click", () => {
        placeAlertBets(id);  // pass id if needed
    });
    headerCell.appendChild(placeBtn);

    headerTitle.appendChild(headerCell);

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

    return table;
}



function table_alert_locations(){
	unHighLightAllNumbers();

	alertItem.forEach((alert, index) => {
		if (alertHighLightStack[index] === highlight_number_groups
			|| alertHighLightStack[index] === highlight_straight_numbers
			|| alertHighLightStack[index] === highlight_uniques)
		 {

			alertItemDetail[index].forEach(spinitem => {
				alertHighLightStack[index](parseInt(spinitem));
			});



		} else {

			alertHighLightStack[index]();
		}

		
		// Splits Down
		if (alertHighLightStack[index] === highlight_split_across
			|| alertHighLightStack[index] === highlight_split_down
			|| alertHighLightStack[index] === highlight_quad
			|| alertHighLightStack[index] === highlight_street
			|| alertHighLightStack[index] === highlight_double_street) {
   
			   var stringId = alertItemDetail[index].join(`, `);
			   alertHighLightStack[index](stringId);
		   }
	});
}

function addAllItemsToAlertWindow()
{
	let triggerItemList = document.getElementById(`trigger-items-list`);
	triggerItemList.innerHTML = '';

	addAddtionalTriggersToAlertWindow();
	addItemsToAlertWindow();


}
function addItemsToAlertWindow()
{
	let triggerItemList = document.getElementById(`trigger-items-list`);
	alertItemDetail.forEach((item, index) => {
		const betItem = document.createElement('div');
		betItem.className = 'bet-item-bet-list';
		if(isOnlyNumbersAndCommas(item))
		{
			betItem.textContent = alert_nameTag[index]+' '+alertWinLoss[index]+` `+alertItem[index] + ` ` +item;
		}
		else{
			betItem.textContent = item;

		}
		
		triggerItemList.appendChild(betItem);
	});
	
}
function addAddtionalTriggersToAlertWindow()
{
	let triggerItemList = document.getElementById(`trigger-items-list`);
	if(bouncyDisplay) {
		const betItem = document.createElement('div');
		betItem.className = 'bet-item-bet-list';
		if(arraysEqual(d1d2, nBounce)) betItem.textContent = "Dozens 1 3";
		if(arraysEqual(d1d3, nBounce)) betItem.textContent = "Dozens 1 2";
		if(arraysEqual(d2d1, nBounce)) betItem.textContent = "Dozens 2 3";
		if(arraysEqual(d2d3, nBounce)) betItem.textContent = "Dozens 1 2";
		if(arraysEqual(d3d1, nBounce)) betItem.textContent = "Dozens 2 3";
		if(arraysEqual(d3d2, nBounce)) betItem.textContent = "Dozen 1 3";
		if(!(betItem.textContent===''))
		{
			triggerItemList.appendChild(betItem);
		}
		
	}
	
	if(bouncyDisplay_bounceRow) {
		const betItem_bounceRow = document.createElement('div');
		betItem_bounceRow.className = 'bet-item-bet-list';
		if(arraysEqual(d1d2_bounceRow, nBounce_bounceRow)) betItem_bounceRow.textContent = "Rows 1 3";
		if(arraysEqual(d1d3_bounceRow, nBounce_bounceRow)) betItem_bounceRow.textContent = "Rows 1 2";
		if(arraysEqual(d2d1_bounceRow, nBounce_bounceRow)) betItem_bounceRow.textContent = "Rows 2 3";
		if(arraysEqual(d2d3_bounceRow, nBounce_bounceRow)) betItem_bounceRow.textContent = "Rows 1 2";
		if(arraysEqual(d3d1_bounceRow, nBounce_bounceRow)) betItem_bounceRow.textContent = "Rows 2 3";
		if(arraysEqual(d3d2_bounceRow, nBounce_bounceRow)) betItem_bounceRow.textContent = "Rows 1 3";
		if(!(betItem_bounceRow.textContent===''))
		{
			triggerItemList.appendChild(betItem_bounceRow);
		}
		
	}
	
	if(comboDisplay) {
		const betItem = document.createElement('div');
		betItem.className = 'bet-item-bet-list';
		if(arraysEqual(d1d2, nBounce)) betItem.textContent = "Dozens 1 3";
		if(arraysEqual(d1d3, nBounce)) betItem.textContent = "Dozens 1 2";
		if(arraysEqual(d2d1, nBounce)) betItem.textContent = "Dozens 2 3";
		if(arraysEqual(d2d3, nBounce)) betItem.textContent = "Dozens 1 2";
		if(arraysEqual(d3d1, nBounce)) betItem.textContent = "Dozens 2 3";
		if(arraysEqual(d3d2, nBounce)) betItem.textContent = "Dozen 1 3";
		if(!(betItem.textContent===''))
		{
			triggerItemList.appendChild(betItem);
		}
		
	}
}
function isOnlyNumbersAndCommas(item) {
    const regex = /^[0-9,]+$/;
    return regex.test(item);
}


function placeAlertBets(id) {
  // Guard: if no id was passed, do nothing
  if (!id) return;

  // Walk all alerts and only act on rows that belong to this table id
  alertId.forEach((aid, idx) => {
    if (aid !== id) return;

    const detail = alertItemDetail[idx];          // numbers or string
    const old_tag = alert_nameTag[idx];               // e.g., "Splits", "Rows", etc.

	const rawTag = alertItem[idx];
	




// choose the right data depending on id
let dataToUse;
if (/^\d+\s*x\s*\d+$/.test(id)) {
  // if id looks like "number x number"
  dataToUse = detail;
} else {
  dataToUse = rawTag;
}

const tag = normalizeTag(dataToUse);


	console.log("DETAIL ",detail);
	console.log("ID: ",id);
	console.log("Old Tag: ",old_tag);
	console.log("New Tag: ", tag);
	console.log(" ");
	// Normalize detail to an array of integers when possible
    let nums = null;
    if (Array.isArray(detail)) {
      nums = detail.map(n => parseInt(n, 10)).filter(n => Number.isInteger(n));
    } else if (typeof detail === "string" && isOnlyNumbersAndCommas(detail)) {
      nums = detail
        .split(",")
        .map(s => parseInt(s.trim(), 10))
        .filter(n => Number.isInteger(n));
    }

    // Call your existing placer:
    // - If we parsed numbers, pass the numeric array
    // - Otherwise pass through the original detail (covers things like "Low", "Row 1 (1,4,7...)" etc.)
    if (nums && nums.length) {
      setChips(nums, tag);
    } else {
      setChips(detail, tag);
    }
  });
}
