<div class="container-fluid py-4">
    <x-title :breadcrumbs="[
        ['link' => route('templates.index'), 'title' => 'Templates'],
        ['link' => '', 'title' => $template?->exists ? 'Edit' : 'Create'],
    ]">
        {{ $template?->exists ? 'Edit template' : 'Create template' }}
        <x-slot:buttons>
            <a wire:navigate href="{{ route('templates.index') }}" wire:navigate class="btn btn-outline-secondary me-2">
                <i class="mdi mdi-arrow-left me-1"></i>Back
            </a>
            @canany(['templates.create', 'templates.edit'])
                <button wire:click="save" class="btn btn-success px-4">Save Template</button>
            @endcanany
        </x-slot:buttons>
    </x-title>

    @if(session('template_saved'))
        <div class="alert alert-success">{{ session('template_saved') }}</div>
    @endif
    @if(session('template_error'))
        <div class="alert alert-warning">{{ session('template_error') }}</div>
    @endif
    @if(!empty($unknownAtSave))
        <div class="alert alert-warning">
            <strong>Unknown placeholders detected:</strong> {{ implode(', ', $unknownAtSave) }}
            <div class="small mt-1">
                These will render as empty strings for manual sends, and cause automatic triggers to fail and be logged.
            </div>
        </div>
    @endif

    <div class="row g-3">
        {{-- LEFT: editor form --}}
        <div class="col-lg-7">
            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h5 class="mb-3">Details</h5>

                    <div class="row g-3">
                        <div class="col-md-8">
                            <label class="form-label fw-bold">Name</label>
                            <input type="text" wire:model.live.debounce.500ms="name" class="form-control" placeholder="e.g. Welcome email">
                            @error('name') <small class="text-danger">{{ $message }}</small> @enderror
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold">Internal key</label>
                            <input type="text" wire:model="key" class="form-control" placeholder="welcome_email">
                            <small class="text-muted">Used by code-driven sends.</small>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label fw-bold">Channel</label>
                            <select wire:model.live="channel" class="form-select">
                                <option value="email">Email</option>
                                <option value="sms">SMS</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold">Category</label>
                            <select wire:model="category_id" class="form-select">
                                <option value="">—</option>
                                @foreach($categories as $c)
                                    <option value="{{ $c->id }}">{{ $c->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold">Applies to</label>
                            <select wire:model.live="applies_to_type" class="form-select">
                                <option value="">Any record</option>
                                <option value="App\Models\Client\Client">Client</option>
                                <option value="App\Models\Claim\Claim">Claim</option>
                            </select>
                            <small class="text-muted">Filters placeholders + triggers.</small>
                        </div>

                        <div class="col-12">
                            <label class="form-label fw-bold">Description <span class="text-muted">(optional)</span></label>
                            <input type="text" wire:model="description" class="form-control" placeholder="What this template is for...">
                        </div>
                    </div>

                    <hr class="my-4"/>
                    <h5 class="mb-3">
                        <i class="mdi {{ $channel === 'email' ? 'mdi-email-outline' : 'mdi-message-text-outline' }} me-1"></i>
                        Content
                    </h5>

                    @if($channel === 'email')
                        <div class="mb-3">
                            <label class="form-label fw-bold d-flex justify-content-between">
                                <span>Subject</span>
                                <small class="text-muted">Placeholders allowed</small>
                            </label>
                            <input type="text" wire:model.live.debounce.400ms="subject" class="form-control">
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold">HTML body</label>
                            <textarea wire:model.live.debounce.500ms="body_html_template"
                                      class="form-control font-monospace"
                                      rows="10"
                                      style="font-size: 0.9rem;"></textarea>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold d-flex justify-content-between">
                                <span>Plain text body</span>
                                <small class="text-muted">Sent as fallback + basis for signature text</small>
                            </label>
                            <textarea wire:model.live.debounce.500ms="body_text_template"
                                      class="form-control"
                                      rows="5"></textarea>
                        </div>
                    @else
                        <div class="mb-3">
                            <label class="form-label fw-bold">SMS body</label>
                            <textarea wire:model.live.debounce.400ms="body_text_template"
                                      class="form-control" rows="5"></textarea>
                            @if($smsLength !== null)
                                <div class="small text-muted mt-1">
                                    <i class="mdi mdi-counter me-1"></i>
                                    {{ $smsLength }} chars &middot;
                                    {{ $smsSegments }} segment{{ $smsSegments === 1 ? '' : 's' }}
                                    &middot; {{ $smsEncoding }}
                                    @if($smsSegments > 1)
                                        <span class="text-warning">— will be sent as multiple parts</span>
                                    @endif
                                </div>
                            @endif
                        </div>
                    @endif
                </div>
            </div>

            {{-- Sender + flags --}}
            <div class="card shadow-sm mb-3">
                <div class="card-body">
                    <h5 class="mb-3">Sender &amp; flags</h5>

                    <div class="row g-3">
                        @if($channel === 'email')
                            <div class="col-md-8">
                                <label class="form-label fw-bold">Default email sender</label>
                                <select wire:model.live="default_sender_email_id" class="form-select">
                                    <option value="">— use solicitor default —</option>
                                    @foreach($emailSenders as $s)
                                        <option value="{{ $s->id }}">{{ $s->label() }}</option>
                                    @endforeach
                                </select>
                                <small class="text-muted">If blank, falls back to the solicitor's general sender.</small>
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <div class="form-check form-switch">
                                    <input type="checkbox" class="form-check-input" id="inc_sig"
                                           wire:model.live="include_signature">
                                    <label class="form-check-label" for="inc_sig">Include signature</label>
                                </div>
                            </div>
                        @else
                            <div class="col-md-12">
                                <label class="form-label fw-bold">Default SMS sender</label>
                                <select wire:model.live="default_sms_sender_id" class="form-select">
                                    <option value="">— use solicitor default —</option>
                                    @foreach($smsSenders as $s)
                                        <option value="{{ $s->id }}">{{ $s->label() }}</option>
                                    @endforeach
                                </select>
                                @if($smsSenders->isEmpty())
                                    <small class="text-warning">
                                        No SMS senders are whitelisted yet. Add one under Solicitor → SMS Senders.
                                    </small>
                                @endif
                            </div>
                        @endif

                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input type="checkbox" class="form-check-input" id="tpl_active"
                                       wire:model.live="is_active">
                                <label class="form-check-label" for="tpl_active">Active</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input type="checkbox" class="form-check-input" id="tpl_manual"
                                       wire:model.live="allow_manual_send">
                                <label class="form-check-label" for="tpl_manual">Available for manual send</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input type="checkbox" class="form-check-input" id="tpl_auto"
                                       wire:model.live="allow_automatic_send">
                                <label class="form-check-label" for="tpl_auto">Usable by triggers</label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {{-- Triggers section (only once the template exists) --}}
            @if($template?->exists)
                <div class="card shadow-sm mb-3">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0">
                                <i class="mdi mdi-robot-outline me-1"></i>Automatic triggers
                            </h5>
                            @can('communications.triggers.manage')
                                <button type="button" class="btn btn-primary btn-sm"
                                        wire:click="openTriggerForm(null)"
                                        @disabled(!$allow_automatic_send)>
                                    <i class="mdi mdi-plus me-1"></i>Add trigger
                                </button>
                            @endcan
                        </div>

                        @if(!$allow_automatic_send)
                            <div class="alert alert-light small mb-3">
                                Enable <em>"Usable by triggers"</em> above to allow this template to fire automatically.
                            </div>
                        @endif

                        @if($triggers->isEmpty())
                            <div class="text-muted small">No triggers configured.</div>
                        @else
                            <table class="table table-sm align-middle">
                                <thead>
                                    <tr>
                                        <th>Event</th>
                                        <th>Model</th>
                                        <th>Conditions</th>
                                        <th>Dedupe</th>
                                        <th>Active</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($triggers as $trig)
                                        <tr wire:key="trg-{{ $trig->id }}">
                                            <td><span class="badge bg-secondary">{{ $trig->trigger_type->label() }}</span></td>
                                            <td class="small">{{ class_basename($trig->model_type ?? 'Any') }}</td>
                                            <td class="small">
                                                @if($trig->conditions)
                                                    <code>{{ json_encode($trig->conditions) }}</code>
                                                @else
                                                    <span class="text-muted">—</span>
                                                @endif
                                            </td>
                                            <td class="small">{{ $trig->dedupe_window_minutes }}m</td>
                                            <td>
                                                @if($trig->is_active)
                                                    <span class="badge bg-success">on</span>
                                                @else
                                                    <span class="badge bg-secondary">off</span>
                                                @endif
                                            </td>
                                            <td class="text-end">
                                                @can('communications.triggers.manage')
                                                    <button class="btn btn-sm btn-outline-primary"
                                                            wire:click="openTriggerForm({{ $trig->id }})">Edit</button>
                                                    <button class="btn btn-sm btn-outline-danger"
                                                            wire:click="deleteTrigger({{ $trig->id }})"
                                                            wire:confirm="Delete this trigger?">
                                                        <i class="mdi mdi-delete"></i>
                                                    </button>
                                                @endcan
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        @endif

                        @if($showTriggerForm)
                            <div class="border rounded p-3 mt-3 bg-light">
                                <h6>{{ $editingTriggerId ? 'Edit trigger' : 'New trigger' }}</h6>
                                <div class="row g-2">
                                    <div class="col-md-4">
                                        <label class="form-label small">Event type</label>
                                        <select wire:model="triggerForm.trigger_type" class="form-select form-select-sm">
                                            @foreach($triggerTypes as $tt)
                                                <option value="{{ $tt->value }}">{{ $tt->label() }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label small">Model class</label>
                                        <input type="text" wire:model="triggerForm.model_type"
                                               class="form-control form-control-sm"
                                               placeholder="App\Models\Claim\Claim">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label small">Dedupe window (minutes)</label>
                                        <input type="number" wire:model="triggerForm.dedupe_window_minutes"
                                               class="form-control form-control-sm">
                                    </div>
                                    <div class="col-12">
                                        <label class="form-label small">Conditions (JSON)</label>
                                        <textarea wire:model="triggerForm.conditions"
                                                  class="form-control form-control-sm font-monospace"
                                                  rows="3"
                                                  placeholder='{"to_status_id": 5}'></textarea>
                                        @error('triggerForm.conditions')
                                            <small class="text-danger">{{ $message }}</small>
                                        @enderror
                                        <small class="text-muted">
                                            Keys are matched against the trigger event payload.
                                            Example for status change: <code>{"to_status_id": 5}</code>.
                                            @if($statuses->count())
                                                Available status ids:
                                                @foreach($statuses->take(10) as $s)
                                                    <code>{{ $s->id }}={{ $s->display_name }}</code>{{ !$loop->last ? ', ' : '' }}
                                                @endforeach
                                                @if($statuses->count() > 10)&hellip;@endif
                                            @endif
                                        </small>
                                    </div>
                                    <div class="col-12">
                                        <div class="form-check form-switch">
                                            <input type="checkbox" class="form-check-input"
                                                   id="trg_active_edit"
                                                   wire:model="triggerForm.is_active">
                                            <label class="form-check-label" for="trg_active_edit">Active</label>
                                        </div>
                                    </div>
                                    <div class="col-12 text-end">
                                        <button class="btn btn-outline-secondary btn-sm" wire:click="cancelTrigger">Cancel</button>
                                        @can('communications.triggers.manage')
                                            <button class="btn btn-success btn-sm" wire:click="saveTrigger">Save trigger</button>
                                        @endcan
                                    </div>
                                </div>
                            </div>
                        @endif
                    </div>
                </div>
            @else
                <div class="alert alert-info small">
                    <i class="mdi mdi-information-outline me-1"></i>
                    Save the template first to configure automatic triggers.
                </div>
            @endif
        </div>

        {{-- RIGHT: placeholders + preview --}}
        <div class="col-lg-5">
            <div class="card shadow-sm mb-3">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span class="fw-bold">
                        <i class="mdi mdi-code-braces me-1"></i>Available placeholders
                    </span>
                    <small class="text-muted">click to insert</small>
                </div>
                <div class="card-body" style="max-height: 320px; overflow-y: auto;">
                    @foreach($placeholdersByPrefix as $prefix => $group)
                        <div class="mb-2">
                            <div class="small text-uppercase text-muted fw-bold">{{ $prefix }}</div>
                            @foreach($group as $p)
                                @php $displayToken = '{' . '{ ' . $p->token . ' }' . '}'; @endphp
                                <div class="d-flex justify-content-between align-items-center py-1 border-bottom">
                                    <div>
                                        <code class="small">{{ $displayToken }}</code>
                                        @if($p->description)
                                            <div class="small text-muted">{{ $p->description }}</div>
                                        @endif
                                    </div>
                                    <div class="btn-group btn-group-sm">
                                        @if($channel === 'email')
                                            <button class="btn btn-outline-secondary btn-sm"
                                                    wire:click="insertPlaceholder('{{ $p->token }}', 'subject')"
                                                    title="Insert into subject">Subj</button>
                                            <button class="btn btn-outline-secondary btn-sm"
                                                    wire:click="insertPlaceholder('{{ $p->token }}', 'html')"
                                                    title="Insert into HTML body">HTML</button>
                                            <button class="btn btn-outline-secondary btn-sm"
                                                    wire:click="insertPlaceholder('{{ $p->token }}', 'text')"
                                                    title="Insert into plain text">Text</button>
                                        @else
                                            <button class="btn btn-outline-secondary btn-sm"
                                                    wire:click="insertPlaceholder('{{ $p->token }}', 'text')">
                                                Insert
                                            </button>
                                        @endif
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @endforeach

                    @if($placeholdersByPrefix->isEmpty())
                        <div class="text-muted small">No placeholders registered.</div>
                    @endif
                </div>
            </div>

            <div class="card shadow-sm">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span class="fw-bold"><i class="mdi mdi-eye-outline me-1"></i>Live preview</span>
                    <select wire:model.live="previewClientId" class="form-select form-select-sm" style="width:auto;">
                        <option value="">Sample client...</option>
                        @foreach($previewClients as $c)
                            <option value="{{ $c->id }}">{{ $c->name_first }} {{ $c->name_last }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="card-body">
                    @if(!empty($previewUnknown))
                        <div class="alert alert-warning py-2 small mb-2">
                            Unknown placeholders: {{ implode(', ', $previewUnknown) }}
                        </div>
                    @endif

                    @if($channel === 'email')
                        @if($previewSubject)
                            <div class="border rounded mb-2 p-2 bg-light">
                                <small class="text-muted">Subject</small>
                                <div class="fw-semibold">{{ $previewSubject }}</div>
                            </div>
                        @endif
                        <div class="border rounded bg-white p-3" style="min-height: 260px; max-height: 460px; overflow:auto;">
                            {!! $previewBodyHtml ?: '<em class="text-muted">Start typing to see a preview...</em>' !!}
                        </div>
                        @if($previewBodyText)
                            <details class="mt-2">
                                <summary class="small text-muted">Plain text version</summary>
                                <pre class="small p-2 bg-light rounded mt-1" style="white-space: pre-wrap;">{{ $previewBodyText }}</pre>
                            </details>
                        @endif
                    @else
                        <div class="border rounded bg-white p-3" style="min-height: 180px;">
                            <pre class="mb-0" style="white-space: pre-wrap; font-family: inherit;">{{ $previewBodyText ?: '—' }}</pre>
                        </div>
                        @if($smsLength !== null)
                            <div class="small text-muted mt-2">
                                {{ $smsLength }} chars &middot; {{ $smsSegments }} segment(s) &middot; {{ $smsEncoding }}
                            </div>
                        @endif
                    @endif

                    @if(!empty($previewPlaceholdersUsed))
                        <details class="mt-3">
                            <summary class="small text-muted">
                                {{ count($previewPlaceholdersUsed) }} placeholder(s) resolved
                            </summary>
                            <table class="table table-sm mt-2 small">
                                <tbody>
                                    @foreach($previewPlaceholdersUsed as $token => $value)
                                        <tr>
                                            <td><code>{{ $token }}</code></td>
                                            <td>{{ $value !== '' ? $value : '(empty)' }}</td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </details>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>
