@extends('layouts.app')
@section('title','Credit Score Calibration')
@section('content')
<x-ui.page-toolbar title="Credit Score Calibration" description="Historical application-score outcomes, repayment performance, migration and drift monitoring." :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Loan & Branch Reports','url'=>route('loan-branch-reports.index')],['label'=>'Credit Score Calibration']]">
    <x-slot:actions>
        <a class="mf-btn" href="{{ route('credit-score-reports.calibration.export', request()->query()) }}">Export CSV</a>
        <button type="button" class="mf-btn" onclick="window.print()">Print</button>
    </x-slot:actions>
</x-ui.page-toolbar>

<div class="mb-3 flex flex-wrap gap-2 print:hidden">
    <a class="mf-btn" href="{{ route('loan-branch-reports.index') }}">Loan & Branch Reports</a>
    <a class="mf-btn" href="{{ route('credit-score-reports.portfolio') }}">Credit Score Portfolio</a>
    <a class="mf-btn mf-btn-primary" href="{{ route('credit-score-reports.calibration') }}">Calibration & Monitoring</a>
</div>

<form method="GET" action="{{ route('credit-score-reports.calibration') }}" class="mf-table-toolbar mb-4 print:hidden" data-ui="table-toolbar">
    <div class="mf-table-toolbar-left">
        <div class="mf-table-quick-filters">
            <details class="mf-columns-menu">
                <summary class="mf-filter-control cursor-pointer min-w-[200px]" aria-label="Select branches">
                    {{ $selectedBranches->count() === 1 ? $selectedBranches->first()->name : $selectedBranches->count().' branches' }}
                </summary>
                <div class="mf-columns-popover">
                    <div class="mf-columns-title">Branches</div>
                    @foreach($branches as $branch)
                        <label>
                            <input type="checkbox" name="branch_ids[]" value="{{ $branch->id }}" @checked($selectedBranchIds->contains($branch->id))>
                            <span>{{ $branch->name }}</span>
                        </label>
                    @endforeach
                    <div class="px-3 pb-2 text-[11px] text-muted-foreground">Clear all selections to include every accessible branch.</div>
                </div>
            </details>

            <select name="score_version" class="mf-filter-control min-w-[120px]" aria-label="Score version">
                @php($versions = collect($data['available_score_versions'])->push($data['selected_score_version'])->unique()->sort()->values())
                @foreach($versions as $version)
                    <option value="{{ $version }}" @selected($data['selected_score_version'] === $version)>{{ $version }}</option>
                @endforeach
            </select>
        </div>
        <button class="mf-btn mf-btn-sm" type="submit">Run Report</button>
    </div>
</form>

<div class="mb-4 border-l-2 pl-3 text-xs text-muted-foreground">
    Monitoring only. This report reads immutable application-time score snapshots and later loan outcomes. It does not recalculate scores, change V1 weights, or approve/reject any loan.
</div>

<div class="mb-4 flex flex-wrap items-start justify-between gap-2">
    <div>
        <div class="text-lg font-semibold">Application cohort · {{ $data['selected_score_version'] }}</div>
        <div class="text-xs text-muted-foreground">{{ $selectedBranches->pluck('name')->join(', ') }} · Generated {{ $data['generated_at']->format('d M Y H:i') }}</div>
        <div class="mt-1 text-xs text-muted-foreground">Repayment outcomes are measured only after a loan has entered repayment. Current arrears use active-loan balances; write-off rate uses all observed repayment loans.</div>
    </div>
</div>

