<div>
    <x-card title="Automatic triggers">
        <button type="button" class="btn btn-primary btn-sm mb-3" wire:click="newTrigger">
            <i class="mdi mdi-plus me-1"></i>Add trigger
        </button>

        <table class="table">
            <thead>
                <tr>
                    <th>Template</th>
                    <th>Trigger</th>
                    <th>Applies to</th>
                    <th>Condition</th>
                    <th>Dedupe</th>
                    <th>Active</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach($triggers as $t)
                    <tr>
                        <td>{{ $t->template?->name ?? '—' }}</td>
                        <td><span class="badge bg-secondary">{{ $t->trigger_type->label() }}</span></td>
                        <td><small>{{ $availableModels[$t->model_type] ?? class_basename($t->model_type ?? 'Any') }}</small></td>
                        <td>
                            @php
                                $parts = [];
                                $resolveNames = fn($ids, $map) => collect((array)$ids)
                                    ->map(fn($id) => $map[$id] ?? "#{$id}")
                                    ->implode(', ');
                                if (!empty($t->conditions['to_status_id'])) {
                                    $parts[] = 'To: ' . $resolveNames($t->conditions['to_status_id'], $statusMap);
                                }
                                if (!empty($t->conditions['from_status_id'])) {
                                    $parts[] = 'From: ' . $resolveNames($t->conditions['from_status_id'], $statusMap);
                                }
                                if (!empty($t->conditions['tag_id'])) {
                                    $parts[] = 'Tag: ' . $resolveNames($t->conditions['tag_id'], $tagMap);
                                }
                            @endphp
                            <small>{{ implode(' · ', $parts) ?: '—' }}</small>
                        </td>
                        <td><small>{{ $t->dedupe_window_minutes }}m</small></td>
                        <td>
                            @if($t->is_active)
                                <span class="badge bg-success">active</span>
                            @else
                                <span class="badge bg-secondary">off</span>
                            @endif
                        </td>
                        <td class="text-end">
                            <button class="btn btn-sm btn-outline-primary" wire:click="edit({{ $t->id }})">Edit</button>
                            <button class="btn btn-sm btn-outline-danger"
                                    wire:click="delete({{ $t->id }})"
                                    wire:confirm="Delete this trigger?">Delete</button>
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>

        @if($editingId !== null)
            <hr/>
            <h6 class="mb-3">{{ $editingId ? 'Edit trigger' : 'New trigger' }}</h6>
            <form wire:submit.prevent="save" class="row g-3">

                <div class="col-md-6">
                    <label class="form-label">Template</label>
                    <select class="form-select" wire:model="form.contact_template_id">
                        <option value="">— choose —</option>
                        @foreach($templates as $t)
                            <option value="{{ $t->id }}">{{ $t->name }}</option>
                        @endforeach
                    </select>
                </div>

                <div class="col-md-3">
                    <label class="form-label">When this happens</label>
                    <select class="form-select" wire:model.live="form.trigger_type">
                        @foreach($triggerTypes as $tt)
                            <option value="{{ $tt->value }}">{{ $tt->label() }}</option>
                        @endforeach
                    </select>
                </div>

                <div class="col-md-3">
                    <label class="form-label">Applies to</label>
                    <select class="form-select" wire:model="form.model_type">
                        @foreach($availableModels as $class => $label)
                            <option value="{{ $class }}">{{ $label }}</option>
                        @endforeach
                    </select>
                </div>

                {{-- Contextual condition builder --}}
                <div class="col-12">
                    @if($form['trigger_type'] === 'status_changed')
                        <label class="form-label fw-semibold">
                            Condition
                            <span class="text-muted fw-normal small ms-1">(optional — tick nothing to fire on any status change)</span>
                        </label>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <p class="form-label small text-muted mb-1">From status <span class="fw-normal">(fires if changing from any ticked status)</span></p>
                                <div class="border rounded p-2" style="max-height:180px;overflow-y:auto;">
                                    @forelse($statuses as $s)
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox"
                                                   value="{{ $s->id }}"
                                                   wire:model="conditionFromStatusIds"
                                                   id="from_s_{{ $s->id }}">
                                            <label class="form-check-label" for="from_s_{{ $s->id }}">
                                                {{ $s->display_name }}
                                            </label>
                                        </div>
                                    @empty
                                        <span class="text-muted small">No statuses configured.</span>
                                    @endforelse
                                </div>
                            </div>
                            <div class="col-md-6">
                                <p class="form-label small text-muted mb-1">To status <span class="fw-normal">(fires if changing to any ticked status)</span></p>
                                <div class="border rounded p-2" style="max-height:180px;overflow-y:auto;">
                                    @forelse($statuses as $s)
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox"
                                                   value="{{ $s->id }}"
                                                   wire:model="conditionToStatusIds"
                                                   id="to_s_{{ $s->id }}">
                                            <label class="form-check-label" for="to_s_{{ $s->id }}">
                                                {{ $s->display_name }}
                                            </label>
                                        </div>
                                    @empty
                                        <span class="text-muted small">No statuses configured.</span>
                                    @endforelse
                                </div>
                            </div>
                        </div>

                    @elseif(in_array($form['trigger_type'], ['tag_added', 'tag_removed']))
                        <label class="form-label fw-semibold">
                            Condition
                            <span class="text-muted fw-normal small ms-1">(optional — tick nothing to fire on any tag)</span>
                        </label>
                        <div class="border rounded p-2" style="max-height:180px;overflow-y:auto;">
                            @forelse($tags as $tag)
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox"
                                           value="{{ $tag->id }}"
                                           wire:model="conditionTagIds"
                                           id="tag_{{ $tag->id }}">
                                    <label class="form-check-label" for="tag_{{ $tag->id }}">
                                        {{ $tag->name }}
                                    </label>
                                </div>
                            @empty
                                <span class="text-muted small">No tags configured.</span>
                            @endforelse
                        </div>

                    @else
                        <p class="text-muted small mb-0">
                            <i class="mdi mdi-information-outline me-1"></i>No conditions are available for this trigger type — it will fire every time the event occurs.
                        </p>
                    @endif

                    <button type="button"
                            class="btn btn-link btn-sm p-0 mt-2 text-muted text-decoration-none"
                            wire:click="toggleAdvancedConditions">
                        <i class="mdi mdi-code-braces me-1"></i>
                        {{ $showAdvancedConditions ? 'Hide JSON editor' : 'Advanced: edit conditions as JSON' }}
                    </button>

                    @if($showAdvancedConditions)
                        <textarea class="form-control font-monospace mt-2" rows="4"
                                  wire:model="form.conditions"
                                  placeholder='{"to_status_id": [5]}'></textarea>
                        <small class="text-muted">Editing JSON directly overrides the checkboxes above when saving.</small>
                    @endif
                </div>

                <div class="col-md-3">
                    <label class="form-label">Don't resend within (minutes)</label>
                    <input type="number" class="form-control" wire:model="form.dedupe_window_minutes" min="0">
                    <small class="text-muted">Prevents duplicate messages. Default: 60.</small>
                </div>

                <div class="col-12">
                    <div class="form-check form-switch">
                        <input type="checkbox" class="form-check-input" wire:model="form.is_active" id="trg_active">
                        <label class="form-check-label" for="trg_active">Active</label>
                    </div>
                </div>

                <div class="col-12">
                    <button type="submit" class="btn btn-success">Save trigger</button>
                    <button type="button" class="btn btn-outline-secondary" wire:click="$set('editingId', null)">Cancel</button>
                </div>

            </form>
        @endif
    </x-card>
</div>
