---
import Layout from '../../layouts/Layout.astro';
---
<Layout title='Drawing Game'>
    <main>
        <div>
        </div>
        <script is:inline src="/assets/js/phaser_3.60.0.js"></script>
    </main>
</Layout>
<script is:inline>
    const drawingZone = {
        x: window.innerWidth / 4,    // X-coordinate of the drawing zone
        y: window.innerHeight / 4,   // Y-coordinate of the drawing zone
        width: window.innerWidth / 2, // Width of the drawing zone
        height: window.innerHeight / 2, // Height of the drawing zone
    };
    var assetsList = {}
    const params = new URLSearchParams(window.location.search);
    const paramsID = params.get('id');
    const data =       fetch(`https://management.beanstalkedu.com/items/game_drawing/${encodeURIComponent(paramsID)}`)
    .then(response => response.json())
    .then(({data}) => {
    const {image} = data;
    assetsList.image = "https://management.beanstalkedu.com/assets/" + image; // + "?width=450";
    const config = {
        type: Phaser.AUTO,
        width: window.innerWidth,
        height: window.innerHeight,
        backgroundColor: '#ffffff',
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_HORIZONTALLY,
        },
        scene: {
            preload: preload,
            create: create,
            update: update,
        },
    };
      const game = new Phaser.Game(config);    
      
    })
    .catch(error => {

      console.error('Error fetching initial data:', error);
    });
    const displayW = window.innerWidth;
    const displayH = window.innerHeight;

    let graphics;
    let isDrawing = false;
    let selectedColor = '#f00f0f'; // Default color
    let brushSize = 10; // Default brush size
    let customCursor;
    const cursorSizeMultiplier = 1;

    function preload() {
        this.load.image('outline', assetsList.image);
    }

    function create() {
        const params = new URLSearchParams(window.location.search);
        const paramsID = params.get('id');
        fetch(`https://management.beanstalkedu.com/items/game_drawing/${encodeURIComponent(paramsID)}`)
            .then(response => response.json())
            .then(({ data }) => {
            const screenCenterX = this.cameras.main.worldView.x + this.cameras.main.width / 2;
            const baseFontSize = 40;
            const responsiveFontSize = (window.innerWidth / 950) * baseFontSize;
            const descrptText = this.add.text(screenCenterX, 50, data.description, {
                font: `${responsiveFontSize}px quicksand`,
                fill: '#7c4c23',
            }).setOrigin(0.5);
        
            })
            .catch(error => {
            console.error('Error fetching initial data:', error);
            });
        const outlineImage = this.add.image(displayW / 2, displayH / 2, 'outline').setScale(0.5);
        outlineImage.setDepth(1);
        graphics = this.add.graphics();

        const colorPicker = document.createElement('input');
        colorPicker.type = 'color';
        colorPicker.value = selectedColor;
        colorPicker.className = 'color-picker';
        document.body.appendChild(colorPicker);
        colorPicker.style.position = 'absolute';
        // colorPicker.textContent = 'Clear';
        colorPicker.style.top = '10%';
        colorPicker.style.left = '20px';
        colorPicker.style.width = '38px';
        colorPicker.style.height = '38px';
        // colorPicker.style.borderRadius = '50%';
        colorPicker.addEventListener('input', (event) => {
            selectedColor = event.target.value; // Update selectedColor
        });
            const colors = ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff'];
            const buttonSize = 40;
            const buttonSpacing = 10;

            // Define the horizontal position for the vertical palette
            const colorPaletteX = 40; // Adjusted position

            // Define the starting position for the vertical palette
            const paletteY = displayH / 1.9 - (colors.length / 1 * (buttonSize + buttonSpacing));

            // Keep track of the selected color
            let selectedButton = null;

            colors.forEach((color, index) => {
                const y = paletteY + index * (buttonSize + buttonSpacing);
                const button = this.add.circle(colorPaletteX, y, buttonSize / 3, Phaser.Display.Color.HexStringToColor(color).color);

                button.setInteractive();
                button.on('pointerdown', function () {
                    // Remove the mark from the previously selected button, if any
                    if (selectedButton) {
                        selectedButton.setStrokeStyle(0); // Remove the border
                    }
                    // Set the new selected color
                    selectedColor = color;

                    // Add a border or tick mark to indicate the selected color
                    button.setStrokeStyle(3, 0x000000); // Add a white border (you can customize this)

                    // Update the selectedButton variable to the current button
                    selectedButton = button;
                });
            });
        const sliderContainer = document.createElement('div');
        sliderContainer.className = 'slider-container';
        document.body.appendChild(sliderContainer);

        sliderContainer.style.position = 'absolute';
        sliderContainer.style.top = '18%';
        sliderContainer.style.left = '15%';

        const slider = document.createElement('input');
        slider.type = 'range';
        slider.min = '2';
        slider.max = '80';
        slider.value = brushSize.toString();
        slider.className = 'slider';
        sliderContainer.appendChild(slider);

        slider.addEventListener('input', (event) => {
            brushSize = parseInt(event.target.value);
            slider.style.backgroundSize = `calc(${(brushSize - 2) * 100 / 18}% + 20px) 100%`;
        });

        const clearButton = document.createElement('button');
        clearButton.textContent = 'Clear';
        // clearButton.className = 'clear-button';
        document.body.appendChild(clearButton);

        clearButton.style.position = 'absolute';
        clearButton.style.top = '10%';
        clearButton.style.left = '120px';
        clearButton.style.backgroundColor = 'blue';
        clearButton.style.color = 'white';
        clearButton.style.padding = '10px 30px';
        clearButton.style.fontSize = '20px';
        clearButton.style.fontWeight = 'bold';
        clearButton.style.borderRadius = '50%';
        clearButton.style.boxShadow = "5px 20px 30px #7c4c2390";
        clearButton.addEventListener('click', () => {
            clearDrawing();
        });

        
        this.input.on('pointerdown', () => {
            isDrawing = true;
            startDrawing(this.input.x, this.input.y);
        });

        this.input.on('pointermove', () => {
            if (isDrawing) {
                continueDrawing(this.input.x, this.input.y);
            }
        });
        this.input.on('pointerup', () => {
            if (isDrawing) {
                finishDrawing();
            }
            isDrawing = false;
        });
        customCursor = this.add.graphics();
        
        // Disable the default cursor
        this.input.setDefaultCursor('none');


        const borderThickness = 2;
    const borderColor = 0x000000; // Black color (you can customize this)

    const borderGraphics = this.add.graphics();
    borderGraphics.lineStyle(borderThickness, borderColor);
    borderGraphics.strokeRect(drawingZone.x, drawingZone.y, drawingZone.width, drawingZone.height);
        function continueDrawing(x, y) {
            // Check if the pointer coordinates are within the drawing zone
            if (
                x >= drawingZone.x &&
                x <= drawingZone.x + drawingZone.width &&
                y >= drawingZone.y &&
                y <= drawingZone.y + drawingZone.height
            ) {
                // The pointer is within the drawing zone, so continue drawing
                graphics.lineTo(x, y);
                graphics.strokePath();
            }
        }
    }

    function startDrawing(x, y) {
        graphics.lineStyle(brushSize * 2, Phaser.Display.Color.HexStringToColor(selectedColor).color);
        graphics.beginPath();
        graphics.moveTo(x, y);
    }

    function continueDrawing(x, y) {
        graphics.lineTo(x, y);
        graphics.strokePath();
    }

    function finishDrawing() {
        // No need for additional actions here
    }

    function clearDrawing() {
        graphics.clear();
    }

    function update() {
        const slider = document.querySelector('input[type="range"]');
        if (slider && !isDrawing) {
            const sliderValue = parseInt(slider.value);
            const max = parseInt(slider.max);
            const width = slider.offsetWidth;
            const offsetX = (sliderValue - 2) / (max - 2) * width;
            slider.style.background = `linear-gradient(to right, #000 0%, #000 ${offsetX}px, #fff ${offsetX}px, #fff 100%)`;
        };
        const cursorSize = brushSize * cursorSizeMultiplier;
        customCursor.clear(); // Clear the previous frame
        customCursor.lineStyle(3, 0x000000); // Set the line style (2 is the line thickness, 0x000000 is black color)
        customCursor.strokeCircle(0, 0, cursorSize);
        // Position the cursor at the current mouse pointer coordinates
        customCursor.x = this.input.x;
        customCursor.y = this.input.y;
    }






