<div class="card shadow-sm mb-4">
    <div class="card-header d-flex align-items-center gap-2 py-2">
        <span class="badge text-white" style="background-color:#7c3aed;">
            <i class="mdi mdi-brain me-1"></i>Synapse
        </span>
        <span class="fw-semibold">DSAR Target Intelligence</span>
        <small class="text-muted ms-auto">AI-assisted — review before acting</small>
    </div>

    <div class="card-body">

        @if($error)
            <div class="alert alert-danger py-2 px-3 small mb-3">
                <i class="mdi mdi-alert-circle-outline me-1"></i>{{ $error }}
            </div>
        @endif

        @if($running)
            <div class="d-flex align-items-center gap-2 text-muted small py-4 justify-content-center">
                <span class="spinner-border spinner-border-sm" style="color:#7c3aed;"></span>
                <span style="color:#7c3aed;">Synapse is analysing case data…</span>
            </div>

        @elseif($ran && $result)
            @php
                $isNewFormat = isset($result['care_setting_reports']);

                // Support both old and new format for overall confidence
                $overallConf = $result['overall_confidence'] ?? $result['confidence'] ?? 'Low';
                $overallConfClass = match($overallConf) {
                    'High'   => 'bg-success',
                    'Medium' => 'bg-warning text-dark',
                    default  => 'bg-danger',
                };

                $vStatusBadge = fn($s) => match($s) {
                    'verified'     => ['Verified',     'bg-success'],
                    'likely'       => ['Likely',       'bg-primary'],
                    'uncertain'    => ['Uncertain',    'bg-warning text-dark'],
                    'unverifiable' => ['Unverifiable', 'bg-danger'],
                    'test_data'    => ['Test Data',    'bg-secondary'],
                    default        => [ucfirst($s ?? '?'), 'bg-secondary'],
                };
            @endphp

            {{-- Overall confidence banner --}}
            <div class="rounded p-3 mb-3 d-flex align-items-center gap-3" style="background:#f5f3ff;">
                <span class="badge fs-6 px-3 py-2 {{ $overallConfClass }}">{{ $overallConf }} Confidence</span>
                <small class="text-muted">
                    {{ $result['overall_confidence_explanation'] ?? $result['confidence_explanation'] ?? '' }}
                </small>
            </div>

            @if($isNewFormat)
                {{-- Per care setting summary cards --}}
                @php $totalTargets = collect($result['care_setting_reports'])->sum(fn($cs) => count($cs['dsar_targets'] ?? [])); @endphp
                <h6 class="fw-semibold mb-2">
                    Care Settings
                    <span class="badge bg-secondary ms-1">{{ count($result['care_setting_reports']) }}</span>
                    <small class="text-muted fw-normal ms-2">{{ $totalTargets }} DSAR target{{ $totalTargets !== 1 ? 's' : '' }} identified</small>
                </h6>

                <div class="d-flex flex-column gap-2 mb-3">
                    @foreach($result['care_setting_reports'] as $i => $cs)
                        @php
                            $inst       = $cs['institution_identification'];
                            $vStatus    = $inst['verification_status'] ?? 'uncertain';
                            [$vLabel, $vClass] = $vStatusBadge($vStatus);
                            $csConf     = $cs['confidence'] ?? 'Low';
                            $csConfClass = match($csConf) {
                                'High'   => 'bg-success',
                                'Medium' => 'bg-warning text-dark',
                                default  => 'bg-danger',
                            };
                            $targetCount   = count($cs['dsar_targets'] ?? []);
                            $isTestData    = $vStatus === 'test_data';
                            $isUnverifiable = $vStatus === 'unverifiable';
                        @endphp
                        <div class="rounded border bg-white p-3 {{ $isTestData ? 'border-warning' : '' }}">
                            <div class="d-flex align-items-start justify-content-between gap-2 mb-1">
                                <div>
                                    <span class="badge rounded-pill text-white me-1" style="background:#7c3aed;min-width:22px;font-size:.7rem;">{{ $i + 1 }}</span>
                                    <span class="fw-semibold small">{{ $cs['care_setting_name'] }}</span>
                                </div>
                                <div class="d-flex gap-1 flex-shrink-0 flex-wrap justify-content-end">
                                    <span class="badge {{ $vClass }}" style="font-size:.65rem;">{{ $vLabel }}</span>
                                    <span class="badge {{ $csConfClass }}" style="font-size:.65rem;">{{ $csConf }}</span>
                                </div>
                            </div>

                            <div class="small text-muted mt-1">
                                @if($isTestData)
                                    <i class="mdi mdi-alert-outline me-1 text-warning"></i>
                                    Test / placeholder institution — no DSAR targets generated.
                                @elseif($isUnverifiable)
                                    <i class="mdi mdi-help-circle-outline me-1 text-danger"></i>
                                    Institution could not be identified — no DSAR targets generated.
                                @else
                                    @if($inst['likely_official_name'] !== $inst['recorded_name'])
                                        <span class="text-muted">Identified as: <em>{{ $inst['likely_official_name'] }}</em> &middot; </span>
                                    @endif
                                    <span>{{ $targetCount }} DSAR target{{ $targetCount !== 1 ? 's' : '' }}</span>
                                    @if($targetCount > 0)
                                        <div class="mt-1 d-flex flex-column gap-1">
                                            @foreach(array_slice($cs['dsar_targets'], 0, 4) as $t)
                                                <div class="d-flex align-items-center gap-2" style="font-size:.75rem;">
                                                    <span class="badge rounded-pill text-white flex-shrink-0" style="background:#7c3aed;min-width:18px;font-size:.6rem;">{{ $t['priority'] }}</span>
                                                    <span class="text-dark">{{ \Illuminate\Support\Str::limit($t['organisation'], 35) }}</span>
                                                    @if(!empty($t['institution_id']))
                                                        <a wire:navigate href="{{ route('institutions.show', $t['institution_id']) }}"
                                                           class="ms-auto text-primary text-decoration-none flex-shrink-0"
                                                           style="font-size:.7rem;"
                                                           title="View institution record">&#8599; In DB</a>
                                                    @else
                                                        <a wire:navigate href="{{ route('institutions.create') }}?display_name={{ urlencode($t['organisation']) }}"
                                                           target="_blank"
                                                           class="ms-auto text-success text-decoration-none flex-shrink-0"
                                                           style="font-size:.7rem;"
                                                           title="Add to institutions">+ Add</a>
                                                    @endif
                                                </div>
                                            @endforeach
                                            @if($targetCount > 4)
                                                <span class="text-muted" style="font-size:.7rem;">+{{ $targetCount - 4 }} more — see full report</span>
                                            @endif
                                        </div>
                                    @endif
                                @endif
                            </div>
                        </div>
                    @endforeach
                </div>

                {{-- Overall strategic notes preview --}}
                @if(!empty($result['overall_strategic_notes']))
                    <h6 class="fw-semibold mb-1">Overall Strategy</h6>
                    <p class="small text-muted mb-3" style="white-space:pre-wrap;">{{ \Illuminate\Support\Str::limit($result['overall_strategic_notes'], 400) }}</p>
                @endif

            @else
                {{-- Legacy format fallback (old runs before restructure) --}}
                <div class="alert alert-warning py-2 px-3 small mb-3">
                    <i class="mdi mdi-information-outline me-1"></i>
                    This analysis was generated with an older version of Synapse. Re-run to see the per-care-setting breakdown.
                </div>

                @php
                    $sourceLabels = [
                        'primary_controller'  => ['label' => 'Primary',    'class' => 'bg-danger'],
                        'secondary_source'    => ['label' => 'Secondary',  'class' => 'bg-warning text-dark'],
                        'supporting_evidence' => ['label' => 'Supporting', 'class' => 'bg-secondary'],
                    ];
                    $likelihoodClass = fn($v) => match($v) {
                        'High'   => 'text-success fw-semibold',
                        'Medium' => 'text-warning fw-semibold',
                        default  => 'text-danger fw-semibold',
                    };
                @endphp
                <h6 class="fw-semibold mb-3">
                    DSAR Targets <span class="badge bg-secondary ms-1">{{ count($result['dsar_targets'] ?? []) }}</span>
                </h6>
                <div class="d-flex flex-column gap-2 mb-4">
                    @foreach($result['dsar_targets'] ?? [] as $target)
                        @php $src = $sourceLabels[$target['source_type']] ?? ['label' => $target['source_type'], 'class' => 'bg-secondary']; @endphp
                        <div class="rounded border bg-white p-3">
                            <div class="d-flex align-items-start justify-content-between gap-2 mb-2">
                                <div class="d-flex align-items-center gap-2 flex-wrap">
                                    <span class="badge rounded-pill text-white" style="background:#7c3aed;min-width:24px;">{{ $target['priority'] }}</span>
                                    <span class="fw-semibold small">{{ $target['organisation'] }}</span>
                                    <span class="badge {{ $src['class'] }}" style="font-size:.65rem;">{{ $src['label'] }}</span>
                                </div>
                                <div class="d-flex gap-2 flex-shrink-0" style="font-size:.7rem;">
                                    <span class="{{ $likelihoodClass($target['record_likelihood']) }}">R:{{ $target['record_likelihood'][0] }}</span>
                                    <span class="{{ $likelihoodClass($target['usefulness']) }}">U:{{ $target['usefulness'][0] }}</span>
                                    <span class="{{ $likelihoodClass($target['strategic_importance']) }}">S:{{ $target['strategic_importance'][0] }}</span>
                                </div>
                            </div>
                            <p class="small text-muted mb-0">{{ $target['rationale'] }}</p>
                        </div>
                    @endforeach
                </div>
            @endif

        @else
            <p class="text-muted small mb-0">
                Synapse will analyse all care settings, institutions, existing DSARs, and call
                transcripts recorded against this claim and produce a prioritised DSAR target list
                with contact details, evidence probability assessments, and strategic recommendations
                — one complete sub-report per care setting.
            </p>
        @endif

        <div class="mt-3 d-flex justify-content-between align-items-center flex-wrap gap-2">
            @can('synapse.use')
                <button wire:click="analyse"
                        wire:loading.attr="disabled"
                        @class(['btn btn-sm', 'btn-outline-secondary' => $ran, 'text-white' => !$ran])
                        @style(['background-color:#7c3aed;border-color:#7c3aed;' => !$ran])>
                    <span wire:loading.remove wire:target="analyse">
                        <i class="mdi mdi-brain me-1"></i>
                        {{ $ran ? 'Re-run Analysis' : 'Run Synapse DSAR Analysis' }}
                    </span>
                    <span wire:loading wire:target="analyse">
                        <span class="spinner-border spinner-border-sm me-1"></span>Analysing…
                    </span>
                </button>
            @else
                <span class="text-muted small"><i class="mdi mdi-lock me-1"></i>Synapse access not permitted</span>
            @endcan

            @if($ran)
                <div class="d-flex align-items-center gap-2 flex-wrap">
                    <a wire:navigate href="{{ route('claims.dsar-report', $claim) }}"
                       target="_blank"
                       class="btn btn-sm btn-outline-secondary">
                        <i class="mdi mdi-file-document-outline me-1"></i>View Report
                    </a>
                    <small class="text-muted">
                        <i class="mdi mdi-information-outline me-1"></i>Review before acting. Output is not legal advice.
                    </small>
                </div>
            @endif
        </div>

    </div>
</div>
