File size: 31,402 Bytes
b2363b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705

// ============================================
// FormForge GeoStudio - Core JavaScript 🗺️
// ============================================

// Global State Management
const FormForge = {
    currentForm: {
        id: null,
        name: '',
        description: '',
        fields: [],
        theme: 'dark',
        version: '2.0.0'
    },
    selectedElement: null,
    currentDevice: 'mobile',
    mapInstances: {},
    undoStack: [],
    redoStack: [],
    maxUndoSteps: 50
};

// Initialize Application
document.addEventListener('DOMContentLoaded', () => {
    console.log('🗺️ FormForge GeoStudio initializing...');
    initTheme();
    initKeyboardShortcuts();
    loadForms();
    animateEntry();
});

// ============================================
// Theme Management 🎨
// ============================================

function initTheme() {
    const savedTheme = localStorage.getItem('geoforms-theme') || 'dark';
    document.documentElement.classList.toggle('dark', savedTheme === 'dark');
    updateThemeIcon(savedTheme === 'dark');
}

function toggleTheme() {
    const isDark = document.documentElement.classList.toggle('dark');
    localStorage.setItem('geoforms-theme', isDark ? 'dark' : 'light');
    updateThemeIcon(isDark);
    
    // Dispatch theme change event
    window.dispatchEvent(new CustomEvent('themeChanged', { detail: { isDark } }));
}

function updateThemeIcon(isDark) {
    // Update all theme toggle buttons
    document.querySelectorAll('.theme-toggle, [onclick*="toggleTheme"]').forEach(btn => {
        const sunIcon = btn.querySelector('.sun-icon, [data-feather="sun"]');
        const moonIcon = btn.querySelector('.moon-icon, [data-feather="moon"]');
        
        if (sunIcon) sunIcon.style.display = isDark ? 'none' : 'block';
        if (moonIcon) moonIcon.style.display = isDark ? 'block' : 'none';
    });
}

// ============================================
// Animation & Effects ✨
// ============================================

function animateEntry() {
    const elements = document.querySelectorAll('.animate-on-load');
    elements.forEach((el, i) => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(20px)';
        setTimeout(() => {
            el.style.transition = 'all 0.5s ease';
            el.style.opacity = '1';
            el.style.transform = 'translateY(0)';
        }, i * 100);
    });
}

function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    const colors = {
        success: 'bg-green-500',
        error: 'bg-red-500',
        warning: 'bg-yellow-500',
        info: 'bg-blue-500'
    };
    
    toast.className = `fixed bottom-4 right-4 ${colors[type]} text-white px-6 py-3 rounded-lg shadow-2xl z-50 transform translate-y-full transition-transform duration-300 flex items-center gap-2`;
    toast.innerHTML = `
        <span>${type === 'success' ? '✅' : type === 'error' ? '❌' : type === 'warning' ? '⚠️' : 'ℹ️'}</span>
        <span>${message}</span>
    `;
    
    document.body.appendChild(toast);
    requestAnimationFrame(() => toast.classList.remove('translate-y-full'));
    
    setTimeout(() => {
        toast.classList.add('translate-y-full');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// ============================================
// Keyboard Shortcuts ⌨️
// ============================================

function initKeyboardShortcuts() {
    document.addEventListener('keydown', (e) => {
        // Ctrl/Cmd + S = Save
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            if (typeof saveCurrentForm === 'function') {
                saveCurrentForm();
                showToast('Formulário salvo! 💾');
            }
        }
        
        // Ctrl/Cmd + Z = Undo
        if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
            e.preventDefault();
            undo();
        }
        
        // Ctrl/Cmd + Shift + Z = Redo
        if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'z') {
            e.preventDefault();
            redo();
        }
        
        // Delete = Remove selected
        if (e.key === 'Delete' && FormForge.selectedElement !== null) {
            deleteElement(FormForge.selectedElement);
        }
    });
}

// ============================================
// Undo/Redo System ↩️
// ============================================

function saveState() {
    const state = JSON.stringify(FormForge.currentForm.fields);
    FormForge.undoStack.push(state);
    if (FormForge.undoStack.length > FormForge.maxUndoSteps) {
        FormForge.undoStack.shift();
    }
    FormForge.redoStack = [];
}

function undo() {
    if (FormForge.undoStack.length === 0) return;
    
    const current = JSON.stringify(FormForge.currentForm.fields);
    FormForge.redoStack.push(current);
    
    const previous = FormForge.undoStack.pop();
    FormForge.currentForm.fields = JSON.parse(previous);
    
    refreshBuilder();
    showToast('Desfeito ↩️', 'info');
}

