let isPopupOpen = false;
let popupContainer = null;



function twoDozenTableDraggable(element) {
    $(element).draggable({
        stop: function(event, ui) {
            // Save the new position when dragging stops
            var position = ui.position;
            localStorage.setItem(element.id, JSON.stringify(position));
        }
    });

    // Apply the last known position, if available
    var savedPosition = localStorage.getItem(element.id);
    if (savedPosition) {
        var position = JSON.parse(savedPosition);
        $(element).css({
            top: position.top + 'px',
            left: position.left + 'px',
            position: 'absolute'
        });
    }
}

function createButtonWithPopup1(id, title, headerData, w, h, buttonLabel) {
    var statButton = document.createElement('button');
    statButton.textContent = buttonLabel;
    statButton.style.padding = '8px 10px';
    statButton.style.fontSize = '14px';
    statButton.style.margin = '5px';
    statButton.style.width = '100px';

    var myTable = createStyledTable(id, title, headerData);
    var div = document.createElement('div');
    div.appendChild(myTable);

    // Create draggable and resizable div
    var draggableDiv = document.createElement('div');
    draggableDiv.id = 'draggable_div_' + id;
    draggableDiv.style.display = 'none';
    draggableDiv.style.width = w;
    draggableDiv.style.height = h;
    draggableDiv.style.background = '#ebf6f7';
    draggableDiv.style.position = 'absolute';
    draggableDiv.style.padding = '10px';
    draggableDiv.style.boxSizing = 'border-box';
    draggableDiv.style.border = '1px solid #ddd';
    draggableDiv.style.borderRadius = '5px';
    draggableDiv.style.cursor = 'move';
    draggableDiv.style.zIndex = '1000';

    draggableDiv.appendChild(div);
    document.body.appendChild(draggableDiv);

    var closeButton = document.createElement('div');
    closeButton.textContent = 'X';
    closeButton.style.cursor = 'pointer';
    closeButton.style.position = 'absolute';
    closeButton.style.top = '5px';
    closeButton.style.right = '5px';
    closeButton.style.fontWeight = 'bold';
    draggableDiv.appendChild(closeButton);

    statButton.addEventListener('click', function(event) {
        // Populate the table with loss data when the button is clicked
        populateLossesTable1(id);

        draggableDiv.style.display = 'block';
        var mouseX = event.clientX;
        var mouseY = event.clientY;
        draggableDiv.style.left = mouseX + 'px';
        draggableDiv.style.top = mouseY + 'px';
    });

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

    var isResizing = false;
    var isDragging = false;

    var resizer = document.createElement('div');
    resizer.style.width = '10px';
    resizer.style.height = '10px';
    resizer.style.background = 'red';
    resizer.style.position = 'absolute';
    resizer.style.right = '0';
    resizer.style.bottom = '0';
    resizer.style.cursor = 'se-resize';
    draggableDiv.appendChild(resizer);

    resizer.addEventListener('mousedown', function(e) {
        e.stopPropagation(); // Prevent triggering drag functionality
        isResizing = true;
        var startX = e.clientX;
        var startY = e.clientY;
        var startWidth = parseInt(window.getComputedStyle(draggableDiv).width, 10);
        var startHeight = parseInt(window.getComputedStyle(draggableDiv).height, 10);

        function mouseMoveHandler(e) {
            if (isResizing) {
                draggableDiv.style.width = startWidth + e.clientX - startX + 'px';
                draggableDiv.style.height = startHeight + e.clientY - startY + 'px';
            }
        }

        function mouseUpHandler() {
            isResizing = false;
            window.removeEventListener('mousemove', mouseMoveHandler);
            window.removeEventListener('mouseup', mouseUpHandler);
        }

        window.addEventListener('mousemove', mouseMoveHandler);
        window.addEventListener('mouseup', mouseUpHandler);
        e.preventDefault(); // Prevent selection start
    });

    // Draggable functionality
    draggableDiv.addEventListener('mousedown', function(e) {
        if (e.target === resizer) return;

        isDragging = true;
        var rect = draggableDiv.getBoundingClientRect();
        var offsetX = e.clientX - rect.left;
        var offsetY = e.clientY - rect.top;

        function mouseMoveHandler(e) {
            if (isDragging) {
                var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
                var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;

                draggableDiv.style.top = (e.clientY - offsetY + scrollTop) + 'px';
                draggableDiv.style.left = (e.clientX - offsetX + scrollLeft) + 'px';
            }
        }

        function mouseUpHandler() {
            isDragging = false;
            window.removeEventListener('mousemove', mouseMoveHandler);
            window.removeEventListener('mouseup', mouseUpHandler);
        }

        window.addEventListener('mousemove', mouseMoveHandler);
        window.addEventListener('mouseup', mouseUpHandler);
    });

    return statButton;
}

