<?php
// Tells the header to switch to the "Back Arrow" and "Language Selector" layout
$is_auth_page = true;

// ==============================================================================
// 1. DATABASE CONNECTION & REGISTRATION LOGIC
// ==============================================================================
session_start();

// --- IF ALREADY LOGGED IN, REDIRECT TO INDEX IMMEDIATELY ---
if (isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

require_once 'config.php'; // Include your DB connection

$message = '';
$messageType = ''; // 'success' or 'error'

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and grab inputs
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $referred_by = trim($_POST['referral_code'] ?? '');
    
    // Check Captcha Status
    $captcha_solved = $_POST['slider_captcha_solved'] ?? '0';

    // Get Real IP Address (Handles Cloudflare & Proxies)
    $ip = $_SERVER['REMOTE_ADDR'];
    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
    } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    }

    // Check IP Limits (Max 3 accounts per IP starting from May 18, 2026)
    $ipStmt = $pdo->prepare("SELECT COUNT(id) FROM users WHERE ip = ? AND created_at >= '2026-05-18 00:00:00'");
    $ipStmt->execute([$ip]);
    $ip_accounts_count = (int)$ipStmt->fetchColumn();

    // Backend Validation
    if ($captcha_solved !== '1') {
        $message = "Please complete the security verification.";
        $messageType = "error";
    } elseif ($password !== $confirm_password) {
        $message = "Passwords do not match!"; 
        $messageType = "error";
    } elseif ($ip_accounts_count >= 3) {
        $message = "Registration limit reached for this network/device."; 
        $messageType = "error";
    } else {
        // Check if phone number already exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE number = ?");
        $stmt->execute([$phone]);
        
        if ($stmt->fetch()) {
            $message = "This phone number is already registered."; 
            $messageType = "error";
        } else {
            // Generate a unique 8-character referral code for the NEW user
            $newReferCode = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 8);
            
            // Generate default member_name
            $memberNameSuffix = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 8);
            $newMemberName = "Member" . $memberNameSuffix;
            
            // Validate the referrer code if one was provided
            if (!empty($referred_by)) {
                $stmtRef = $pdo->prepare("SELECT id FROM users WHERE refercode = ?");
                $stmtRef->execute([$referred_by]);
                if (!$stmtRef->fetch()) {
                    // If the code is fake/invalid, just set it to null and proceed safely
                    $referred_by = null; 
                }
            } else {
                $referred_by = null;
            }

            try {
                // Insert into Database 
                $insertStmt = $pdo->prepare("INSERT INTO users (number, password, refercode, referedby, ip, member_name) VALUES (?, ?, ?, ?, ?, ?)");
                $insertStmt->execute([$phone, $password, $newReferCode, $referred_by, $ip, $newMemberName]);
                
                // Auto-Login the user right after successful registration
                $_SESSION['user_id'] = $pdo->lastInsertId();
                $_SESSION['phone'] = $phone;
                $_SESSION['is_demo'] = 0;

                $message = "Registration successful!"; 
                $messageType = "success";
                
            } catch(PDOException $e) {
                $message = "Database error!"; 
                $messageType = "error";
            }
        }
    }
}