<div class="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Applications scored</div>
        <div class="mt-1 text-lg font-semibold">{{ number_format($data['summary']['applications']) }}</div>
        <div class="text-[11px] text-muted-foreground">Application snapshots</div>
    </div>
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Average application score</div>
        <div class="mt-1 text-lg font-semibold">{{ $data['summary']['average_application_score'] === null ? '—' : number_format($data['summary']['average_application_score'],1) }}</div>
        <div class="text-[11px] text-muted-foreground">Confidence {{ $data['summary']['average_confidence'] === null ? '—' : number_format($data['summary']['average_confidence'],1).'%' }}</div>
    </div>
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Approval rate</div>
        <div class="mt-1 text-lg font-semibold">{{ number_format($data['summary']['approval_rate'],2) }}%</div>
        <div class="text-[11px] text-muted-foreground">{{ number_format($data['summary']['approved']) }} approved · {{ number_format($data['summary']['rejected']) }} rejected</div>
    </div>
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Observed repayment loans</div>
        <div class="mt-1 text-lg font-semibold">{{ number_format($data['summary']['observed_loans']) }}</div>
        <div class="text-[11px] text-muted-foreground">{{ number_format($data['summary']['active_loans']) }} currently active</div>
    </div>
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">30+ day arrears</div>
        <div class="mt-1 text-lg font-semibold">{{ number_format($data['summary']['serious_arrears_loans']) }}</div>
        <div class="text-[11px] text-muted-foreground">Active loans at {{ $data['monitoring']['serious_arrears_days'] }}+ DPD</div>
    </div>
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Write-off rate</div>
        <div class="mt-1 text-lg font-semibold">{{ number_format($data['summary']['write_off_rate'],2) }}%</div>
        <div class="text-[11px] text-muted-foreground">{{ number_format($data['summary']['written_off_loans']) }} written off</div>
    </div>
</div>

@php($drift = $data['drift']['overall'])
<div class="mb-5">
    <div class="mb-2 flex flex-wrap items-end justify-between gap-2">
        <div>
            <div class="text-sm font-semibold">Score-distribution drift</div>
            <div class="text-xs text-muted-foreground">Recent {{ $data['drift']['window_days'] }} days compared with the previous {{ $data['drift']['window_days'] }} days. Alert thresholds are monitoring-only.</div>
        </div>
        <span class="text-xs font-medium">
            @if($drift['status'] === 'warning') Warning
            @elseif($drift['status'] === 'stable') Stable
            @else Insufficient data
            @endif
        </span>
    </div>
    <div class="mf-card">
        <div class="mf-table-frame border-0">
            <table class="mf-table">
                <thead><tr><th>Window</th><th class="text-right">Applications</th><th class="text-right">Average score</th><th class="text-right">Change</th></tr></thead>
                <tbody>
                    <tr><td>Recent</td><td class="text-right">{{ number_format($drift['recent_applications']) }}</td><td class="text-right">{{ $drift['recent_average_score'] === null ? '—' : number_format($drift['recent_average_score'],1) }}</td><td class="text-right" rowspan="2">{{ $drift['average_score_change'] === null ? '—' : (($drift['average_score_change'] > 0 ? '+' : '').number_format($drift['average_score_change'],1)) }}</td></tr>
                    <tr><td>Previous</td><td class="text-right">{{ number_format($drift['previous_applications']) }}</td><td class="text-right">{{ $drift['previous_average_score'] === null ? '—' : number_format($drift['previous_average_score'],1) }}</td></tr>
                </tbody>
            </table>
        </div>
    </div>
    <div class="mt-2 grid gap-2 sm:grid-cols-2 lg:grid-cols-5">
        @foreach($drift['band_shifts'] as $row)
            <div class="border px-3 py-2 text-xs">
                <div class="font-medium">{{ $row['label'] }}</div>
                <div class="mt-1 text-muted-foreground">{{ number_format($row['previous_share'],1) }}% → {{ number_format($row['recent_share'],1) }}%</div>
                <div class="mt-1 {{ $row['warning'] ? 'font-medium' : 'text-muted-foreground' }}">{{ $row['change'] > 0 ? '+' : '' }}{{ number_format($row['change'],1) }} pp</div>
            </div>
        @endforeach
    </div>
</div>