function redo() {
    if (FormForge.redoStack.length === 0) return;
    
    const current = JSON.stringify(FormForge.currentForm.fields);
    FormForge.undoStack.push(current);
    
    const next = FormForge.redoStack.pop();
    FormForge.currentForm.fields = JSON.parse(next);
    
    refreshBuilder();
    showToast('Refeito ↪️', 'info');
}

function refreshBuilder() {
    const preview = document.getElementById('devicePreview');
    if (preview) {
        // Clear and rebuild
        const content = preview.shadowRoot?.getElementById('formContent');
        if (content) {
            content.innerHTML = '';
            FormForge.currentForm.fields.forEach(field => {
                preview.addField(field);
            });
        }
    }
    saveCurrentForm();
}

// Legacy compatibility
let currentForm = FormForge.currentForm;
let selectedElement = FormForge.selectedElement;
let currentDevice = FormForge.currentDevice;
let mapInstances = FormForge.mapInstances;
// Dashboard Functions
function loadForms() {
    const forms = JSON.parse(localStorage.getItem('geoforms_list') || '[]');
    const grid = document.getElementById('formsGrid');
    const emptyState = document.getElementById('emptyState');
    
    if (!grid) return;
    
    if (forms.length === 0) {
        grid.innerHTML = '';
        emptyState.classList.remove('hidden');
        return;
    }
    
    emptyState.classList.add('hidden');
    grid.innerHTML = forms.map(form => `
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-md hover:shadow-xl transition-all duration-300 overflow-hidden group border border-gray-200 dark:border-gray-700">
            <div class="h-32 bg-gradient-to-br from-primary-500 to-secondary-500 relative overflow-hidden">
                <div class="absolute inset-0 opacity-20">
                    <svg class="w-full h-full" viewBox="0 0 100 100" preserveAspectRatio="none">
                        <path d="M0 100 C 20 0 50 0 100 100 Z" fill="white"/>
                    </svg>
                </div>
                <div class="absolute top-4 right-4 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button onclick="editForm('${form.id}')" class="p-2 bg-white rounded-lg shadow-md hover:bg-gray-100 text-gray-700">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                    </button>
                    <button onclick="deleteForm('${form.id}')" class="p-2 bg-white rounded-lg shadow-md hover:bg-red-50 text-red-600">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                    </button>
                </div>
            </div>
            <div class="p-6">
                <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-2">${form.name}</h3>
                <p class="text-gray-600 dark:text-gray-400 text-sm mb-4 line-clamp-2">${form.description || 'Sem descrição'}</p>
                <div class="flex items-center justify-between text-sm text-gray-500 dark:text-gray-400">
                    <span class="flex items-center gap-1">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                        ${new Date(form.createdAt).toLocaleDateString('pt-BR')}
                    </span>
                    <span class="bg-primary-100 dark:bg-primary-900 text-primary-700 dark:text-primary-300 px-2 py-1 rounded-full text-xs font-medium">
                        ${form.fields?.length || 0} campos
                    </span>
                </div>
                <div class="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 flex gap-2">
                    <a href="preview.html?form=${form.id}" target="_blank" class="flex-1 text-center py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300 transition-colors">
                        Visualizar
                    </a>
                    <button onclick="exportSingleForm('${form.id}')" class="px-3 py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg text-gray-700 dark:text-gray-300">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                    </button>
                </div>
            </div>
        </div>
    `).join('');
}

function createNewForm() {
    document.getElementById('newFormModal').classList.remove('hidden');
}

function closeModal() {
    document.getElementById('newFormModal').classList.add('hidden');
    document.getElementById('formName').value = '';
    document.getElementById('formDescription').value = '';
}

function confirmNewForm() {
    const name = document.getElementById('formName').value;
    const description = document.getElementById('formDescription').value;
    
    if (!name) {
        alert('Por favor, insira um nome para o formulário');
        return;
    }
    
    const form = {
        id: 'form_' + Date.now(),
        name,
        description,
        fields: [],
        createdAt: new Date().toISOString(),
        theme: 'dark'
    };
    
    const forms = JSON.parse(localStorage.getItem('geoforms_list') || '[]');
    forms.push(form);
    localStorage.setItem('geoforms_list', JSON.stringify(forms));
    localStorage.setItem(`geoform_${form.id}`, JSON.stringify([]));
    
    window.location.href = `builder.html?form=${form.id}`;
}