//     const config = {
//     type: Phaser.AUTO,
//     width: window.innerWidth,
//     height: window.innerHeight,
//     backgroundColor: '#05b3a4',
//     scale: {
//         mode: Phaser.Scale.FIT,
//         autoCenter: Phaser.Scale.CENTER_HORIZONTALLY,
//     },
//     scene: {
//         preload: preload,
//         create: create,
//         update: update,
//     },
// };

// const game = new Phaser.Game(config);
// const displayW = window.innerWidth;
// const displayH = window.innerHeight;

// let graphics;
// let outlineImage;
// let isDrawing = false;
// let selectedColor = '#ff0000'; // Default color
// let brushSize = 5; // Default brush size

// function preload() {
//     this.load.image('outline', '/assets/cow.png');
// }

// function create() {
//     outlineImage = this.add.image(displayW / 2, displayH / 2, 'outline');

//     graphics = this.add.graphics();

//     // Create a color picker using HTML input type color
//     const colorPicker = document.createElement('input');
//     colorPicker.type = 'color';
//     colorPicker.value = selectedColor;
//     colorPicker.className = 'color-picker';
//     colorPicker.addEventListener('input', (event) => {
//         selectedColor = event.target.value;
//     });
//     document.body.appendChild(colorPicker);

//     // Create a brush size slider using HTML input type range
//     const sliderContainer = document.createElement('div');
//     sliderContainer.className = 'slider-container';
//     document.body.appendChild(sliderContainer);

