<div class="bulk-email-station">
    <x-title>
        Bulk Email Station
        <x-slot:buttons>
            <a wire:navigate href="{{ route('communications.bulk-email.history') }}"
               class="btn btn-outline-secondary waves-effect waves-light">
                <i class="mdi mdi-history me-1"></i> History
            </a>
        </x-slot:buttons>
    </x-title>

    @if($error)
        <div class="alert alert-danger">{{ $error }}</div>
    @endif
    @if($success)
        <div class="alert alert-success">{{ $success }}</div>
    @endif

    <div class="row">
        {{-- Message + preview --}}
        <div class="col-12 col-md-8">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title mb-3">Message</h5>
                    <x-ui.select :options="$templates" name="templateId" label="Email Template"/>
                    <x-ui.select :options="$senders" name="senderId" label="Send As (optional)"/>

                    <button class="btn btn-primary" wire:click="buildPreview" wire:loading.attr="disabled"
                            @disabled($matchedCount < 1)>
                        <span wire:loading.remove wire:target="buildPreview">
                            <i class="mdi mdi-eye-check-outline me-1"></i>
                            Review &amp; send to {{ number_format($matchedCount) }}
                        </span>
                        <span wire:loading wire:target="buildPreview">
                            <span class="spinner-border spinner-border-sm me-1"></span> Preparing...
                        </span>
                    </button>
                </div>
            </div>

            {{-- Live matched recipients — updates as filters change --}}
            <div class="card mt-3">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="card-title mb-0">
                            Matched recipients
                            <span class="badge bg-primary ms-1">{{ number_format($matchedCount) }}</span>
                        </h5>
                        <select class="form-select form-select-sm w-auto" wire:model.live="perPage">
                            <option value="10">10</option>
                            <option value="25">25</option>
                            <option value="50">50</option>
                        </select>
                    </div>

                    @if($noEmailCount > 0)
                        <div class="alert alert-warning py-2 mb-3">
                            <i class="mdi mdi-email-off-outline me-1"></i>
                            {{ number_format($noEmailCount) }}
                            matched client{{ $noEmailCount === 1 ? '' : 's' }}
                            {{ $noEmailCount === 1 ? 'has' : 'have' }} no email address and will be skipped.
                        </div>
                    @endif

                    <div class="table-responsive">
                        <table class="table table-sm table-hover table-striped mb-0">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th class="d-none d-md-table-cell">Status</th>
                            </tr>
                            </thead>
                            <tbody>
                            @forelse($matchedClients as $client)
                                <tr>
                                    <td>{{ $client->displayId }}</td>
                                    <td>{{ $client->title }} {{ $client->name_first }} {{ $client->name_last }}</td>
                                    <td>
                                        @if($client->email_address)
                                            {{ $client->email_address }}
                                        @else
                                            <span class="badge bg-warning text-dark">no email</span>
                                        @endif
                                    </td>
                                    <td class="d-none d-md-table-cell">
                                        {{ $client->claim?->status?->display_name ?? '—' }}
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-3">
                                        No clients match the current filter.
                                    </td>
                                </tr>
                            @endforelse
                            </tbody>
                        </table>
                    </div>

                    <div class="mt-3">
                        {{ $matchedClients->links() }}
                    </div>
                </div>
            </div>

            @if($previewBuilt)
                <div class="card border-primary mt-3">
                    <div class="card-header bg-primary text-white">Confirm send</div>
                    <div class="card-body">
                        <p class="fs-5 mb-3">
                            This will email
                            <strong>{{ number_format($recipientCount) }}</strong>
                            client{{ $recipientCount === 1 ? '' : 's' }}.
                        </p>

                        @if($recipientCount > 0)
                            <div class="border rounded p-3 mb-3 bg-light">
                                <div class="text-muted small mb-1">
                                    Sample render for {{ $sampleClientName }}
                                </div>
                                <div class="fw-bold mb-2">{{ $sampleSubject ?: '(no subject)' }}</div>
                                <div class="bulk-email-preview-body">
                                    @if($sampleBodyHtml)
                                        {!! $sampleBodyHtml !!}
                                    @else
                                        <pre class="mb-0" style="white-space: pre-wrap;">{{ $sampleBodyText }}</pre>
                                    @endif
                                </div>
                            </div>
                        @else
                            <div class="alert alert-warning">No clients match the current filter.</div>
                        @endif

                        @if($isUnfiltered && $recipientCount > 0)
                            <div class="alert alert-warning">
                                <div class="form-check mb-0">
                                    <input class="form-check-input" type="checkbox" id="confirmUnfiltered"
                                           wire:model.live="confirmedUnfiltered">
                                    <label class="form-check-label" for="confirmUnfiltered">
                                        No filters are set — I understand this will email
                                        <strong>ALL</strong> clients.
                                    </label>
                                </div>
                            </div>
                        @endif

                        <div class="d-flex gap-2">
                            <button class="btn btn-success"
                                    wire:click="confirmAndSend"
                                    wire:loading.attr="disabled"
                                    @disabled($recipientCount < 1)>
                                <i class="mdi mdi-send me-1"></i>
                                Confirm &amp; send to {{ number_format($recipientCount) }}
                            </button>
                            <button class="btn btn-outline-secondary" wire:click="$set('previewBuilt', false)">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            @endif

            @if($campaign)
                <div class="card mt-3" @if(!$campaign->status->isFinished()) wire:poll.5s @endif>
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>Latest campaign #{{ $campaign->id }}</span>
                        <span class="badge bg-{{ $campaign->status->color() }}">
                            {{ $campaign->status->label() }}
                        </span>
                    </div>
                    <div class="card-body">
                        <div class="row text-center g-2">
                            <div class="col">
                                <div class="fs-4">{{ number_format($campaign->total_recipients) }}</div>
                                <div class="text-muted small">Targeted</div>
                            </div>
                            <div class="col">
                                <div class="fs-4 text-info">{{ number_format($campaign->processed_count) }}</div>
                                <div class="text-muted small">Processed</div>
                            </div>
                            <div class="col">
                                <div class="fs-4 text-success">{{ number_format($campaign->queued_count) }}</div>
                                <div class="text-muted small">Queued</div>
                            </div>
                            <div class="col">
                                <div class="fs-4 text-dark">{{ number_format($campaign->suppressed_count) }}</div>
                                <div class="text-muted small">Opted-out</div>
                            </div>
                            <div class="col">
                                <div class="fs-4 text-warning">
                                    {{ number_format($campaign->deduped_count + $campaign->rate_limited_count) }}
                                </div>
                                <div class="text-muted small">Skipped</div>
                            </div>
                            <div class="col">
                                <div class="fs-4 text-danger">{{ number_format($campaign->failed_count) }}</div>
                                <div class="text-muted small">Failed</div>
                            </div>
                        </div>
                        @if($campaign->last_error)
                            <div class="alert alert-danger mt-3 mb-0">{{ $campaign->last_error }}</div>
                        @endif
                    </div>
                </div>
            @endif
        </div>

        {{-- Filters --}}
        <div class="col-12 col-md-4">
            <button class="btn btn-dark w-100 d-md-none mb-3" type="button" data-bs-toggle="collapse"
                    data-bs-target="#bulkFilterSidebar">
                <i class="mdi mdi-filter-variant me-1"></i> Filters
            </button>

            <div class="collapse d-md-block" id="bulkFilterSidebar">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title mb-3">Filter recipients</h5>

                        <x-ui.input type="text" name="search" label="Search"/>
                        <x-ui.checkbox-list :options="$statuses" name="status_id" label="Status" :selected="$status_id"/>
                        <x-ui.checkbox-list :options="$tags" name="tag_id" label="Tag" :selected="$tag_id"/>
                        <x-ui.checkbox-list :options="$leadSources" name="lead_source_id" label="Lead Source" :selected="$lead_source_id"/>
                        <x-ui.checkbox-list :options="$urls" name="url" label="URL / Endpoint" :selected="$url"/>
                        <x-ui.checkbox-list :options="$tranches" name="tranche_id" label="Tranche" :selected="$tranche_id"/>
                        <x-ui.checkbox-list :options="[1 => 'High Priority', 2 => 'Low Priority']" name="priority" label="Priority" :selected="$priority"/>
                        <x-ui.checkbox-list :options="$careSettings" name="care_setting_id" label="Care Setting" :selected="$care_setting_id"/>
                        <x-ui.checkbox-list :options="$handlers" name="handler" label="Handler" :selected="$handler"/>

                        <div class="row g-2">
                            <div class="col-6"><x-ui.input type="date" name="date_from" label="From"/></div>
                            <div class="col-6"><x-ui.input type="date" name="date_to" label="To"/></div>
                        </div>
                    </div>
                    <div class="card-footer bg-transparent border-top-0 d-grid">
                        <button class="btn btn-sm btn-outline-danger rounded-pill" wire:click="clearFilters">
                            Clear filters
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
