@extends('layouts.app')

@section('title', 'Edit Form: ' . $form->title)

@section('content')
<div x-data="formBuilder()" x-init="init()">
    {{-- Top bar --}}
    <div class="fb-topbar">
        <div class="fb-topbar-left">
            <a href="{{ route('form-builder.index') }}" class="btn btn-ghost btn-sm" style="border:1px solid rgba(99,102,241,0.1);">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>
            </a>
            <input type="text" x-model="formTitle" class="fb-title-input" placeholder="Form title...">
            <span class="fb-save-indicator" x-show="saving">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="animation:spin 1s linear infinite;"><circle cx="12" cy="12" r="10" stroke-dasharray="60" stroke-dashoffset="20"/></svg>
                Saving...
            </span>
            <span class="fb-save-indicator saved" x-show="lastSaved" x-text="'✓ Saved ' + lastSaved"></span>
        </div>
        <div class="fb-topbar-right">
            <a href="{{ route('form-builder.preview', $form) }}" target="_blank" class="btn btn-ghost btn-sm" style="border:1px solid rgba(99,102,241,0.1);">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                Preview
            </a>
            <a href="{{ route('form-builder.submissions', $form) }}" class="btn btn-ghost btn-sm" style="border:1px solid rgba(99,102,241,0.1);">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                Submissions
            </a>
            <button @click="saveAll()" class="btn btn-primary btn-sm" style="background:linear-gradient(135deg, var(--accent-primary), #a78bfa); border:none; box-shadow:0 4px 12px rgba(99,102,241,0.2);">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                Save
            </button>
        </div>
    </div>

    <div class="fb-layout">
        {{-- Left: Field Palette --}}
        <div class="fb-palette">
            <h4 class="fb-palette-title">Add Field</h4>
            <div class="fb-palette-fields">
                @foreach($fieldTypes as $type => $info)
                <button class="fb-palette-item" @click="addField('{{ $type }}', '{{ $info['label'] }}')">
                    <span class="fb-palette-icon">
                        @switch($info['icon'])
                            @case('text') <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg> @break
                            @case('align-left') <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="17" y1="10" x2="3" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="17" y1="18" x2="3" y2="18"/></svg> @break
                            @case('hash') <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="9" x2="20" y2="9"/><line x1="4" y1="15" x2="20" y2="15"/><line x1="10" y1="3" x2="8" y2="21"/><line x1="16" y1="3" x2="14" y2="21"/></svg> @break
                            @case('calendar') <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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> @break
                            @case('chevron-down') <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg> @break
                            @case('check-square') <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg> @break
                            @case('paperclip') <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg> @break
                            @case('minus') <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"/></svg> @break
                            @case('type') <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg> @break
                        @endswitch
                    </span>
                    <span>{{ $info['label'] }}</span>
                </button>
                @endforeach
            </div>
        </div>

        {{-- Center: Canvas --}}
        <div class="fb-canvas">
            <div class="fb-canvas-header">
                <h2 x-text="formTitle || 'Untitled Form'" class="fb-canvas-title"></h2>
                <p x-text="formDescription || 'Add a description...'" class="fb-canvas-desc" contenteditable="true" @blur="formDescription = $el.textContent"></p>
            </div>

            <div class="fb-fields-list" id="fb-sortable">
                <template x-for="(field, index) in fields" :key="field._uid">
                    <div class="fb-field-item" :class="{'active': selectedField === index}" @click="selectField(index)">
                        <div class="fb-field-drag-handle">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="9" cy="5" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="19" r="1"/></svg>
                        </div>
                        <div class="fb-field-body" x-show="field.type !== 'section' && field.type !== 'heading'">
                            <label class="fb-field-label">
                                <span x-text="field.label"></span>
                                <span x-show="field.is_required" class="fb-required">*</span>
                            </label>
                            <div class="fb-field-preview">
                                <template x-if="field.type === 'text'">
                                    <input type="text" :placeholder="field.placeholder || 'Text input'" class="form-input" disabled>
                                </template>
                                <template x-if="field.type === 'textarea'">
                                    <textarea :placeholder="field.placeholder || 'Long text'" class="form-input" rows="2" disabled></textarea>
                                </template>
                                <template x-if="field.type === 'number'">
                                    <input type="number" :placeholder="field.placeholder || '0'" class="form-input" disabled>
                                </template>
                                <template x-if="field.type === 'date'">
                                    <input type="date" class="form-input" disabled>
                                </template>
                                <template x-if="field.type === 'select'">
                                    <select class="form-input" disabled>
                                        <option x-text="field.placeholder || 'Select an option'"></option>
                                        <template x-for="opt in (field.options || [])">
                                            <option x-text="opt.label"></option>
                                        </template>
                                    </select>
                                </template>
                                <template x-if="field.type === 'multi_select'">
                                    <div class="fb-multi-preview">
                                        <template x-for="opt in (field.options || [])">
                                            <label class="fb-checkbox-item"><input type="checkbox" disabled> <span x-text="opt.label"></span></label>
                                        </template>
                                    </div>
                                </template>
                                <template x-if="field.type === 'file'">
                                    <div class="fb-file-preview">
                                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                                        <span>Drop files or click to upload</span>
                                    </div>
                                </template>
                            </div>
                            <p x-show="field.help_text" class="fb-field-help" x-text="field.help_text"></p>
                            <div x-show="field.conditional_rules && field.conditional_rules.conditions && field.conditional_rules.conditions.length > 0" class="fb-cond-badge">
                                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
                                Has conditions
                            </div>
                        </div>
                        <div class="fb-field-section" x-show="field.type === 'section' || field.type === 'heading'">
                            <div class="fb-section-line"></div>
                            <span x-text="field.label" :class="field.type === 'heading' ? 'fb-heading-text' : 'fb-section-text'"></span>
                        </div>
                        <button class="fb-field-delete" @click.stop="removeField(index)" title="Remove">
                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                        </button>
                    </div>
                </template>
            </div>

            <div x-show="fields.length === 0" class="fb-empty-canvas">
                <div style="width:64px; height:64px; margin:0 auto 12px; border-radius:16px; background:linear-gradient(135deg, rgba(99,102,241,0.08), rgba(139,92,246,0.08)); display:flex; align-items:center; justify-content:center;">
                    <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--accent-primary)" stroke-width="1.5" style="opacity:.6;"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
                </div>
                <p>Click a field type from the left panel to add it</p>
            </div>
        </div>

        {{-- Right: Properties Panel --}}
        <div class="fb-properties" x-show="selectedField !== null">
            <template x-if="selectedField !== null && fields[selectedField]">
                <div>
                    <h4 class="fb-prop-title">
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.604.852.997 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
                        Field Properties
                    </h4>
                    <div class="fb-prop-section">
                        <label class="form-label">Label</label>
                        <input type="text" x-model="fields[selectedField].label" class="form-input">
                    </div>
                    <div class="fb-prop-section" x-show="!['section','heading'].includes(fields[selectedField].type)">
                        <label class="form-label">Field Key</label>
                        <input type="text" x-model="fields[selectedField].field_key" class="form-input" style="font-family:'SF Mono','Fira Code',monospace; font-size:0.78rem;">
                    </div>
                    <div class="fb-prop-section" x-show="['text','textarea','number','select'].includes(fields[selectedField].type)">
                        <label class="form-label">Placeholder</label>
                        <input type="text" x-model="fields[selectedField].placeholder" class="form-input">
                    </div>
                    <div class="fb-prop-section" x-show="!['section','heading'].includes(fields[selectedField].type)">
                        <label class="form-label">Help Text</label>
                        <input type="text" x-model="fields[selectedField].help_text" class="form-input">
                    </div>
                    <div class="fb-prop-section" x-show="!['section','heading'].includes(fields[selectedField].type)">
                        <label class="toggle-inline">
                            <input type="checkbox" x-model="fields[selectedField].is_required">
                            <span>Required</span>
                        </label>
                    </div>
                    <div class="fb-prop-section" x-show="!['section','heading'].includes(fields[selectedField].type)">
                        <label class="form-label">Width</label>
                        <select x-model="fields[selectedField].width" class="form-input">
                            <option value="full">Full Width</option>
                            <option value="half">Half Width</option>
                        </select>
                    </div>

                    {{-- Options for select / multi_select --}}
                    <div class="fb-prop-section" x-show="['select','multi_select'].includes(fields[selectedField].type)">
                        <label class="form-label">Options</label>
                        <div class="fb-options-list">
                            <template x-for="(opt, oi) in (fields[selectedField].options || [])" :key="oi">
                                <div class="fb-option-row">
                                    <input type="text" x-model="opt.label" class="form-input" placeholder="Label" @blur="opt.value = opt.value || opt.label.toLowerCase().replace(/\s+/g, '_')">
                                    <input type="text" x-model="opt.value" class="form-input" placeholder="Value" style="font-family:monospace; font-size:0.75rem;">
                                    <button @click="fields[selectedField].options.splice(oi, 1)" class="fb-opt-remove">&times;</button>
                                </div>
                            </template>
                        </div>
                        <button @click="if(!fields[selectedField].options) fields[selectedField].options = []; fields[selectedField].options.push({label:'',value:''})" class="td-add-btn" style="margin-top:8px;">
                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                            Add Option
                        </button>
                    </div>

                    {{-- Conditional Logic --}}
                    <div class="fb-prop-section" x-show="!['section','heading'].includes(fields[selectedField].type)">
                        <label class="form-label" style="display:flex; align-items:center; gap:6px;">
                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
                            Conditional Logic
                        </label>
                        <div x-data="{showLogic: !!(fields[selectedField].conditional_rules && fields[selectedField].conditional_rules.conditions && fields[selectedField].conditional_rules.conditions.length)}">
                            <label class="toggle-inline" style="margin-bottom:10px;">
                                <input type="checkbox" x-model="showLogic" @change="if(!showLogic) fields[selectedField].conditional_rules = null; else fields[selectedField].conditional_rules = {action:'show', logic:'and', conditions:[{field_key:'',operator:'equals',value:''}]}">
                                <span>Enable conditions</span>
                            </label>
                            <div x-show="showLogic && fields[selectedField].conditional_rules">
                                <select x-model="fields[selectedField].conditional_rules.action" class="form-input" style="margin-bottom:8px;">
                                    <option value="show">Show this field if</option>
                                    <option value="hide">Hide this field if</option>
                                </select>
                                <template x-for="(cond, ci) in (fields[selectedField].conditional_rules?.conditions || [])" :key="ci">
                                    <div class="fb-cond-row">
                                        <select x-model="cond.field_key" class="form-input">
                                            <option value="">Select field</option>
                                            <template x-for="f in fields.filter((f,i) => i !== selectedField && !['section','heading'].includes(f.type))">
                                                <option :value="f.field_key" x-text="f.label"></option>
                                            </template>
                                        </select>
                                        <select x-model="cond.operator" class="form-input">
                                            <option value="equals">equals</option>
                                            <option value="not_equals">not equals</option>
                                            <option value="contains">contains</option>
                                            <option value="is_empty">is empty</option>
                                            <option value="is_not_empty">is not empty</option>
                                        </select>
                                        <input x-show="!['is_empty','is_not_empty'].includes(cond.operator)" type="text" x-model="cond.value" class="form-input" placeholder="Value">
                                        <button @click="fields[selectedField].conditional_rules.conditions.splice(ci, 1)" class="fb-opt-remove">&times;</button>
                                    </div>
                                </template>
                                <div style="display:flex; gap:6px; margin-top:8px;">
                                    <button @click="fields[selectedField].conditional_rules.conditions.push({field_key:'',operator:'equals',value:''})" class="td-add-btn" style="font-size:0.75rem;">+ Condition</button>
                                    <select x-model="fields[selectedField].conditional_rules.logic" class="form-input" style="width:80px; font-size:0.78rem;">
                                        <option value="and">AND</option>
                                        <option value="or">OR</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </div>

        {{-- Right: Settings Panel (when no field selected) --}}
        <div class="fb-properties" x-show="selectedField === null">
            <h4 class="fb-prop-title">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/></svg>
                Form Settings
            </h4>

            <div class="fb-prop-section">
                <label class="form-label">Accent Color</label>
                <input type="color" x-model="settings.accent_color" class="form-input" style="height:38px; padding:3px; border-radius:8px; cursor:pointer;">
            </div>
            <div class="fb-prop-section">
                <label class="form-label">Success Message</label>
                <textarea x-model="settings.success_message" class="form-input" rows="2"></textarea>
            </div>
            <div class="fb-prop-section">
                <label class="toggle-inline">
                    <input type="checkbox" x-model="isPublic">
                    <span>Public Access</span>
                </label>
                <p x-show="isPublic" class="fb-field-help" style="margin-top:8px;">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
                    <a href="{{ $form->public_url }}" target="_blank" style="color:var(--accent-primary); font-weight:600;">{{ $form->public_url }}</a>
                </p>
            </div>
            <div class="fb-prop-section">
                <label class="toggle-inline">
                    <input type="checkbox" x-model="isActive">
                    <span>Active (accepting submissions)</span>
                </label>
            </div>

            <h4 class="fb-prop-title" style="margin-top:24px;">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
                Task Automation
            </h4>
            <div class="fb-prop-section">
                <label class="form-label">Title from field</label>
                <select x-model="taskMapping.title_field" class="form-input">
                    <option value="">None</option>
                    <template x-for="f in fields.filter(f => f.type === 'text')">
                        <option :value="f.field_key" x-text="f.label"></option>
                    </template>
                </select>
            </div>
            <div class="fb-prop-section">
                <label class="form-label">Project</label>
                <select x-model="taskMapping.project_id" class="form-input">
                    <option value="">Same as form</option>
                    @foreach($projects as $project)
                    <option value="{{ $project->id }}">{{ $project->name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="fb-prop-section">
                <label class="toggle-inline">
                    <input type="checkbox" x-model="taskMapping.attach_uploads">
                    <span>Attach uploaded files to task</span>
                </label>
            </div>

            <h4 class="fb-prop-title" style="margin-top:24px;">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                SLA
            </h4>
            <div class="fb-prop-section">
                <label class="form-label">SLA Deadline (hours)</label>
                <input type="number" x-model.number="slaHours" class="form-input" min="0" placeholder="Leave empty for no SLA">
            </div>
        </div>
    </div>
</div>

<style>@keyframes spin { to { transform: rotate(360deg); } }</style>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
function formBuilder() {
    return {
        formTitle: @json($form->title),
        formDescription: @json($form->description ?? ''),
        fields: @json($form->fields->map(fn($f) => array_merge($f->toArray(), ['_uid' => $f->id ?? uniqid()]))->values()),
        selectedField: null,
        saving: false,
        lastSaved: null,
        isPublic: @json($form->is_public),
        isActive: @json($form->is_active),
        settings: @json($form->settings ?? ['accent_color' => '#6366f1', 'success_message' => 'Thank you!']),
        taskMapping: @json($form->task_mapping ?? ['title_field' => '', 'project_id' => '', 'attach_uploads' => false]),
        slaHours: @json($form->sla_hours ?? ''),

        init() {
            this.$nextTick(() => {
                this.initSortable();
            });
            this.fields.forEach((f, i) => {
                if (!f._uid) f._uid = f.id || ('new_' + Date.now() + '_' + i);
            });
        },

        initSortable() {
            const el = document.getElementById('fb-sortable');
            if (!el) return;
            new Sortable(el, {
                handle: '.fb-field-drag-handle',
                animation: 250,
                ghostClass: 'fb-sortable-ghost',
                onEnd: (evt) => {
                    const moved = this.fields.splice(evt.oldIndex, 1)[0];
                    this.fields.splice(evt.newIndex, 0, moved);
                    this.fields.forEach((f, i) => f.sort_order = i);
                }
            });
        },

        addField(type, label) {
            const key = label.toLowerCase().replace(/[^a-z0-9]+/g, '_') + '_' + Date.now().toString(36).slice(-4);
            const field = {
                _uid: 'new_' + Date.now(),
                id: null,
                field_key: key,
                type: type,
                label: label,
                placeholder: '',
                help_text: '',
                options: ['select', 'multi_select'].includes(type) ? [{label: 'Option 1', value: 'option_1'}] : null,
                validations: null,
                is_required: false,
                sort_order: this.fields.length,
                width: 'full',
                conditional_rules: null,
            };
            this.fields.push(field);
            this.selectedField = this.fields.length - 1;
            this.$nextTick(() => this.initSortable());
        },

        removeField(index) {
            this.fields.splice(index, 1);
            if (this.selectedField === index) this.selectedField = null;
            else if (this.selectedField > index) this.selectedField--;
        },

        selectField(index) {
            this.selectedField = this.selectedField === index ? null : index;
        },

        async saveAll() {
            this.saving = true;
            try {
                await fetch('{{ route("form-builder.update", $form) }}', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json'},
                    body: JSON.stringify({
                        title: this.formTitle,
                        description: this.formDescription,
                        is_public: this.isPublic,
                        is_active: this.isActive,
                        settings: this.settings,
                        task_mapping: this.taskMapping,
                        sla_hours: this.slaHours || null,
                    })
                });

                const fieldsPayload = this.fields.map((f, i) => ({...f, sort_order: i}));
                await fetch('{{ route("form-builder.fields.update", $form) }}', {
                    method: 'PUT',
                    headers: {'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json'},
                    body: JSON.stringify({fields: fieldsPayload})
                });

                this.lastSaved = new Date().toLocaleTimeString();
                setTimeout(() => this.lastSaved = null, 3000);
            } catch(e) {
                console.error('Save failed', e);
            }
            this.saving = false;
        }
    };
}
</script>
@endsection
