<div x-data="publicForm()" class="pf-container">
    @if(session('success'))
    <div class="pf-success">
        <div style="width:72px; height:72px; margin:0 auto 8px; border-radius:50%; background:linear-gradient(135deg, rgba(34,197,94,0.12), rgba(22,163,74,0.12)); display:flex; align-items:center; justify-content:center;">
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><polyline points="16 8 10 16 7 13"/></svg>
        </div>
        <h2>{{ session('success') }}</h2>
        @if(session('ticket_id'))
        <p class="pf-ticket">Ticket ID: <strong>{{ session('ticket_id') }}</strong></p>
        @endif
        <a href="{{ route('forms.public', $form->slug) }}" class="btn btn-primary" style="margin-top:20px; background:linear-gradient(135deg, var(--accent-primary), #a78bfa); border:none; padding:10px 28px; border-radius:10px;">Submit Another</a>
    </div>
    @else

    <div class="pf-card">
        <div class="pf-header" style="border-top: none;">
            <h1 class="pf-title">{{ $form->title }}</h1>
            @if($form->description)
            <p class="pf-desc">{{ $form->description }}</p>
            @endif
        </div>

        @if($preview ?? false)
        <div class="pf-preview-banner">
            <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 Mode — submissions are disabled
        </div>
        @endif

        <form action="{{ route('forms.submit', $form->slug) }}" method="POST" enctype="multipart/form-data" class="pf-form" @submit="submitting = true">
            @csrf

            @if($errors->any())
            <div class="alert alert-danger" style="margin-bottom:20px; border-radius:12px; border:1px solid rgba(239,68,68,0.15);">
                <ul style="margin:0; padding-left:16px;">
                    @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            @endif

            @foreach($form->fields as $fi => $field)
            <div class="pf-field-wrap"
                 x-show="isFieldVisible('{{ $field->field_key }}')"
                 style="{{ $field->width === 'half' ? 'width:calc(50% - 8px); display:inline-block; vertical-align:top;' : '' }} animation-delay: {{ $fi * 0.05 }}s;"
            >
                @if($field->type === 'section')
                    <div class="pf-section">
                        <div class="pf-section-line"></div>
                        <span>{{ $field->label }}</span>
                    </div>
                @elseif($field->type === 'heading')
                    <h3 class="pf-heading">{{ $field->label }}</h3>
                @else
                    <label class="pf-label">
                        {{ $field->label }}
                        @if($field->is_required)<span class="pf-required">*</span>@endif
                    </label>

                    @switch($field->type)
                        @case('text')
                            <input type="text" name="field_{{ $field->field_key }}" class="form-input"
                                   placeholder="{{ $field->placeholder }}"
                                   {{ $field->is_required ? 'required' : '' }}
                                   value="{{ old('field_' . $field->field_key) }}"
                                   x-model="formData.{{ $field->field_key }}">
                            @break
                        @case('textarea')
                            <textarea name="field_{{ $field->field_key }}" class="form-input" rows="4"
                                      placeholder="{{ $field->placeholder }}"
                                      {{ $field->is_required ? 'required' : '' }}
                                      x-model="formData.{{ $field->field_key }}">{{ old('field_' . $field->field_key) }}</textarea>
                            @break
                        @case('number')
                            <input type="number" name="field_{{ $field->field_key }}" class="form-input"
                                   placeholder="{{ $field->placeholder }}"
                                   {{ $field->is_required ? 'required' : '' }}
                                   value="{{ old('field_' . $field->field_key) }}"
                                   x-model="formData.{{ $field->field_key }}">
                            @break
                        @case('date')
                            <input type="date" name="field_{{ $field->field_key }}" class="form-input"
                                   {{ $field->is_required ? 'required' : '' }}
                                   value="{{ old('field_' . $field->field_key) }}"
                                   x-model="formData.{{ $field->field_key }}">
                            @break
                        @case('select')
                            <select name="field_{{ $field->field_key }}" class="form-input"
                                    {{ $field->is_required ? 'required' : '' }}
                                    x-model="formData.{{ $field->field_key }}">
                                <option value="">{{ $field->placeholder ?: 'Select...' }}</option>
                                @foreach($field->options ?? [] as $opt)
                                <option value="{{ $opt['value'] }}">{{ $opt['label'] }}</option>
                                @endforeach
                            </select>
                            @break
                        @case('multi_select')
                            <div class="pf-multi-group">
                                @foreach($field->options ?? [] as $opt)
                                <label class="pf-checkbox">
                                    <input type="checkbox" name="field_{{ $field->field_key }}[]" value="{{ $opt['value'] }}">
                                    <span>{{ $opt['label'] }}</span>
                                </label>
                                @endforeach
                            </div>
                            @break
                        @case('file')
                            <div class="pf-file-drop" @dragover.prevent="$el.classList.add('dragover')" @dragleave="$el.classList.remove('dragover')" @drop.prevent="$el.classList.remove('dragover'); $refs.fileInput_{{ $field->field_key }}.files = $event.dataTransfer.files; $el.querySelector('.pf-file-name').textContent = $event.dataTransfer.files[0]?.name || '';">
                                <input type="file" name="field_{{ $field->field_key }}" x-ref="fileInput_{{ $field->field_key }}" class="pf-file-input" @change="$el.closest('.pf-file-drop').querySelector('.pf-file-name').textContent = $el.files[0]?.name || ''">
                                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="opacity:.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 file or <strong style="color:var(--accent-primary);">browse</strong></span>
                                <span class="pf-file-name"></span>
                            </div>
                            @break
                    @endswitch

                    @if($field->help_text)
                    <p class="pf-help">{{ $field->help_text }}</p>
                    @endif

                    @error('field_' . $field->field_key)
                    <p class="pf-error">
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
                        {{ $message }}
                    </p>
                    @enderror
                @endif
            </div>
            @endforeach

            @unless($preview ?? false)
            <button type="submit" class="pf-submit" :disabled="submitting" style="background: linear-gradient(135deg, {{ $form->settings['accent_color'] ?? '#6366f1' }}, #a78bfa);">
                <span x-show="!submitting">Submit</span>
                <span x-show="submitting" style="display:flex; align-items:center; justify-content:center; gap:8px;">
                    <svg width="16" height="16" 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>
                    Submitting...
                </span>
            </button>
            @endunless
        </form>
    </div>
    @endif
</div>

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

<script>
function publicForm() {
    return {
        formData: {},
        submitting: false,
        conditionalRules: @json($form->fields->whereNotNull('conditional_rules')->mapWithKeys(fn($f) => [$f->field_key => $f->conditional_rules])),

        isFieldVisible(fieldKey) {
            const rules = this.conditionalRules[fieldKey];
            if (!rules || !rules.conditions || rules.conditions.length === 0) return true;

            const results = rules.conditions.map(cond => {
                const val = this.formData[cond.field_key] ?? '';
                switch(cond.operator) {
                    case 'equals': return val == cond.value;
                    case 'not_equals': return val != cond.value;
                    case 'contains': return String(val).includes(cond.value || '');
                    case 'is_empty': return !val || val === '';
                    case 'is_not_empty': return val && val !== '';
                    default: return true;
                }
            });

            const passes = rules.logic === 'or' ? results.some(r => r) : results.every(r => r);
            return rules.action === 'show' ? passes : !passes;
        }
    }
}
</script>