<div class="mb-5">
    <div class="mb-2">
        <div class="text-sm font-semibold">Outcome performance by application score band</div>
        <div class="text-xs text-muted-foreground">Uses the immutable score attached when the loan entered approval review, not the customer's current score.</div>
    </div>
    <div class="mf-card">
        <div class="mf-table-frame border-0">
            <table class="mf-table">
                <thead>
                    <tr><th>Band</th><th class="text-right">Apps</th><th class="text-right">Avg score</th><th class="text-right">Approved</th><th class="text-right">Rejected</th><th class="text-right">Approval</th><th class="text-right">Observed</th><th class="text-right">30+ DPD</th><th class="text-right">Written off</th><th class="text-right">Write-off</th><th class="text-right">Arrears</th></tr>
                </thead>
                <tbody>
                    @foreach($data['bands'] as $row)
                        <tr>
                            <td class="font-medium">{{ $row['label'] }}</td>
                            <td class="text-right">{{ number_format($row['applications']) }}</td>
                            <td class="text-right">{{ $row['average_application_score'] === null ? '—' : number_format($row['average_application_score'],1) }}</td>
                            <td class="text-right">{{ number_format($row['approved']) }}</td>
                            <td class="text-right">{{ number_format($row['rejected']) }}</td>
                            <td class="text-right">{{ number_format($row['approval_rate'],2) }}%</td>
                            <td class="text-right">{{ number_format($row['observed_loans']) }}</td>
                            <td class="text-right">{{ number_format($row['serious_arrears_loans']) }}</td>
                            <td class="text-right">{{ number_format($row['written_off_loans']) }}</td>
                            <td class="text-right">{{ number_format($row['write_off_rate'],2) }}%</td>
                            <td class="text-right">{{ number_format($row['arrears_rate'],2) }}%</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="mb-5">
    <div class="mb-2">
        <div class="text-sm font-semibold">Score migration</div>
        <div class="text-xs text-muted-foreground">Application score versus latest current score. Band movement is compared only when both scores use the same scoring version.</div>
    </div>
    <div class="mf-card">
        <div class="mf-table-frame border-0">
            <table class="mf-table">
                <thead><tr><th>Application band</th><th class="text-right">Comparable</th><th class="text-right">Avg score change</th><th class="text-right">Improved</th><th class="text-right">Stable</th><th class="text-right">Worsened</th><th class="text-right">Cross-version</th><th class="text-right">No current score</th></tr></thead>
                <tbody>
                    @foreach($data['migration']['bands'] as $row)
                        <tr>
                            <td class="font-medium">{{ $row['label'] }}</td>
                            <td class="text-right">{{ number_format($row['comparable']) }}</td>
                            <td class="text-right">{{ $row['average_score_change'] === null ? '—' : (($row['average_score_change'] > 0 ? '+' : '').number_format($row['average_score_change'],1)) }}</td>
                            <td class="text-right">{{ number_format($row['improved_band']) }}</td>
                            <td class="text-right">{{ number_format($row['stable_band']) }}</td>
                            <td class="text-right">{{ number_format($row['worsened_band']) }}</td>
                            <td class="text-right">{{ number_format($row['cross_version']) }}</td>
                            <td class="text-right">{{ number_format($row['missing_current']) }}</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="mb-5 grid gap-5 xl:grid-cols-2">
    <div>
        <div class="mb-2">
            <div class="text-sm font-semibold">Branch calibration summary</div>
            <div class="text-xs text-muted-foreground">Branch scope remains limited to branches available to the signed-in user.</div>
        </div>
        <div class="mf-card">
            <div class="mf-table-frame border-0">
                <table class="mf-table">
                    <thead><tr><th>Branch</th><th class="text-right">Apps</th><th class="text-right">Avg score</th><th class="text-right">Approval</th><th class="text-right">30+ DPD</th><th class="text-right">Write-off</th></tr></thead>
                    <tbody>
                        @foreach($data['branches'] as $row)
                            <tr><td class="font-medium">{{ $row['branch_name'] }}</td><td class="text-right">{{ number_format($row['applications']) }}</td><td class="text-right">{{ $row['average_application_score'] === null ? '—' : number_format($row['average_application_score'],1) }}</td><td class="text-right">{{ number_format($row['approval_rate'],2) }}%</td><td class="text-right">{{ number_format($row['serious_arrears_loans']) }}</td><td class="text-right">{{ number_format($row['write_off_rate'],2) }}%</td></tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div>
        <div class="mb-2">
            <div class="text-sm font-semibold">Performance by score version</div>
            <div class="text-xs text-muted-foreground">Allows future V2 performance to be compared without rewriting historical V1 snapshots.</div>
        </div>
        <div class="mf-card">
            <div class="mf-table-frame border-0">
                <table class="mf-table">
                    <thead><tr><th>Version</th><th class="text-right">Apps</th><th class="text-right">Avg score</th><th class="text-right">Approval</th><th class="text-right">Observed</th><th class="text-right">Write-off</th><th class="text-right">Arrears</th></tr></thead>
                    <tbody>
                        @forelse($data['versions'] as $row)
                            <tr><td class="font-medium">{{ $row['score_version'] }}</td><td class="text-right">{{ number_format($row['applications']) }}</td><td class="text-right">{{ $row['average_application_score'] === null ? '—' : number_format($row['average_application_score'],1) }}</td><td class="text-right">{{ number_format($row['approval_rate'],2) }}%</td><td class="text-right">{{ number_format($row['observed_loans']) }}</td><td class="text-right">{{ number_format($row['write_off_rate'],2) }}%</td><td class="text-right">{{ number_format($row['arrears_rate'],2) }}%</td></tr>
                        @empty
                            <tr><td colspan="7" class="text-center text-muted-foreground">No application score snapshots are available in this scope.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="mb-5">
    <div class="mb-2">
        <div class="text-sm font-semibold">Branch drift monitor</div>
        <div class="text-xs text-muted-foreground">Average application score shift by branch across the same recent/prior windows.</div>
    </div>
    <div class="mf-card">
        <div class="mf-table-frame border-0">
            <table class="mf-table">
                <thead><tr><th>Branch</th><th>Status</th><th class="text-right">Previous apps</th><th class="text-right">Recent apps</th><th class="text-right">Previous avg</th><th class="text-right">Recent avg</th><th class="text-right">Change</th></tr></thead>
                <tbody>
                    @foreach($data['drift']['branches'] as $row)
                        <tr>
                            <td class="font-medium">{{ $row['branch_name'] }}</td>
                            <td>{{ $row['status'] === 'warning' ? 'Warning' : ($row['status'] === 'stable' ? 'Stable' : 'Insufficient data') }}</td>
                            <td class="text-right">{{ number_format($row['previous_applications']) }}</td>
                            <td class="text-right">{{ number_format($row['recent_applications']) }}</td>
                            <td class="text-right">{{ $row['previous_average_score'] === null ? '—' : number_format($row['previous_average_score'],1) }}</td>
                            <td class="text-right">{{ $row['recent_average_score'] === null ? '—' : number_format($row['recent_average_score'],1) }}</td>
                            <td class="text-right">{{ $row['average_score_change'] === null ? '—' : (($row['average_score_change'] > 0 ? '+' : '').number_format($row['average_score_change'],1)) }}</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<div>
    <div class="mb-2">
        <div class="text-sm font-semibold">Application-score trend</div>
        <div class="text-xs text-muted-foreground">Latest 12 monthly application cohorts for the selected score version.</div>
    </div>
    <div class="mf-card">
        <div class="mf-table-frame border-0">
            <table class="mf-table">
                <thead><tr><th>Month</th><th class="text-right">Apps</th><th class="text-right">Avg score</th><th class="text-right">Approval</th><th class="text-right">Observed</th><th class="text-right">30+ DPD</th><th class="text-right">Write-off</th><th class="text-right">Arrears</th></tr></thead>
                <tbody>
                    @forelse($data['monthly_trend'] as $row)
                        <tr><td class="font-medium">{{ $row['label'] }}</td><td class="text-right">{{ number_format($row['applications']) }}</td><td class="text-right">{{ $row['average_application_score'] === null ? '—' : number_format($row['average_application_score'],1) }}</td><td class="text-right">{{ number_format($row['approval_rate'],2) }}%</td><td class="text-right">{{ number_format($row['observed_loans']) }}</td><td class="text-right">{{ number_format($row['serious_arrears_loans']) }}</td><td class="text-right">{{ number_format($row['write_off_rate'],2) }}%</td><td class="text-right">{{ number_format($row['arrears_rate'],2) }}%</td></tr>
                    @empty
                        <tr><td colspan="8" class="text-center text-muted-foreground">No monthly application-score data is available for the selected version.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>@media print{.mf-sidebar,.mf-topbar,.print\:hidden{display:none!important}.mf-content{margin:0!important}.mf-page{padding:0!important}.mf-card{box-shadow:none!important}.mf-table{font-size:9px!important}}</style>
@endpush