//     const slider = document.createElement('input');
//     slider.type = 'range';
//     slider.min = '2';
//     slider.max = '20';
//     slider.value = brushSize.toString(); // Set initial value to brushSize
//     slider.className = 'slider';
//     sliderContainer.appendChild(slider);

//     slider.addEventListener('input', (event) => {
//         brushSize = parseInt(event.target.value);
//         slider.style.backgroundSize = `calc(${(brushSize - 2) * 100 / 18}% + 20px) 100%`;
//     });

//     const clearButton = document.createElement('button');
//     clearButton.textContent = 'Clear';
//     clearButton.className = 'clear-button';
//     clearButton.addEventListener('click', () => {
//         clearDrawing();
//     });
//     document.body.appendChild(clearButton);
//     this.input.on('pointerdown', () => {
//         isDrawing = true;
//         startDrawing(this.input.x, this.input.y);
//     });

//     this.input.on('pointermove', () => {
//         if (isDrawing) {
//             continueDrawing(this.input.x, this.input.y);
//         }
//     });

//     this.input.on('pointerup', () => {
//         if (isDrawing) {
//             finishDrawing();
//         }
//         isDrawing = false;
//     });
// }
// function startDrawing(x, y) {
//     graphics.lineStyle(brushSize * 2, Phaser.Display.Color.HexStringToColor(selectedColor).color);
//     graphics.beginPath();
//     graphics.moveTo(x, y);
// }

// function continueDrawing(x, y) {
//     graphics.lineTo(x, y);
//     graphics.strokePath();
// }

// function finishDrawing() {
//     // No need for additional actions here
// }

// function clearDrawing() {
//     graphics.clear();
// }

