<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile Poster Editor</title>
    <!-- CropperJS -->
    <script src="https://cdn.jsdelivr.net/npm/cropperjs@1.5.12/dist/cropper.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cropperjs@1.5.12/dist/cropper.min.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&family=Poppins:wght@600&display=swap" rel="stylesheet">
    <style>
        /* Reset some default styles */
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Roboto', sans-serif;
            text-align: center;
            background-color: #1e1e2f;
            color: #ffffff;
            padding: 20px;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: flex-start;
        }

        h1 {
            margin-bottom: 30px;
            font-size: 2.5em;
            font-family: 'Poppins', sans-serif;
            color: #ff6b6b;
            text-shadow: 2px 2px 8px rgba(0,0,0,0.5);
        }

        #poster-container {
            position: relative;
            display: inline-block;
            width: 90vw;
            max-width: 800px;
            margin-bottom: 30px;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            transition: transform 0.3s;
        }

        #poster-container:hover {
            transform: scale(1.02);
        }

        #poster {
            width: 100%;
            height: auto;
            display: block;
        }

        #profile-photo {
            position: absolute;
            top: 61.5%;
            left: 72%;
            width: 32.5%; /* 260px / 800px = 32.5% */
            height: 34.75%; /* 350px / 800px = 43.75% */
            transform: translate(-50%, -50%);
            overflow: hidden;
            border-radius: 25%;
            box-shadow: 0 8px 16px rgba(0,0,0,0.3);
            cursor: pointer; /* Indicate it's clickable */
            transition: transform 0.3s, box-shadow 0.3s;
        }

        #profile-photo:hover {
            transform: translate(-50%, -50%) scale(1.05);
            box-shadow: 0 12px 24px rgba(0,0,0,0.4);
        }

        #profile-photo img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s;
        }

        /* Overlay for upload indication */
        #profile-photo::after {
            content: "\1F4F7"; /* Camera Emoji */
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 2.5em;
            color: rgba(255, 255, 255, 0.8);
            pointer-events: none;
            display: none; /* Initially hidden */
            transition: opacity 0.3s;
        }

        /* Show overlay on hover */
        #profile-photo:hover::after {
            display: block;
            opacity: 1;
        }

        #name-input {
            position: absolute;
            top: 68%;
            left: 24%;
            transform: translate(-10%, -50%);
            font-size: 130%; /* Responsive font size */
            font-weight: bold;
            color: #ffde59;
            text-shadow: 2px 2px 6px rgba(0,0,0,0.7);
            white-space: nowrap;
            transition: color 0.3s, text-shadow 0.3s;
        }

        #name-input:hover {
            color: #ffe066;
            text-shadow: 2px 2px 8px rgba(0,0,0,0.9);
        }

        /* Modal Styles */
        #modal {
            display: none; /* Hidden by default */
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.85);
            justify-content: center;
            align-items: center;
            z-index: 1000; /* Ensure it stays on top */
            animation: fadeIn 0.5s;
        }

        #modal-content {
            background: #2e2e3e;
            padding: 2em;
            border-radius: 10px;
            max-width: 90vw;
            width: 500px;
            box-sizing: border-box;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0,0,0,0.5);
            animation: slideDown 0.5s;
        }

        #modal-content h2 {
            margin-bottom: 20px;
            color: #ff6b6b;
            font-family: 'Poppins', sans-serif;
        }

        #modal-content img {
            max-width: 100%;
            height: auto;
            margin-bottom: 20px;
            border-radius: 10px;
        }

        /* Controls */
        .controls {
            margin-bottom: 30px;
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
            max-width: 500px;
        }

        .controls input[type="text"],
        .controls button {
            padding: 0.75em 1em;
            margin: 0.5em 0;
            font-size: 1em;
            width: 100%;
            max-width: 400px;
            border: none;
            border-radius: 8px;
            transition: background-color 0.3s, transform 0.3s;
        }

        .controls input[type="text"] {
            background-color: #3e3e55;
            color: #fff;
            padding-left: 15px;
            font-family: 'Roboto', sans-serif;
        }

        .controls input[type="text"]::placeholder {
            color: #bbb;
        }

        .controls input[type="text"]:focus {
            outline: none;
            background-color: #4e4e6b;
        }

        /* Download Button */
        #download {
            background-color: #ff6b6b;
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.3s;
            width: 50%;
            max-width: 200px;
            font-family: 'Poppins', sans-serif;
            font-weight: 600;
        }

        #download:hover {
            background-color: #ff4757;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        }

        #download:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        /* Crop and Close Buttons */
        #crop-btn,
        #close-modal {
            padding: 0.75em 1.5em;
            margin: 0.5em;
            font-size: 1em;
            cursor: pointer;
            border: none;
            border-radius: 8px;
            transition: background-color 0.3s, transform 0.3s;
            font-family: 'Roboto', sans-serif;
        }

        #crop-btn {
            background-color: #28a745;
            color: white;
        }

        #crop-btn:hover {
            background-color: #218838;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }

        #close-modal {
            background-color: #dc3545;
            color: white;
        }

        #close-modal:hover {
            background-color: #c82333;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }

        /* Responsive Adjustments */
        @media (max-width: 600px) {
            #name-input {
                font-size: 4.5vw;
            }

            .controls input[type="text"],
            .controls button {
                width: 90%;
            }

            #download {
                width: 70%;
            }
        }

        /* Hide the file input */
        #photo-upload {
            display: none;
        }

        /* Animations */
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideDown {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
    </style>
</head>
<body>
    <h1>Ukkaz Arts Fest</h1>

    <div id="poster-container">
        <!-- Set crossOrigin to 'anonymous' -->
        <img id="poster" src="./bg.jpeg" alt="Poster Background" crossorigin="anonymous">
        <div id="profile-photo">
            <img id="profile-preview" src="" alt="Profile Preview">
        </div>
        <div id="name-input" maxlength="20">Your Name Here</div>
    </div>

    <div class="controls">
        <!-- Removed the visible file input -->
        <input type="text" id="name" maxlength="25" placeholder="Enter Your Name">
        <button id="download">Download Poster</button>
    </div>

    <!-- Hidden File Input -->
    <input type="file" id="photo-upload" accept="image/*">

    <!-- Cropping Modal -->
    <div id="modal">
        <div id="modal-content">
            <h2>Crop Your Image</h2>
            <img id="image-to-crop" src="" alt="Image to Crop" crossorigin="anonymous">
            <div>
                <button id="crop-btn">Crop</button>
                <button id="close-modal">Close</button>
            </div>
        </div>
    </div>

    <script>
        // Utility Function
        /**
         * Converts a percentage value to pixels based on the total size.
         * @param {number} percentage - The percentage to convert.
         * @param {number} total - The total size (width or height).
         * @returns {number} - The calculated pixel value.
         */
        function percentageToPixel(percentage, total) {
            return (percentage / 100) * total;
        }

        // Select DOM elements
        const photoUpload = document.getElementById('photo-upload');
        const poster = document.getElementById('poster');
        const profilePreview = document.getElementById('profile-preview');
        const nameInputDiv = document.getElementById('name-input');
        const nameInput = document.getElementById('name');
        const downloadBtn = document.getElementById('download');
        const modal = document.getElementById('modal');
        const imageToCrop = document.getElementById('image-to-crop');
        const cropBtn = document.getElementById('crop-btn');
        const closeModal = document.getElementById('close-modal');
        const profilePhotoDiv = document.getElementById('profile-photo');

        let cropper;

        // Make profile photo div clickable to upload image
        profilePhotoDiv.addEventListener('click', function () {
            photoUpload.click();
        });

        poster.addEventListener('click', function () {
            photoUpload.click();
        });

        // Handle Image Upload
        photoUpload.addEventListener('change', function (event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    imageToCrop.src = e.target.result;
                    modal.style.display = 'flex';

                    // Initialize CropperJS
                    if (cropper) {
                        cropper.destroy();
                    }

                    cropper = new Cropper(imageToCrop, {
                        aspectRatio: 260 / 350, // Match profile-photo dimensions
                        viewMode: 1,
                        responsive: true,
                        autoCropArea: 1,
                        movable: true,
                        zoomable: true,
                        rotatable: false,
                        scalable: false,
                        background: false,
                        guides: true,
                        highlight: true,
                        cropBoxResizable: true,
                    });
                };
                reader.readAsDataURL(file);
            }
        });

        // Handle Cropping
        cropBtn.addEventListener('click', function () {
            if (cropper) {
                const canvas = cropper.getCroppedCanvas({
                    width: 260, // Match profile-photo width
                    height: 350, // Match profile-photo height
                });
                profilePreview.src = canvas.toDataURL();
                modal.style.display = 'none';
                cropper.destroy();
                cropper = null;
                // Reset file input
                photoUpload.value = '';
            }
        });

        // Handle Modal Close
        closeModal.addEventListener('click', function () {
            modal.style.display = 'none';
            if (cropper) {
                cropper.destroy();
                cropper = null;
            }
            // Reset file input
            photoUpload.value = '';
        });

        // Update Name in Poster
        nameInput.addEventListener('input', function () {
            nameInputDiv.textContent = nameInput.value || 'Your Name Here';
        });

        // Function to Draw Rounded Image on Canvas
        function drawRoundedImage(ctx, img, x, y, width, height, radius) {
            ctx.beginPath();
            ctx.moveTo(x + radius, y);
            ctx.lineTo(x + width - radius, y);
            ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
            ctx.lineTo(x + width, y + height - radius);
            ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
            ctx.lineTo(x + radius, y + height);
            ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
            ctx.lineTo(x, y + radius);
            ctx.quadraticCurveTo(x, y, x + radius, y);
            ctx.closePath();
            ctx.clip();

            ctx.drawImage(img, x, y, width, height);
            // Note: ctx.restore() is handled in the download function after clipping
        }

        // Handle Downloading the Poster
        downloadBtn.addEventListener('click', function () {
            if (!profilePreview.src) {
                alert('Please upload and crop a profile photo before downloading the poster.');
                return;
            }

            // Change button state to 'Downloading...'
            downloadBtn.textContent = 'Downloading...';
            downloadBtn.disabled = true;

            const poster = document.getElementById('poster');
            const profileImg = new Image();
            profileImg.src = profilePreview.src;
            profileImg.crossOrigin = "anonymous"; // Ensure crossOrigin is set

            profileImg.onload = function () {
                // Create a canvas with the poster's natural dimensions
                const canvas = document.createElement('canvas');
                canvas.width = poster.naturalWidth;
                canvas.height = poster.naturalHeight;
                const ctx = canvas.getContext('2d');

                // Draw the poster background
                ctx.drawImage(poster, 0, 0, canvas.width, canvas.height);

                // Define percentage values for positioning and sizing
                const PROFILE_WIDTH_PERCENTAGE = 32.5; // 32.5%
                const PROFILE_HEIGHT_PERCENTAGE = 34.75; // 34.75%

                const PROFILE_X_PERCENTAGE = 72; // 72%
                const PROFILE_Y_PERCENTAGE = 61.5; // 61.5%

                const NAME_X_PERCENTAGE = 24; // 24%
                const NAME_Y_PERCENTAGE = 68; // 68%

                // Calculate pixel values based on percentages
                const profileWidth = percentageToPixel(PROFILE_WIDTH_PERCENTAGE, canvas.width);
                const profileHeight = percentageToPixel(PROFILE_HEIGHT_PERCENTAGE, canvas.height);

                const profileX = percentageToPixel(PROFILE_X_PERCENTAGE, canvas.width) - (profileWidth / 2);
                const profileY = percentageToPixel(PROFILE_Y_PERCENTAGE, canvas.height) - (profileHeight / 2);

                const nameX = percentageToPixel(NAME_X_PERCENTAGE, canvas.width);
                const nameY = percentageToPixel(NAME_Y_PERCENTAGE, canvas.height);

                // Define border radius as 30% of profile width
                const radius = 0.30 * profileWidth; // Adjust as needed

                // Save the current context state
                ctx.save();

                // Draw the profile image with rounded corners
                drawRoundedImage(ctx, profileImg, profileX, profileY, profileWidth, profileHeight, radius);

                // Restore the context to remove clipping
                ctx.restore();

                // Add the name text
                const fontSize = Math.max(canvas.width, canvas.height) * 0.020; // 2% of the larger dimension
                ctx.font = `bold ${fontSize}px 'Poppins', sans-serif`;
                ctx.fillStyle = '#ffde59';
                ctx.textAlign = 'left';
                ctx.textBaseline = 'middle';
                ctx.shadowColor = 'rgba(0, 0, 0, 0.7)';
                ctx.shadowOffsetX = 2;
                ctx.shadowOffsetY = 2;
                ctx.shadowBlur = 4;
                ctx.fillText(nameInput.value || 'Your Name Here', nameX, nameY);

                // Convert canvas to image and trigger download
                canvas.toBlob(function(blob) {
                    const link = document.createElement('a');
                    link.download = 'poster.png';
                    link.href = URL.createObjectURL(blob);
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);

                    // Revert button state after download
                    downloadBtn.textContent = 'Download Poster';
                    downloadBtn.disabled = false;
                }, 'image/png');
            };

            profileImg.onerror = function () {
                alert('1. ചിത്രത്തിൽ ക്ലിക്കുചെയ്യുക\n2. ഫോട്ടോ അപ്‌ലോഡ് ചെയ്യുക\n3. പേര് നൽകുക');
                // Revert button state
                downloadBtn.textContent = 'Download Poster';
                downloadBtn.disabled = false;
            };
        });
    </script>
</body>
</html>