function updateTwoDozenTable() {
    // Ensure the table exists before attempting to update it
    const table = document.getElementById('id_stats_table_dozens5');
    if (table) {
        // Clear the existing rows
        while (table.rows.length > 1) {
            table.deleteRow(1);
        }

        // Populate the table with fresh data
        populateLossesTable1('id_stats_table_dozens5');

        // Adjust the popup container size to prevent it from expanding indefinitely
        adjustPopupContainerSize();
    }
}

function adjustPopupContainerSize() {
    if (popupContainer) {
        // Set fixed size or limit maximum size
        popupContainer.style.maxWidth = '510px';
        popupContainer.style.maxHeight = '600px';
        popupContainer.style.overflow = 'auto'; // Add scrollbars if needed

        // Ensure the container resizes to fit the table without expanding indefinitely
        popupContainer.style.width = 'auto';
        popupContainer.style.height = 'auto';
        popupContainer.style.width = popupContainer.scrollWidth + 'px';
        popupContainer.style.height = popupContainer.scrollHeight + 'px';
    }
}


function createStyledTable1(id, title, headerData) {
    // Create table
    var table = document.createElement('table');
    table.className = "table-alert";
    table.style.width = 'auto'; 
    table.style.maxWidth = 'auto'; 
    table.style.borderCollapse = 'collapse';
    table.style.marginLeft = '10px';
    table.style.marginRight = '10px';
    table.style.marginBottom = '10px';

    table.id = id;

    // Sample headers
    var headers = headerData;
    var headerRow = document.createElement('tr');

    headers.forEach(function(headerText) {
        var header = document.createElement('th');
        header.textContent = headerText;
        header.style.padding = '8px';
        header.style.border = '1px solid #ddd';
        header.style.backgroundColor = '#ed9542';
        header.style.whiteSpace = 'nowrap'; // Prevent wrapping
        headerRow.appendChild(header);
    });

    table.appendChild(headerRow);

    return table;
}

function calculateDozenLosses1() {
    const rows = [
        [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34],  // First row
        [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35],  // Second row
        [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36]   // Third row
    ];

    const dozens = [
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],   // First dozen
        [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],  // Second dozen
        [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]   // Third dozen
    ];

    const missCounts = {};

    const combinations = [
        { name: 'Dozen 1 Row 1', dozen: dozens[0], row: rows[0] },
        { name: 'Dozen 1 Row 2', dozen: dozens[0], row: rows[1] },
        { name: 'Dozen 1 Row 3', dozen: dozens[0], row: rows[2] },
        { name: 'Dozen 2 Row 1', dozen: dozens[1], row: rows[0] },
        { name: 'Dozen 2 Row 2', dozen: dozens[1], row: rows[1] },
        { name: 'Dozen 2 Row 3', dozen: dozens[1], row: rows[2] },
        { name: 'Dozen 3 Row 1', dozen: dozens[2], row: rows[0] },
        { name: 'Dozen 3 Row 2', dozen: dozens[2], row: rows[1] },
        { name: 'Dozen 3 Row 3', dozen: dozens[2], row: rows[2] },
        { name: 'Dozen 1 Dozen 2', dozen1: dozens[0], dozen2: dozens[1] },
        { name: 'Dozen 1 Dozen 3', dozen1: dozens[0], dozen2: dozens[2] },
        { name: 'Dozen 2 Dozen 3', dozen1: dozens[1], dozen2: dozens[2] },
        { name: 'Row 1 Row 2', row1: rows[0], row2: rows[1] },
        { name: 'Row 1 Row 3', row1: rows[0], row2: rows[2] },
        { name: 'Row 2 Row 3', row1: rows[1], row2: rows[2] },
    ];

    combinations.forEach(combo => missCounts[combo.name] = 0);

    for (let i = 0; i < numbers.length; i++) {
        combinations.forEach(combo => {
            let missed = false;

            if (combo.row && combo.dozen) {
                missed = !combo.row.includes(numbers[i]) && !combo.dozen.includes(numbers[i]);
            } else if (combo.dozen1 && combo.dozen2) {
                missed = !combo.dozen1.includes(numbers[i]) && !combo.dozen2.includes(numbers[i]);
            } else if (combo.row1 && combo.row2) {
                missed = !combo.row1.includes(numbers[i]) && !combo.row2.includes(numbers[i]);
            }

            if (missed) {
                missCounts[combo.name]++;
            } else {
                missCounts[combo.name] = 0;
            }
        });
    }

    return Object.keys(missCounts).map(key => ({
        combination: key,
        losses: missCounts[key]
    })).sort((a, b) => b.losses - a.losses);
}


