<div wire:poll.120000ms="touchPresence">

    {{-- ══════════════════════════════════════════════════════════════════════ --}}
    {{-- AGENT STATUS BAR  (always visible in the header)                      --}}
    {{-- ══════════════════════════════════════════════════════════════════════ --}}
    <div class="d-flex align-items-center gap-3">

        {{-- Live-call badge (shown while a call is active) --}}
        @if($phase === 'connected')
            <div class="bg-white border border-danger rounded-pill px-3 py-1
                        d-flex align-items-center gap-2 shadow-sm">
                <span class="spinner-grow text-danger"
                      style="width:.55rem;height:.55rem;flex-shrink:0"></span>
                <span class="text-danger fw-semibold" style="font-size:.82rem">
                    In Call
                </span>
                <div class="vr mx-1"></div>
                <button wire:click="hangup"
                        class="btn btn-sm btn-danger rounded-pill py-0 px-3"
                        style="font-size:.78rem;height:24px;line-height:1">
                    End
                </button>
            </div>
        @endif

        {{-- Presence + dialpad — one pill. Opens the panel below, where you both
             set your status and dial. Colour reflects the current presence. --}}
        <button wire:click="toggleDialpad"
                type="button"
                title="Status &amp; dialpad"
                class="btn btn-sm rounded-pill d-flex align-items-center gap-2 {{ $this->presenceButtonClass() }}"
                style="font-size:.85rem;font-weight:500">
            <span class="d-inline-block rounded-circle bg-white"
                  style="width:8px;height:8px;flex-shrink:0;opacity:.9"></span>
            {{ str_replace('_', ' ', ucwords($agentPresence)) }}
            <i class="mdi mdi-dialpad ms-1"></i>
        </button>

    </div>

    {{-- ══════════════════════════════════════════════════════════════════════ --}}
    {{-- AD-HOC DIALPAD  (fixed bottom-right, shown when idle)                 --}}
    {{-- ══════════════════════════════════════════════════════════════════════ --}}
    @if($showDialpad && !$visible)
    <div class="dialler-overlay shadow-lg" role="dialog" aria-label="Dialpad"
         x-data="{ num: '' }">

        <div class="dialler-overlay__header dialler-overlay__header--dialpad">
            <div class="d-flex align-items-center justify-content-between">
                <div class="d-flex align-items-center gap-2">
                    <i class="mdi mdi-dialpad"></i>
                    <span class="dialler-overlay__title">Dialpad</span>
                </div>
                <button wire:click="toggleDialpad"
                        class="btn-close btn-close-white btn-sm" aria-label="Close"></button>
            </div>
        </div>

        <div class="dialler-overlay__body">

            {{-- Presence / status --}}
            <div class="mb-1">
                <div class="text-uppercase text-muted fw-semibold mb-2"
                     style="font-size:.65rem;letter-spacing:.05em">Your status</div>
                <div class="d-flex flex-wrap gap-1">
                    @foreach([
                        'available'      => ['success',   'Available'],
                        'busy'           => ['danger',    'Busy'],
                        'wrap_up'        => ['warning',   'Wrap Up'],
                        'do_not_disturb' => ['secondary', 'Do Not Disturb'],
                        'offline'        => ['secondary', 'Offline'],
                    ] as $val => [$color, $label])
                        <button type="button"
                                wire:click="setPresence('{{ $val }}')"
                                @class([
                                    'btn btn-sm rounded-pill',
                                    'btn-'.$color         => $agentPresence === $val,
                                    'btn-outline-'.$color => $agentPresence !== $val,
                                ])
                                style="font-size:.72rem;padding:.15rem .6rem">
                            {{ $label }}
                        </button>
                    @endforeach
                </div>
            </div>

            @can('communications.call.adhoc')
            <hr class="my-3">

            {{-- Number entry --}}
            <div class="d-flex align-items-center gap-2 mb-2">
                <input type="text"
                       class="form-control form-control-lg text-center fw-semibold bg-light border-0"
                       style="font-size:1.2rem;letter-spacing:1px"
                       x-model="num"
                       inputmode="tel"
                       placeholder="Enter number"
                       aria-label="Number to dial"
                       @keydown.enter="if (num.trim() !== '') $wire.startAdHocCall(num)">
                <button type="button" class="btn btn-light" title="Backspace"
                        @click="num = num.slice(0, -1)">
                    <i class="mdi mdi-backspace-outline"></i>
                </button>
            </div>

            {{-- Keypad --}}
            <div class="dialpad-grid mb-3">
                @foreach(['1','2','3','4','5','6','7','8','9','*','0','#'] as $key)
                    <button type="button" class="btn btn-outline-secondary dialpad-key"
                            @click="num = num + '{{ $key }}'">{{ $key }}</button>
                @endforeach
            </div>

            {{-- Optional client reference --}}
            <div class="mb-3">
                @if($adHocClientId)
                    <div class="d-flex align-items-center justify-content-between bg-light rounded px-2 py-1">
                        <span class="small text-truncate">
                            <i class="mdi mdi-account-outline me-1"></i>{{ $adHocClientLabel }}
                        </span>
                        <button wire:click="clearAdHocClient"
                                class="btn-close btn-sm" aria-label="Remove client"></button>
                    </div>
                @else
                    <label class="form-label small fw-semibold mb-1">
                        Reference a client <span class="text-muted fw-normal">(optional)</span>
                    </label>
                    <input type="text" class="form-control form-control-sm"
                           wire:model.live.debounce.350ms="clientSearch"
                           placeholder="Search by name or number…">
                    @if(strlen(trim($clientSearch)) >= 2)
                        <div class="list-group list-group-flush border rounded mt-1"
                             style="max-height:140px;overflow-y:auto">
                            @forelse($this->clientResults as $c)
                                <button type="button"
                                        wire:key="adhoc-cl-{{ $c['id'] }}"
                                        wire:click="selectAdHocClient({{ $c['id'] }})"
                                        class="list-group-item list-group-item-action py-1 px-2 small text-start">
                                    <span class="fw-semibold">{{ $c['label'] }}</span>
                                    @if($c['phone'])<span class="text-muted">· {{ $c['phone'] }}</span>@endif
                                </button>
                            @empty
                                <div class="list-group-item py-1 px-2 small text-muted">No matches.</div>
                            @endforelse
                        </div>
                    @endif
                @endif
            </div>

            @if($dialpadError)
                <div class="alert alert-danger py-1 px-2 small mb-2">{{ $dialpadError }}</div>
            @endif

            {{-- Call --}}
            <button type="button"
                    class="btn btn-success w-100 rounded-pill"
                    :disabled="num.trim() === ''"
                    @click="$wire.startAdHocCall(num)">
                <i class="mdi mdi-phone me-1"></i>Call
            </button>
            @endcan

        </div>
    </div>
    @endif

    {{-- ══════════════════════════════════════════════════════════════════════ --}}
    {{-- SOFTPHONE OVERLAY CARD  (fixed bottom-right, shown only when active)  --}}
    {{-- ══════════════════════════════════════════════════════════════════════ --}}
    @if($visible)
    <div class="dialler-overlay shadow-lg"
         role="dialog"
         aria-live="assertive"
         x-data="{
             seconds: 0,
             _t: null,
             start() {
                 this.seconds = 0;
                 clearInterval(this._t);
                 this._t = setInterval(() => this.seconds++, 1000);
             },
             stop() { clearInterval(this._t); this._t = null; },
             get dur() {
                 return String(Math.floor(this.seconds/60)).padStart(2,'0')
                      + ':' + String(this.seconds%60).padStart(2,'0');
             }
         }"
         @twilio-call-accepted.window="start()"
         @twilio-call-disconnected.window="stop()"
         @twilio-call-cancelled.window="stop()"
         @twilio-call-error.window="stop()"
    >

        {{-- ── Phase: INCOMING ────────────────────────────────────────────── --}}
        @if($phase === 'incoming')
            <div class="dialler-overlay__header dialler-overlay__header--incoming">
                <div class="d-flex align-items-center gap-3">
                    <div class="dialler-overlay__avatar dialler-overlay__avatar--pulse">
                        <i class="mdi mdi-phone-ring"></i>
                    </div>
                    <div>
                        <div class="dialler-overlay__title">Incoming Call</div>
                        <div class="dialler-overlay__sub">
                            {{ $callerLabel }}
                            @if($callerUrl)
                                <a wire:navigate href="{{ $callerUrl }}"
                                   onclick="window.open(this.href,'_blank','noopener,noreferrer');return false;"
                                   class="text-white ms-1"
                                   title="Open client profile in new tab">
                                    <i class="mdi mdi-open-in-new" style="font-size:.7rem;opacity:.8"></i>
                                </a>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
            <div class="dialler-overlay__body">
                <div class="d-flex gap-2">
                    <button wire:click="reject"
                            class="btn btn-outline-danger flex-fill dialler-overlay__action-btn">
                        <i class="mdi mdi-phone-hangup d-block" style="font-size:1.2rem"></i>
                        <span>Decline</span>
                    </button>
                    <button wire:click="accept"
                            @click="$dispatch('twilio-accept-browser-call')"
                            class="btn btn-success flex-fill dialler-overlay__action-btn">
                        <i class="mdi mdi-phone d-block" style="font-size:1.2rem"></i>
                        <span>Answer</span>
                    </button>
                </div>
            </div>

        {{-- ── Phase: RINGING / CONNECTING ────────────────────────────────── --}}
        @elseif($phase === 'ringing')
            {{-- Outbound: poll the server for answered_at (set when the PSTN
                 recipient actually picks up). The SDK 'accept' event fires
                 too early — only on browser↔Twilio media establishment. --}}
            @if($direction === 'outbound')
                <div wire:poll.1500ms="pollOutboundConnected"
                     style="display:none"
                     aria-hidden="true"></div>
            @endif
            <div class="dialler-overlay__header dialler-overlay__header--ringing">
                <div class="d-flex align-items-center gap-3">
                    <div class="dialler-overlay__avatar">
                        <span class="spinner-grow text-white"
                              style="width:1.3rem;height:1.3rem"
                              role="status"></span>
                    </div>
                    <div>
                        <div class="dialler-overlay__title">
                            {{ $direction === 'inbound' ? 'Connecting...' : 'Calling...' }}
                        </div>
                        <div class="dialler-overlay__sub">
                            {{ $callerLabel }}
                            @if($callerUrl)
                                <a wire:navigate href="{{ $callerUrl }}"
                                   onclick="window.open(this.href,'_blank','noopener,noreferrer');return false;"
                                   class="text-white ms-1"
                                   title="Open client profile in new tab">
                                    <i class="mdi mdi-open-in-new" style="font-size:.7rem;opacity:.8"></i>
                                </a>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
            <div class="dialler-overlay__body">
                <button wire:click="hangup"
                        class="btn btn-danger w-100 rounded-pill">
                    <i class="mdi mdi-phone-hangup me-1"></i>Cancel
                </button>
            </div>

        {{-- ── Phase: CONNECTED ────────────────────────────────────────────── --}}
        @elseif($phase === 'connected')
            <div class="dialler-overlay__header dialler-overlay__header--live">
                <div class="d-flex align-items-center justify-content-between w-100">
                    <div class="d-flex align-items-center gap-2">
                        <span class="dialler-overlay__live-dot"></span>
                        <span class="dialler-overlay__title">Live Call</span>
                    </div>
                    <span class="font-monospace fw-bold small" x-text="dur">00:00</span>
                </div>
                <div class="dialler-overlay__sub mt-1">
                    {{ $callerLabel }}
                    @if($callerUrl)
                        <a wire:navigate href="{{ $callerUrl }}"
                           onclick="window.open(this.href,'_blank','noopener,noreferrer');return false;"
                           class="text-white ms-1"
                           title="Open client profile in new tab">
                            <i class="mdi mdi-open-in-new" style="font-size:.7rem;opacity:.8"></i>
                        </a>
                    @endif
                    @if($muted)
                        &ensp;<i class="mdi mdi-microphone-off"></i>
                        <span style="font-size:.75rem">Muted</span>
                    @endif
                </div>
            </div>
            <div class="dialler-overlay__body">
                <div class="d-flex gap-2">
                    <button wire:click="toggleMute"
                            @class([
                                'btn flex-fill dialler-overlay__action-btn',
                                'btn-danger'            => $muted,
                                'btn-outline-secondary' => !$muted,
                            ])>
                        <i @class(['mdi d-block', 'mdi-microphone-off' => $muted,
                                   'mdi-microphone' => !$muted])
                           style="font-size:1.2rem"></i>
                        <span>{{ $muted ? 'Unmute' : 'Mute' }}</span>
                    </button>
                    <button wire:click="openTransferPicker"
                            wire:loading.attr="disabled" wire:target="initiateTransfer"
                            class="btn btn-outline-primary flex-fill dialler-overlay__action-btn"
                            title="Transfer call">
                        <i class="mdi mdi-phone-forward d-block" style="font-size:1.2rem"></i>
                        <span>Transfer</span>
                    </button>
                    <button wire:click="hangup"
                            class="btn btn-danger flex-fill dialler-overlay__action-btn">
                        <i class="mdi mdi-phone-hangup d-block" style="font-size:1.2rem"></i>
                        <span>End</span>
                    </button>
                </div>

                @if($showTransferPicker)
                    <div class="border-top pt-3 mt-2">
                        <div class="d-flex align-items-center justify-content-between mb-2">
                            <span class="small fw-semibold">Transfer to agent</span>
                            <button wire:click="closeTransferPicker"
                                    class="btn-close btn-sm" aria-label="Cancel"></button>
                        </div>
                        @if(count($this->availableAgents) === 0)
                            <p class="text-muted small mb-0">No agents are currently available.</p>
                        @else
                            <div class="list-group list-group-flush" style="max-height:160px;overflow-y:auto">
                                @foreach($this->availableAgents as $a)
                                    <button wire:click="initiateTransfer({{ $a['id'] }})"
                                            wire:key="ta-{{ $a['id'] }}"
                                            wire:loading.attr="disabled" wire:target="initiateTransfer"
                                            class="list-group-item list-group-item-action d-flex align-items-center gap-2 py-2 px-0 border-0"
                                            @disabled($transferring)>
                                        <span class="d-inline-block rounded-circle bg-success flex-shrink-0"
                                              style="width:8px;height:8px"></span>
                                        <span class="small">{{ $a['name'] }}</span>
                                        <span wire:loading wire:target="initiateTransfer({{ $a['id'] }})"
                                              class="spinner-border spinner-border-sm ms-auto"
                                              style="width:.75rem;height:.75rem"></span>
                                    </button>
                                @endforeach
                            </div>
                        @endif
                    </div>
                @endif

                {{-- In-call DTMF keypad — for IVR menus and keying reference numbers --}}
                <div class="border-top pt-2 mt-2" x-data="{ showKeys: false, sent: '' }">
                    <button type="button"
                            class="btn btn-sm btn-link text-decoration-none p-0 d-flex align-items-center gap-1"
                            @click="showKeys = !showKeys">
                        <i class="mdi mdi-dialpad"></i>
                        <span x-text="showKeys ? 'Hide keypad' : 'Keypad'"></span>
                        <span class="text-muted font-monospace ms-1" x-text="sent"></span>
                    </button>
                    <div x-show="showKeys" class="dialpad-grid mt-2">
                        @foreach(['1','2','3','4','5','6','7','8','9','*','0','#'] as $key)
                            <button type="button" class="btn btn-outline-secondary dialpad-key"
                                    @click="sent = (sent + '{{ $key }}').slice(-16);
                                            window.dispatchEvent(new CustomEvent('twilio-send-digits', { detail: { digits: '{{ $key }}' } }))">
                                {{ $key }}
                            </button>
                        @endforeach
                    </div>
                </div>
            </div>

        {{-- ── Phase: WRAP-UP ──────────────────────────────────────────────── --}}
        @elseif($phase === 'wrapup')
            <div class="dialler-overlay__header dialler-overlay__header--wrapup">
                <div class="d-flex align-items-center justify-content-between">
                    <div class="d-flex align-items-center gap-2">
                        <i class="mdi mdi-{{ $transferredToId ? 'phone-forward' : 'clipboard-text-outline' }}"></i>
                        <span class="dialler-overlay__title">
                            {{ $transferredToId ? 'Call Transferred' : 'Call Wrap-Up' }}
                        </span>
                    </div>
                    <button wire:click="dismissWrapUp"
                            class="btn-close btn-close-white btn-sm"
                            aria-label="Dismiss"></button>
                </div>
                <div class="dialler-overlay__sub mt-1">
                    @if($transferredToId)
                        Transferred to {{ $transferredToName }}
                    @else
                        {{ $callerLabel }}
                        @if($callerUrl)
                            <a wire:navigate href="{{ $callerUrl }}"
                               onclick="window.open(this.href,'_blank','noopener,noreferrer');return false;"
                               class="text-white ms-1"
                               title="Open client profile in new tab">
                                <i class="mdi mdi-open-in-new" style="font-size:.7rem;opacity:.8"></i>
                            </a>
                        @endif
                    @endif
                </div>
            </div>
            <div class="dialler-overlay__body">

                @if(!$communicationId)
                    <div class="alert alert-warning py-2 px-3 small mb-3">
                        <i class="mdi mdi-alert-outline me-1"></i>
                        Call record not found — cannot save disposition.
                    </div>
                @endif

                <div class="mb-3">
                    <label class="form-label small fw-semibold mb-1">
                        Outcome <span class="text-danger">*</span>
                    </label>
                    <select wire:model.live="disposition"
                            class="form-select form-select-sm
                                   @error('disposition') is-invalid @enderror">
                        <option value="">Select outcome...</option>
                        @foreach($this->dispositionOptions as $val => $label)
                            <option value="{{ $val }}">{{ $label }}</option>
                        @endforeach
                    </select>
                    @error('disposition')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>

                <div class="mb-3">
                    <label class="form-label small fw-semibold mb-1">Notes</label>
                    <textarea wire:model="notes"
                              class="form-control form-control-sm"
                              rows="2"
                              placeholder="Optional notes..."></textarea>
                </div>

                <div class="mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox"
                               wire:model.live="callbackRequired"
                               id="overlay-cb">
                        <label class="form-check-label small fw-semibold"
                               for="overlay-cb">
                            Callback required
                        </label>
                    </div>
                </div>

                @if($callbackRequired)
                    <div class="mb-3">
                        <label class="form-label small fw-semibold mb-1">
                            Callback Date & Time <span class="text-danger">*</span>
                        </label>
                        <input type="datetime-local"
                               wire:model="callbackAt"
                               class="form-control form-control-sm
                                      @error('callbackAt') is-invalid @enderror">
                        @error('callbackAt')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                @endif

                <div class="d-flex gap-2">
                    <button wire:click="saveWrapUp"
                            @disabled(!$communicationId)
                            class="btn btn-primary btn-sm flex-fill">
                        <span wire:loading.remove wire:target="saveWrapUp">
                            <i class="mdi mdi-content-save me-1"></i>Save
                        </span>
                        <span wire:loading wire:target="saveWrapUp">
                            <span class="spinner-border spinner-border-sm me-1"></span>
                            Saving...
                        </span>
                    </button>
                    <button wire:click="dismissWrapUp"
                            class="btn btn-outline-secondary btn-sm">
                        Dismiss
                    </button>
                </div>

            </div>

        {{-- ── Phase: ERROR ────────────────────────────────────────────────── --}}
        @elseif($phase === 'error')
            <div class="dialler-overlay__header dialler-overlay__header--error">
                <div class="d-flex align-items-center justify-content-between">
                    <div class="d-flex align-items-center gap-2">
                        <i class="mdi mdi-phone-off"></i>
                        <span class="dialler-overlay__title">Call Failed</span>
                    </div>
                    <button wire:click="dismiss"
                            class="btn-close btn-close-white btn-sm"
                            aria-label="Close"></button>
                </div>
            </div>
            <div class="dialler-overlay__body">
                <p class="text-danger small mb-3">{{ $errorMessage }}</p>
                <button wire:click="dismiss"
                        class="btn btn-outline-secondary btn-sm w-100">
                    Close
                </button>
            </div>

        @endif
    </div>
    @endif
    {{-- ── Overlay styles ──────────────────────────────────────────────────────── --}}
    <style>
        .dialler-overlay {
            position:      fixed;
            bottom:        24px;
            right:         24px;
            z-index:       9050;
            width:         300px;
            border-radius: 14px;
            overflow:      hidden;
            background:    #fff;
            border:        1px solid rgba(0,0,0,.13);
        }

        /* ── Phase headers ── */
        .dialler-overlay__header {
            padding: 13px 15px;
            color:   #fff;
        }
        .dialler-overlay__header--incoming { background: #0d6efd; }
        .dialler-overlay__header--ringing  { background: #6f42c1; }
        .dialler-overlay__header--live     { background: #198754; }
        .dialler-overlay__header--wrapup   { background: #0d6efd; }
        .dialler-overlay__header--error    { background: #dc3545; }

        .dialler-overlay__title { font-weight: 600; font-size: .88rem; }
        .dialler-overlay__sub   { font-size: .77rem; opacity: .85; }

        /* ── Body ── */
        .dialler-overlay__body { padding: 13px 15px; }

        /* ── Avatar circle ── */
        .dialler-overlay__avatar {
            width:           42px;
            height:          42px;
            border-radius:   50%;
            background:      rgba(255,255,255,.2);
            display:         flex;
            align-items:     center;
            justify-content: center;
            font-size:       1.25rem;
            flex-shrink:     0;
        }
        .dialler-overlay__avatar--pulse {
            animation: overlay-pulse 1.4s ease-in-out infinite;
        }
        @keyframes overlay-pulse {
            0%,100% { box-shadow: 0 0 0 0   rgba(255,255,255,.5); }
            50%     { box-shadow: 0 0 0 8px rgba(255,255,255,0);   }
        }

        /* ── Live-call blink dot ── */
        .dialler-overlay__live-dot {
            display:       inline-block;
            width:         8px; height: 8px;
            border-radius: 50%;
            background:    #fff;
            animation:     overlay-blink 1.2s ease infinite;
        }
        @keyframes overlay-blink {
            0%,100% { opacity: 1; }
            50%     { opacity: .25; }
        }

        /* ── Accept / decline / mute / end buttons ── */
        .dialler-overlay__action-btn {
            padding:     8px 4px;
            line-height: 1;
            font-size:   .75rem;
        }

        /* ── Dialpad ── */
        .dialler-overlay__header--dialpad { background: #334155; }
        .dialpad-grid {
            display:               grid;
            grid-template-columns: repeat(3, 1fr);
            gap:                   6px;
        }
        .dialpad-key {
            padding:     9px 0;
            font-size:   1.05rem;
            font-weight: 600;
        }
    </style>

</div>
