  var htmlsection = `  <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: #f5f5f5;
            padding: 20px;
            color: #333;
        }
        
        .container {
            display: flex;
            gap: 20px;
            max-width: 1400px;
            margin: 0 auto;
            height: calc(100vh - 40px);
        }
        
        .form-panel {
            width: 400px;
            background: white;
            border-radius: 8px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
        }
        
        .map-panel {
            flex: 1;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        h1 {
            color: #2c3e50;
            margin-bottom: 25px;
            font-size: 24px;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }
        
        .form-section {
            margin-bottom: 25px;
        }
        
        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 1px solid #eee;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            color: #555;
            font-size: 14px;
        }
        
        .required::after {
            content: " *";
            color: #e74c3c;
        }
        
        input, select, textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            transition: border 0.2s;
        }
        
        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
        }
        
        textarea {
            height: 80px;
            resize: vertical;
            font-family: inherit;
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 10px;
        }
        
        .checkbox-group label {
            margin-bottom: 0;
            cursor: pointer;
        }
        
        .checkbox-group input[type="checkbox"] {
            width: auto;
            cursor: pointer;
        }
        
        .draw-controls {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #e9ecef;
        }
        
        .draw-buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .draw-buttons button {
            padding: 12px;
            border: none;
            border-radius: 4px;
            background: #3498db;
            color: white;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .draw-buttons button:hover {
            background: #2980b9;
            transform: translateY(-1px);
        }
        
        .draw-buttons button.active {
            background: #1a5276;
            box-shadow: inset 0 2px 4px rgba(0,0,0,0.2);
        }
        
        .draw-buttons button.cancel {
            background: #e74c3c;
        }
        
        .draw-buttons button.cancel:hover {
            background: #c0392b;
        }
        
        .instructions {
            color: #7f8c8d;
            font-size: 13px;
            font-style: italic;
            line-height: 1.4;
            background: #fef9e7;
            padding: 10px;
            border-radius: 4px;
            border-left: 3px solid #f1c40f;
        }
        
        .coordinates-container {
            max-height: 200px;
            overflow-y: auto;
            background: #f8f9fa;
            border-radius: 4px;
            padding: 10px;
            margin-top: 10px;
            border: 1px solid #eee;
        }
        
        .coordinate-item {
            padding: 8px 10px;
            background: white;
            margin-bottom: 5px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            border-left: 3px solid #3498db;
        }
        
        .coordinate-item:last-child {
            margin-bottom: 0;
        }
        
        .submit-btn {
            padding: 15px;
            background: #2ecc71;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            margin-top: 10px;
        }
        
        .submit-btn:hover {
            background: #27ae60;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(46, 204, 113, 0.3);
        }
        
        .submit-btn:disabled {
            background: #95a5a6;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        #map {
            height: 100%;
        }
        
        .response-message {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            font-size: 14px;
            display: none;
            animation: fadeIn 0.3s ease;
        }
        
        .response-message.success {
            background: #d5edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .response-message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .response-message.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .form-scroll {
            flex: 1;
            overflow-y: auto;
            padding-right: 5px;
        }
        
        .form-scroll::-webkit-scrollbar {
            width: 6px;
        }
        
        .form-scroll::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }
        
        .form-scroll::-webkit-scrollbar-thumb {
            background: #bdc3c7;
            border-radius: 3px;
        }
        
        .form-scroll::-webkit-scrollbar-thumb:hover {
            background: #7f8c8d;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .field-group {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .color-picker {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .color-picker input[type="color"] {
            width: 40px;
            height: 40px;
            padding: 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .radio-group {
            display: flex;
            gap: 20px;
            margin-top: 5px;
        }
        
        .radio-option {
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .radio-option input[type="radio"] {
            width: auto;
        }
    </style> <div class="container">
        <div class="form-panel">
            <h1>Create Geofence</h1>
            
            <div class="form-scroll">
                <form id="geofenceForm">
                    <div class="form-section">
                        <div class="section-title">Basic Information</div>
                        
                        <div class="form-group">
                            <label for="name" class="required">Geofence Name</label>
                            <input type="text" id="name" name="name" required 
                                   placeholder="Enter geofence name" maxlength="200">
                        </div>
                        
                        <div class="form-group">
                            <label for="description">Description</label>
                            <textarea id="description" name="description" 
                                      placeholder="Enter description" maxlength="500"></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="fenceType" class="required">Fence Type</label>
                            <select id="fenceType" name="fenceType" required>
                                <option value="">Select fence type</option>
                                <option value="POLYGON">Polygon</option>
                                <option value="CIRCLE">Circle</option>
                                <option value="RECTANGLE">Rectangle</option>
                                <option value="LINE">Line</option>
                                <option value="CORRIDOR">Corridor</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="colorHex">Color</label>
                            <div class="color-picker">
                                <input type="color" id="colorHex" name="colorHex" value="#3B82F6">
                                <span id="colorValue">#3B82F6</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <div class="section-title">Station Configuration</div>
                        
                        <div class="form-group">
                            <div class="radio-group">
                                <div class="radio-option">
                                    <input type="radio" id="regularGeofence" name="isStation" value="false" checked>
                                    <label for="regularGeofence">Regular Geofence</label>
                                </div>
                                <div class="radio-option">
                                    <input type="radio" id="stationGeofence" name="isStation" value="true">
                                    <label for="stationGeofence">Station</label>
                                </div>
                            </div>
                        </div>
                        
                        <div id="stationConfig" style="display: none;">
                            <div class="form-group">
                                <label for="stationType">Station Type</label>
                                <select id="stationType" name="stationType">
                                    <option value="">Select station type</option>
                                    <option value="BUS_STOP">Bus Stop</option>
                                    <option value="CHECKPOINT">Checkpoint</option>
                                    <option value="DEPOT">Depot</option>
                                    <option value="TERMINAL">Terminal</option>
                                    <option value="PARKING">Parking</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="dwellTimeSeconds">Dwell Time (seconds)</label>
                                <input type="number" id="dwellTimeSeconds" name="dwellTimeSeconds" 
                                       min="1" value="60" placeholder="Enter dwell time">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <div class="section-title">Draw Geofence</div>
                        
                        <div class="draw-controls">
                            <div class="draw-buttons">
                                <button type="button" id="drawBtn">Start Drawing</button>
                                <button type="button" id="cancelDrawBtn" class="cancel">Cancel</button>
                            </div>
                            
                            <div class="instructions" id="instructions">
                                Select fence type above, then click "Start Drawing" and draw on the map
                            </div>
                        </div>
                        
                        <div id="circleFields" style="display: none;">
                            <div class="form-group">
                                <label for="radiusMeters" class="required">Radius (meters)</label>
                                <input type="number" id="radiusMeters" name="radiusMeters" 
                                       min="1" step="0.1" placeholder="Enter radius in meters">
                            </div>
                        </div>
                        
                        <div id="bufferFields" style="display: none;">
                            <div class="form-group">
                                <label for="bufferWidthMeters" class="required">Buffer Width (meters)</label>
                                <input type="number" id="bufferWidthMeters" name="bufferWidthMeters" 
                                       min="1" step="0.1" placeholder="Enter buffer width">
                            </div>
                        </div>
                        
                        <div id="coordinatesSection" style="display: none;">
                            <label>Coordinates</label>
                            <div class="coordinates-container" id="coordinatesContainer">
                                <!-- Coordinates will be displayed here -->
                            </div>
                        </div>
                    </div>
                    
                    <!-- Hidden fields for geometry data -->
                    <input type="hidden" id="centerLat" name="centerLat">
                    <input type="hidden" id="centerLng" name="centerLng">
                    <input type="hidden" id="minLat" name="minLat">
                    <input type="hidden" id="minLng" name="minLng">
                    <input type="hidden" id="maxLat" name="maxLat">
                    <input type="hidden" id="maxLng" name="maxLng">
                    
                    <button type="submit" class="submit-btn" id="submitBtn" disabled>Create Geofence</button>
                </form>
                
                <div id="responseMessage" class="response-message"></div>
            </div>
        </div>
        
        <div class="map-panel">
            <div id="map"></div>
        </div>
    </div>
     <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js"></script>
`
    $(".crud_section").html(htmlsection);
    $('.ui.dropdown').dropdown({
        fullTextSearch: true
    });









    
        // Initialize map centered on Nairobi
        const map = L.map('map').setView([-1.2921, 36.8219], 12);
        
        // Add OpenStreetMap tiles
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors'
        }).addTo(map);
        
        // Variables for drawing
        let drawnItems = new L.FeatureGroup();
        map.addLayer(drawnItems);
        let drawControl = null;
        let currentDrawing = false;
        
        // DOM Elements
        const elements = {
            form: document.getElementById('geofenceForm'),
            fenceType: document.getElementById('fenceType'),
            drawBtn: document.getElementById('drawBtn'),
            cancelDrawBtn: document.getElementById('cancelDrawBtn'),
            submitBtn: document.getElementById('submitBtn'),
            responseMessage: document.getElementById('responseMessage'),
            circleFields: document.getElementById('circleFields'),
            bufferFields: document.getElementById('bufferFields'),
            coordinatesSection: document.getElementById('coordinatesSection'),
            coordinatesContainer: document.getElementById('coordinatesContainer'),
            stationConfig: document.getElementById('stationConfig'),
            colorHex: document.getElementById('colorHex'),
            colorValue: document.getElementById('colorValue'),
            radiusMeters: document.getElementById('radiusMeters'),
            bufferWidthMeters: document.getElementById('bufferWidthMeters')
        };
        
        // Initialize event listeners
        function initEventListeners() {
            // Fence type change
            elements.fenceType.addEventListener('change', handleFenceTypeChange);
            
            // Station radio buttons
            document.querySelectorAll('input[name="isStation"]').forEach(radio => {
                radio.addEventListener('change', handleStationToggle);
            });
            
            // Color picker
            elements.colorHex.addEventListener('input', updateColorValue);
            
            // Draw buttons
            elements.drawBtn.addEventListener('click', startDrawing);
            elements.cancelDrawBtn.addEventListener('click', cancelDrawing);
            
            // Form submission
            elements.form.addEventListener('submit', handleFormSubmit);
            
            // Map drawing events
            map.on(L.Draw.Event.CREATED, handleDrawCreated);
            map.on(L.Draw.Event.DRAWSTART, () => currentDrawing = true);
            map.on(L.Draw.Event.DRAWSTOP, () => currentDrawing = false);
        }
        
        function handleFenceTypeChange() {
            const type = elements.fenceType.value;
            
            // Reset all fields
            elements.circleFields.style.display = 'none';
            elements.bufferFields.style.display = 'none';
            elements.coordinatesSection.style.display = 'none';
            elements.radiusMeters.value = '';
            elements.bufferWidthMeters.value = '';
            elements.coordinatesContainer.innerHTML = '';
            
            // Clear any existing drawings
            drawnItems.clearLayers();
            elements.submitBtn.disabled = true;
            
            // Update instructions
            updateInstructions(type);
            
            // Show/hide fields based on type
            switch(type) {
                case 'CIRCLE':
                    elements.circleFields.style.display = 'block';
                    break;
                case 'LINE':
                case 'CORRIDOR':
                    elements.bufferFields.style.display = 'block';
                    elements.coordinatesSection.style.display = 'block';
                    break;
                case 'POLYGON':
                    elements.coordinatesSection.style.display = 'block';
                    break;
                case 'RECTANGLE':
                    // Rectangle uses hidden fields, no extra UI needed
                    break;
            }
        }
        
        function updateInstructions(type) {
            const instructions = document.getElementById('instructions');
            const messages = {
                'POLYGON': 'Click "Start Drawing", then click on map to create polygon vertices. Double-click to finish.',
                'CIRCLE': 'Click "Start Drawing", then click and drag on map to create a circle.',
                'RECTANGLE': 'Click "Start Drawing", then click and drag on map to create a rectangle.',
                'LINE': 'Click "Start Drawing", then click on map to create line points. Double-click to finish.',
                'CORRIDOR': 'Click "Start Drawing", then click on map to create corridor path. Double-click to finish.',
                '': 'Select fence type above, then click "Start Drawing" and draw on the map'
            };
            
            instructions.textContent = messages[type] || messages[''];
        }
        
        function handleStationToggle(e) {
            elements.stationConfig.style.display = e.target.value === 'true' ? 'block' : 'none';
        }
        
        function updateColorValue() {
            elements.colorValue.textContent = elements.colorHex.value;
        }
        
        function startDrawing() {
            const fenceType = elements.fenceType.value;
            if (!fenceType) {
                showMessage('Please select a fence type first', 'error');
                return;
            }
            
            // Remove existing draw control
            if (drawControl) {
                map.removeControl(drawControl);
            }
            
            // Clear any previous drawings
            drawnItems.clearLayers();
            
            // Configure draw options
            const drawOptions = {
                position: 'topright',
                draw: {
                    polygon: fenceType === 'POLYGON',
                    circle: fenceType === 'CIRCLE',
                    rectangle: fenceType === 'RECTANGLE',
                    polyline: fenceType === 'LINE' || fenceType === 'CORRIDOR',
                    marker: false,
                    circlemarker: false,
                    polyline: false
                },
                edit: {
                    featureGroup: drawnItems,
                    remove: true
                }
            };
            
            // Enable the appropriate drawing tool
            let drawTool;
            switch(fenceType) {
                case 'POLYGON':
                    drawTool = new L.Draw.Polygon(map, drawOptions.draw);
                    break;
                case 'CIRCLE':
                    drawTool = new L.Draw.Circle(map, drawOptions.draw);
                    break;
                case 'RECTANGLE':
                    drawTool = new L.Draw.Rectangle(map, drawOptions.draw);
                    break;
                case 'LINE':
                case 'CORRIDOR':
                    drawTool = new L.Draw.Polyline(map, drawOptions.draw);
                    break;
            }
            
            if (drawTool) {
                drawTool.enable();
                elements.drawBtn.textContent = 'Drawing...';
                elements.drawBtn.disabled = true;
                elements.drawBtn.classList.add('active');
            }
        }
        
        function cancelDrawing() {
            if (drawControl) {
                map.removeControl(drawControl);
                drawControl = null;
            }
            
            // Disable any active drawing
            map.fire('draw:drawstop');
            
            drawnItems.clearLayers();
            elements.drawBtn.textContent = 'Start Drawing';
            elements.drawBtn.disabled = false;
            elements.drawBtn.classList.remove('active');
            elements.submitBtn.disabled = true;
            showMessage('Drawing cancelled', 'info');
        }
        
        function handleDrawCreated(e) {
            const layer = e.layer;
            drawnItems.clearLayers();
            drawnItems.addLayer(layer);
            
            // Extract data based on layer type
            const fenceType = elements.fenceType.value;
            
            switch(fenceType) {
                case 'CIRCLE':
                    if (layer instanceof L.Circle) {
                        const center = layer.getLatLng();
                        const radius = layer.getRadius();
                        
                        document.getElementById('centerLat').value = center.lat;
                        document.getElementById('centerLng').value = center.lng;
                        elements.radiusMeters.value = radius.toFixed(2);
                    }
                    break;
                    
                case 'RECTANGLE':
                    if (layer instanceof L.Rectangle) {
                        const bounds = layer.getBounds();
                        document.getElementById('minLat').value = bounds.getSouth();
                        document.getElementById('minLng').value = bounds.getWest();
                        document.getElementById('maxLat').value = bounds.getNorth();
                        document.getElementById('maxLng').value = bounds.getEast();
                    }
                    break;
                    
                case 'POLYGON':
                    if (layer instanceof L.Polygon) {
                        const latlngs = layer.getLatLngs()[0];
                        displayCoordinates(latlngs);
                    }
                    break;
                    
                case 'LINE':
                case 'CORRIDOR':
                    if (layer instanceof L.Polyline) {
                        const latlngs = layer.getLatLngs();
                        displayCoordinates(latlngs);
                    }
                    break;
            }
            
            // Reset draw button
            elements.drawBtn.textContent = 'Start Drawing';
            elements.drawBtn.disabled = false;
            elements.drawBtn.classList.remove('active');
            
            // Enable submit button
            elements.submitBtn.disabled = false;
            
            showMessage('Geofence drawn successfully. Fill remaining details and submit.', 'info');
        }
        
        function displayCoordinates(latlngs) {
            elements.coordinatesContainer.innerHTML = '';
            
            latlngs.forEach((latlng, index) => {
                const div = document.createElement('div');
                div.className = 'coordinate-item';
                div.textContent = `Point ${index + 1}: ${latlng.lat.toFixed(6)}, ${latlng.lng.toFixed(6)}`;
                elements.coordinatesContainer.appendChild(div);
            });
        }
        
        async function handleFormSubmit(e) {
            e.preventDefault();
            
            // Disable submit button
            elements.submitBtn.disabled = true;
            elements.submitBtn.textContent = 'Creating...';
            
            // Build request payload
            const payload = buildPayload();
            
            // Log payload for debugging
            console.log('Payload to send:', JSON.stringify(payload, null, 2));
            
            // Validate payload
            if (!validatePayload(payload)) {
                elements.submitBtn.disabled = false;
                elements.submitBtn.textContent = 'Create Geofence';
                return;
            }
            
            try {
                // Send to backend API
                const response = await fetch('http://localhost:8080/api/v1/geofences', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(payload)
                });
                
                const data = await response.json();
                console.log('Response from server:', data);
                
                if (response.ok) {
                    showMessage(`Geofence created successfully! ID: ${data.id}`, 'success');
                    resetForm();
                } else {
                    const errorMsg = data.message || `HTTP ${response.status}: ${response.statusText}`;
                    showMessage(`Error: ${errorMsg}`, 'error');
                    
                    // Log detailed error information
                    if (data.errors) {
                        console.error('Validation errors:', data.errors);
                    }
                }
            } catch (error) {
                showMessage(`Error: ${error.message}`, 'error');
                console.error('Fetch error:', error);
            } finally {
                elements.submitBtn.disabled = false;
                elements.submitBtn.textContent = 'Create Geofence';
            }
        }
        
        function buildPayload() {
            const formData = new FormData(elements.form);
            const fenceType = formData.get('fenceType');
            
            // Build base payload - ensure all fields match DTO exactly
            const payload = {
                name: formData.get('name'),
                description: formData.get('description') || null,
                fenceType: fenceType, // This should match GeofenceType enum values
                colorHex: formData.get('colorHex'),
                isStation: formData.get('isStation') === 'true'
            };
            
            // Add station config if applicable
            if (payload.isStation) {
                const stationType = formData.get('stationType');
                if (stationType) {
                    payload.stationType = stationType; // This should match StationType enum
                }
                const dwellTime = formData.get('dwellTimeSeconds');
                payload.dwellTimeSeconds = dwellTime ? parseInt(dwellTime) : 60;
            }
            
            // Extract geometry from drawn layer
            const layers = drawnItems.getLayers();
            if (layers.length > 0) {
                const layer = layers[0];
                
                switch(fenceType) {
                    case 'CIRCLE':
                        if (layer instanceof L.Circle) {
                            const center = layer.getLatLng();
                            payload.centerLat = center.lat;
                            payload.centerLng = center.lng;
                            const radius = parseFloat(formData.get('radiusMeters'));
                            if (!isNaN(radius) && radius > 0) {
                                payload.radiusMeters = radius;
                            }
                        }
                        break;
                        
                    case 'RECTANGLE':
                        if (layer instanceof L.Rectangle) {
                            const bounds = layer.getBounds();
                            payload.minLat = bounds.getSouth();
                            payload.minLng = bounds.getWest();
                            payload.maxLat = bounds.getNorth();
                            payload.maxLng = bounds.getEast();
                        }
                        break;
                        
                    case 'POLYGON':
                        if (layer instanceof L.Polygon) {
                            const latlngs = layer.getLatLngs()[0];
                            payload.coordinates = latlngs.map(latlng => ({
                                lat: latlng.lat,
                                lng: latlng.lng
                            }));
                        }
                        break;
                        
                    case 'LINE':
                    case 'CORRIDOR':
                        if (layer instanceof L.Polyline) {
                            const latlngs = layer.getLatLngs();
                            payload.coordinates = latlngs.map(latlng => ({
                                lat: latlng.lat,
                                lng: latlng.lng
                            }));
                            const bufferWidth = parseFloat(formData.get('bufferWidthMeters'));
                            if (!isNaN(bufferWidth) && bufferWidth > 0) {
                                payload.bufferWidthMeters = bufferWidth;
                            }
                        }
                        break;
                }
            }
            
            // Clean up payload - remove undefined or null values for optional fields
            Object.keys(payload).forEach(key => {
                if (payload[key] === undefined || payload[key] === null || payload[key] === '') {
                    delete payload[key];
                }
            });
            
            return payload;
        }
        
        function validatePayload(payload) {
            console.log('Validating payload:', payload);
            
            // Check name
            if (!payload.name || payload.name.trim() === '') {
                showMessage('Geofence name is required', 'error');
                return false;
            }
            
            // Check fence type - ensure it's a valid enum value
            const validFenceTypes = ['POLYGON', 'CIRCLE', 'RECTANGLE', 'LINE', 'CORRIDOR'];
            if (!payload.fenceType || !validFenceTypes.includes(payload.fenceType)) {
                showMessage('Valid fence type is required', 'error');
                return false;
            }
            
            // Validate geometry based on fence type
            const layers = drawnItems.getLayers();
            if (layers.length === 0) {
                showMessage('Please draw a geofence on the map first', 'error');
                return false;
            }
            
            // Type-specific validations
            switch(payload.fenceType) {
                case 'CIRCLE':
                    if (!payload.radiusMeters || payload.radiusMeters <= 0) {
                        showMessage('Radius must be a positive number', 'error');
                        return false;
                    }
                    if (!payload.centerLat || !payload.centerLng) {
                        showMessage('Circle center coordinates are required', 'error');
                        return false;
                    }
                    break;
                    
                case 'LINE':
                case 'CORRIDOR':
                    if (!payload.bufferWidthMeters || payload.bufferWidthMeters <= 0) {
                        showMessage('Buffer width must be a positive number', 'error');
                        return false;
                    }
                    if (!payload.coordinates || payload.coordinates.length < 2) {
                        showMessage('Line/Corridor must have at least 2 points', 'error');
                        return false;
                    }
                    break;
                    
                case 'POLYGON':
                    if (!payload.coordinates || payload.coordinates.length < 3) {
                        showMessage('Polygon must have at least 3 points', 'error');
                        return false;
                    }
                    break;
                    
                case 'RECTANGLE':
                    if (!payload.minLat || !payload.minLng || !payload.maxLat || !payload.maxLng) {
                        showMessage('Rectangle bounds are required', 'error');
                        return false;
                    }
                    break;
            }
            
            return true;
        }
        
        function resetForm() {
            // Reset form fields
            elements.form.reset();
            
            // Reset color
            elements.colorHex.value = '#3B82F6';
            elements.colorValue.textContent = '#3B82F6';
            
            // Clear map drawings
            drawnItems.clearLayers();
            
            // Hide dynamic fields
            elements.circleFields.style.display = 'none';
            elements.bufferFields.style.display = 'none';
            elements.coordinatesSection.style.display = 'none';
            elements.stationConfig.style.display = 'none';
            
            // Clear coordinates display
            elements.coordinatesContainer.innerHTML = '';
            
            // Disable submit button
            elements.submitBtn.disabled = true;
            
            // Reset fence type dropdown
            elements.fenceType.selectedIndex = 0;
            updateInstructions('');
            
            // Cancel any active drawing
            cancelDrawing();
        }
        
        function showMessage(message, type) {
            elements.responseMessage.textContent = message;
            elements.responseMessage.className = `response-message ${type}`;
            elements.responseMessage.style.display = 'block';
            
            // Auto-hide after 5 seconds (except for success messages which stay longer)
            const hideDelay = type === 'success' ? 8000 : 5000;
            
            setTimeout(() => {
                elements.responseMessage.style.display = 'none';
            }, hideDelay);
        }
        
        // Initialize the application
        function init() {
            initEventListeners();
            updateColorValue();
            
            // Add sample markers for reference
            addSampleMarkers();
            
            console.log('Geofence Creator UI initialized');
            console.log('Backend URL: http://localhost:8080/api/v1/geofences');
        }
        
        function addSampleMarkers() {
            // Add some reference markers (optional)
            const locations = [
                { name: "Nairobi CBD", lat: -1.2921, lng: 36.8219 },
                { name: "Karen", lat: -1.3189, lng: 36.7085 },
                { name: "Westlands", lat: -1.2649, lng: 36.8035 }
            ];
            
            locations.forEach(loc => {
                L.marker([loc.lat, loc.lng])
                    .bindPopup(`<b>${loc.name}</b><br>Reference Point`)
                    .addTo(map);
            });
        }
        
        // Start the application when DOM is loaded
        document.addEventListener('DOMContentLoaded', init);
    