function editForm(formId) {
    window.location.href = `builder.html?form=${formId}`;
}

function deleteForm(formId) {
    if (!confirm('Tem certeza que deseja excluir este formulário?')) return;
    
    let forms = JSON.parse(localStorage.getItem('geoforms_list') || '[]');
    forms = forms.filter(f => f.id !== formId);
    localStorage.setItem('geoforms_list', JSON.stringify(forms));
    localStorage.removeItem(`geoform_${formId}`);
    
    loadForms();
}

function exportSingleForm(formId) {
    const form = JSON.parse(localStorage.getItem(`geoform_${formId}`) || '[]');
    const metadata = JSON.parse(localStorage.getItem('geoforms_list') || '[]').find(f => f.id === formId);
    
    const exportData = {
        metadata,
        schema: form,
        generatedAt: new Date().toISOString(),
        version: '1.0'
    };
    
    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${metadata.name.replace(/\s+/g, '_')}_schema.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// Builder Functions
function initBuilder() {
    const urlParams = new URLSearchParams(window.location.search);
    const formId = urlParams.get('form');
    
    if (!formId) {
        window.location.href = 'index.html';
        return;
    }
    
    const forms = JSON.parse(localStorage.getItem('geoforms_list') || '[]');
    const form = forms.find(f => f.id === formId);
    
    if (!form) {
        window.location.href = 'index.html';
        return;
    }
    
    currentForm = {
        ...form,
        fields: JSON.parse(localStorage.getItem(`geoform_${formId}`) || '[]')
    };
    
    renderBuilder();
    setupDragAndDrop();
}

function renderBuilder() {
    const preview = document.getElementById('devicePreview');
    if (!preview) return;
    
    preview.innerHTML = currentForm.fields.map((field, index) => `
        <div class="form-element ${selectedElement === index ? 'selected' : ''}" 
             data-index="${index}"
             onclick="selectElement(${index})">
            <button class="delete-btn" onclick="event.stopPropagation(); deleteElement(${index})">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
            ${renderFieldPreview(field)}
        </div>
    `).join('');
    
    if (currentForm.fields.length === 0) {
        preview.innerHTML = `
            <div class="text-center py-12 text-gray-400 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg">
                <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="mx-auto mb-3"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
                <p>Arraste componentes aqui</p>
            </div>
        `;
    }
}

function renderFieldPreview(field) {
    const baseClass = "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white";
    
    switch(field.type) {
        case 'text':
            return `
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
                <input type="text" class="${baseClass} text-sm" placeholder="${field.placeholder || ''}" disabled>
            `;
        case 'textarea':
            return `
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
                <textarea class="${baseClass} text-sm resize-none" rows="2" placeholder="${field.placeholder || ''}" disabled></textarea>
            `;
        case 'select':
            return `
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
                <select class="${baseClass} text-sm" disabled>
                    <option>Selecione...</option>
                </select>
            `;
        case 'number':
            return `
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
                <input type="number" class="${baseClass} text-sm" disabled>
            `;
        case 'date':
            return `
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
                <input type="date" class="${baseClass} text-sm" disabled>
            `;
        case 'photo':
            return `
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
                <div class="${baseClass} text-center py-4 text-gray-400 text-sm">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mx-auto mb-2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                    Área de foto
                </div>
            `;
        case 'map':
            return `
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
                <div class="${baseClass} h-32 flex items-center justify-center text-gray-400 text-sm bg-gray-50 dark:bg-gray-800">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2"><polygon points="1 6 1 22 8 18 16 22 21 18 21 2 16 6 8 2 1 6"/><line x1="8" y1="2" x2="8" y2="18"/><line x1="16" y1="6" x2="16" y2="22"/></svg>
                    Mapa (${field.geometryType === 'point' ? 'Ponto' : field.geometryType === 'line' ? 'Linha' : 'Polígono'})
                </div>
            `;
        default:
            return `<div>Unknown field type</div>`;
    }
}

function setupDragAndDrop() {
    const dropZone = document.getElementById('devicePreview');
    
    document.querySelectorAll('.draggable-item').forEach(item => {
        item.addEventListener('dragstart', (e) => {
            e.dataTransfer.setData('fieldType', item.dataset.type);
            item.classList.add('dragging');
        });
        
        item.addEventListener('dragend', () => {
            item.classList.remove('dragging');
        });
    });
    
    if (dropZone) {
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('drag-over');
        });
        
        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('drag-over');
        });
        
        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('drag-over');
            const fieldType = e.dataTransfer.getData('fieldType');
            addField(fieldType);
        });
    }
}

