@php
    $courierPerformanceSummary = $courierPerformanceSummary ?? ['rows' => [], 'totals' => [], 'has_any_history' => false];
    $codRestriction            = $codRestriction ?? null;
    $actionButtonUrl           = $actionButtonUrl ?? null;
    $actionButtonLabel         = $actionButtonLabel ?? translate('Customer Checking');

    $totalOrders    = (int) data_get($courierPerformanceSummary, 'totals.total_orders', 0);
    $totalDelivered = (int) data_get($courierPerformanceSummary, 'totals.delivered_orders', 0);
    $totalReturned  = (int) data_get($courierPerformanceSummary, 'totals.returned_orders', 0);
    $totalCancelled = (int) data_get($courierPerformanceSummary, 'totals.cancelled_failed_orders', 0);

    $overallSuccessRatio = $totalOrders > 0 ? round(($totalDelivered / $totalOrders) * 100, 1) : 0;
    $overallReturnRatio  = $totalOrders > 0 ? round(($totalReturned  / $totalOrders) * 100, 1) : 0;

    // Courier Score = delivery success %
    $courierScore = (int) round($overallSuccessRatio);

    if ($totalOrders === 0) {
        $riskLevel = 'new';
        $riskLabel = translate('New Customer');
        $riskClass = 'badge-soft-secondary';
        $riskIcon  = 'tio-user';
        $scoreColor = '#6c757d';
        $scoreBg    = '#f0f0f0';
    } elseif ($overallSuccessRatio >= 70 && $overallReturnRatio <= 15) {
        $riskLevel  = 'low';
        $riskLabel  = translate('Low Risk');
        $riskClass  = 'badge-soft-success';
        $riskIcon   = 'tio-checkmark-circle';
        $scoreColor = '#28a745';
        $scoreBg    = '#e8f8f0';
    } elseif ($overallSuccessRatio >= 40 || $overallReturnRatio <= 30) {
        $riskLevel  = 'medium';
        $riskLabel  = translate('Medium Risk');
        $riskClass  = 'badge-soft-warning';
        $riskIcon   = 'tio-warning';
        $scoreColor = '#f0ad4e';
        $scoreBg    = '#fff8e1';
    } else {
        $riskLevel  = 'high';
        $riskLabel  = translate('High Risk');
        $riskClass  = 'badge-soft-danger';
        $riskIcon   = 'tio-warning-outlined';
        $scoreColor = '#dc3545';
        $scoreBg    = '#fff0f0';
    }

    // COD Restriction
    $codEnabled      = (bool) data_get($codRestriction, 'enabled', false);
    $codIsRestricted = (bool) data_get($codRestriction, 'is_restricted', false);
    $codRiskRatio    = (float) data_get($codRestriction, 'risk_ratio', 0);
    $codThreshold    = (float) data_get($codRestriction, 'threshold', 70);
    $codFinalized    = (int) data_get($codRestriction, 'finalized_orders', 0);
    $codRisky        = (int) data_get($codRestriction, 'risky_orders', 0);

    $activeRows   = collect(data_get($courierPerformanceSummary, 'rows', []))->filter(fn($r) => (int) data_get($r, 'total_orders', 0) > 0)->values();
    $inactiveRows = collect(data_get($courierPerformanceSummary, 'rows', []))->filter(fn($r) => (int) data_get($r, 'total_orders', 0) === 0)->values();

    // SVG circle math
    $radius = 42;
    $circumference = round(2 * M_PI * $radius, 2);
    $dashoffset = $totalOrders > 0 ? round($circumference * (1 - $courierScore / 100), 2) : $circumference;
@endphp

