<div class="container py-4">
    <x-title>
        Email Senders
        <x-slot:buttons>
            <a href="{{ route('settings.index') }}" class="btn btn-outline-secondary">Back</a>
        </x-slot:buttons>
    </x-title>

    <div class="card shadow-sm">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h4 class="fw-bold mb-0">Email Senders</h4>
                <button class="btn btn-primary btn-sm" wire:click="showAdd">
                    <i class="mdi mdi-plus"></i> Add Sender
                </button>
            </div>

            @php
                $purposeColours = [
                    'dsar'    => 'bg-primary',
                    'client'  => 'bg-success',
                    'general' => 'bg-secondary',
                ];
            @endphp

            @if($senders->count())
                @foreach($senders as $sender)
                    <div class="p-3 rounded border bg-light position-relative mb-2">
                        <div class="pe-5">
                            <div class="fw-semibold">{{ $sender->display_name }}</div>
                            <div class="text-muted small">{{ $sender->email_address }}</div>
                            <div class="mt-1">
                                <span class="badge {{ $purposeColours[$sender->purpose] ?? 'bg-secondary' }} me-1">
                                    {{ $purposes[$sender->purpose] ?? ucfirst($sender->purpose) }}
                                </span>
                                @if($sender->is_default)
                                    <span class="badge bg-warning text-dark">Default</span>
                                @endif
                            </div>
                        </div>
                        <div class="position-absolute top-0 end-0 p-2 d-flex gap-2">
                            <i class="mdi mdi-star action-icon {{ $sender->is_default ? 'text-warning' : 'text-muted opacity-25' }}"
                               wire:click="makeDefault({{ $sender->id }})"
                               title="{{ $sender->is_default ? 'Default for ' . ($purposes[$sender->purpose] ?? $sender->purpose) : 'Set as default' }}"
                               style="cursor:pointer;"></i>
                            <i class="mdi mdi-pencil-outline action-icon"
                               wire:click="loadSender({{ $sender->id }})"
                               style="cursor:pointer;"></i>
                            <i class="mdi mdi-delete-outline action-icon text-danger"
                               wire:click="deleteSender({{ $sender->id }})"
                               wire:confirm="Delete this email sender?"
                               style="cursor:pointer;"></i>
                        </div>
                    </div>
                @endforeach
            @else
                <div class="text-center p-5 text-muted">
                    <i class="mdi mdi-email-outline" style="font-size:48px;"></i>
                    <p class="mt-3 fw-bold">No email senders configured.</p>
                    <p class="small">Add a sender to override the default system address per email type.</p>
                </div>
            @endif
        </div>

        @if($show)
            <div class="offcanvas offcanvas-end show" tabindex="-1" style="--bs-offcanvas-width:520px;" role="dialog">
                <div class="offcanvas-header">
                    <h5>{{ $editing ? 'Edit' : 'Add' }} Email Sender</h5>
                    <button type="button" class="btn-close" wire:click="hideAdd"></button>
                </div>
                <div class="offcanvas-body bg-light">
                    <form wire:submit="save">
                        @csrf

                        <x-ui.input name="display_name" label="Display Name" placeholder="e.g. DSAR Outbox"/>
                        <x-ui.input name="email_address" label="Email Address" placeholder="dsars@example.com"/>

                        <div class="mb-3">
                            <label class="form-label">Purpose</label>
                            <select class="form-select @error('purpose') is-invalid @enderror" wire:model="purpose">
                                @foreach($purposes as $key => $label)
                                    <option value="{{ $key }}">{{ $label }}</option>
                                @endforeach
                            </select>
                            @error('purpose')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                            <div class="form-text">
                                Controls which emails use this sender address.
                                Only one sender per purpose can be marked as default.
                            </div>
                        </div>

                        <div class="mb-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="is_default" wire:model="is_default">
                                <label class="form-check-label" for="is_default">
                                    Set as default for this purpose
                                </label>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label">Email Signature</label>
                            <input type="hidden" wire:model="signature" data-signature-sync>
                            <div data-signature-trix wire:ignore class="trix-signature-wrapper">
                                <input id="trix-input-{{ $this->getId() }}" type="hidden" value="{{ $signature }}">
                                <trix-editor input="trix-input-{{ $this->getId() }}"
                                             class="bg-white trix-content"
                                             style="min-height:150px; border-radius:.375rem; border:1px solid #dee2e6;">
                                </trix-editor>
                            </div>
                            <div class="form-text">Appended to all emails sent from this address.</div>
                        </div>

                        <x-ui.button class="btn-success w-100 btn-lg">
                            {{ $editing ? 'Save Changes' : 'Add Sender' }}
                        </x-ui.button>
                    </form>
                </div>
            </div>
            <div class="offcanvas-backdrop fade show" wire:click="hideAdd"></div>
        @endif
    </div>

    <link rel="stylesheet" href="https://unpkg.com/trix@2.1.1/dist/trix.css">
    <script src="https://unpkg.com/trix@2.1.1/dist/trix.umd.min.js"></script>
    <style>
        trix-editor.trix-content { border: none !important; outline: none !important; }
        trix-toolbar .trix-button-group { margin-bottom: 0; }
    </style>
    <script>
        (function () {
            function initSignatureEditor(wrapper) {
                if (wrapper._trixInit) return;
                wrapper._trixInit = true;

                const editorEl = wrapper.querySelector('trix-editor');
                if (!editorEl) return;

                const syncEl = wrapper.previousElementSibling?.matches('[data-signature-sync]')
                    ? wrapper.previousElementSibling
                    : wrapper.closest('form')?.querySelector('[data-signature-sync]');

                const innerInput  = wrapper.querySelector('input[type="hidden"]');
                const initialHtml = innerInput ? innerInput.value : '';

                function loadInitialContent() {
                    editorEl.editor.loadHTML(initialHtml);
                }

                if (editorEl.editor) {
                    loadInitialContent();
                } else {
                    editorEl.addEventListener('trix-initialize', loadInitialContent, { once: true });
                }

                editorEl.addEventListener('trix-change', () => {
                    if (syncEl) {
                        syncEl.value = editorEl.value;
                        syncEl.dispatchEvent(new Event('input', { bubbles: true }));
                    }
                });
            }

            const observer = new MutationObserver(() => {
                document.querySelectorAll('[data-signature-trix]:not([data-trix-ready])').forEach(el => {
                    el.setAttribute('data-trix-ready', '');
                    initSignatureEditor(el);
                });
            });

            observer.observe(document.body, { childList: true, subtree: true });
        })();
    </script>
</div>