function addField(type) {
    const field = {
        id: 'field_' + Date.now(),
        type: type,
        label: getDefaultLabel(type),
        required: false,
        placeholder: ''
    };
    
    if (type === 'select') {
        field.options = 'Opção 1, Opção 2, Opção 3';
    } else if (type === 'map') {
        field.geometryType = 'point';
    }
    
    currentForm.fields.push(field);
    saveCurrentForm();
    renderBuilder();
    selectElement(currentForm.fields.length - 1);
}

function getDefaultLabel(type) {
    const labels = {
        text: 'Texto',
        textarea: 'Texto Longo',
        select: 'Seleção',
        number: 'Número',
        date: 'Data',
        photo: 'Foto',
        map: 'Localização'
    };
    return labels[type] || 'Campo';
}

function selectElement(index) {
    selectedElement = index;
    renderBuilder();
    updatePropertiesPanel();
}

function deleteElement(index) {
    currentForm.fields.splice(index, 1);
    selectedElement = null;
    saveCurrentForm();
    renderBuilder();
    updatePropertiesPanel();
}

function updatePropertiesPanel() {
    const panel = document.getElementById('propertiesContent');
    if (!panel) return;
    
    if (selectedElement === null) {
        panel.innerHTML = `
            <div class="text-center text-gray-500 mt-8">
                <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="mx-auto mb-3 opacity-50"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
                <p>Selecione um elemento para editar</p>
            </div>
        `;
        return;
    }
    
    const field = currentForm.fields[selectedElement];
    
    let extraFields = '';
    if (field.type === 'select') {
        extraFields = `
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Opções (separadas por vírgula)</label>
                <textarea class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm" rows="3" onchange="updateField(${selectedElement}, 'options', this.value)">${field.options || ''}</textarea>
            </div>
        `;
    } else if (field.type === 'map') {
        extraFields = `
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Tipo de Geometria</label>
                <select class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm" onchange="updateField(${selectedElement}, 'geometryType', this.value)">
                    <option value="point" ${field.geometryType === 'point' ? 'selected' : ''}>Ponto</option>
                    <option value="line" ${field.geometryType === 'line' ? 'selected' : ''}>Linha</option>
                    <option value="polygon" ${field.geometryType === 'polygon' ? 'selected' : ''}>Polígono</option>
                </select>
            </div>
        `;
    } else if (['text', 'textarea'].includes(field.type)) {
        extraFields = `
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Placeholder</label>
                <input type="text" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm" value="${field.placeholder || ''}" onchange="updateField(${selectedElement}, 'placeholder', this.value)">
            </div>
        `;
    }
    
    panel.innerHTML = `
        <div class="space-y-4 animate-slide-in">
            <div class="mb-4">
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Rótulo</label>
                <input type="text" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm" value="${field.label}" onchange="updateField(${selectedElement}, 'label', this.value)">
            </div>
            
            ${extraFields}
            
            <div class="mb-4">
                <label class="flex items-center cursor-pointer">
                    <div class="relative">
                        <input type="checkbox" class="sr-only" ${field.required ? 'checked' : ''} onchange="updateField(${selectedElement}, 'required', this.checked)">
                        <div class="w-10 h-6 bg-gray-200 dark:bg-gray-600 rounded-full shadow-inner"></div>
                        <div class="dot absolute w-4 h-4 bg-white rounded-full shadow -left-1 -top-1 transition transform ${field.required ? 'translate-x-6 bg-primary-500' : 'translate-x-1'} mt-1"></div>
                    </div>
                    <div class="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300">Campo obrigatório</div>
                </label>
            </div>
            
            <div class="pt-4 border-t border-gray-200 dark:border-gray-700">
                <button onclick="deleteElement(${selectedElement})" class="w-full py-2 bg-red-100 dark:bg-red-900 text-red-600 dark:text-red-200 rounded-lg text-sm font-medium hover:bg-red-200 dark:hover:bg-red-800 transition-colors flex items-center justify-center gap-2">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                    Remover Campo
                </button>
            </div>
        </div>
    `;
}

function updateField(index, property, value) {
    currentForm.fields[index][property] = value;
    saveCurrentForm();
    renderBuilder();
}