<div class="card">
    <div class="card-header border-0 d-flex flex-wrap justify-content-between align-items-center gap-2 pb-0">
        <div>
            <h4 class="card-title mb-1">{{ translate('Courier Score & Risk') }}</h4>
            <p class="fs-12 text-muted mb-0">
                {{ translate('Courier-wise customer performance summary for courier selection and risk checking.') }}
            </p>
        </div>
        <div class="d-flex align-items-center gap-2">
            <span class="badge {{ $riskClass }} py-2 px-3 fs-12">
                <i class="tio-{{ $riskIcon }} mr-1"></i>
                {{ $riskLabel }}
            </span>
            @if ($codEnabled)
                @if ($codIsRestricted)
                    <span class="badge badge-soft-danger py-2 px-3 fs-12">
                        <i class="tio-block mr-1"></i>
                        {{ translate('COD Restricted') }}
                    </span>
                @else
                    <span class="badge badge-soft-success py-2 px-3 fs-12">
                        <i class="tio-checkmark mr-1"></i>
                        {{ translate('COD Active') }}
                    </span>
                @endif
            @endif
            @if ($actionButtonUrl)
                <a href="{{ $actionButtonUrl }}" class="btn btn-sm btn--primary">
                    <i class="tio-visible"></i>
                    {{ $actionButtonLabel }}
                </a>
            @endif
        </div>
    </div>

    <div class="card-body">

        {{-- Top Row: Score Circle + Stats + COD --}}
        <div class="row g-3 mb-3 align-items-center">

            {{-- Courier Score Circle --}}
            <div class="col-auto">
                <div class="d-flex flex-column align-items-center">
                    <svg width="110" height="110" viewBox="0 0 100 100">
                        <circle cx="50" cy="50" r="{{ $radius }}" fill="none" stroke="#e9ecef" stroke-width="10"/>
                        <circle cx="50" cy="50" r="{{ $radius }}" fill="none"
                                stroke="{{ $scoreColor }}" stroke-width="10"
                                stroke-dasharray="{{ $circumference }}"
                                stroke-dashoffset="{{ $dashoffset }}"
                                stroke-linecap="round"
                                transform="rotate(-90 50 50)"/>
                        <text x="50" y="45" text-anchor="middle" font-size="20" font-weight="700" fill="{{ $scoreColor }}">{{ $courierScore }}</text>
                        <text x="50" y="60" text-anchor="middle" font-size="9" fill="#6c757d">/100</text>
                    </svg>
                    <span class="fs-12 font-weight-semibold text-muted mt-1">{{ translate('Courier Score') }}</span>
                </div>
            </div>

            {{-- Stats Cards --}}
            <div class="col">
                <div class="row g-2">
                    <div class="col-6 col-xl-3">
                        <div class="bg-light rounded p-3 h-100">
                            <div class="text-muted fs-11 mb-1">{{ translate('Total Orders') }}</div>
                            <h4 class="mb-0">{{ $totalOrders }}</h4>
                        </div>
                    </div>
                    <div class="col-6 col-xl-3">
                        <div class="rounded p-3 h-100" style="background:#e8f8f0;">
                            <div class="text-muted fs-11 mb-1">{{ translate('Delivered') }}</div>
                            <h4 class="mb-0 text-success">{{ $totalDelivered }}</h4>
                            @if($totalOrders > 0)
                                <small class="text-muted">{{ $overallSuccessRatio }}%</small>
                            @endif
                        </div>
                    </div>
                    <div class="col-6 col-xl-3">
                        <div class="rounded p-3 h-100" style="background:#fff8e1;">
                            <div class="text-muted fs-11 mb-1">{{ translate('Returned') }}</div>
                            <h4 class="mb-0 text-warning">{{ $totalReturned }}</h4>
                            @if($totalOrders > 0)
                                <small class="text-muted">{{ $overallReturnRatio }}%</small>
                            @endif
                        </div>
                    </div>
                    <div class="col-6 col-xl-3">
                        <div class="rounded p-3 h-100" style="background:#fff0f0;">
                            <div class="text-muted fs-11 mb-1">{{ translate('Cancelled/Failed') }}</div>
                            <h4 class="mb-0 text-danger">{{ $totalCancelled }}</h4>
                        </div>
                    </div>
                </div>

                {{-- COD Risk Bar --}}
                @if($codEnabled && $codFinalized > 0)
                    <div class="mt-3 p-3 rounded" style="background:{{ $codIsRestricted ? '#fff0f0' : '#f8f9fa' }}; border:1px solid {{ $codIsRestricted ? '#f5c6cb' : '#dee2e6' }};">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <span class="fs-12 font-weight-semibold">
                                <i class="tio-warning-outlined mr-1 {{ $codIsRestricted ? 'text-danger' : 'text-muted' }}"></i>
                                {{ translate('COD Risk Ratio') }}
                            </span>
                            <span class="fs-12 font-weight-bold {{ $codIsRestricted ? 'text-danger' : 'text-success' }}">
                                {{ number_format($codRiskRatio, 1) }}%
                                <span class="text-muted font-weight-normal">/ {{ $codThreshold }}% {{ translate('threshold') }}</span>
                            </span>
                        </div>
                        <div class="progress" style="height:6px;">
                            <div class="progress-bar {{ $codIsRestricted ? 'bg-danger' : ($codRiskRatio >= $codThreshold * 0.7 ? 'bg-warning' : 'bg-success') }}"
                                 style="width:{{ min(100, $codRiskRatio) }}%"></div>
                        </div>
                        <div class="fs-11 text-muted mt-1">
                            {{ $codRisky }} {{ translate('risky') }} / {{ $codFinalized }} {{ translate('finalized orders') }}
                            @if($codIsRestricted)
                                — <strong class="text-danger">{{ translate('COD & Offline payment blocked') }}</strong>
                            @endif
                        </div>
                    </div>
                @endif
            </div>
        </div>

        {{-- Per-Courier Table --}}
        @if($activeRows->isEmpty())
            <div class="alert alert-soft-secondary text-center py-4">
                <i class="tio-info-outined fs-24 d-block mb-1"></i>
                {{ translate('No courier booking history found yet for this customer.') }}
            </div>
        @else
            <div class="table-responsive">
                <table class="table table-thead-bordered table-nowrap mb-0">
                    <thead class="thead-light">
                    <tr>
                        <th>{{ translate('Courier') }}</th>
                        <th class="text-center">{{ translate('Total') }}</th>
                        <th class="text-center">{{ translate('Delivered') }}</th>
                        <th class="text-center">{{ translate('Returned') }}</th>
                        <th class="text-center">{{ translate('Cancelled/Failed') }}</th>
                        <th class="text-center">{{ translate('Score') }}</th>
                        <th class="text-center">{{ translate('Return Rate') }}</th>
                        <th class="text-center">{{ translate('Risk') }}</th>
                    </tr>
                    </thead>
                    <tbody>
                    @foreach($activeRows as $row)
                        @php
                            $rSuccessRatio = (float) data_get($row, 'delivery_success_ratio', 0);
                            $rReturnRatio  = (float) data_get($row, 'return_ratio', 0);
                            $rScore        = (int) round($rSuccessRatio);

                            if ($rSuccessRatio >= 70 && $rReturnRatio <= 15) {
                                $rowRiskClass  = 'badge-soft-success';
                                $rowRiskLabel  = translate('Low');
                                $scoreClass    = 'text-success';
                            } elseif ($rSuccessRatio >= 40 || $rReturnRatio <= 30) {
                                $rowRiskClass  = 'badge-soft-warning';
                                $rowRiskLabel  = translate('Medium');
                                $scoreClass    = 'text-warning';
                            } else {
                                $rowRiskClass  = 'badge-soft-danger';
                                $rowRiskLabel  = translate('High');
                                $scoreClass    = 'text-danger';
                            }

                            $returnClass = $rReturnRatio <= 15 ? 'text-success' : ($rReturnRatio <= 30 ? 'text-warning' : 'text-danger');
                        @endphp
                        <tr>
                            <td><span class="font-weight-semibold">{{ data_get($row, 'provider_name') }}</span></td>
                            <td class="text-center">{{ data_get($row, 'total_orders', 0) }}</td>
                            <td class="text-center text-success font-weight-semibold">{{ data_get($row, 'delivered_orders', 0) }}</td>
                            <td class="text-center text-warning font-weight-semibold">{{ data_get($row, 'returned_orders', 0) }}</td>
                            <td class="text-center text-danger font-weight-semibold">{{ data_get($row, 'cancelled_failed_orders', 0) }}</td>
                            <td class="text-center">
                                <span class="font-weight-bold {{ $scoreClass }}">{{ $rScore }}/100</span>
                            </td>
                            <td class="text-center font-weight-semibold {{ $returnClass }}">{{ number_format($rReturnRatio, 1) }}%</td>
                            <td class="text-center">
                                <span class="badge {{ $rowRiskClass }}">{{ $rowRiskLabel }}</span>
                            </td>
                        </tr>
                    @endforeach
                    </tbody>
                </table>
            </div>

            @if($inactiveRows->isNotEmpty())
                <div class="mt-2">
                    <p class="text-muted fs-12 mb-1">
                        {{ translate('No history with') }}:
                        @foreach($inactiveRows as $r)
                            <span class="badge badge-soft-secondary mr-1">{{ data_get($r, 'provider_name') }}</span>
                        @endforeach
                    </p>
                </div>
            @endif
        @endif

        {{-- Legend --}}
        <div class="alert alert-soft-info mt-3 mb-0 fs-12">
            <div class="d-flex flex-wrap gap-3">
                <span><strong>{{ translate('Score 70–100') }}</strong>: {{ translate('Low Risk') }} ✓</span>
                <span><strong>{{ translate('Score 40–69') }}</strong>: {{ translate('Medium Risk') }}</span>
                <span><strong>{{ translate('Score 0–39') }}</strong>: {{ translate('High Risk') }} ✗</span>
                @if($codEnabled)
                    <span class="ml-auto"><strong>{{ translate('COD blocked when risk ratio') }} ≥ {{ $codThreshold }}%</strong></span>
                @endif
            </div>
        </div>

    </div>
</div>
