<?php
/**
 * Location-Based Land Scanner
 * Uses GPS to check if current location is within any registered land
 */

// Production-ready database connection
$isProduction = (strpos($_SERVER['HTTP_HOST'] ?? '', 'landsecure.co.tz') !== false);

if ($isProduction) {
    $db_host = 'localhost';
    $db_user = 'pitechco_mylands';
    $db_pass = 'RomilusK>%+66';
    $db_name = 'pitechco_mylands';
} else {
    $db_host = 'localhost';
    $db_user = 'root';
    $db_pass = '';
    $db_name = 'uhakikimadalali';
}

$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'error' => 'Database connection failed']);
        exit;
    }
    die("Database connection failed");
}
mysqli_set_charset($conn, 'utf8mb4');

// Handle AJAX request for location lookup
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'check_location') {
    header('Content-Type: application/json');

    try {
        $lat = floatval($_POST['lat'] ?? 0);
        $lng = floatval($_POST['lng'] ?? 0);

        if ($lat == 0 || $lng == 0) {
            echo json_encode(['success' => false, 'error' => 'Invalid coordinates']);
            exit;
        }

        // Find lands that might contain this point
        // Expanded bounding box (~5km to ensure we catch all nearby lands)
        $latMin = $lat - 0.05;
        $latMax = $lat + 0.05;
        $lngMin = $lng - 0.05;
        $lngMax = $lng + 0.05;

        // Check which points table exists
        $pointsTable = 'beacon_points';
        $tableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'land_points'");
        if ($tableCheck && mysqli_num_rows($tableCheck) > 0) {
            $pointsTable = 'land_points';
        }

        // Also check for beacon_points
        $beaconCheck = mysqli_query($conn, "SHOW TABLES LIKE 'beacon_points'");
        if ($beaconCheck && mysqli_num_rows($beaconCheck) > 0) {
            $pointsTable = 'beacon_points';
        }

        // Check column names in points table (might be lat/lng instead of latitude/longitude)
        $latCol = 'latitude';
        $lngCol = 'longitude';
        $orderCol = 'point_order';

        $colsResult = mysqli_query($conn, "SHOW COLUMNS FROM $pointsTable");
        $pointsCols = [];
        while ($col = mysqli_fetch_assoc($colsResult)) {
            $pointsCols[] = strtolower($col['Field']);
        }

        // Check for alternative column names
        if (in_array('lat', $pointsCols) && !in_array('latitude', $pointsCols)) {
            $latCol = 'lat';
        }
        if (in_array('lng', $pointsCols) && !in_array('longitude', $pointsCols)) {
            $lngCol = 'lng';
        }
        if (in_array('order_num', $pointsCols) && !in_array('point_order', $pointsCols)) {
            $orderCol = 'order_num';
        }
        if (in_array('sequence', $pointsCols) && !in_array('point_order', $pointsCols)) {
            $orderCol = 'sequence';
        }
        if (!in_array('point_order', $pointsCols) && !in_array('order_num', $pointsCols) && !in_array('sequence', $pointsCols)) {
            $orderCol = 'id'; // fallback to id if no order column
        }

        // Check lands table column names
        $landNameCol = 'land_name';
        $areaCol = 'area_sqm';
        $colCheck = mysqli_query($conn, "SHOW COLUMNS FROM lands LIKE 'name'");
        if ($colCheck && mysqli_num_rows($colCheck) > 0) {
            $landNameCol = 'name';
        }
        $areaCheck = mysqli_query($conn, "SHOW COLUMNS FROM lands LIKE 'total_area'");
        if ($areaCheck && mysqli_num_rows($areaCheck) > 0) {
            $areaCol = 'total_area';
        }

        // First check if there are ANY points in the bounding box
        $pointsInBox = mysqli_query($conn, "
            SELECT COUNT(*) as cnt, GROUP_CONCAT(DISTINCT land_id) as land_ids
            FROM $pointsTable
            WHERE $latCol BETWEEN $latMin AND $latMax
            AND $lngCol BETWEEN $lngMin AND $lngMax
        ");
        $boxCheck = mysqli_fetch_assoc($pointsInBox);

        // Also get total points in database for debugging
        $totalPointsQuery = mysqli_query($conn, "SELECT COUNT(*) as total, COUNT(DISTINCT land_id) as land_count FROM $pointsTable");
        $totalPoints = mysqli_fetch_assoc($totalPointsQuery);

        // Get sample coordinates to verify data exists
        $sampleQuery = mysqli_query($conn, "SELECT $latCol as lat, $lngCol as lng FROM $pointsTable LIMIT 5");
        $sampleCoords = [];
        while ($sample = mysqli_fetch_assoc($sampleQuery)) {
            $sampleCoords[] = ['lat' => floatval($sample['lat']), 'lng' => floatval($sample['lng'])];
        }

        // Query lands with flexible column names
        // If bounding box found points, use those; otherwise check ALL lands with points
        $landsQuery = "";
        if (intval($boxCheck['cnt']) > 0) {
            // Bounding box found some points
            $landsQuery = "
                SELECT DISTINCT l.id,
                       l.$landNameCol as land_name,
                       l.$areaCol as area_sqm,
                       COALESCE(l.status, 'pending') as status,
                       l.created_at,
                       u.full_name as owner_name,
                       u.phone as owner_phone
                FROM lands l
                JOIN users u ON l.user_id = u.id
                WHERE l.id IN (
                    SELECT DISTINCT land_id FROM $pointsTable
                    WHERE $latCol BETWEEN $latMin AND $latMax
                    AND $lngCol BETWEEN $lngMin AND $lngMax
                )
            ";
        } else {
            // Fallback: check ALL lands that have beacon points (limit to 100 for performance)
            $landsQuery = "
                SELECT DISTINCT l.id,
                       l.$landNameCol as land_name,
                       l.$areaCol as area_sqm,
                       COALESCE(l.status, 'pending') as status,
                       l.created_at,
                       u.full_name as owner_name,
                       u.phone as owner_phone
                FROM lands l
                JOIN users u ON l.user_id = u.id
                WHERE l.id IN (SELECT DISTINCT land_id FROM $pointsTable)
                LIMIT 100
            ";
        }

        $result = mysqli_query($conn, $landsQuery);

        if (!$result) {
            throw new Exception(mysqli_error($conn));
        }

        $foundLands = [];
        $checkedLands = []; // For debugging

        while ($land = mysqli_fetch_assoc($result)) {
            // Get GPS polygon points for this land (use same table detected earlier)
            $pointsResult = mysqli_query($conn, "
                SELECT $latCol as latitude, $lngCol as longitude FROM $pointsTable
                WHERE land_id = {$land['id']}
                ORDER BY $orderCol
            ");

            $polygon = [];
            while ($point = mysqli_fetch_assoc($pointsResult)) {
                $polygon[] = [
                    'lat' => floatval($point['latitude']),
                    'lng' => floatval($point['longitude'])
                ];
            }

            // Get visual boundary points (user-adjusted for satellite alignment)
            $visualPolygon = [];
            $visualTableCheck = mysqli_query($conn, "SHOW TABLES LIKE 'visual_boundary_points'");
            if (mysqli_num_rows($visualTableCheck) > 0) {
                $visualResult = mysqli_query($conn, "
                    SELECT latitude, longitude FROM visual_boundary_points
                    WHERE land_id = {$land['id']}
                    ORDER BY point_order
                ");
                while ($vpoint = mysqli_fetch_assoc($visualResult)) {
                    $visualPolygon[] = [
                        'lat' => floatval($vpoint['latitude']),
                        'lng' => floatval($vpoint['longitude'])
                    ];
                }
            }

            // Calculate polygon bounding box for debugging
            $polyBounds = null;
            if (count($polygon) >= 3) {
                $minLat = $maxLat = $polygon[0]['lat'];
                $minLng = $maxLng = $polygon[0]['lng'];
                foreach ($polygon as $pt) {
                    $minLat = min($minLat, $pt['lat']);
                    $maxLat = max($maxLat, $pt['lat']);
                    $minLng = min($minLng, $pt['lng']);
                    $maxLng = max($maxLng, $pt['lng']);
                }
                $polyBounds = [
                    'minLat' => $minLat, 'maxLat' => $maxLat,
                    'minLng' => $minLng, 'maxLng' => $maxLng
                ];
            }

            // Check if user is within polygon bounding box first (quick check)
            $inBoundingBox = false;
            if ($polyBounds) {
                $inBoundingBox = ($lat >= $polyBounds['minLat'] && $lat <= $polyBounds['maxLat'] &&
                                  $lng >= $polyBounds['minLng'] && $lng <= $polyBounds['maxLng']);
            }

            // Use multiple algorithms for accurate detection
            $isInside = false;
            $isNearby = false;
            $rayCastResult = false;
            $windingResult = false;
            $distanceToLand = null;

            if (count($polygon) >= 3) {
                // Try ray casting algorithm
                $rayCastResult = isPointInPolygon($lat, $lng, $polygon);

                // Try winding number algorithm (more reliable)
                $windingResult = isPointInPolygonWinding($lat, $lng, $polygon);

                // ONLY mark as inside if BOTH algorithms agree for maximum accuracy
                // This ensures TRUE inside detection - no false positives
                $isInside = $rayCastResult && $windingResult;

                // Always calculate distance to polygon edge (for nearby lands feature)
                $distanceToLand = getDistanceToPolygon($lat, $lng, $polygon);

                // If truly inside, distance is 0
                if ($isInside) {
                    $distanceToLand = 0;
                }

                // Determine if nearby (within 200 meters) but NOT inside
                // This shows registered lands that are close but user is outside of them
                if (!$isInside && $distanceToLand !== null && $distanceToLand <= 200) {
                    $isNearby = true;
                }
            }

            // Track checked lands for debugging
            $checkedLands[] = [
                'id' => $land['id'],
                'name' => $land['land_name'],
                'points_count' => count($polygon),
                'polygon_points' => $polygon,
                'bounds' => $polyBounds,
                'in_bounding_box' => $inBoundingBox,
                'ray_cast_result' => $rayCastResult,
                'winding_result' => $windingResult,
                'is_inside' => $isInside,
                'is_nearby' => $isNearby,
                'distance_meters' => $distanceToLand
            ];

            // Include land if inside OR nearby
            if ($isInside || $isNearby) {
                // Privacy protection
                $nameParts = explode(' ', trim($land['owner_name']));
                $maskedName = '';
                foreach ($nameParts as $part) {
                    if (strlen($part) > 0) {
                        $maskedName .= strtoupper(substr($part, 0, 1)) . '. ';
                    }
                }

                $maskedPhone = 'xxxxxx' . substr($land['owner_phone'], -4);

                $foundLands[] = [
                    'id' => $land['id'],
                    'land_id' => 'LS-' . str_pad($land['id'], 5, '0', STR_PAD_LEFT),
                    'land_name' => $land['land_name'],
                    'owner_name' => trim($maskedName),
                    'is_inside' => $isInside,
                    'is_nearby' => $isNearby,
                    'distance_meters' => $isInside ? 0 : round($distanceToLand),
                    'owner_phone' => $maskedPhone,
                    'area_sqm' => $land['area_sqm'],
                    'village' => null,
                    'district' => null,
                    'region' => null,
                    'status' => $land['status'],
                    'is_verified' => ($land['status'] === 'verified' || $land['status'] === 'approved'),
                    'verified_date' => null,
                    'confirmed_neighbors' => 0,
                    'registered_date' => date('d M Y', strtotime($land['created_at'])),
                    'polygon' => $polygon,
                    'visual_polygon' => !empty($visualPolygon) ? $visualPolygon : $polygon
                ];
            }
        }

        // Log this scan
        $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        $foundCount = count($foundLands);
        @mysqli_query($conn, "
            INSERT INTO location_scan_logs (latitude, longitude, ip_address, lands_found, scanned_at)
            VALUES ($lat, $lng, '$ip', $foundCount, NOW())
        ");

        echo json_encode([
            'success' => true,
            'found' => count($foundLands) > 0,
            'lands' => $foundLands,
            'scanned_at' => date('d M Y, H:i:s'),
            'coordinates' => ['lat' => $lat, 'lng' => $lng],
            'debug' => [
                'points_table' => $pointsTable,
                'lat_column' => $latCol,
                'lng_column' => $lngCol,
                'order_column' => $orderCol,
                'points_columns' => $pointsCols,
                'total_points_in_db' => intval($totalPoints['total']),
                'total_lands_with_points' => intval($totalPoints['land_count']),
                'points_in_box' => intval($boxCheck['cnt']),
                'land_ids_in_box' => $boxCheck['land_ids'],
                'sample_coords' => $sampleCoords,
                'lands_checked' => array_slice($checkedLands, 0, 10), // Limit to first 10 for response size
                'bounding_box' => [
                    'lat_min' => $latMin,
                    'lat_max' => $latMax,
                    'lng_min' => $lngMin,
                    'lng_max' => $lngMax
                ]
            ]
        ]);

    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'error' => 'Database error: ' . $e->getMessage()
        ]);
    }
    exit;
}

/**
 * Ray casting algorithm to check if point is inside polygon
 * Improved version with better edge case handling
 */
function isPointInPolygon($lat, $lng, $polygon) {
    $n = count($polygon);
    if ($n < 3) return false;

    $inside = false;

    for ($i = 0, $j = $n - 1; $i < $n; $j = $i++) {
        $xi = floatval($polygon[$i]['lng']);
        $yi = floatval($polygon[$i]['lat']);
        $xj = floatval($polygon[$j]['lng']);
        $yj = floatval($polygon[$j]['lat']);

        // Check if point is exactly on a vertex
        if (abs($lat - $yi) < 0.0000001 && abs($lng - $xi) < 0.0000001) {
            return true; // Point is on vertex
        }

        // Ray casting algorithm
        if ((($yi > $lat) !== ($yj > $lat)) &&
            ($lng < ($xj - $xi) * ($lat - $yi) / ($yj - $yi) + $xi)) {
            $inside = !$inside;
        }
    }

    return $inside;
}

/**
 * Check if point is inside polygon using winding number algorithm
 * More reliable for complex polygons
 */
function isPointInPolygonWinding($lat, $lng, $polygon) {
    $n = count($polygon);
    if ($n < 3) return false;

    $windingNumber = 0;

    for ($i = 0; $i < $n; $i++) {
        $x1 = floatval($polygon[$i]['lng']);
        $y1 = floatval($polygon[$i]['lat']);
        $x2 = floatval($polygon[($i + 1) % $n]['lng']);
        $y2 = floatval($polygon[($i + 1) % $n]['lat']);

        if ($y1 <= $lat) {
            if ($y2 > $lat) {
                // Upward crossing
                if (isLeft($x1, $y1, $x2, $y2, $lng, $lat) > 0) {
                    $windingNumber++;
                }
            }
        } else {
            if ($y2 <= $lat) {
                // Downward crossing
                if (isLeft($x1, $y1, $x2, $y2, $lng, $lat) < 0) {
                    $windingNumber--;
                }
            }
        }
    }

    return $windingNumber != 0;
}

/**
 * Helper function for winding number algorithm
 */
function isLeft($x1, $y1, $x2, $y2, $px, $py) {
    return (($x2 - $x1) * ($py - $y1) - ($px - $x1) * ($y2 - $y1));
}

/**
 * Calculate distance from point to nearest edge of polygon (in meters)
 */
function getDistanceToPolygon($lat, $lng, $polygon) {
    $n = count($polygon);
    if ($n < 3) return null;

    $minDistance = PHP_FLOAT_MAX;

    // Check distance to each edge of the polygon
    for ($i = 0; $i < $n; $i++) {
        $j = ($i + 1) % $n;

        $lat1 = floatval($polygon[$i]['lat']);
        $lng1 = floatval($polygon[$i]['lng']);
        $lat2 = floatval($polygon[$j]['lat']);
        $lng2 = floatval($polygon[$j]['lng']);

        // Calculate distance to this edge
        $distance = pointToLineDistance($lat, $lng, $lat1, $lng1, $lat2, $lng2);
        if ($distance < $minDistance) {
            $minDistance = $distance;
        }
    }

    return $minDistance;
}

/**
 * Calculate shortest distance from point to line segment (in meters)
 */
function pointToLineDistance($pLat, $pLng, $lat1, $lng1, $lat2, $lng2) {
    // Convert to radians
    $pLatRad = deg2rad($pLat);
    $pLngRad = deg2rad($pLng);
    $lat1Rad = deg2rad($lat1);
    $lng1Rad = deg2rad($lng1);
    $lat2Rad = deg2rad($lat2);
    $lng2Rad = deg2rad($lng2);

    // Calculate the perpendicular distance to the line
    $A = $pLatRad - $lat1Rad;
    $B = $pLngRad - $lng1Rad;
    $C = $lat2Rad - $lat1Rad;
    $D = $lng2Rad - $lng1Rad;

    $dot = $A * $C + $B * $D;
    $lenSq = $C * $C + $D * $D;

    $param = -1;
    if ($lenSq != 0) {
        $param = $dot / $lenSq;
    }

    $nearestLat = $nearestLng = 0;

    if ($param < 0) {
        $nearestLat = $lat1;
        $nearestLng = $lng1;
    } elseif ($param > 1) {
        $nearestLat = $lat2;
        $nearestLng = $lng2;
    } else {
        $nearestLat = $lat1 + $param * ($lat2 - $lat1);
        $nearestLng = $lng1 + $param * ($lng2 - $lng1);
    }

    // Calculate distance using Haversine formula
    return haversineDistance($pLat, $pLng, $nearestLat, $nearestLng);
}

/**
 * Calculate distance between two points using Haversine formula (returns meters)
 */
function haversineDistance($lat1, $lng1, $lat2, $lng2) {
    $earthRadius = 6371000; // Earth's radius in meters

    $lat1Rad = deg2rad($lat1);
    $lat2Rad = deg2rad($lat2);
    $deltaLat = deg2rad($lat2 - $lat1);
    $deltaLng = deg2rad($lng2 - $lng1);

    $a = sin($deltaLat / 2) * sin($deltaLat / 2) +
         cos($lat1Rad) * cos($lat2Rad) *
         sin($deltaLng / 2) * sin($deltaLng / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

    return $earthRadius * $c;
}

/**
 * Check if point is near polygon boundary (within tolerance)
 */
function isPointNearPolygon($lat, $lng, $polygon, $tolerance = 0.0001) {
    $n = count($polygon);
    if ($n < 3) return false;

    // Check if point is within bounding box of polygon (with tolerance)
    $minLat = $maxLat = $polygon[0]['lat'];
    $minLng = $maxLng = $polygon[0]['lng'];

    for ($i = 1; $i < $n; $i++) {
        $minLat = min($minLat, $polygon[$i]['lat']);
        $maxLat = max($maxLat, $polygon[$i]['lat']);
        $minLng = min($minLng, $polygon[$i]['lng']);
        $maxLng = max($maxLng, $polygon[$i]['lng']);
    }

    // Check if within bounding box (with tolerance)
    if ($lat >= $minLat - $tolerance && $lat <= $maxLat + $tolerance &&
        $lng >= $minLng - $tolerance && $lng <= $maxLng + $tolerance) {

        // Check distance to each edge
        for ($i = 0, $j = $n - 1; $i < $n; $j = $i++) {
            $dist = pointToLineDistance(
                $lat, $lng,
                $polygon[$i]['lat'], $polygon[$i]['lng'],
                $polygon[$j]['lat'], $polygon[$j]['lng']
            );
            if ($dist <= $tolerance) {
                return true;
            }
        }
    }

    return false;
}
?>
<!DOCTYPE html>
<html lang="sw">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scan Eneo - LandSecure</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Inter', sans-serif;
    }

    html {
        height: 100%;
        overflow-y: scroll;
        -webkit-overflow-scrolling: touch;
    }

    body {
        background: #f1f5f9;
        min-height: 100vh;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
        touch-action: pan-y;
    }

    .header {
        background: linear-gradient(135deg, #1e3a5f 0%, #0d1b2a 100%);
        padding: 20px;
        color: white;
        text-align: center;
    }

    .logo {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        margin-bottom: 8px;
    }

    .logo-icon {
        width: 40px;
        height: 40px;
        background: linear-gradient(135deg, #22c55e, #16a34a);
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
    }

    .logo-text {
        font-size: 24px;
        font-weight: 700;
    }

    .header p {
        color: rgba(255,255,255,0.7);
        font-size: 14px;
    }

    .main-content {
        padding: 20px;
        max-width: 600px;
        margin: 0 auto;
        touch-action: pan-y;
        -webkit-overflow-scrolling: touch;
    }

    .scan-card {
        background: white;
        border-radius: 16px;
        overflow: visible;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        margin-bottom: 20px;
        touch-action: pan-y;
    }

    .map-container {
        height: 300px;
        position: relative;
        overflow: hidden;
        border-radius: 16px 16px 0 0;
    }

    #map {
        height: 100%;
        width: 100%;
        z-index: 1;
        background: #e5e7eb;
    }

    /* Ensure Leaflet tiles display properly */
    .leaflet-container {
        background: #e5e7eb !important;
    }

    .leaflet-tile-pane {
        z-index: 2 !important;
    }

    .leaflet-tile {
        visibility: visible !important;
    }

    .map-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.5);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: white;
        z-index: 1000;
    }

    .map-overlay.hidden {
        display: none;
    }

    .map-overlay i {
        font-size: 48px;
        margin-bottom: 16px;
        animation: pulse 2s infinite;
    }

    @keyframes pulse {
        0%, 100% { opacity: 1; transform: scale(1); }
        50% { opacity: 0.7; transform: scale(1.1); }
    }

    .scan-actions {
        padding: 20px;
    }

    .btn {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        width: 100%;
        padding: 16px 24px;
        border: none;
        border-radius: 12px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .btn-primary {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
    }

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
    }

    .btn-success {
        background: linear-gradient(135deg, #22c55e, #16a34a);
        color: white;
    }

    .btn:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none !important;
    }

    .coordinates-display {
        background: #f8fafc;
        border-radius: 10px;
        padding: 12px 16px;
        margin-bottom: 16px;
        font-size: 13px;
        color: #64748b;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .coordinates-display i {
        color: #667eea;
    }

    .coordinates-display span {
        font-family: monospace;
        color: #1e293b;
        flex: 1;
    }

    .recenter-btn {
        width: 36px;
        height: 36px;
        border: none;
        background: linear-gradient(135deg, #22c55e, #16a34a);
        color: white;
        border-radius: 50%;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(34, 197, 94, 0.3);
    }

    .recenter-btn:hover {
        transform: scale(1.1);
        box-shadow: 0 4px 12px rgba(34, 197, 94, 0.4);
    }

    .recenter-btn:active {
        transform: scale(0.95);
    }

    .btn-group {
        display: flex;
        gap: 10px;
    }

    .btn-group .btn-primary {
        flex: 1;
    }

    .btn-secondary {
        background: linear-gradient(135deg, #64748b, #475569);
        color: white;
        width: 56px;
        min-width: 56px;
    }

    .btn-secondary:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(100, 116, 139, 0.4);
    }

    .btn-secondary.refreshing i {
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }

    /* Results */
    .results-section {
        display: none;
    }

    .results-section.visible {
        display: block;
        touch-action: pan-y;
        -webkit-overflow-scrolling: touch;
    }

    .result-header {
        padding: 20px;
        text-align: center;
        border-bottom: 1px solid #e2e8f0;
    }

    .result-icon {
        width: 70px;
        height: 70px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 16px;
        font-size: 32px;
    }

    .result-icon.found {
        background: rgba(34, 197, 94, 0.1);
        color: #22c55e;
    }

    .result-icon.not-found {
        background: rgba(239, 68, 68, 0.1);
        color: #ef4444;
    }

    .result-icon.outside-nearby {
        background: rgba(245, 158, 11, 0.1);
        color: #f59e0b;
    }

    .result-header h3 {
        font-size: 20px;
        color: #1e293b;
        margin-bottom: 4px;
    }

    .result-header p {
        color: #64748b;
        font-size: 14px;
    }

    .land-result {
        padding: 20px;
        border-bottom: 1px solid #e2e8f0;
    }

    .land-result:last-child {
        border-bottom: none;
    }

    .land-result-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16px;
        flex-wrap: wrap;
        gap: 8px;
    }

    .land-id-badge {
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        padding: 6px 14px;
        border-radius: 20px;
        font-size: 14px;
        font-weight: 700;
        letter-spacing: 0.5px;
    }

    .location-badge {
        padding: 5px 12px;
        border-radius: 15px;
        font-size: 12px;
        font-weight: 600;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }

    .location-badge.inside {
        background: linear-gradient(135deg, #22c55e, #16a34a);
        color: white;
    }

    .location-badge.nearby {
        background: linear-gradient(135deg, #f59e0b, #d97706);
        color: white;
    }

    .verification-status {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 13px;
        font-weight: 600;
    }

    .verification-status.verified {
        color: #22c55e;
    }

    .verification-status.pending {
        color: #f97316;
    }

    .land-details {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 12px;
    }

    .detail-item {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }

    .detail-label {
        font-size: 11px;
        color: #64748b;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .detail-value {
        font-size: 14px;
        font-weight: 600;
        color: #1e293b;
    }

    .view-details-btn {
        display: block;
        text-align: center;
        padding: 12px;
        background: #f8fafc;
        color: #667eea;
        text-decoration: none;
        font-weight: 600;
        font-size: 14px;
        margin-top: 16px;
        border-radius: 10px;
        transition: all 0.3s ease;
    }

    .view-details-btn:hover {
        background: #667eea;
        color: white;
    }

    .scan-another {
        padding: 20px;
        text-align: center;
    }

    .info-box {
        background: rgba(59, 130, 246, 0.1);
        border: 1px solid rgba(59, 130, 246, 0.2);
        border-radius: 12px;
        padding: 16px;
        margin: 20px;
    }

    .info-box h4 {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #1e3a5f;
        font-size: 14px;
        margin-bottom: 8px;
    }

    .info-box p {
        color: #64748b;
        font-size: 13px;
        line-height: 1.5;
    }

    .qr-scan-section {
        padding: 20px;
        border-top: 1px solid #e2e8f0;
    }

    .qr-scan-section h4 {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 15px;
        color: #1e293b;
        margin-bottom: 12px;
    }

    .qr-input-group {
        display: flex;
        gap: 10px;
    }

    .qr-input-group input {
        flex: 1;
        padding: 12px 16px;
        border: 2px solid #e2e8f0;
        border-radius: 10px;
        font-size: 14px;
        transition: all 0.3s ease;
    }

    .qr-input-group input:focus {
        outline: none;
        border-color: #667eea;
    }

    .qr-input-group button {
        padding: 12px 20px;
        background: linear-gradient(135deg, #22c55e, #16a34a);
        color: white;
        border: none;
        border-radius: 10px;
        font-weight: 600;
        cursor: pointer;
    }

    .footer-links {
        text-align: center;
        padding: 20px;
    }

    .footer-links a {
        color: #64748b;
        text-decoration: none;
        margin: 0 12px;
        font-size: 14px;
    }

    .footer-links a:hover {
        color: #667eea;
    }

    .loading-spinner {
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid rgba(255,255,255,0.3);
        border-radius: 50%;
        border-top-color: white;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        to { transform: rotate(360deg); }
    }

    /* Result Map Styles */
    .result-map-container {
        padding: 0 20px 20px 20px;
    }

    #resultMap {
        border: 2px solid #e2e8f0;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        z-index: 1;
        background: #e5e7eb;
    }

    #resultMap .leaflet-tile-pane {
        z-index: 2 !important;
    }

    .map-controls-row {
        display: flex;
        gap: 10px;
        margin-top: 12px;
        justify-content: center;
    }

    .map-control-btn {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 8px 16px;
        border: none;
        border-radius: 8px;
        font-size: 12px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
    }

    .map-control-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }

    .map-control-btn:active {
        transform: translateY(0);
    }

    .map-legend {
        display: flex;
        justify-content: center;
        gap: 20px;
        margin-top: 12px;
        flex-wrap: wrap;
    }

    .legend-item {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 12px;
        color: #64748b;
    }

    .legend-color {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        border: 2px solid white;
        box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    }

    .legend-color.verified {
        background: #22c55e;
    }

    .legend-color.pending {
        background: #f97316;
    }

    /* Pulsing user marker animation */
    .user-location-pulse {
        animation: pulse-ring 1.5s cubic-bezier(0.215, 0.61, 0.355, 1) infinite;
    }

    @keyframes pulse-ring {
        0% {
            box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.7);
        }
        70% {
            box-shadow: 0 0 0 15px rgba(102, 126, 234, 0);
        }
        100% {
            box-shadow: 0 0 0 0 rgba(102, 126, 234, 0);
        }
    }

    /* Beacon point markers on result map */
    .beacon-marker {
        background: #1e3a5f;
        color: white;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 11px;
        border: 2px solid white;
        box-shadow: 0 2px 6px rgba(0,0,0,0.3);
    }

    @media (max-width: 480px) {
        .land-details {
            grid-template-columns: 1fr;
        }

        .map-legend {
            gap: 12px;
        }
    }

    /* Live tracking marker with pulse animation */
    .live-marker-pulse {
        position: relative;
        width: 30px;
        height: 30px;
    }

    .live-marker-dot {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 16px;
        height: 16px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        border-radius: 50%;
        border: 3px solid white;
        box-shadow: 0 2px 10px rgba(0,0,0,0.3);
        z-index: 2;
    }

    .live-marker-pulse::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 30px;
        height: 30px;
        background: rgba(102, 126, 234, 0.4);
        border-radius: 50%;
        animation: live-pulse 2s ease-out infinite;
    }

    .live-marker-pulse::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 20px;
        height: 20px;
        background: rgba(102, 126, 234, 0.6);
        border-radius: 50%;
        animation: live-pulse 2s ease-out infinite 0.5s;
    }

    @keyframes live-pulse {
        0% {
            transform: translate(-50%, -50%) scale(0.8);
            opacity: 1;
        }
        100% {
            transform: translate(-50%, -50%) scale(2.5);
            opacity: 0;
        }
    }

    /* Live tracking indicator badge */
    .live-tracking-badge {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        background: linear-gradient(135deg, #22c55e, #16a34a);
        color: white;
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: 600;
        margin-left: 8px;
    }

    .live-tracking-badge .dot {
        width: 6px;
        height: 6px;
        background: white;
        border-radius: 50%;
        animation: blink 1s infinite;
    }

    @keyframes blink {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.3; }
    }

    /* Accuracy indicator colors */
    .accuracy-good { color: #22c55e; }
    .accuracy-medium { color: #f59e0b; }
    .accuracy-poor { color: #ef4444; }

    /* Scan accuracy tip */
    .scan-accuracy-tip {
        display: flex;
        align-items: center;
        gap: 10px;
        background: linear-gradient(135deg, rgba(34, 197, 94, 0.1), rgba(22, 163, 74, 0.1));
        border: 1px solid rgba(34, 197, 94, 0.3);
        border-radius: 10px;
        padding: 12px 16px;
        margin-top: 16px;
        font-size: 13px;
        color: #166534;
    }

    .scan-accuracy-tip i {
        font-size: 18px;
        color: #22c55e;
        flex-shrink: 0;
    }

    .scan-accuracy-tip span {
        line-height: 1.4;
    }

    /* Simple GPS Status */
    .gps-status-simple {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 10px 16px;
        background: rgba(102, 126, 234, 0.1);
        border-radius: 20px;
        font-size: 13px;
        color: #667eea;
        margin-bottom: 12px;
    }

    .gps-dot-indicator {
        width: 10px;
        height: 10px;
        background: #667eea;
        border-radius: 50%;
        animation: pulse-dot 1.5s infinite;
    }

    .gps-status-simple.ready {
        background: rgba(34, 197, 94, 0.1);
        color: #16a34a;
    }

    .gps-status-simple.ready .gps-dot-indicator {
        background: #22c55e;
        animation: none;
    }

    @keyframes pulse-dot {
        0%, 100% { opacity: 1; transform: scale(1); }
        50% { opacity: 0.5; transform: scale(1.2); }
    }

    /* Scanning Overlay Animation - Inside Map Only */
    .scanning-overlay {
        display: none;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.75);
        z-index: 1000;
        justify-content: center;
        align-items: center;
        border-radius: 16px;
    }

    .scanning-overlay.active {
        display: flex;
    }

    .scanner-box {
        width: 80%;
        height: 80%;
        max-width: 280px;
        max-height: 280px;
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .scanner-corners {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
    }

    .scanner-corners .corner {
        position: absolute;
        width: 40px;
        height: 40px;
        border-color: #ef4444;
        border-style: solid;
    }

    .corner.top-left {
        top: 0;
        left: 0;
        border-width: 4px 0 0 4px;
        border-radius: 8px 0 0 0;
    }

    .corner.top-right {
        top: 0;
        right: 0;
        border-width: 4px 4px 0 0;
        border-radius: 0 8px 0 0;
    }

    .corner.bottom-left {
        bottom: 0;
        left: 0;
        border-width: 0 0 4px 4px;
        border-radius: 0 0 0 8px;
    }

    .corner.bottom-right {
        bottom: 0;
        right: 0;
        border-width: 0 4px 4px 0;
        border-radius: 0 0 8px 0;
    }

    .scan-line {
        position: absolute;
        top: 10px;
        left: 10px;
        right: 10px;
        height: 3px;
        background: linear-gradient(90deg, transparent, #ef4444 20%, #ef4444 80%, transparent);
        box-shadow: 0 0 15px #ef4444, 0 0 30px #ef4444;
        animation: scan-move 2s ease-in-out infinite;
    }

    @keyframes scan-move {
        0%, 100% {
            top: 10px;
        }
        50% {
            top: calc(100% - 13px);
        }
    }

    .scanner-text {
        text-align: center;
        color: white;
        z-index: 1;
    }

    .scanner-text i {
        font-size: 36px;
        color: #ef4444;
        margin-bottom: 10px;
        display: block;
    }

    .scanner-text p {
        font-size: 16px;
        font-weight: 600;
        margin: 0 0 4px 0;
    }

    .scanner-text small {
        font-size: 12px;
        color: #9ca3af;
    }
    </style>
</head>
<body>
    <div class="header">
        <div class="logo">
            <div class="logo-icon">
                <i class="fas fa-map-marker-alt"></i>
            </div>
            <span class="logo-text">LandSecure</span>
        </div>
        <p>Angalia umiliki wa ardhi kwa eneo ulilosimama</p>
    </div>

    <div class="main-content">
        <!-- Scan Card -->
        <div class="scan-card" id="scanCard">
            <div class="map-container">
                <div id="map"></div>
                <div class="map-overlay" id="mapOverlay">
                    <i class="fas fa-satellite"></i>
                    <p>Inapata eneo lako...</p>
                </div>
                <!-- Scanning Animation Overlay - Inside Map -->
                <div class="scanning-overlay" id="scanningOverlay">
                    <div class="scanner-box">
                        <div class="scanner-corners">
                            <span class="corner top-left"></span>
                            <span class="corner top-right"></span>
                            <span class="corner bottom-left"></span>
                            <span class="corner bottom-right"></span>
                        </div>
                        <div class="scan-line"></div>
                        <div class="scanner-text">
                            <i class="fas fa-satellite-dish fa-pulse"></i>
                            <p>Inascan eneo...</p>
                            <small>Tafadhali subiri</small>
                        </div>
                    </div>
                </div>
            </div>

            <div class="scan-actions">
                <div class="gps-status-simple" id="gpsStatusSimple">
                    <span class="gps-dot-indicator"></span>
                    <span id="gpsStatusText">Inapata eneo...</span>
                </div>

                <div class="btn-group">
                    <button class="btn btn-primary" id="scanBtn" onclick="startScan()">
                        <i class="fas fa-search-location"></i>
                        Scan Eneo Hili
                    </button>
                    <button class="btn btn-secondary" id="refreshGpsBtn" onclick="refreshGPS()" title="Refresh GPS">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>

                <div class="scan-accuracy-tip">
                    <i class="fas fa-bullseye"></i>
                    <span>For accuracy scanning stand at center of the land / Kaa katikati ya Eneo</span>
                </div>
            </div>

            <div class="info-box">
                <h4><i class="fas fa-info-circle"></i> Jinsi ya Kutumia</h4>
                <p>
                    1. Ruhusu programu kupata eneo lako<br>
                    2. Bonyeza "Scan Eneo Hili"<br>
                    3. Utaona kama eneo hili lina mmiliki aliyesajiliwa
                </p>
            </div>

            <div class="qr-scan-section">
                <h4><i class="fas fa-qrcode"></i> Au Ingiza Nambari ya Ardhi</h4>
                <div class="qr-input-group">
                    <input type="text" id="landIdInput" placeholder="Mfano: LS-00123">
                    <button onclick="lookupLandId()">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- Results Section -->
        <div class="scan-card results-section" id="resultsSection">
            <div class="result-header" id="resultHeader">
                <div class="result-icon" id="resultIcon">
                    <i class="fas fa-check"></i>
                </div>
                <h3 id="resultTitle">Ardhi Imepatikana!</h3>
                <p id="resultSubtitle">Eneo hili lina mmiliki aliyesajiliwa</p>
            </div>

            <!-- Results Map showing land polygon and user location -->
            <div class="result-map-container" id="resultMapContainer" style="display: none;">
                <div id="resultMap" style="height: 300px; width: 100%; border-radius: 12px;"></div>
                <div class="map-controls-row">
                    <button class="map-control-btn" onclick="centerOnUserLocation()" title="Rudi kwenye eneo lako">
                        <i class="fas fa-location-arrow"></i> Eneo Langu
                    </button>
                    <button class="map-control-btn" onclick="fitAllOnMap()" title="Onyesha yote">
                        <i class="fas fa-expand"></i> Onyesha Yote
                    </button>
                </div>
                <div class="map-legend">
                    <span class="legend-item"><span class="legend-color" style="background: linear-gradient(135deg, #667eea, #764ba2);"></span> Eneo Lako</span>
                    <span class="legend-item"><span class="legend-color verified"></span> Ardhi Imethibitishwa</span>
                </div>
            </div>

            <div id="landResults">
                <!-- Land results will be inserted here -->
            </div>

            <div class="scan-another">
                <button class="btn btn-primary" onclick="resetScan()">
                    <i class="fas fa-redo"></i>
                    Scan Tena
                </button>
            </div>
        </div>
    </div>

    <div class="footer-links">
        <a href="home"><i class="fas fa-home"></i> Nyumbani</a>
        <a href="login"><i class="fas fa-sign-in-alt"></i> Ingia</a>
        <a href="register"><i class="fas fa-user-plus"></i> Jisajili</a>
    </div>

    <script>
    let map;
    let resultMap = null;
    let userMarker;
    let resultUserMarker = null;
    let currentLat = null;
    let currentLng = null;
    let currentAccuracy = null;
    let foundPolygons = [];
    let resultPolygons = [];
    let resultMarkers = [];
    let liveTrackingId = null;
    let accuracyCircle = null;
    let isFirstLocation = true;

    // Initialize map
    document.addEventListener('DOMContentLoaded', function() {
        // Wait a moment for DOM to be fully ready
        setTimeout(function() {
            try {
                // Check if map container exists and has dimensions
                const mapContainer = document.getElementById('map');
                if (!mapContainer) {
                    console.error('Map container not found');
                    return;
                }

                // Default to Tanzania center
                map = L.map('map', {
                    center: [-6.369028, 34.888822],
                    zoom: 6,
                    zoomControl: true
                });

                // Google Maps layers (using mt subdomains for better reliability)
                const googleHybrid = L.tileLayer('https://mt{s}.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', {
                    maxZoom: 20,
                    subdomains: '0123',
                    attribution: '&copy; Google Maps'
                });

                const googleSatellite = L.tileLayer('https://mt{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
                    maxZoom: 20,
                    subdomains: '0123',
                    attribution: '&copy; Google Maps'
                });

                const googleStreets = L.tileLayer('https://mt{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
                    maxZoom: 20,
                    subdomains: '0123',
                    attribution: '&copy; Google Maps'
                });

                const googleTerrain = L.tileLayer('https://mt{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}', {
                    maxZoom: 20,
                    subdomains: '0123',
                    attribution: '&copy; Google Maps'
                });

                const esriSatellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
                    maxZoom: 19,
                    attribution: '&copy; Esri'
                });

                const osmStreet = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '&copy; OpenStreetMap',
                    maxZoom: 19,
                    crossOrigin: true
                });

                // Add Google Hybrid as default (best GPS alignment)
                googleHybrid.addTo(map);

                // Layer control with all options
                L.control.layers({
                    "Google Hybrid": googleHybrid,
                    "Google Satellite": googleSatellite,
                    "Google Streets": googleStreets,
                    "Google Terrain": googleTerrain,
                    "Esri Satellite": esriSatellite,
                    "OpenStreetMap": osmStreet
                }, null, { position: 'topright' }).addTo(map);

                // Force map to recalculate size
                setTimeout(function() {
                    map.invalidateSize();
                }, 100);

                // Setup click handler now that map is ready
                setupMapClickHandler();

                // Auto-start live GPS tracking on page load
                startLiveTracking();
            } catch (e) {
                console.error('Map initialization error:', e);
            }
        }, 100);
    });

    let gpsRetryCount = 0;
    const maxRetries = 3;

    // Start continuous live tracking on page load
    function startLiveTracking() {
        const overlay = document.getElementById('mapOverlay');
        overlay.classList.remove('hidden');
        overlay.innerHTML = '<i class="fas fa-satellite"></i><p>Inapata eneo lako...</p>';

        if (!navigator.geolocation) {
            showGPSError('GPS haipo kwenye kifaa hiki');
            return;
        }

        // Stop any existing tracking
        if (liveTrackingId) {
            navigator.geolocation.clearWatch(liveTrackingId);
        }

        // Use watchPosition for CONTINUOUS live updates
        liveTrackingId = navigator.geolocation.watchPosition(
            function(position) {
                currentLat = position.coords.latitude;
                currentLng = position.coords.longitude;
                currentAccuracy = position.coords.accuracy;

                // Only zoom to location on first position
                if (isFirstLocation) {
                    map.setView([currentLat, currentLng], 18);
                    isFirstLocation = false;
                    document.getElementById('mapOverlay').classList.add('hidden');
                }

                // Update or create user marker with pulsing animation
                if (userMarker) {
                    userMarker.setLatLng([currentLat, currentLng]);
                } else {
                    userMarker = L.marker([currentLat, currentLng], {
                        icon: L.divIcon({
                            className: 'user-marker-live',
                            html: `<div class="live-marker-pulse">
                                <div class="live-marker-dot"></div>
                            </div>`,
                            iconSize: [30, 30],
                            iconAnchor: [15, 15]
                        }),
                        zIndexOffset: 1000
                    }).addTo(map);
                    userMarker.bindPopup('<strong>Eneo Lako</strong><br><small>Live tracking active</small>');
                }

                // Update or create accuracy circle
                if (accuracyCircle) {
                    accuracyCircle.setLatLng([currentLat, currentLng]);
                    accuracyCircle.setRadius(currentAccuracy);
                } else {
                    accuracyCircle = L.circle([currentLat, currentLng], {
                        radius: currentAccuracy,
                        color: '#667eea',
                        fillColor: '#667eea',
                        fillOpacity: 0.1,
                        weight: 1
                    }).addTo(map);
                }

                // Update GPS status (simple - no coordinates shown)
                updateGpsStatus(true);

                gpsRetryCount = 0;
            },
            function(error) {
                let errorMsg = '';
                switch(error.code) {
                    case error.PERMISSION_DENIED:
                        errorMsg = 'GPS imezuiwa. Bonyeza kitufe hapa chini kuruhusu.';
                        break;
                    case error.POSITION_UNAVAILABLE:
                        errorMsg = 'Eneo haliwezi kupatikana. Hakikisha GPS imewashwa.';
                        break;
                    case error.TIMEOUT:
                        errorMsg = 'Muda umekwisha. Inajaribu tena...';
                        // Auto retry on timeout
                        if (gpsRetryCount < maxRetries) {
                            gpsRetryCount++;
                            setTimeout(startLiveTracking, 2000);
                            return;
                        }
                        errorMsg = 'Haikuweza kupata eneo. Jaribu tena.';
                        break;
                    default:
                        errorMsg = 'Kosa lisilojulikana. Jaribu tena.';
                }
                showGPSError(errorMsg);
            },
            {
                enableHighAccuracy: true,
                timeout: 15000,
                maximumAge: 0 // Always get fresh position
            }
        );
    }

    // Update GPS status display (simple, no coordinates)
    function updateGpsStatus(ready) {
        const statusEl = document.getElementById('gpsStatusSimple');
        const statusText = document.getElementById('gpsStatusText');

        if (ready) {
            statusEl.classList.add('ready');
            statusText.textContent = 'Eneo limepatikana ✓';
        } else {
            statusEl.classList.remove('ready');
            statusText.textContent = 'Inapata eneo...';
        }
    }

    // Legacy function for compatibility
    function requestGPSLocation() {
        startLiveTracking();
    }

    function showGPSError(message) {
        const overlay = document.getElementById('mapOverlay');
        overlay.innerHTML = `
            <i class="fas fa-map-marker-alt" style="animation: none; color: #f97316;"></i>
            <p style="margin-bottom: 16px;">${message}</p>
            <button onclick="requestGPSLocation()" style="
                background: linear-gradient(135deg, #22c55e, #16a34a);
                color: white;
                border: none;
                padding: 12px 24px;
                border-radius: 10px;
                font-weight: 600;
                cursor: pointer;
                display: flex;
                align-items: center;
                gap: 8px;
            ">
                <i class="fas fa-sync-alt"></i> Jaribu Kupata Eneo Tena
            </button>
        `;
    }

    // Recenter map to current GPS location
    function recenterMap() {
        if (currentLat && currentLng) {
            map.setView([currentLat, currentLng], 18);
            if (userMarker) {
                userMarker.setLatLng([currentLat, currentLng]);
            }
        } else {
            refreshGPS();
        }
    }

    // Refresh GPS location - forces immediate update and recenters map
    function refreshGPS() {
        const btn = document.getElementById('refreshGpsBtn');
        btn.classList.add('refreshing');
        btn.disabled = true;

        // Clear previous polygons if any
        foundPolygons.forEach(p => map.removeLayer(p));
        foundPolygons = [];

        // Request fresh GPS location immediately
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                function(position) {
                    currentLat = position.coords.latitude;
                    currentLng = position.coords.longitude;
                    currentAccuracy = position.coords.accuracy;

                    // Always center map on refresh
                    map.setView([currentLat, currentLng], 18);

                    // Update marker
                    if (userMarker) {
                        userMarker.setLatLng([currentLat, currentLng]);
                    } else {
                        userMarker = L.marker([currentLat, currentLng], {
                            icon: L.divIcon({
                                className: 'user-marker-live',
                                html: `<div class="live-marker-pulse">
                                    <div class="live-marker-dot"></div>
                                </div>`,
                                iconSize: [30, 30],
                                iconAnchor: [15, 15]
                            }),
                            zIndexOffset: 1000
                        }).addTo(map);
                    }

                    // Update accuracy circle
                    if (accuracyCircle) {
                        accuracyCircle.setLatLng([currentLat, currentLng]);
                        accuracyCircle.setRadius(currentAccuracy);
                    } else {
                        accuracyCircle = L.circle([currentLat, currentLng], {
                            radius: currentAccuracy,
                            color: '#667eea',
                            fillColor: '#667eea',
                            fillOpacity: 0.1,
                            weight: 1
                        }).addTo(map);
                    }

                    document.getElementById('coordsDisplay').style.display = 'flex';
                    updateCoordsDisplay();

                    btn.classList.remove('refreshing');
                    btn.disabled = false;

                    // Restart live tracking if it was stopped
                    if (!liveTrackingId) {
                        startLiveTracking();
                    }
                },
                function(error) {
                    btn.classList.remove('refreshing');
                    btn.disabled = false;
                    alert('Imeshindwa kupata eneo. Hakikisha GPS imewashwa.');
                },
                {
                    enableHighAccuracy: true,
                    timeout: 10000,
                    maximumAge: 0
                }
            );
        } else {
            btn.classList.remove('refreshing');
            btn.disabled = false;
            alert('GPS haipo kwenye kifaa hiki');
        }
    }

    // Allow clicking on map to set location - wrapped in function to be called after map init
    function setupMapClickHandler() {
        if (!map) return;
        map.on('click', function(e) {
            currentLat = e.latlng.lat;
            currentLng = e.latlng.lng;

            if (userMarker) {
                userMarker.setLatLng([currentLat, currentLng]);
            } else {
                userMarker = L.marker([currentLat, currentLng], {
                    icon: L.divIcon({
                        className: 'user-marker',
                        html: '<div style="background: linear-gradient(135deg, #667eea, #764ba2); width: 24px; height: 24px; border-radius: 50%; border: 3px solid white; box-shadow: 0 2px 10px rgba(0,0,0,0.3);"></div>',
                        iconSize: [24, 24],
                        iconAnchor: [12, 12]
                    })
                }).addTo(map);
            }

            document.getElementById('mapOverlay').classList.add('hidden');
            document.getElementById('coordsDisplay').style.display = 'flex';
            document.getElementById('coordsText').textContent =
                currentLat.toFixed(6) + '°, ' + currentLng.toFixed(6) + '°';
        });
    }

    function startScan() {
        if (!currentLat || !currentLng) {
            alert('Tafadhali subiri eneo lipatikane au bonyeza kwenye ramani.');
            return;
        }

        const btn = document.getElementById('scanBtn');
        const scanOverlay = document.getElementById('scanningOverlay');

        btn.disabled = true;
        btn.innerHTML = '<span class="loading-spinner"></span> Inatafuta...';

        // Show scanning animation
        scanOverlay.classList.add('active');
        const scanStartTime = Date.now();
        const MIN_SCAN_DURATION = 4000; // Minimum 4 seconds for scanning animation

        // Send request to check location
        fetch('scan-location', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=check_location&lat=' + currentLat + '&lng=' + currentLng
        })
        .then(response => response.json())
        .then(data => {
            // Calculate remaining time to show animation
            const elapsed = Date.now() - scanStartTime;
            const remainingTime = Math.max(0, MIN_SCAN_DURATION - elapsed);

            // Wait for minimum scan duration before showing results
            setTimeout(() => {
                // Hide scanning animation
                scanOverlay.classList.remove('active');

                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-search-location"></i> Scan Eneo Hili';

                // Log debug info to console
                console.log('=== SCAN DEBUG INFO ===');
                console.log('Your coordinates:', data.coordinates);
                console.log('Debug data:', data.debug);
                if (data.debug) {
                    console.log('Points table:', data.debug.points_table);
                    console.log('Total points in DB:', data.debug.total_points_in_db);
                    console.log('Total lands with points:', data.debug.total_lands_with_points);
                    console.log('Points in bounding box:', data.debug.points_in_box);
                    console.log('Land IDs in box:', data.debug.land_ids_in_box);
                    console.log('Sample coords from DB:', data.debug.sample_coords);
                    console.log('Lands checked:', data.debug.lands_checked);
                }
                console.log('======================');

                if (data.success) {
                    showResults(data);
                } else {
                    alert('Kosa: ' + (data.error || 'Imeshindwa kutafuta'));
                }
            }, remainingTime);
        })
        .catch(error => {
            // Calculate remaining time even on error
            const elapsed = Date.now() - scanStartTime;
            const remainingTime = Math.max(0, MIN_SCAN_DURATION - elapsed);

            setTimeout(() => {
                // Hide scanning animation
                scanOverlay.classList.remove('active');

                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-search-location"></i> Scan Eneo Hili';
                alert('Kosa la mtandao. Jaribu tena.');
            }, remainingTime);
        });
    }

    function showResults(data) {
        document.getElementById('scanCard').style.display = 'none';
        document.getElementById('resultsSection').classList.add('visible');

        // Fix for mobile scroll issues (Vivo, Oppo, etc.)
        // Force repaint and enable scrolling
        setTimeout(function() {
            document.body.style.overflow = 'auto';
            document.documentElement.style.overflow = 'auto';
            window.scrollTo(0, 0);
            // Trigger reflow
            document.body.offsetHeight;
        }, 100);

        const resultIcon = document.getElementById('resultIcon');
        const resultTitle = document.getElementById('resultTitle');
        const resultSubtitle = document.getElementById('resultSubtitle');
        const landResults = document.getElementById('landResults');
        const resultMapContainer = document.getElementById('resultMapContainer');

        // Clear previous polygons from main map
        foundPolygons.forEach(p => map.removeLayer(p));
        foundPolygons = [];

        // Count inside vs nearby
        const insideCount = data.lands ? data.lands.filter(l => l.is_inside).length : 0;
        const nearbyCount = data.lands ? data.lands.filter(l => l.is_nearby && !l.is_inside).length : 0;

        if (data.found && data.lands.length > 0 && insideCount > 0) {
            // User is INSIDE at least one land
            resultIcon.className = 'result-icon found';
            resultIcon.innerHTML = '<i class="fas fa-check-circle"></i>';
            resultTitle.textContent = 'Ardhi Imepatikana!';

            let subtitleText = '';
            if (insideCount > 0 && nearbyCount > 0) {
                subtitleText = `Uko ndani ya ardhi ${insideCount}, na karibu na ardhi ${nearbyCount}`;
            } else if (insideCount > 0) {
                subtitleText = `Uko ndani ya ardhi ${insideCount} iliyosajiliwa`;
            }
            resultSubtitle.textContent = subtitleText;

            // Show the result map container first
            resultMapContainer.style.display = 'block';

            // Initialize result map after container is visible and rendered
            // Use a longer timeout to ensure DOM is ready
            setTimeout(() => {
                initResultMap(data);
            }, 300);

            let html = '';
            data.lands.forEach((land, index) => {
                // Determine location status badge
                let locationBadge = '';
                if (land.is_inside) {
                    locationBadge = '<span class="location-badge inside"><i class="fas fa-map-marker-alt"></i> Uko Ndani</span>';
                } else if (land.is_nearby) {
                    locationBadge = `<span class="location-badge nearby"><i class="fas fa-location-arrow"></i> Karibu (${land.distance_meters}m)</span>`;
                }

                html += `
                    <div class="land-result" onclick="focusLandOnMap(${index})" style="cursor: pointer;">
                        <div class="land-result-header">
                            <span class="land-id-badge">${land.land_id}</span>
                            ${locationBadge}
                            ${land.is_verified ? `<span class="verification-status verified">
                                <i class="fas fa-check-circle"></i>
                                Imethibitishwa
                            </span>` : ''}
                        </div>
                        <div class="land-details">
                            <div class="detail-item">
                                <span class="detail-label">Mmiliki</span>
                                <span class="detail-value">${land.owner_name}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Simu</span>
                                <span class="detail-value">${land.owner_phone}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Jina la Ardhi</span>
                                <span class="detail-value">${land.land_name}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Ukubwa</span>
                                <span class="detail-value">${land.area_sqm ? land.area_sqm.toLocaleString() + ' m²' : '-'}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Eneo</span>
                                <span class="detail-value">${land.village || '-'}${land.district ? ', ' + land.district : ''}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Ilisajiliwa</span>
                                <span class="detail-value">${land.registered_date}</span>
                            </div>
                        </div>
                        <a href="verify-land?id=${land.id}" class="view-details-btn">
                            <i class="fas fa-eye"></i> Tazama Zaidi
                        </a>
                    </div>
                `;
            });

            landResults.innerHTML = html;

        } else if (nearbyCount > 0 && data.lands && data.lands.length > 0) {
            // User is OUTSIDE but there are NEARBY lands (within 200m)
            resultIcon.className = 'result-icon outside-nearby';
            resultIcon.innerHTML = '<i class="fas fa-map-marker-alt"></i>';
            resultTitle.textContent = 'Uko Nje ya Eneo';
            resultSubtitle.textContent = `Lakini kuna ardhi ${nearbyCount} zilizosajiliwa karibu nawe`;

            // Show the result map with nearby lands
            resultMapContainer.style.display = 'block';

            // Initialize result map after container is visible
            setTimeout(() => {
                initResultMap(data);
            }, 300);

            // Show warning banner first, then nearby lands
            let html = `
                <div style="padding: 16px 20px; background: rgba(245, 158, 11, 0.1); border-bottom: 1px solid rgba(245, 158, 11, 0.2);">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <i class="fas fa-exclamation-triangle" style="font-size: 24px; color: #f59e0b;"></i>
                        <div>
                            <h4 style="color: #b45309; font-size: 15px; margin: 0 0 4px 0;">Uko Nje ya Eneo Lolote</h4>
                            <p style="color: #92400e; font-size: 13px; margin: 0;">Haupo ndani ya ardhi yoyote, lakini ardhi zifuatazo zipo karibu nawe:</p>
                        </div>
                    </div>
                </div>
            `;

            data.lands.forEach((land, index) => {
                let locationBadge = `<span class="location-badge nearby"><i class="fas fa-location-arrow"></i> Karibu (${land.distance_meters}m)</span>`;

                html += `
                    <div class="land-result" onclick="focusLandOnMap(${index})" style="cursor: pointer;">
                        <div class="land-result-header">
                            <span class="land-id-badge">${land.land_id}</span>
                            ${locationBadge}
                            ${land.is_verified ? `<span class="verification-status verified">
                                <i class="fas fa-check-circle"></i>
                                Imethibitishwa
                            </span>` : ''}
                        </div>
                        <div class="land-details">
                            <div class="detail-item">
                                <span class="detail-label">Mmiliki</span>
                                <span class="detail-value">${land.owner_name}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Simu</span>
                                <span class="detail-value">${land.owner_phone}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Jina la Ardhi</span>
                                <span class="detail-value">${land.land_name}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Ukubwa</span>
                                <span class="detail-value">${land.area_sqm ? land.area_sqm.toLocaleString() + ' m²' : '-'}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Eneo</span>
                                <span class="detail-value">${land.village || '-'}${land.district ? ', ' + land.district : ''}</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Ilisajiliwa</span>
                                <span class="detail-value">${land.registered_date}</span>
                            </div>
                        </div>
                        <a href="verify-land?id=${land.id}" class="view-details-btn">
                            <i class="fas fa-eye"></i> Tazama Zaidi
                        </a>
                    </div>
                `;
            });

            landResults.innerHTML = html;

        } else {
            // User is OUTSIDE and NO lands nearby at all
            resultIcon.className = 'result-icon not-found';
            resultIcon.innerHTML = '<i class="fas fa-map-marker-alt" style="color: #ef4444;"></i>';
            resultTitle.textContent = 'Uko Nje ya Eneo';
            resultSubtitle.textContent = 'Hakuna ardhi iliyosajiliwa kwenye eneo hili';

            // Hide result map when no land found
            resultMapContainer.style.display = 'none';

            landResults.innerHTML = `
                <div style="padding: 30px; text-align: center;">
                    <div style="background: rgba(239, 68, 68, 0.1); border: 2px solid rgba(239, 68, 68, 0.3); border-radius: 16px; padding: 24px; margin-bottom: 20px;">
                        <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #ef4444; margin-bottom: 16px; display: block;"></i>
                        <h4 style="color: #dc2626; font-size: 18px; margin-bottom: 8px;">Uko Nje ya Eneo Lolote Lililosajiliwa</h4>
                        <p style="color: #64748b; font-size: 14px;">
                            Eneo unalolosimama halipo ndani ya ardhi yoyote iliyosajiliwa kwenye LandSecure.
                        </p>
                    </div>
                    <p style="color: #64748b; margin-bottom: 16px; font-size: 14px;">
                        <strong>Sababu zinazowezekana:</strong>
                    </p>
                    <ul style="text-align: left; color: #64748b; padding-left: 20px; margin-bottom: 20px; font-size: 13px;">
                        <li style="margin-bottom: 8px;"><i class="fas fa-user-slash" style="color: #f97316; margin-right: 8px;"></i> Mmiliki wa ardhi hajaisajili bado</li>
                        <li style="margin-bottom: 8px;"><i class="fas fa-landmark" style="color: #3b82f6; margin-right: 8px;"></i> Eneo hili ni ardhi ya serikali</li>
                        <li style="margin-bottom: 8px;"><i class="fas fa-ruler-combined" style="color: #8b5cf6; margin-right: 8px;"></i> Ardhi haijapimwa rasmi</li>
                        <li style="margin-bottom: 8px;"><i class="fas fa-satellite" style="color: #06b6d4; margin-right: 8px;"></i> GPS accuracy issue - jaribu tena</li>
                    </ul>
                    <div style="border-top: 1px solid #e2e8f0; padding-top: 20px;">
                        <p style="color: #1e293b; font-weight: 600; margin-bottom: 12px;">Je, una ardhi hapa?</p>
                        <a href="register" style="display: inline-flex; align-items: center; gap: 8px; background: linear-gradient(135deg, #22c55e, #16a34a); color: white; text-decoration: none; font-weight: 600; padding: 12px 24px; border-radius: 10px;">
                            <i class="fas fa-plus"></i> Sajili Ardhi Yako Sasa
                        </a>
                    </div>
                </div>
            `;
        }
    }

    // Store found lands for map interaction
    let foundLandsData = [];

    function initResultMap(data) {
        // Store lands data for later use
        foundLandsData = data.lands;

        // Clear previous result map if exists
        if (resultMap) {
            resultMap.remove();
            resultMap = null;
        }

        // Clear arrays
        resultPolygons = [];
        resultMarkers = [];

        // Ensure we have valid coordinates
        const mapLat = currentLat || (data.coordinates ? data.coordinates.lat : -6.369028);
        const mapLng = currentLng || (data.coordinates ? data.coordinates.lng : 34.888822);

        // Create new result map with explicit options
        resultMap = L.map('resultMap', {
            center: [mapLat, mapLng],
            zoom: 18,
            zoomControl: true
        });

        // Google Maps layers (using mt subdomains for better reliability)
        const resultGoogleHybrid = L.tileLayer('https://mt{s}.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', {
            maxZoom: 20,
            subdomains: '0123',
            attribution: '&copy; Google Maps'
        });

        const resultGoogleSatellite = L.tileLayer('https://mt{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
            maxZoom: 20,
            subdomains: '0123',
            attribution: '&copy; Google Maps'
        });

        const resultGoogleStreets = L.tileLayer('https://mt{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
            maxZoom: 20,
            subdomains: '0123',
            attribution: '&copy; Google Maps'
        });

        const resultGoogleTerrain = L.tileLayer('https://mt{s}.google.com/vt/lyrs=p&x={x}&y={y}&z={z}', {
            maxZoom: 20,
            subdomains: '0123',
            attribution: '&copy; Google Maps'
        });

        const resultEsriSatellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
            maxZoom: 19,
            attribution: '&copy; Esri'
        });

        const resultOsmStreet = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap',
            maxZoom: 19,
            crossOrigin: true
        });

        // Add Google Hybrid as default (best GPS alignment)
        resultGoogleHybrid.addTo(resultMap);

        // Layer control with all options
        L.control.layers({
            "Google Hybrid": resultGoogleHybrid,
            "Google Satellite": resultGoogleSatellite,
            "Google Streets": resultGoogleStreets,
            "Google Terrain": resultGoogleTerrain,
            "Esri Satellite": resultEsriSatellite,
            "OpenStreetMap": resultOsmStreet
        }, null, { position: 'topright' }).addTo(resultMap);

        // Force map to recalculate size after container is visible
        setTimeout(() => {
            if (resultMap) {
                resultMap.invalidateSize();
            }
        }, 200);

        // Add user location marker with pulsing animation
        const userIcon = L.divIcon({
            className: 'user-location-marker',
            html: `<div class="user-location-pulse" style="
                background: linear-gradient(135deg, #667eea, #764ba2);
                width: 20px;
                height: 20px;
                border-radius: 50%;
                border: 3px solid white;
                box-shadow: 0 2px 10px rgba(0,0,0,0.3);
            "></div>`,
            iconSize: [20, 20],
            iconAnchor: [10, 10]
        });

        resultUserMarker = L.marker([mapLat, mapLng], { icon: userIcon, zIndexOffset: 1000 })
            .addTo(resultMap)
            .bindPopup('<strong>Eneo Lako</strong><br>Upo hapa sasa');

        // Add land polygons with beacon point markers
        data.lands.forEach((land, landIndex) => {
            if (land.polygon && land.polygon.length >= 3) {
                const gpsLatlngs = land.polygon.map(p => [p.lat, p.lng]);
                const visualLatlngs = land.visual_polygon && land.visual_polygon.length >= 3
                    ? land.visual_polygon.map(p => [p.lat, p.lng])
                    : gpsLatlngs;
                const isVerified = land.is_verified;

                // Draw GPS polygon (dashed blue line, no fill)
                const gpsPolygon = L.polygon(gpsLatlngs, {
                    color: '#667eea',
                    weight: 2,
                    opacity: 0.7,
                    fill: false,
                    dashArray: '6, 6'
                }).addTo(resultMap);
                resultPolygons.push(gpsPolygon);

                // Draw Visual polygon (solid orange line, no fill)
                const visualPolygon = L.polygon(visualLatlngs, {
                    color: '#f59e0b',
                    weight: 3,
                    opacity: 1,
                    fill: false
                }).addTo(resultMap);
                resultPolygons.push(visualPolygon);

                // Add popup to visual polygon
                visualPolygon.bindPopup(`
                    <div style="text-align: center;">
                        <strong style="font-size: 14px;">${land.land_name}</strong><br>
                        <span style="color: #64748b; font-size: 12px;">${land.land_id}</span><br>
                        ${isVerified ? `<span style="color: #22c55e; font-size: 11px;">✓ Imethibitishwa</span><br>` : ''}
                        <span style="color: #64748b; font-size: 11px;">Mmiliki: ${land.owner_name}</span>
                    </div>
                `);

                // Add beacon point markers (use GPS points for markers)
                land.polygon.forEach((point, pointIndex) => {
                    const beaconIcon = L.divIcon({
                        className: 'beacon-point-marker',
                        html: `<div class="beacon-marker">${pointIndex + 1}</div>`,
                        iconSize: [24, 24],
                        iconAnchor: [12, 12]
                    });

                    const marker = L.marker([point.lat, point.lng], { icon: beaconIcon })
                        .addTo(resultMap)
                        .bindPopup(`<strong>GPS Point ${pointIndex + 1}</strong><br>
                            Lat: ${point.lat.toFixed(6)}<br>
                            Lng: ${point.lng.toFixed(6)}`);

                    resultMarkers.push(marker);
                });
            }
        });

        // Fit map bounds to show all polygons and user location
        const allPoints = [];
        allPoints.push([mapLat, mapLng]);

        data.lands.forEach(land => {
            if (land.polygon) {
                land.polygon.forEach(p => allPoints.push([p.lat, p.lng]));
            }
        });

        if (allPoints.length > 1) {
            const bounds = L.latLngBounds(allPoints);
            // Wait for map to be fully loaded then fit bounds
            setTimeout(() => {
                if (resultMap) {
                    resultMap.invalidateSize();
                    resultMap.fitBounds(bounds, { padding: [30, 30] });
                }
            }, 300);
        }

        // Start live location updates on result map
        startLiveLocationUpdates();
    }

    // Live location updates for result map
    let liveWatchId = null;

    function startLiveLocationUpdates() {
        if (!navigator.geolocation) return;

        // Clear any existing watch
        if (liveWatchId) {
            navigator.geolocation.clearWatch(liveWatchId);
        }

        liveWatchId = navigator.geolocation.watchPosition(
            function(position) {
                currentLat = position.coords.latitude;
                currentLng = position.coords.longitude;

                // Update marker on result map
                if (resultUserMarker && resultMap) {
                    resultUserMarker.setLatLng([currentLat, currentLng]);
                }

                // Update marker on main map
                if (userMarker) {
                    userMarker.setLatLng([currentLat, currentLng]);
                }

                // Update coordinates display
                document.getElementById('coordsText').textContent =
                    currentLat.toFixed(6) + '°, ' + currentLng.toFixed(6) + '°';
            },
            function(error) {
                console.log('Live GPS error:', error);
            },
            {
                enableHighAccuracy: true,
                maximumAge: 5000,
                timeout: 10000
            }
        );
    }

    function stopLiveLocationUpdates() {
        if (liveWatchId) {
            navigator.geolocation.clearWatch(liveWatchId);
            liveWatchId = null;
        }
    }

    // Focus on a specific land polygon when clicked
    function focusLandOnMap(landIndex) {
        if (!resultMap || !foundLandsData[landIndex]) return;

        const land = foundLandsData[landIndex];
        if (land.polygon && land.polygon.length >= 3) {
            const latlngs = land.polygon.map(p => [p.lat, p.lng]);
            const bounds = L.latLngBounds(latlngs);
            resultMap.fitBounds(bounds, { padding: [50, 50] });

            // Open polygon popup
            if (resultPolygons[landIndex]) {
                resultPolygons[landIndex].openPopup();
            }
        }
    }

    // Center map on user's current location
    function centerOnUserLocation() {
        if (!resultMap || !currentLat || !currentLng) return;

        resultMap.setView([currentLat, currentLng], 18);

        if (resultUserMarker) {
            resultUserMarker.openPopup();
        }
    }

    // Fit all polygons and user location on map
    function fitAllOnMap() {
        if (!resultMap || foundLandsData.length === 0) return;

        const allPoints = [];
        allPoints.push([currentLat, currentLng]);

        foundLandsData.forEach(land => {
            if (land.polygon) {
                land.polygon.forEach(p => allPoints.push([p.lat, p.lng]));
            }
        });

        if (allPoints.length > 1) {
            const bounds = L.latLngBounds(allPoints);
            resultMap.fitBounds(bounds, { padding: [30, 30] });
        }
    }

    function resetScan() {
        document.getElementById('scanCard').style.display = 'block';
        document.getElementById('resultsSection').classList.remove('visible');
        document.getElementById('resultMapContainer').style.display = 'none';

        // Clear polygons from main map
        foundPolygons.forEach(p => map.removeLayer(p));
        foundPolygons = [];

        // Clean up result map
        if (resultMap) {
            resultMap.remove();
            resultMap = null;
        }
        resultPolygons = [];
        resultMarkers = [];
        foundLandsData = [];

        // Stop live location updates
        stopLiveLocationUpdates();

        // Reset map view
        if (currentLat && currentLng) {
            map.setView([currentLat, currentLng], 18);
        }
    }

    function lookupLandId() {
        const input = document.getElementById('landIdInput').value.trim();
        if (!input) {
            alert('Tafadhali ingiza nambari ya ardhi');
            return;
        }

        // Extract numeric ID from input like "LS-00123"
        let landId = input.replace(/[^0-9]/g, '');
        if (landId) {
            window.location.href = 'verify-land?id=' + parseInt(landId);
        } else {
            window.location.href = 'verify-land?code=' + encodeURIComponent(input);
        }
    }

    // Allow Enter key to search
    document.getElementById('landIdInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            lookupLandId();
        }
    });
    </script>
</body>
</html>