function saveCurrentForm() {
    localStorage.setItem(`geoform_${currentForm.id}`, JSON.stringify(currentForm.fields));
    
    // Update metadata
    const forms = JSON.parse(localStorage.getItem('geoforms_list') || '[]');
    const formIndex = forms.findIndex(f => f.id === currentForm.id);
    if (formIndex !== -1) {
        forms[formIndex].fields = currentForm.fields;
        forms[formIndex].updatedAt = new Date().toISOString();
        localStorage.setItem('geoforms_list', JSON.stringify(forms));
    }
}

function setDevice(device) {
    currentDevice = device;
    const preview = document.getElementById('devicePreview');
    const buttons = document.querySelectorAll('.device-btn');
    
    buttons.forEach(btn => {
        btn.classList.toggle('bg-primary-100', btn.dataset.device === device);
        btn.classList.toggle('dark:bg-primary-900', btn.dataset.device === device);
        btn.classList.toggle('text-primary-600', btn.dataset.device === device);
    });
    
    preview.className = `device-${device} bg-white dark:bg-gray-800 p-4 overflow-y-auto`;
}

function exportForm() {
    const exportData = {
        metadata: {
            id: currentForm.id,
            name: currentForm.name,
            description: currentForm.description,
            createdAt: currentForm.createdAt,
            updatedAt: new Date().toISOString()
        },
        schema: currentForm.fields,
        config: {
            theme: currentForm.theme,
            version: '1.0.0'
        }
    };
    
    // Create downloadable package
    const jsonContent = JSON.stringify(exportData, null, 2);
    const htmlContent = generateMobileHTML(exportData);
    
    // Create a zip-like structure using data URLs
    const manifest = {
        name: currentForm.name,
        files: {
            'config.json': jsonContent,
            'index.html': htmlContent,
            'readme.txt': `geoForms Mobile Package\nFormulário: ${currentForm.name}\nGerado em: ${new Date().toLocaleString('pt-BR')}`
        }
    };
    
    // Download as JSON for now (in real app, would be a zip)
    const blob = new Blob([JSON.stringify(manifest, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${currentForm.name.replace(/\s+/g, '_')}_mobile_package.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    alert('Pacote exportado! Em uma aplicação real, isso geraria um arquivo .zip com HTML standalone para iOS/Android.');
}

function generateMobileHTML(data) {
    // Generates a standalone HTML file for mobile deployment
    return `<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>${data.metadata.name}</title>
    <style>
        * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        body { font-family: -apple-system, sans-serif; margin: 0; padding: 0; background: #f3f4f6; }
        .header { background: #4f46e5; color: white; padding: 1rem; position: sticky; top: 0; z-index: 100; }
        .form { padding: 1rem; max-width: 600px; margin: 0 auto; }
        .field { margin-bottom: 1rem; background: white; padding: 1rem; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #374151; }
        input, select, textarea { width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 6px; font-size: 16px; }
        .required { color: #ef4444; }
        button { width: 100%; padding: 1rem; background: #4f46e5; color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; margin-top: 1rem; }
        .map { height: 200px; background: #e5e7eb; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: #6b7280; }
    </style>
</head>
<body>
    <div class="header">
        <h1>${data.metadata.name}</h1>
        <small>${data.metadata.description || ''}</small>
    </div>
    <form class="form" onsubmit="event.preventDefault(); alert('Enviado!');">
        ${data.schema.map(field => {
            let input = '';
            if (field.type === 'text') input = `<input type="text" ${field.required ? 'required' : ''} placeholder="${field.placeholder || ''}">`;
            else if (field.type === 'textarea') input = `<textarea rows="3" ${field.required ? 'required' : ''} placeholder="${field.placeholder || ''}"></textarea>`;
            else if (field.type === 'number') input = `<input type="number" ${field.required ? 'required' : ''}>`;
            else if (field.type === 'date') input = `<input type="date" ${field.required ? 'required' : ''}>`;
            else if (field.type === 'select') input = `<select ${field.required ? 'required' : ''}><option value="">Selecione...</option>${(field.options || '').split(',').map(o => `<option value="${o.trim()}">${o.trim()}</option>`).join('')}</select>`;
            else if (field.type === 'photo') input = `<div style="border: 2px dashed #d1d5db; padding: 2rem; text-align: center; color: #6b7280;">📷 Capturar Foto</div>`;
            else if (field.type === 'map') input = `<div class="map">🗺️ Mapa ${field.geometryType || 'point'}</div>`;
            return `<div class="field"><label>${field.label} ${field.required ? '<span class="required">*</span>' : ''}</label>${input}</div>`;
        }).join('')}
        <button type="submit">Enviar Dados</button>
    </form>
</body>
</html>`;
}