// function update() {
//     // Update the slider position based on the pointer's movement
//     const slider = document.querySelector('input[type="range"]');
//     if (slider && !isDrawing) {
//         const sliderValue = parseInt(slider.value);
//         const max = parseInt(slider.max);
//         const width = slider.offsetWidth;
//         const offsetX = (sliderValue - 2) / (max - 2) * width;
//         slider.style.background = `linear-gradient(to right, #000 0%, #000 ${offsetX}px, #fff ${offsetX}px, #fff 100%)`;
//     }
// }

    // const config = {
    // type: Phaser.AUTO,
    // width: window.innerWidth,
    // height: window.innerHeight,
    // backgroundColor: '#05b3a4',
    // scale: {
    //       mode: Phaser.Scale.FIT,
    //       autoCenter: Phaser.Scale.CENTER_HORIZONTALLY,
    //       },
    // scene: {
    //     preload: preload,
    //     create: create,
    //     update: update
    //     }
    // };

    // const game = new Phaser.Game(config);
    // const displayW = window.innerWidth;
    // const displayH = window.innerHeight;

    // let graphics;
    // let outlineImage;
    // let isDrawing = false;
    // let selectedColor = 0xff0000; // Default color
    // let brushSize = 5; // Default brush size

    // function preload() {
    //     this.load.image('outline', '/assets/cow.png');
    // }

    // function create() {
    // outlineImage = this.add.image(displayW / 2, displayH / 2, 'outline');

    // graphics = this.add.graphics();

    // // Create color palette buttons
    // const colorPalette = [0xff0000, 0x00ff00, 0x0000ff]; // Example colors

    // colorPalette.forEach((color, index) => {
    //     const button = this.add.rectangle(50 + index * 70, 500, 50, 50, color);
    //     button.setInteractive();
    //     button.on('pointerdown', () => {
    //     selectedColor = color;
    //     });
    // });

    // // Create a brush size slider using HTML input type range
    // const sliderContainer = document.createElement('div');
    // sliderContainer.className = 'slider-container';
    // document.body.appendChild(sliderContainer);

    // const slider = document.createElement('input');
    // slider.type = 'range';
    // slider.min = '2';
    // slider.max = '20';
    // slider.value = brushSize.toString(); // Set initial value to brushSize
    // slider.className = 'slider';
    // sliderContainer.appendChild(slider);

    // slider.addEventListener('input', (event) => {
    //     brushSize = parseInt(event.target.value);
    //     slider.style.backgroundSize = `calc(${(brushSize - 2) * 100 / 18}% + 20px) 100%`;
    // });

    // const clearButton = document.createElement('button');
    // clearButton.textContent = 'Clear';
    // clearButton.className = 'clear-button';
    // clearButton.addEventListener('click', () => {
    //     clearDrawing();
    // });
    // document.body.appendChild(clearButton);

    // this.input.on('pointerdown', () => {
    //     isDrawing = true;
    //     startDrawing(this.input.x, this.input.y);
    // });

    // this.input.on('pointermove', () => {
    //     if (isDrawing) {
    //     continueDrawing(this.input.x, this.input.y);
    //     }
    // });

    // this.input.on('pointerup', () => {
    //     if (isDrawing) {
    //     finishDrawing();
    //     }
    //     isDrawing = false;
    // });
    // }

    // function startDrawing(x, y) {
    // graphics.lineStyle(brushSize * 2, selectedColor);
    // graphics.beginPath();
    // graphics.moveTo(x, y);
    // }

    // function continueDrawing(x, y) {
    // graphics.lineTo(x, y);
    // graphics.strokePath();
    // }

    // function finishDrawing() {
    // // No need for additional actions here
    // }

    // function clearDrawing() {
    // graphics.clear();
    // }

    // function update() {
    // // Update the slider position based on the pointer's movement
    // const slider = document.querySelector('input[type="range"]');
    // if (slider && !isDrawing) {
    //     const sliderValue = parseInt(slider.value);
    //     const max = parseInt(slider.max);
    //     const width = slider.offsetWidth;
    //     const offsetX = (sliderValue - 2) / (max - 2) * width;
    //     slider.style.background = `linear-gradient(to right, #000 0%, #000 ${offsetX}px, #fff ${offsetX}px, #fff 100%)`;
    // }
    // }
</script>
<style>
    .clear-button {
        background-color: blue;
    }
</style>
