<div class="agent-availability-report">
    <x-title>
        Agent Availability
        <x-slot:buttons>
            <button wire:click="$refresh" class="btn btn-primary btn-sm" title="Refresh">
                <i class="mdi mdi-sync"></i>
            </button>
        </x-slot:buttons>
    </x-title>

    <style>
        .avail-track {
            position: relative;
            height: 22px;
            min-width: 220px;
            background: #f1f3f5;
            border-radius: 4px;
            overflow: hidden;
            /* faint gridlines every 6 hours (25% of the day) */
            background-image: repeating-linear-gradient(to right, transparent 0, transparent calc(25% - 1px), #e0e3e7 calc(25% - 1px), #e0e3e7 25%);
        }
        .avail-block {
            position: absolute;
            top: 0;
            bottom: 0;
            min-width: 2px;
        }
        .avail-block--open {
            box-shadow: inset -2px 0 0 0 rgba(0, 0, 0, .35);
        }
        .avail-scale {
            display: flex;
            justify-content: space-between;
            font-size: .65rem;
        }
        .avail-legend .dot {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 2px;
            margin-right: 4px;
            vertical-align: baseline;
        }
        .kpi-stat { min-width: 90px; }
        .kpi-stat .kpi-value { font-size: 1.05rem; font-weight: 600; line-height: 1.1; }
        .kpi-stat .kpi-label { font-size: .7rem; }
    </style>

    {{-- FILTERS --}}
    <div class="card mb-3">
        <div class="card-body">
            <div class="row g-2 align-items-end">
                <div class="col-6 col-md-2">
                    <label class="form-label">From</label>
                    <input type="date" class="form-control form-control-sm" wire:model.live="from">
                </div>
                <div class="col-6 col-md-2">
                    <label class="form-label">To</label>
                    <input type="date" class="form-control form-control-sm" wire:model.live="to">
                </div>
                <div class="col-12 col-md-4">
                    <label class="form-label">Agent</label>
                    <select class="form-select form-select-sm" wire:model.live="agentId">
                        <option value="">All agents</option>
                        @foreach($agents as $a)
                            <option value="{{ $a['id'] }}">{{ $a['name'] }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-12 col-md-4">
                    <div class="avail-legend small text-muted pt-2">
                        @foreach($statuses as $key => $meta)
                            <span class="me-3 text-nowrap">
                                <span class="dot" style="background: {{ $meta['colour'] }}"></span>{{ $meta['label'] }}
                            </span>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>

    @if(empty($report['agents']))
        <div class="card">
            <div class="card-body text-center text-muted py-5">
                <i class="mdi mdi-account-clock-outline d-block mb-2 fs-2"></i>
                No agent availability recorded in this range.
            </div>
        </div>
    @else
        {{-- DAILY STACKED CHART --}}
        <div class="card mb-3">
            <div class="card-body">
                <h5 class="card-title mb-3">Time per status, by day</h5>
                <div style="position:relative;height:260px">
                    <canvas id="availabilityChart"></canvas>
                </div>
            </div>
        </div>

        {{-- PER-AGENT TIMELINE + DURATIONS --}}
        @foreach($report['agents'] as $agent)
            @php $kpi = $agent['kpi']; @endphp
            <div class="card mb-3">
                <div class="card-body">
                    <div class="d-flex flex-wrap justify-content-between align-items-start mb-3 gap-3">
                        <h5 class="card-title mb-0">{{ $agent['name'] }}</h5>
                        <div class="d-flex flex-wrap gap-3 text-center">
                            <div class="kpi-stat">
                                <div class="kpi-value">{{ $this->fmt($kpi['online']) }}</div>
                                <div class="kpi-label text-muted text-uppercase">Online</div>
                            </div>
                            <div class="kpi-stat">
                                <div class="kpi-value">{{ $kpi['occupancyPct'] }}%</div>
                                <div class="kpi-label text-muted text-uppercase">Occupancy</div>
                            </div>
                            <div class="kpi-stat">
                                <div class="kpi-value text-danger">{{ $this->fmt($kpi['busy']) }}</div>
                                <div class="kpi-label text-muted text-uppercase">On Call</div>
                            </div>
                            <div class="kpi-stat">
                                <div class="kpi-value text-warning">{{ $this->fmt($kpi['wrap_up']) }}</div>
                                <div class="kpi-label text-muted text-uppercase">
                                    Wrap-Up · {{ $kpi['wrap_up_count'] }}× · avg {{ $this->fmt($kpi['avg_wrap_up']) }}
                                </div>
                            </div>
                            <div class="kpi-stat">
                                <div class="kpi-value text-success">{{ $this->fmt($kpi['available']) }}</div>
                                <div class="kpi-label text-muted text-uppercase">Available</div>
                            </div>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-sm table-hover align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th style="width:130px">Day</th>
                                    <th>
                                        Timeline
                                        <div class="avail-scale text-muted">
                                            <span>00</span><span>06</span><span>12</span><span>18</span><span>24</span>
                                        </div>
                                    </th>
                                    @foreach($statuses as $meta)
                                        <th class="text-end text-nowrap" style="width:78px">{{ $meta['label'] }}</th>
                                    @endforeach
                                    <th class="text-end text-nowrap" style="width:86px">Online</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($report['days'] as $date)
                                    @php
                                        $day = $agent['days'][$date] ?? null;
                                        $totals = $day['totals'] ?? [];
                                        $dayOnline = ($totals['available'] ?? 0) + ($totals['busy'] ?? 0)
                                            + ($totals['wrap_up'] ?? 0) + ($totals['do_not_disturb'] ?? 0);
                                    @endphp
                                    <tr>
                                        <td class="text-nowrap small">{{ \Carbon\Carbon::parse($date)->format('D j M') }}</td>
                                        <td>
                                            <div class="avail-track">
                                                @foreach(($day['blocks'] ?? []) as $block)
                                                    @php
                                                        $meta = $statuses[$block['status']] ?? ['colour' => '#dee2e6', 'label' => $block['status']];
                                                        $left = $block['offset'] / 864;
                                                        $width = max($block['duration'] / 864, 0.4);
                                                    @endphp
                                                    <div class="avail-block {{ $block['open'] ? 'avail-block--open' : '' }}"
                                                         style="left: {{ $left }}%; width: {{ $width }}%; background: {{ $meta['colour'] }};"
                                                         title="{{ $meta['label'] }} · {{ $block['start'] }}–{{ $block['end'] }} · {{ $this->fmt($block['duration']) }}{{ $block['open'] ? ' (ongoing)' : '' }}"></div>
                                                @endforeach
                                            </div>
                                        </td>
                                        @foreach($statuses as $key => $meta)
                                            <td class="text-end small text-nowrap">{{ $this->fmt($totals[$key] ?? 0) }}</td>
                                        @endforeach
                                        <td class="text-end small text-nowrap fw-semibold">{{ $this->fmt($dayOnline) }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        @endforeach
    @endif
</div>

@assets
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
@endassets

@script
<script>
    const chart    = @json($report['chart']);
    const statuses = @json($statuses);

    const datasets = Object.entries(statuses).map(([key, meta]) => ({
        label: meta.label,
        data: (chart.datasets[key] ?? []).map(s => +(s / 3600).toFixed(2)),
        backgroundColor: meta.colour,
        borderWidth: 0,
    }));

    setTimeout(() => {
        const el = document.getElementById('availabilityChart');
        if (!el) return;

        new Chart(el, {
            type: 'bar',
            data: { labels: chart.labels, datasets },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: { mode: 'index', intersect: false },
                plugins: {
                    legend: { position: 'bottom', labels: { boxWidth: 12, padding: 16 } },
                    tooltip: {
                        callbacks: {
                            label: (ctx) => {
                                const h = Math.floor(ctx.parsed.y);
                                const m = Math.round((ctx.parsed.y - h) * 60);
                                return `${ctx.dataset.label}: ${h}h ${String(m).padStart(2, '0')}m`;
                            },
                        },
                    },
                },
                scales: {
                    x: { stacked: true, grid: { display: false } },
                    y: { stacked: true, beginAtZero: true, title: { display: true, text: 'Hours' } },
                },
            },
        });
    }, 0);
</script>
@endscript