// ==============================================================================
// 2. REFERRAL CODE DETECTION (URL)
// ==============================================================================
$ref_code = '';
if (isset($_GET['ref'])) {
    $ref_code = htmlspecialchars($_GET['ref'], ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
    <title>Signup - PAKclub</title>
    
    <meta name="google" content="notranslate">
    <meta name="robots" content="notranslate">
    <meta http-equiv="Content-Language" content="en">
    <script>
        document.documentElement.setAttribute("translate", "no");
        document.documentElement.classList.add("notranslate");
        document.documentElement.setAttribute("lang", "en");

        const translateObserver = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                mutation.addedNodes.forEach((node) => {
                    if (node.tagName === 'SCRIPT' && node.src && node.src.includes('translate.google.com')) {
                        node.remove(); 
                    }
                    if (node.className && typeof node.className === 'string' && node.className.includes('goog-te-')) {
                        node.remove(); 
                    }
                });
            });
        });
        translateObserver.observe(document.documentElement, { childList: true, subtree: true });
    </script>

    <link rel="icon" type="image/png" href="./img/ico.png">
    <link rel="apple-touch-icon" href="./img/ico.png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        /* TRANSLATION CSS CLOAKING DEVICE */
        .goog-te-banner-frame.skiptranslate, 
        .goog-te-banner-frame, 
        #goog-gt-tt, 
        .goog-te-balloon-frame { 
            display: none !important; 
            visibility: hidden !important; 
            opacity: 0 !important;
        }
        body { top: 0px !important; }
        .goog-text-highlight { background-color: transparent !important; box-shadow: none !important; }

        /* ANTI-BEHAVIOR GLOBAL LOCKS */
        * {
            box-sizing: border-box; 
            font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; 
            -webkit-tap-highlight-color: transparent !important;
            -webkit-touch-callout: none !important; 
            -webkit-user-select: none !important;   
            -moz-user-select: none !important;      
            -ms-user-select: none !important;       
            user-select: none !important;            
        }
        input, textarea {
            -webkit-user-select: auto !important;
            -moz-user-select: auto !important;
            -ms-user-select: auto !important;
            user-select: auto !important;
        }
        a, button, img, .lang-selector, .auth-header-left {
            touch-action: manipulation !important;
            outline: none !important; 
        }

        html, body {
            background-color: #0e0a07 !important; 
            background-image: none !important; 
            margin: 0 auto !important;
            padding: 0;
            min-height: 100vh;
            width: 100% !important;
            max-width: 414px !important; 
            position: relative !important;
            overflow-x: hidden !important;
            -ms-overflow-style: none; 
            -webkit-overflow-scrolling: touch !important; 
            scroll-behavior: smooth; 
        }
        ::-webkit-scrollbar { display: none; width: 0px; background: transparent; }

        /* CUSTOM TOP HEADER */
        .custom-top-header {
            position: absolute !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            display: flex !important;
            justify-content: space-between !important;
            align-items: center !important;
            padding: 15px 20px !important;
            z-index: 10 !important; 
            background: transparent !important; 
            border: none !important;
            box-shadow: none !important;
        }
        .custom-top-header .back-btn { color: #ffffff !important; font-size: 22px !important; text-decoration: none !important; display: flex !important; align-items: center !important; justify-content: center !important; }
        .custom-top-header .header-right-actions { display: flex !important; align-items: center !important; gap: 15px !important; }
        .custom-top-header .support-btn { color: #ff9800 !important; font-size: 20px !important; text-decoration: none !important; display: flex !important; align-items: center !important; justify-content: center !important; }
        .custom-top-header .lang-selector { display: flex !important; align-items: center !important; gap: 6px !important; color: #ffffff !important; font-weight: bold !important; font-size: 15px !important; cursor: pointer !important; }
        .custom-top-header .lang-selector img { width: 20px !important; height: 20px !important; border-radius: 50% !important; object-fit: cover !important; }

        /* HERO IMAGE */
        .login-hero {
            position: absolute !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            height: 320px !important; 
            background: url('./img/login-bg.png') center top/cover no-repeat !important;
            -webkit-mask-image: linear-gradient(to bottom, rgba(0,0,0,1) 40%, rgba(0,0,0,0) 100%) !important;
            mask-image: linear-gradient(to bottom, rgba(0,0,0,1) 40%, rgba(0,0,0,0) 100%) !important;
            z-index: 0 !important;
            display: flex !important;
            justify-content: center !important;
        }
        .hero-logo { position: absolute; top: 90px; width: 130px; }

        /* FORM CONTAINER */
        .login-container {
            position: relative;
            z-index: 1;
            margin-top: 220px; 
            padding: 0 20px;
            display: flex;
            flex-direction: column;
            gap: 15px;
            padding-bottom: 40px; 
        }

        /* TOAST NOTIFICATION */
        .ios-toast {
            position: fixed;
            bottom: -80px; 
            left: 50%;
            transform: translateX(-50%);
            background: rgba(28, 28, 30, 0.95); 
            backdrop-filter: blur(15px);
            -webkit-backdrop-filter: blur(15px);
            color: #fff;
            padding: 12px 24px;
            border-radius: 30px; 
            font-size: 14px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
            z-index: 99999;
            box-shadow: 0 8px 30px rgba(0,0,0,0.8); 
            transition: bottom 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); 
            white-space: nowrap;
            pointer-events: none;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .ios-toast.show { bottom: 60px; }
        .toast-error i { color: #ff453a; font-size: 16px; } 
        .toast-success i { color: #32d74b; font-size: 16px; } 

        /* INPUT GROUPS */
        .input-group {
            background-color: #111111; 
            border: 1px solid #2a2a2a; 
            border-radius: 6px; 
            display: flex;
            align-items: center;
            padding: 12px 15px;
            gap: 12px;
            transition: border-color 0.2s ease;
        }
        .input-group:focus-within { border-color: #cf7029; }
        .input-icon { color: #b09e91; font-size: 16px; width: 16px; text-align: center; }
        .prefix { color: #ffffff; font-weight: bold; font-size: 14px; border-right: 1px solid #2a2a2a; padding-right: 12px; }
        .input-field { flex: 1; background: transparent; border: none; color: #ffffff; font-size: 14px; outline: none; text-align: left; width: 100%; }
        .input-field::placeholder { color: #6b5c52; }
        
        .input-field:-webkit-autofill,
        .input-field:-webkit-autofill:hover, 
        .input-field:-webkit-autofill:focus, 
        .input-field:-webkit-autofill:active {
            -webkit-box-shadow: 0 0 0 30px #111111 inset !important;
            -webkit-text-fill-color: #ffffff !important;
            transition: background-color 5000s ease-in-out 0s;
            caret-color: #ffffff;
        }

        /* JIGSAW CAPTCHA MODAL */
        .jigsaw-modal-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.7); backdrop-filter: blur(3px); -webkit-backdrop-filter: blur(3px);
            display: none; align-items: center; justify-content: center; z-index: 100000;
            opacity: 0; transition: opacity 0.3s ease;
        }
        .jigsaw-modal-overlay.show { display: flex; opacity: 1; }
        .jigsaw-modal {
            background: #ffffff; width: 340px; max-width: 90%; border-radius: 12px;
            padding: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.5); transform: scale(0.95); transition: transform 0.3s ease;
        }
        .jigsaw-modal-overlay.show .jigsaw-modal { transform: scale(1); }
        .jm-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
        .jm-header span { color: #333; font-weight: 700; font-size: 15px; }
        .jm-header i { color: #999; font-size: 20px; cursor: pointer; padding: 5px; }
        
        .jm-img-wrapper { position: relative; width: 100%; height: 160px; border-radius: 6px; overflow: hidden; background: #eee; }
        
        /* Uses background-image set via JS for perfect alignment */
        .jm-img-bg { width: 100%; height: 100%; background-repeat: no-repeat; border-radius: 6px; }
        
        /* The exact puzzle path used for masking */
        .jm-puzzle-mask { clip-path: path("M 10 15 H 20 A 5 5 0 0 1 30 15 H 40 V 25 A 5 5 0 0 0 40 35 V 45 H 30 A 5 5 0 0 1 20 45 H 10 V 35 A 5 5 0 0 1 10 25 Z"); }
        
        /* SVG Overlay to create the crisp white borders */
        .jm-svg-overlay {
            position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 12; pointer-events: none;
        }

        .jm-hole {
            position: absolute; top: 0; left: 0; width: 50px; height: 60px; z-index: 5;
        }
        
        .jm-piece-container {
            position: absolute; top: 0; left: 0; width: 50px; height: 60px; z-index: 10;
            filter: drop-shadow(0 0 3px rgba(0,0,0,0.4));
        }
        
        .jm-piece {
            width: 100%; height: 100%;
            background-repeat: no-repeat;
        }
        
        .jm-slider-track {
            position: relative; width: 100%; height: 40px; background: #f0f0f0;
            border-radius: 4px; margin-top: 15px; border: 1px solid #e0e0e0;
            display: flex; align-items: center; justify-content: center;
        }
        .jm-slider-text { position: absolute; color: #888; font-size: 13px; pointer-events: none; user-select: none; }
        .jm-slider-fill { position: absolute; left: 0; top: 0; height: 100%; width: 0; background: rgba(209, 112, 40, 0.2); border-radius: 4px 0 0 4px; border: 1px solid #d17028; border-right: none; opacity: 0; }
        .jm-slider-thumb {
            position: absolute; left: 0; top: -1px; width: 50px; height: 40px;
            background: #ffffff; border: 1px solid #ccc; border-radius: 4px;
            display: flex; align-items: center; justify-content: center; color: #666;
            cursor: grab; box-shadow: 0 2px 5px rgba(0,0,0,0.1); z-index: 15;
            transition: background 0.2s, color 0.2s;
        }
        .jm-slider-thumb:active { cursor: grabbing; background: #d17028; color: #fff; border-color: #d17028; }
        .jm-slider-track.success .jm-slider-fill { background: rgba(0, 200, 83, 0.2); border-color: #00c853; }
        .jm-slider-track.success .jm-slider-thumb { background: #00c853; color: #fff; border-color: #00c853; }
        .jm-slider-track.fail .jm-slider-thumb { background: #ff453a; color: #fff; border-color: #ff453a; }

        /* BUTTONS & LINKS */
        .bottom-link-container { text-align: right; width: 100%; margin-top: -5px; }
        .bottom-link { color: #cfc529; font-size: 13px; text-decoration: underline; margin-bottom: 20px; cursor: pointer; display: inline-block; }
        .btn-main { background: #d17028; color: #fff; border: none; border-radius: 25px; padding: 14px; font-size: 16px; cursor: pointer; width: 100%; margin-bottom: 12px; transition: opacity 0.2s ease; font-weight: bold; }
        .btn-main:active { opacity: 0.8; }
        .btn-outline { background: transparent; color: #d17028; border: 1px solid #d17028; border-radius: 25px; padding: 14px; font-size: 16px; cursor: pointer; width: 100%; transition: opacity 0.2s ease; font-weight: bold; }
        .btn-outline:active { opacity: 0.8; }
        .eye-icon { color: #6b5c52; cursor: pointer; font-size: 16px; }
    </style>
</head>
<body>

    <?php if (!empty($message)): ?>
        <div id="iosToast" class="ios-toast toast-<?php echo $messageType; ?>">
            <i class="fa-solid <?php echo $messageType === 'success' ? 'fa-circle-check' : 'fa-circle-exclamation'; ?>"></i>
            <span><?php echo $message; ?></span>
        </div>
        <script>
            document.addEventListener("DOMContentLoaded", () => {
                const toast = document.getElementById('iosToast');
                setTimeout(() => { toast.classList.add('show'); }, 10);
                
                <?php if ($messageType === 'success'): ?>
                    setTimeout(() => { window.location.href = 'index.php'; }, 600);
                <?php else: ?>
                    setTimeout(() => { toast.classList.remove('show'); }, 3000);
                <?php endif; ?>
            });
        </script>
    <?php endif; ?>

    <div style="display: none !important; visibility: hidden !important;">
        <?php include 'external/header.php'; ?>
    </div>

    <div class="custom-top-header">
        <a href="javascript:history.back()" class="back-btn"><i class="fa-solid fa-chevron-left"></i></a>
        <div class="header-right-actions">
            <a href="support.php" class="support-btn"><i class="fa-solid fa-headset"></i></a>
            <div class="lang-selector">
                <img src="https://flagcdn.com/w40/gb.png" alt="English Flag">
                <span>EN</span>
            </div>
        </div>
    </div>

    <div class="login-hero">
        <img src="./img/logo.png" alt="PAKclub" class="hero-logo">
    </div>

    <div class="login-container">
        
        <form id="signupForm" method="POST" action="">
            
            <div class="input-group" style="margin-bottom: 15px;">
                <i class="fa-solid fa-mobile-screen input-icon"></i>
                <span class="prefix">+92</span>
                <input type="tel" id="signupPhone" name="phone" class="input-field pk-phone" placeholder="Enter your phone number" required>
            </div>

            <div class="input-group" style="margin-bottom: 15px;">
                <i class="fa-solid fa-lock input-icon"></i>
                <input type="password" id="signupPwd" name="password" class="input-field" placeholder="Please enter password" minlength="8" required>
                <i class="fa-solid fa-eye-slash eye-icon pwd-toggle" data-target="signupPwd"></i>
            </div>

            <div class="input-group" style="margin-bottom: 15px;">
                <i class="fa-solid fa-lock input-icon"></i>
                <input type="password" id="signupConfirmPwd" name="confirm_password" class="input-field" placeholder="Re-enter password" minlength="8" required>
                <i class="fa-solid fa-eye-slash eye-icon pwd-toggle" data-target="signupConfirmPwd"></i>
            </div>

            <div class="input-group" style="margin-bottom: 15px;">
                <i class="fa-solid fa-user-plus input-icon"></i>
                <input type="text" id="signupRef" name="referral_code" class="input-field" placeholder="Invitation code (Optional)" value="<?php echo $ref_code; ?>">
            </div>
            
            <input type="hidden" name="slider_captcha_solved" id="slider_captcha_solved" value="0">

            <div class="bottom-link-container">
                <a href="login.php" class="bottom-link">Already have an account? Log in</a>
            </div>

            <button type="button" class="btn-main" onclick="submitSignup(event)">Register Now</button>
            <button type="button" class="btn-outline" onclick="window.location.href='login.php'">Log in</button>

        </form>

    </div>

    <div id="jigsawModalOverlay" class="jigsaw-modal-overlay">
        <div class="jigsaw-modal">
            <div class="jm-header">
                <span>Security Verification</span>
                <i class="fa-solid fa-xmark" onclick="closeJigsawCaptcha()"></i>
            </div>
            
            <div class="jm-img-wrapper" id="jmImgWrapper">
                <div id="jmBgImage" class="jm-img-bg"></div>
                
                <div class="jm-hole" id="jmHole">
                    <svg class="jm-svg-overlay" viewBox="0 0 50 60">
                        <path d="M 10 15 H 20 A 5 5 0 0 1 30 15 H 40 V 25 A 5 5 0 0 0 40 35 V 45 H 30 A 5 5 0 0 1 20 45 H 10 V 35 A 5 5 0 0 1 10 25 Z" fill="rgba(0,0,0,0.65)" stroke="#ffffff" stroke-width="1.5"/>
                    </svg>
                </div>
                
                <div class="jm-piece-container" id="jmPieceContainer">
                    <svg class="jm-svg-overlay" viewBox="0 0 50 60">
                        <path d="M 10 15 H 20 A 5 5 0 0 1 30 15 H 40 V 25 A 5 5 0 0 0 40 35 V 45 H 30 A 5 5 0 0 1 20 45 H 10 V 35 A 5 5 0 0 1 10 25 Z" fill="none" stroke="#ffffff" stroke-width="1.5"/>
                    </svg>
                    <div class="jm-piece jm-puzzle-mask" id="jmPiece"></div>
                </div>
            </div>

            <div class="jm-slider-track" id="jmTrack">
                <div class="jm-slider-fill" id="jmFill"></div>
                <div class="jm-slider-text" id="jmText">Hold and slide</div>
                <div class="jm-slider-thumb" id="jmThumb"><i class="fa-solid fa-angles-right"></i></div>
            </div>
        </div>
    </div>

    <script>
        // PK Phone Formatting
        document.querySelectorAll('.pk-phone').forEach(input => {
            input.addEventListener('input', function(e) {
                let value = this.value.replace(/\D/g, '');
                if (value.startsWith('0')) value = value.substring(1);
                if (value.length > 10) value = value.substring(0, 10);
                this.value = value;
            });
        });

        // Password Visibility Toggle
        document.querySelectorAll('.pwd-toggle').forEach(icon => {
            icon.addEventListener('click', function() {
                const targetInput = document.getElementById(this.getAttribute('data-target'));
                if(targetInput.type === 'password') {
                    targetInput.type = 'text';
                    this.classList.replace('fa-eye-slash', 'fa-eye');
                } else {
                    targetInput.type = 'password';
                    this.classList.replace('fa-eye', 'fa-eye-slash');
                }
            });
        });

        // Custom Toast Function
        function showCustomToast(msg) {
            const toast = document.createElement('div');
            toast.className = 'ios-toast toast-error';
            toast.innerHTML = `<i class="fa-solid fa-circle-exclamation"></i><span>${msg}</span>`;
            document.body.appendChild(toast);
            setTimeout(() => toast.classList.add('show'), 10);
            setTimeout(() => { 
                toast.classList.remove('show'); 
                setTimeout(() => toast.remove(), 500);
            }, 3000);
        }

        // ==========================================
        // MAIN SIGNUP INTERCEPTOR
        // ==========================================
        function submitSignup(e) {
            e.preventDefault();
            
            const form = document.getElementById('signupForm');
            const pwd = document.getElementById('signupPwd').value;
            const confirmPwd = document.getElementById('signupConfirmPwd').value;
            
            // 1. Native HTML5 Validation Check
            if (!form.checkValidity()) {
                form.reportValidity();
                return false;
            }

            // 2. Password Match Check
            if (pwd !== confirmPwd) {
                showCustomToast('Passwords do not match!');
                return false;
            }

            // 3. Captcha Check
            if (!isVerified) {
                openJigsawCaptcha();
                return false;
            }

            // If already verified, allow direct submission
            form.submit();
        }

        // ==========================================
        // JIGSAW CAPTCHA LOGIC
        // ==========================================
        const modalOverlay = document.getElementById('jigsawModalOverlay');
        const imgWrapper = document.getElementById('jmImgWrapper');
        const bgImage = document.getElementById('jmBgImage');
        const pieceContainer = document.getElementById('jmPieceContainer');
        const piece = document.getElementById('jmPiece');
        const hole = document.getElementById('jmHole');
        const track = document.getElementById('jmTrack');
        const thumb = document.getElementById('jmThumb');
        const fill = document.getElementById('jmFill');
        const hiddenInput = document.getElementById('slider_captcha_solved');

        let isDragging = false;
        let startX = 0;
        let currentThumbX = 0;
        let targetX = 0;
        let targetY = 0;
        let maxDrag = 0;
        let isVerified = false;

        const captchaImages = [
            'https://picsum.photos/id/1018/400/200',
            'https://picsum.photos/id/1015/400/200',
            'https://picsum.photos/id/1043/400/200',
            'https://picsum.photos/id/1036/400/200'
        ];

        function initJigsaw() {
            // Reset styles
            track.className = 'jm-slider-track';
            thumb.innerHTML = '<i class="fa-solid fa-angles-right"></i>';
            thumb.style.left = '0px';
            fill.style.opacity = '1';
            fill.style.width = '0px';
            pieceContainer.style.left = '0px';
            
            const randomImg = captchaImages[Math.floor(Math.random() * captchaImages.length)];
            
            // Calculate Dimensions
            const containerWidth = imgWrapper.offsetWidth || 310;
            const containerHeight = imgWrapper.offsetHeight || 160;
            const pieceWidth = 50; 
            maxDrag = containerWidth - pieceWidth;

            // Apply EXACT same styling to both background and piece to guarantee alignment
            bgImage.style.backgroundImage = `url(${randomImg})`;
            bgImage.style.backgroundSize = `${containerWidth}px ${containerHeight}px`;
            
            piece.style.backgroundImage = `url(${randomImg})`;
            piece.style.backgroundSize = `${containerWidth}px ${containerHeight}px`;

            // Generate Random Target Coordinates
            targetX = Math.floor(Math.random() * (maxDrag - 60)) + 60; 
            targetY = Math.floor(Math.random() * (containerHeight - 60)); 

            // Position Hole
            hole.style.left = targetX + 'px';
            hole.style.top = targetY + 'px';

            // Position Piece Y and internal Background Offset
            pieceContainer.style.top = targetY + 'px';
            piece.style.backgroundPosition = `-${targetX}px -${targetY}px`;
        }

        function openJigsawCaptcha() {
            if (isVerified) return;
            initJigsaw();
            modalOverlay.classList.add('show');
        }

        function closeJigsawCaptcha() {
            modalOverlay.classList.remove('show');
        }

        // Mouse & Touch Events
        function handleDragStart(e) {
            if (isVerified) return;
            isDragging = true;
            startX = e.type.includes('mouse') ? e.clientX : e.touches[0].clientX;
            track.classList.remove('fail');
        }

        function handleDragMove(e) {
            if (!isDragging) return;
            let clientX = e.type.includes('mouse') ? e.clientX : e.touches[0].clientX;
            let moveX = clientX - startX;
            
            if (moveX < 0) moveX = 0;
            if (moveX > maxDrag) moveX = maxDrag;
            
            currentThumbX = moveX;
            thumb.style.left = moveX + 'px';
            fill.style.width = (moveX + 25) + 'px';
            pieceContainer.style.left = moveX + 'px';
        }

        function handleDragEnd() {
            if (!isDragging) return;
            isDragging = false;
            
            // Validation: Allow 5px margin of error
            if (Math.abs(currentThumbX - targetX) < 5) {
                // Success
                isVerified = true;
                track.classList.add('success');
                thumb.innerHTML = '<i class="fa-solid fa-check"></i>';
                hiddenInput.value = '1';
                
                // Close modal and AUTO SUBMIT the form
                setTimeout(() => { 
                    closeJigsawCaptcha(); 
                    document.getElementById('signupForm').submit();
                }, 600);

            } else {
                // Fail
                track.classList.add('fail');
                thumb.innerHTML = '<i class="fa-solid fa-xmark"></i>';
                setTimeout(() => {
                    thumb.style.transition = 'left 0.3s ease';
                    pieceContainer.style.transition = 'left 0.3s ease';
                    fill.style.transition = 'width 0.3s ease';
                    
                    thumb.style.left = '0px';
                    pieceContainer.style.left = '0px';
                    fill.style.width = '0px';
                    
                    setTimeout(() => {
                        thumb.style.transition = '';
                        pieceContainer.style.transition = '';
                        fill.style.transition = '';
                        track.classList.remove('fail');
                        thumb.innerHTML = '<i class="fa-solid fa-angles-right"></i>';
                    }, 300);
                }, 400);
            }
        }

        thumb.addEventListener('mousedown', handleDragStart);
        document.addEventListener('mousemove', handleDragMove);
        document.addEventListener('mouseup', handleDragEnd);

        thumb.addEventListener('touchstart', handleDragStart, {passive: true});
        document.addEventListener('touchmove', handleDragMove, {passive: true});
        document.addEventListener('touchend', handleDragEnd);
    </script>

</body>
</html>