function twoDozenPopup() {
    var buttonLabel = 'Dozens/Rows';
    var statButton = document.createElement('button');
    statButton.textContent = buttonLabel;
    statButton.className = "large-button";

    statButton.addEventListener('click', function(event) {
        // Remove any existing popup to ensure a fresh start
        if (popupContainer) {
            popupContainer.remove();
            isPopupOpen = false;
        }

        // Always rebuild the popup from scratch
        buildStatsPage1(event.clientX, event.clientY);
    });

    return statButton;
}

function buildStatsPage1(mouseX, mouseY) {
    isPopupOpen = true;

    // Create the table with header and title
    var headerData_evens = ['Losses', 'Combination'];
    var id = 'id_stats_table_dozens5';
    var tableTitle = 'Dozens Losses in a Row';

    var myTable = createStyledTable1(id, tableTitle, headerData_evens);

    popupContainer = document.createElement('div');
    popupContainer.style.display = 'inline-block'; 
    popupContainer.style.border = '1px solid #ddd';
    popupContainer.style.backgroundColor = '#ebf6f7';
    popupContainer.style.padding = '10px';
    popupContainer.style.position = 'absolute';
    popupContainer.style.left = mouseX + 'px';
    popupContainer.style.top = mouseY + 'px';
    popupContainer.style.zIndex = '1000';

    var closeButton = document.createElement('div');
    closeButton.textContent = 'X';
    closeButton.style.cursor = 'pointer';
    closeButton.style.position = 'absolute';
    closeButton.style.top = '5px';
    closeButton.style.right = '5px';
    closeButton.style.fontWeight = 'bold';
    closeButton.addEventListener('click', function() {
        popupContainer.style.display = 'none';
        isPopupOpen = false;
    });

    popupContainer.appendChild(myTable);
    popupContainer.appendChild(closeButton);

    var howToUseLink = document.createElement('a');
    howToUseLink.textContent = 'How to Use';
    howToUseLink.href = 'twodozen.html';
    howToUseLink.target = '_blank';
    howToUseLink.style.display = 'block';
    howToUseLink.style.marginTop = '10px';
    howToUseLink.style.textDecoration = 'underline';
    howToUseLink.style.color = '#007BFF';

    popupContainer.appendChild(howToUseLink);

    document.body.appendChild(popupContainer);

    twoDozenTableDraggable(popupContainer);

    // Populate the table with loss data
    populateLossesTable1(id);

    // Resize the container to fit the table
    adjustPopupContainerSize();
}


function populateLossesTable1(tableId) {
  

    const table = document.getElementById(tableId);

    if (!table) {
        console.error("Table not found:", tableId);
        return;
    }

    // Clear the existing rows (if any)
    while (table.rows.length > 1) {
        table.deleteRow(1);
    }

    const lossData = calculateDozenLosses1();


    if (lossData.length === 0) {
        console.warn("No loss data available.");
        return;
    }

    lossData.forEach(entry => {
        const row = table.insertRow();
        const cell1 = row.insertCell(0);
        const cell2 = row.insertCell(1);
        cell1.textContent = entry.losses;
        cell2.textContent = entry.combination;

        cell1.style.whiteSpace = 'nowrap'; // Prevent wrapping
        cell2.style.whiteSpace = 'nowrap'; // Prevent wrapping
        /*
        if (entry.losses >= 5) {
            row.style.backgroundColor = 'yellow';
        }
            */
    });

    // Force a repaint (reflow)
    table.style.display = 'none';
    table.offsetHeight; // Accessing this property forces a reflow
    table.style.display = 'table'; // Set it back to table

    // Adjust container size to fit the table
    adjustPopupContainerSize();
}

