<div>
    <x-title>Lead Performance Dashboard</x-title>

    @php
        $heatClass = function (int $value, int $max): string {
            if ($value === 0 || $max === 0) {
                return 'bg-light';
            }

            $ratio = $value / $max;

            return match (true) {
                $ratio <= .25 => 'bg-warning-subtle',
                $ratio <= .5 => 'bg-warning',
                $ratio <= .75 => 'bg-danger-subtle',
                default => 'bg-danger text-white',
            };
        };
    @endphp

    <div class="card mb-4">
        <div class="card-body">
            <div class="row align-items-center g-3">
                <div class="col">
                    <h4 class="card-title mb-1">Lead Performance Dashboard</h4>
                    <p class="text-muted mb-0">Enquiry volume, engagement and conversion performance.</p>
                </div>
                <div class="col-auto">
                    <span class="badge bg-primary">
                        <i class="mdi mdi-calendar-range me-1"></i>
                        {{ $dashboard['periodLabel'] }}
                    </span>
                </div>
            </div>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-body">
            <div class="row mb-3">
                <div class="col-12 col-md-5 col-lg-4">
                    <label for="lead-source-filter" class="form-label">Leads</label>
                    <select id="lead-source-filter" class="form-select" wire:model.live="leadSourceId">
                        <option value="">All Leads</option>
                        @foreach($leadSourceOptions as $source)
                            <option value="{{ $source['id'] }}">{{ $source['name'] }}</option>
                        @endforeach
                    </select>
                </div>
            </div>

            <div class="btn-group mb-3" role="group" aria-label="Reporting period type">
                <button type="button"
                        class="btn {{ $filterMode === 'month' ? 'btn-primary' : 'btn-outline-primary' }}"
                        wire:click="$set('filterMode', 'month')">
                    Monthly
                </button>
                <button type="button"
                        class="btn {{ $filterMode === 'custom' ? 'btn-primary' : 'btn-outline-primary' }}"
                        wire:click="$set('filterMode', 'custom')">
                    Date range
                </button>
            </div>

            @if($filterMode === 'month')
                <form wire:submit="applyMonth" class="row align-items-end g-3">
                    <div class="col-12 col-md-4 col-lg-3">
                        <label for="lead-month" class="form-label">Reporting month</label>
                        <input id="lead-month" type="month" class="form-control" wire:model="month">
                    </div>
                    <div class="col-auto">
                        <button class="btn btn-primary" type="submit">
                            <i class="mdi mdi-filter-outline me-1"></i>Apply
                        </button>
                    </div>
                </form>
            @else
                <form wire:submit="applyCustomRange" class="row align-items-end g-3">
                    <div class="col-12 col-md-4 col-lg-3">
                        <label for="lead-start-date" class="form-label">From</label>
                        <input id="lead-start-date" type="date" class="form-control" wire:model="startDate">
                    </div>
                    <div class="col-12 col-md-4 col-lg-3">
                        <label for="lead-end-date" class="form-label">To</label>
                        <input id="lead-end-date" type="date" class="form-control" wire:model="endDate">
                    </div>
                    <div class="col-auto">
                        <button class="btn btn-primary" type="submit">
                            <i class="mdi mdi-filter-outline me-1"></i>Apply
                        </button>
                    </div>
                </form>
            @endif

            <div wire:loading class="text-primary small mt-3">
                <span class="spinner-border spinner-border-sm me-1"></span>
                Updating dashboard...
            </div>

            @error('month') <div class="text-danger small mt-2">{{ $message }}</div> @enderror
            @error('startDate') <div class="text-danger small mt-2">{{ $message }}</div> @enderror
            @error('endDate') <div class="text-danger small mt-2">{{ $message }}</div> @enderror
        </div>
    </div>

    <div class="row g-4 mb-4">
        <div class="col-12 col-md-6 col-xl-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        <div class="avatar-sm bg-primary-subtle rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                            <i class="mdi mdi-account-group-outline text-primary fs-4"></i>
                        </div>
                        <h6 class="mb-0">New Leads Received</h6>
                    </div>
                    <div class="display-6 fw-bold text-primary">{{ number_format($dashboard['newLeads']) }}</div>
                    <div class="text-muted small">Leads received in the selected period</div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 col-xl-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        <div class="avatar-sm bg-primary-subtle rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                            <i class="mdi mdi-phone-check-outline text-primary fs-4"></i>
                        </div>
                        <h6 class="mb-0">Lead to Contact Rate</h6>
                    </div>
                    <div class="display-6 fw-bold text-primary">
                        {{ $dashboard['contactRate'] === null ? '-' : number_format($dashboard['contactRate'], 1) . '%' }}
                    </div>
                    <div class="text-muted small">Successful two-way contact</div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 col-xl-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        <div class="avatar-sm bg-primary-subtle rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                            <i class="mdi mdi-file-check-outline text-primary fs-4"></i>
                        </div>
                        <h6 class="mb-0">Lead Conversion Rate</h6>
                    </div>
                    <div class="display-6 fw-bold text-primary">
                        {{ $dashboard['conversionRate'] === null ? '-' : number_format($dashboard['conversionRate'], 1) . '%' }}
                    </div>
                    <div class="text-muted small">Signed contracts received</div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 col-xl-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center mb-3">
                        <div class="avatar-sm bg-primary-subtle rounded-circle d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                            <i class="mdi mdi-timer-outline text-primary fs-4"></i>
                        </div>
                        <h6 class="mb-0">Speed to Conversion</h6>
                    </div>
                    <div class="display-6 fw-bold text-primary">{{ $dashboard['medianConversionLabel'] }}</div>
                    <div class="text-muted small">Median lead-to-signature time</div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mb-4">
        <div class="col-12 col-xl-7">
            <div class="card h-100">
                <div class="card-body">
                    <h5 class="card-title">Lead Volume Over Time</h5>
                    <p class="text-muted">Daily volume of new leads received.</p>
                    <div wire:ignore>
                        <canvas id="leadVolumeChart" aria-label="Daily lead volume line chart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-12 col-xl-5">
            <div class="card h-100">
                <div class="card-body">
                    <div class="d-flex flex-wrap justify-content-between align-items-start gap-2 mb-3">
                        <div>
                            <h5 class="card-title mb-1">Leads by Time of Day</h5>
                            <p class="text-muted mb-0">
                                {{ $dashboard['heatmapWeekLabel'] }}
                                <span class="d-block small">{{ $dashboard['heatmapWeekDates'] }}</span>
                            </p>
                        </div>
                        <div class="btn-group" role="group" aria-label="Change heatmap week">
                            <button type="button"
                                    class="btn btn-outline-primary btn-sm"
                                    wire:click="previousHeatmapWeek"
                                    @disabled(!$dashboard['canPreviousHeatmapWeek'])>
                                <i class="mdi mdi-chevron-left"></i>
                                Previous
                            </button>
                            <button type="button"
                                    class="btn btn-outline-primary btn-sm"
                                    wire:click="nextHeatmapWeek"
                                    @disabled(!$dashboard['canNextHeatmapWeek'])>
                                Next
                                <i class="mdi mdi-chevron-right"></i>
                            </button>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-bordered table-sm align-middle text-center mb-0">
                            <thead>
                                <tr>
                                    <th scope="col">Time</th>
                                    @foreach(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as $dayIndex => $day)
                                        <th scope="col">
                                            {{ $day }}
                                            @if($dashboard['heatmapDates'][$dayIndex])
                                                <span class="d-block text-muted small">
                                                    {{ $dashboard['heatmapDates'][$dayIndex] }}
                                                </span>
                                            @endif
                                        </th>
                                    @endforeach
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($dashboard['heatmap'] as $hour => $days)
                                    <tr>
                                        <th scope="row" class="text-nowrap">
                                            {{ str_pad($hour, 2, '0', STR_PAD_LEFT) }}:00
                                        </th>
                                        @foreach($days as $dayIndex => $value)
                                            <td class="{{ $heatClass($value, $dashboard['heatmapMax']) }}"
                                                title="{{ ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'][$dayIndex] }} {{ str_pad($hour, 2, '0', STR_PAD_LEFT) }}:00 - {{ $value }} {{ Str::plural('lead', $value) }}">
                                                {{ $value ?: '' }}
                                            </td>
                                        @endforeach
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <h5 class="card-title">Lead Status Breakdown</h5>
            <p class="text-muted">Current outcome of leads received in the selected period.</p>

            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th scope="col">Status</th>
                            <th scope="col" class="text-end">Leads</th>
                            <th scope="col" class="text-end">Percentage</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($dashboard['statuses'] as $status)
                            <tr>
                                <td>{{ $status['label'] }}</td>
                                <td class="text-end fw-semibold">{{ number_format($status['count']) }}</td>
                                <td class="text-end">{{ number_format($status['percentage'], 1) }}%</td>
                            </tr>
                        @endforeach
                    </tbody>
                    <tfoot class="table-light">
                        <tr>
                            <th scope="row">Total</th>
                            <th class="text-end">{{ number_format($dashboard['statusTotal']) }}</th>
                            <th class="text-end">{{ $dashboard['statusTotal'] > 0 ? '100%' : '0%' }}</th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>

    @script
    <script>
        let leadVolumeChart;

        const renderLeadVolumeChart = (data) => {
            const canvas = document.getElementById('leadVolumeChart');
            if (!canvas || !window.Chart) return;

            if (leadVolumeChart) leadVolumeChart.destroy();

            leadVolumeChart = new Chart(canvas, {
                type: 'line',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: 'New leads',
                        data: data.values,
                        borderColor: '#556ee6',
                        backgroundColor: 'rgba(85, 110, 230, 0.1)',
                        pointBackgroundColor: '#556ee6',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.3,
                    }],
                },
                options: {
                    responsive: true,
                    interaction: { intersect: false, mode: 'index' },
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            displayColors: false,
                            callbacks: {
                                label: context => `${context.parsed.y} ${context.parsed.y === 1 ? 'lead' : 'leads'}`,
                            },
                        },
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: { precision: 0 },
                        },
                    },
                },
            });
        };

        renderLeadVolumeChart(@js($dashboard['leadVolume']));

        Livewire.on('lead-performance-updated', (event) => {
            const payload = Array.isArray(event) ? event[0] : event;
            renderLeadVolumeChart(payload.leadVolume);
        });
    </script>
    @endscript
</div>
