<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DSAR Intelligence Report — {{ $claim->client->full_name ?? 'Client' }}</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: 'Georgia', serif;
            font-size: 11pt;
            line-height: 1.6;
            color: #1a1a1a;
            background: #fff;
        }

        @media print {
            body { font-size: 10pt; }
            .no-print { display: none !important; }
            .page-break { page-break-before: always; }
            section { page-break-inside: avoid; }
            .care-setting-block { page-break-before: always; }
            .care-setting-block:first-of-type { page-break-before: avoid; }
        }

        .wrapper {
            max-width: 900px;
            margin: 0 auto;
            padding: 30px 40px;
        }

        /* --- Cover Header --- */
        .report-header {
            border-bottom: 3px solid #7c3aed;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }
        .report-header .brand {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 16px;
        }
        .badge-synapse {
            background: #7c3aed;
            color: #fff;
            font-family: sans-serif;
            font-size: 9pt;
            font-weight: 700;
            letter-spacing: .05em;
            padding: 3px 10px;
            border-radius: 4px;
        }
        .report-title {
            font-size: 18pt;
            font-weight: 700;
            font-family: sans-serif;
            margin-bottom: 4px;
        }
        .report-subtitle {
            font-size: 11pt;
            color: #555;
            font-family: sans-serif;
        }
        .report-meta {
            margin-top: 12px;
            font-family: sans-serif;
            font-size: 9pt;
            color: #666;
            display: flex;
            gap: 30px;
            flex-wrap: wrap;
        }
        .report-meta span strong { color: #333; }

        /* --- Care setting divider --- */
        .care-setting-divider {
            background: #7c3aed;
            color: #fff;
            font-family: sans-serif;
            padding: 10px 16px;
            border-radius: 6px;
            margin: 36px 0 20px;
            display: flex;
            align-items: baseline;
            gap: 12px;
        }
        .care-setting-number {
            font-size: 8.5pt;
            font-weight: 700;
            opacity: .8;
            text-transform: uppercase;
            letter-spacing: .06em;
            white-space: nowrap;
        }
        .care-setting-name {
            font-size: 13pt;
            font-weight: 700;
        }
        .care-setting-divider:first-of-type {
            margin-top: 0;
        }

        /* --- Section headings --- */
        .section {
            margin-bottom: 28px;
        }
        .section-heading {
            font-family: sans-serif;
            font-size: 12pt;
            font-weight: 700;
            color: #7c3aed;
            border-bottom: 1px solid #e9d5ff;
            padding-bottom: 5px;
            margin-bottom: 14px;
            letter-spacing: .02em;
        }
        .section-heading .section-letter {
            display: inline-block;
            background: #7c3aed;
            color: #fff;
            font-size: 9pt;
            font-weight: 700;
            border-radius: 3px;
            padding: 1px 7px;
            margin-right: 8px;
        }
        .overall-section .section-heading {
            color: #374151;
            border-color: #d1d5db;
        }
        .overall-section .section-heading .section-letter {
            background: #374151;
        }

        /* --- Confidence banner --- */
        .confidence-banner {
            display: flex;
            align-items: flex-start;
            gap: 14px;
            background: #f5f3ff;
            border-left: 4px solid #7c3aed;
            padding: 12px 16px;
            border-radius: 4px;
            margin-bottom: 20px;
            font-family: sans-serif;
        }
        .confidence-badge {
            font-size: 10pt;
            font-weight: 700;
            padding: 4px 12px;
            border-radius: 20px;
            white-space: nowrap;
            flex-shrink: 0;
        }
        .conf-high   { background: #dcfce7; color: #166534; }
        .conf-medium { background: #fef9c3; color: #854d0e; }
        .conf-low    { background: #fee2e2; color: #991b1b; }
        .confidence-explanation { font-size: 10pt; color: #444; line-height: 1.5; }

        /* --- Verification badges --- */
        .verification-badge {
            font-family: sans-serif;
            font-size: 8pt;
            font-weight: 700;
            border-radius: 10px;
            padding: 2px 9px;
            white-space: nowrap;
        }
        .vbadge-verified     { background: #dcfce7; color: #166534; }
        .vbadge-likely       { background: #dbeafe; color: #1e40af; }
        .vbadge-uncertain    { background: #fef9c3; color: #854d0e; }
        .vbadge-unverifiable { background: #fee2e2; color: #991b1b; }
        .vbadge-test_data    { background: #fce7f3; color: #9d174d; }

        /* --- Warning banners --- */
        .warning-banner {
            border-radius: 6px;
            padding: 14px 16px;
            margin-bottom: 16px;
            font-family: sans-serif;
            font-size: 10pt;
        }
        .warning-banner strong { display: block; margin-bottom: 6px; font-size: 10.5pt; }
        .warning-test-data {
            background: #fce7f3;
            border-left: 4px solid #db2777;
            color: #831843;
        }
        .warning-unverifiable {
            background: #fee2e2;
            border-left: 4px solid #dc2626;
            color: #7f1d1d;
        }
        .warning-stale {
            background: #fef9c3;
            border-left: 4px solid #ca8a04;
            color: #713f12;
        }

        /* --- Institution cards --- */
        .institution-card {
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            padding: 14px 16px;
            margin-bottom: 12px;
        }
        .institution-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 6px;
            gap: 12px;
        }
        .institution-name {
            font-family: sans-serif;
            font-weight: 700;
            font-size: 10.5pt;
        }
        .institution-recorded {
            font-family: sans-serif;
            font-size: 8.5pt;
            color: #888;
            margin-top: 2px;
        }
        .institution-type-badge {
            font-family: sans-serif;
            font-size: 8pt;
            background: #ede9fe;
            color: #5b21b6;
            border-radius: 10px;
            padding: 2px 9px;
            white-space: nowrap;
        }
        .institution-description {
            color: #374151;
            font-size: 10pt;
            margin-top: 6px;
        }
        .institution-notes {
            font-family: sans-serif;
            font-size: 9pt;
            color: #6b7280;
            margin-top: 6px;
            font-style: italic;
        }

        /* --- Timeline & tables --- */
        .timeline-table, .evidence-table, .record-holders-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 10pt;
        }
        .timeline-table th, .evidence-table th, .record-holders-table th {
            font-family: sans-serif;
            font-size: 9pt;
            font-weight: 600;
            text-align: left;
            padding: 6px 10px;
            background: #f5f3ff;
            border: 1px solid #e5e7eb;
            color: #5b21b6;
        }
        .timeline-table td, .evidence-table td, .record-holders-table td {
            padding: 7px 10px;
            border: 1px solid #e5e7eb;
            vertical-align: top;
        }
        .timeline-table tr:nth-child(even) td,
        .evidence-table tr:nth-child(even) td,
        .record-holders-table tr:nth-child(even) td { background: #fafaf9; }
        .period-cell {
            font-family: sans-serif;
            font-weight: 600;
            color: #374151;
            white-space: nowrap;
        }
        .ev-org { font-family: sans-serif; font-weight: 600; }

        /* --- Gaps list --- */
        .gaps-block {
            margin-top: 12px;
            background: #fafaf9;
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            padding: 10px 14px;
        }
        .gaps-heading {
            font-family: sans-serif;
            font-size: 9pt;
            font-weight: 700;
            color: #6b7280;
            margin-bottom: 6px;
            text-transform: uppercase;
            letter-spacing: .04em;
        }
        .gaps-block ul {
            padding-left: 18px;
            color: #374151;
            font-size: 10pt;
        }
        .gaps-block ul li { margin-bottom: 3px; }

        /* --- DSAR Targets --- */
        .target-card {
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            padding: 14px 16px;
            margin-bottom: 12px;
            position: relative;
        }
        .target-priority {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 26px;
            height: 26px;
            background: #7c3aed;
            color: #fff;
            border-radius: 50%;
            font-family: sans-serif;
            font-weight: 700;
            font-size: 9.5pt;
            flex-shrink: 0;
        }
        .target-header {
            display: flex;
            align-items: flex-start;
            gap: 10px;
            margin-bottom: 8px;
        }
        .target-header-info { flex: 1; }
        .target-org {
            font-family: sans-serif;
            font-weight: 700;
            font-size: 10.5pt;
        }
        .target-badges {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin-top: 4px;
        }
        .target-badge {
            font-family: sans-serif;
            font-size: 7.5pt;
            padding: 1px 7px;
            border-radius: 10px;
            font-weight: 600;
        }
        .badge-primary    { background: #fee2e2; color: #991b1b; }
        .badge-secondary  { background: #fef9c3; color: #854d0e; }
        .badge-supporting { background: #f3f4f6; color: #374151; }
        .badge-exists     { background: #dcfce7; color: #166534; }
        .badge-dissolved  { background: #fee2e2; color: #991b1b; }
        .badge-merged     { background: #fef9c3; color: #854d0e; }
        .badge-unknown    { background: #f3f4f6; color: #374151; }

        .target-scores {
            display: flex;
            gap: 14px;
            font-family: sans-serif;
            font-size: 8.5pt;
            margin: 8px 0;
        }
        .score-item { display: flex; flex-direction: column; align-items: center; gap: 2px; }
        .score-label { color: #9ca3af; font-size: 7.5pt; }
        .score-val { font-weight: 700; }
        .s-high   { color: #16a34a; }
        .s-medium { color: #ca8a04; }
        .s-low    { color: #dc2626; }

        .target-rationale { font-size: 10pt; color: #374151; margin-bottom: 8px; }
        .target-successor {
            font-family: sans-serif;
            font-size: 9pt;
            color: #6b7280;
            margin-bottom: 6px;
        }
        .contacts-block {
            border-top: 1px solid #f3f4f6;
            padding-top: 8px;
            margin-top: 6px;
        }
        .contact-entry {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 4px 20px;
            font-family: sans-serif;
            font-size: 9pt;
            color: #374151;
            padding: 6px 0;
        }
        .contact-entry + .contact-entry {
            border-top: 1px dashed #e5e7eb;
        }
        .contact-label { color: #9ca3af; font-size: 8pt; display: block; }

        /* --- Cross-institution links --- */
        .link-card {
            background: #f9fafb;
            border-left: 3px solid #a78bfa;
            padding: 8px 12px;
            border-radius: 0 4px 4px 0;
            margin-bottom: 8px;
            font-size: 10pt;
        }
        .link-orgs { font-family: sans-serif; font-weight: 600; color: #374151; }
        .link-desc { color: #555; margin-top: 3px; }

        /* --- Strategic notes / fallback --- */
        .prose { font-size: 10.5pt; color: #374151; white-space: pre-wrap; }
        .fallback-item {
            border-left: 3px solid #d1d5db;
            padding: 6px 12px;
            margin-bottom: 8px;
            border-radius: 0 4px 4px 0;
        }
        .fallback-route { font-family: sans-serif; font-weight: 700; font-size: 10pt; }
        .fallback-rationale { font-size: 10pt; color: #555; margin-top: 3px; }

        /* --- Disclaimer --- */
        .disclaimer {
            background: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            padding: 12px 16px;
            font-family: sans-serif;
            font-size: 8.5pt;
            color: #6b7280;
            margin-top: 30px;
        }

        /* --- Print button --- */
        .print-bar {
            position: fixed;
            bottom: 24px;
            right: 24px;
            display: flex;
            gap: 10px;
            z-index: 100;
        }
        .btn-print {
            background: #7c3aed;
            color: #fff;
            border: none;
            border-radius: 6px;
            padding: 10px 20px;
            font-family: sans-serif;
            font-size: 10pt;
            font-weight: 600;
            cursor: pointer;
        }
        .btn-back {
            background: #fff;
            color: #374151;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            padding: 10px 20px;
            font-family: sans-serif;
            font-size: 10pt;
            cursor: pointer;
            text-decoration: none;
            display: flex;
            align-items: center;
        }
    </style>
</head>
<body>

@php
    $client      = $claim->client;
    $isNewFormat = isset($result['care_setting_reports']);

    $overallConfidence = $result['overall_confidence'] ?? $result['confidence'] ?? 'Low';
    $overallConfidenceClass = match($overallConfidence) {
        'High'   => 'conf-high',
        'Medium' => 'conf-medium',
        default  => 'conf-low',
    };

    $sourceLabels = [
        'primary_controller'  => ['label' => 'Primary Controller',  'class' => 'badge-primary'],
        'secondary_source'    => ['label' => 'Secondary Source',     'class' => 'badge-secondary'],
        'supporting_evidence' => ['label' => 'Supporting Evidence',  'class' => 'badge-supporting'],
    ];
    $statusClasses = [
        'exists'    => 'badge-exists',
        'dissolved' => 'badge-dissolved',
        'merged'    => 'badge-merged',
        'unknown'   => 'badge-unknown',
    ];
    $scoreClass = fn($v) => match($v) {
        'High'   => 's-high',
        'Medium' => 's-medium',
        default  => 's-low',
    };
    $verificationBadge = fn($status) => match($status) {
        'verified'     => ['label' => 'Verified',     'class' => 'vbadge-verified'],
        'likely'       => ['label' => 'Likely',       'class' => 'vbadge-likely'],
        'uncertain'    => ['label' => 'Uncertain',    'class' => 'vbadge-uncertain'],
        'unverifiable' => ['label' => 'Unverifiable', 'class' => 'vbadge-unverifiable'],
        'test_data'    => ['label' => 'Test Data',    'class' => 'vbadge-test_data'],
        default        => ['label' => ucfirst($status ?? 'Unknown'), 'class' => 'vbadge-uncertain'],
    };
@endphp

<div class="wrapper">

    {{-- ===== HEADER ===== --}}
    <div class="report-header">
        <div class="brand">
            <span class="badge-synapse">SYNAPSE</span>
            <span style="font-family:sans-serif;font-size:9pt;color:#888;">AI-Assisted Intelligence Report</span>
        </div>
        <div class="report-title">DSAR Intelligence Report</div>
        <div class="report-subtitle">Subject Access Request Strategy &amp; Target Identification</div>
        <div class="report-meta">
            <span><strong>Client:</strong> {{ $client->full_name ?? '—' }}</span>
            <span><strong>Date of Birth:</strong> {{ optional($client->date_of_birth)->format('d M Y') ?? '—' }}</span>
            <span><strong>Claim Ref:</strong> {{ $claim->reference ?? $claim->id }}</span>
            <span><strong>Report Generated:</strong> {{ $run->created_at->format('d M Y, H:i') }}</span>
            <span><strong>Overall Confidence:</strong>
                <span class="confidence-badge {{ $overallConfidenceClass }}" style="display:inline;padding:1px 8px;border-radius:10px;font-size:8.5pt;font-weight:700;">
                    {{ $overallConfidence }}
                </span>
            </span>
        </div>
    </div>

    @if(!$isNewFormat)

        {{-- ===== STALE FORMAT NOTICE ===== --}}
        <div class="warning-banner warning-stale">
            <strong>Report format outdated</strong>
            This report was generated with an older version of Synapse and cannot be displayed in the updated per-care-setting format.
            Please re-run the analysis to generate a new report.
        </div>

    @else

        {{-- ===== OVERALL CONFIDENCE BANNER ===== --}}
        <section class="section">
            <div class="section-heading">
                <span class="section-letter">Overview</span> Overall Assessment
            </div>
            <div class="confidence-banner">
                <span class="confidence-badge {{ $overallConfidenceClass }}">{{ $overallConfidence }} Confidence</span>
                <span class="confidence-explanation">{{ $result['overall_confidence_explanation'] ?? '' }}</span>
            </div>
        </section>

        {{-- ===== GLOBAL TIMELINE ===== --}}
        @if(!empty($result['timeline']))
        <section class="section">
            <div class="section-heading">
                <span class="section-letter">Timeline</span> Chronological Timeline of Care Settings
            </div>
            <table class="timeline-table">
                <thead>
                    <tr>
                        <th style="width:130px;">Period</th>
                        <th style="width:220px;">Care Setting</th>
                        <th>Notes</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($result['timeline'] as $entry)
                    <tr>
                        <td class="period-cell">{{ $entry['period'] }}</td>
                        <td style="font-family:sans-serif;font-weight:600;">{{ $entry['care_setting'] }}</td>
                        <td style="color:#6b7280;font-style:italic;">{{ $entry['notes'] ?? '' }}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
            @if(!empty($result['timeline_gaps']))
            <div class="gaps-block">
                <p class="gaps-heading">Gaps / Missing Periods</p>
                <ul>
                    @foreach($result['timeline_gaps'] as $gap)
                        <li>{{ $gap }}</li>
                    @endforeach
                </ul>
            </div>
            @endif
        </section>
        @endif

        {{-- ===== PER CARE SETTING ===== --}}
        @foreach($result['care_setting_reports'] as $i => $cs)
        @php
            $inst        = $cs['institution_identification'];
            $vStatus     = $inst['verification_status'] ?? 'uncertain';
            $vBadge      = $verificationBadge($vStatus);
            $isTestData  = $vStatus === 'test_data';
            $isUnverifiable = $vStatus === 'unverifiable';
            $skipTargets = $isTestData || $isUnverifiable;
            $csConfClass = match($cs['confidence'] ?? 'Low') {
                'High'   => 'conf-high',
                'Medium' => 'conf-medium',
                default  => 'conf-low',
            };
        @endphp

        <div class="care-setting-block">

            {{-- Care Setting Divider --}}
            <div class="care-setting-divider">
                <span class="care-setting-number">Care Setting {{ $i + 1 }}</span>
                <span class="care-setting-name">{{ $cs['care_setting_name'] }}</span>
            </div>

            {{-- ===== A: INSTITUTION IDENTIFICATION ===== --}}
            <section class="section">
                <div class="section-heading">
                    <span class="section-letter">A</span> Institution Identification
                </div>

                @if($isTestData)
                    <div class="warning-banner warning-test-data">
                        <strong>Test / Placeholder Institution — No DSAR targets generated</strong>
                        {{ $inst['verification_notes'] }}
                    </div>
                @elseif($isUnverifiable)
                    <div class="warning-banner warning-unverifiable">
                        <strong>Institution Could Not Be Identified</strong>
                        {{ $inst['verification_notes'] }}
                    </div>
                @endif

                <div class="institution-card">
                    <div class="institution-header">
                        <div>
                            <div class="institution-name">{{ $inst['likely_official_name'] }}</div>
                            @if(($inst['recorded_name'] ?? '') !== ($inst['likely_official_name'] ?? ''))
                                <div class="institution-recorded">Recorded as: "{{ $inst['recorded_name'] }}"</div>
                            @endif
                        </div>
                        <div style="display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end;">
                            <span class="institution-type-badge">{{ $inst['type'] }}</span>
                            <span class="verification-badge {{ $vBadge['class'] }}">{{ $vBadge['label'] }}</span>
                        </div>
                    </div>
                    @if(!empty($inst['description']))
                        <p class="institution-description">{{ $inst['description'] }}</p>
                    @endif
                    @if(!empty($inst['verification_notes']) && !$isTestData && !$isUnverifiable)
                        <p class="institution-notes">Identification notes: {{ $inst['verification_notes'] }}</p>
                    @endif
                </div>
            </section>

            @if(!$skipTargets)

                {{-- ===== C: CURRENT STATUS & SUCCESSORS ===== --}}
                <section class="section">
                    <div class="section-heading">
                        <span class="section-letter">C</span> Current Status &amp; Successors
                    </div>
                    @if(!empty($cs['current_status']['description']))
                        <p class="prose" style="margin-bottom:12px;">{{ $cs['current_status']['description'] }}</p>
                    @endif
                    @if(!empty($cs['current_status']['record_holders']))
                        <table class="record-holders-table">
                            <thead>
                                <tr>
                                    <th>Likely Record Holder</th>
                                    <th>Role</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($cs['current_status']['record_holders'] as $rh)
                                <tr>
                                    <td style="font-family:sans-serif;font-weight:600;">{{ $rh['organisation'] }}</td>
                                    <td>{{ $rh['role'] }}</td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    @endif
                </section>

                {{-- ===== D: CROSS-INSTITUTION LINKS ===== --}}
                @if(!empty($cs['cross_institution_links']))
                <section class="section">
                    <div class="section-heading">
                        <span class="section-letter">D</span> Cross-Institution Record Links
                    </div>
                    @foreach($cs['cross_institution_links'] as $link)
                    <div class="link-card">
                        <div class="link-orgs">{{ implode(' · ', $link['organisations']) }}</div>
                        <div class="link-desc">{{ $link['description'] }}</div>
                    </div>
                    @endforeach
                </section>
                @endif

                {{-- ===== E & F: DSAR TARGETS WITH CONTACT DETAILS ===== --}}
                @if(!empty($cs['dsar_targets']))
                <section class="section page-break">
                    <div class="section-heading">
                        <span class="section-letter">E &amp; F</span> Prioritised DSAR Targets &amp; Contact Details
                        <span style="font-size:9pt;font-weight:400;color:#888;margin-left:10px;">{{ count($cs['dsar_targets']) }} organisations identified</span>
                    </div>
                    @foreach($cs['dsar_targets'] as $target)
                    @php
                        $src   = $sourceLabels[$target['source_type']] ?? ['label' => ucfirst($target['source_type'] ?? ''), 'class' => 'badge-supporting'];
                        $stCls = $statusClasses[$target['current_status'] ?? 'unknown'] ?? 'badge-unknown';
                    @endphp
                    <div class="target-card">
                        <div class="target-header">
                            <span class="target-priority">{{ $target['priority'] }}</span>
                            <div class="target-header-info">
                                <div class="target-org">{{ $target['organisation'] }}</div>
                                <div class="target-badges">
                                    <span class="target-badge {{ $src['class'] }}">{{ $src['label'] }}</span>
                                    <span class="target-badge {{ $stCls }}">{{ ucfirst($target['current_status'] ?? 'Unknown') }}</span>
                                </div>
                            </div>
                            <div class="target-scores">
                                <div class="score-item">
                                    <span class="score-label">Records</span>
                                    <span class="score-val {{ $scoreClass($target['record_likelihood'] ?? '') }}">{{ ($target['record_likelihood'] ?? '—')[0] ?? '—' }}</span>
                                </div>
                                <div class="score-item">
                                    <span class="score-label">Useful</span>
                                    <span class="score-val {{ $scoreClass($target['usefulness'] ?? '') }}">{{ ($target['usefulness'] ?? '—')[0] ?? '—' }}</span>
                                </div>
                                <div class="score-item">
                                    <span class="score-label">Retrieval</span>
                                    <span class="score-val {{ $scoreClass($target['retrieval_difficulty'] ?? '') }}">{{ ($target['retrieval_difficulty'] ?? '—')[0] ?? '—' }}</span>
                                </div>
                                <div class="score-item">
                                    <span class="score-label">Strategic</span>
                                    <span class="score-val {{ $scoreClass($target['strategic_importance'] ?? '') }}">{{ ($target['strategic_importance'] ?? '—')[0] ?? '—' }}</span>
                                </div>
                            </div>
                        </div>

                        <p class="target-rationale">{{ $target['rationale'] }}</p>

                        @if(!empty($target['successor']))
                            <p class="target-successor">&#8594; Successor / record holder: {{ $target['successor'] }}</p>
                        @endif

                        @php
                            $targetContacts    = $target['contacts'] ?? [];
                            $instId            = $target['institution_id'] ?? null;
                            $contactInDb       = $target['contact_in_db'] ?? false;
                        @endphp

                        @if(count($targetContacts) > 0)
                        <div class="contacts-block">
                            @foreach($targetContacts as $contact)
                            @php
                                $cType  = $contact['type'] ?? 'address';
                                $cValue = $contact['value'] ?? null;
                                $cDept  = $contact['department'] ?? null;
                                $canAdd = $instId && in_array($cType, ['email', 'phone']);
                                $typeLabel = match($cType) {
                                    'email'   => 'Email',
                                    'phone'   => 'Telephone',
                                    'address' => 'Postal / SAR Route',
                                    default   => ucfirst($cType),
                                };
                            @endphp
                            @if($cValue)
                            <div class="contact-entry">
                                @if($cDept)
                                    <div>
                                        <span class="contact-label">Department</span>
                                        {{ $cDept }}
                                    </div>
                                @endif
                                <div @class(['grid-col-full' => !$cDept])>
                                    <span class="contact-label">{{ $typeLabel }}</span>
                                    {{ $cValue }}
                                </div>
                                @if($canAdd)
                                    <div style="grid-column:1/-1;margin-top:4px;" class="no-print">
                                        <button
                                            onclick="synapseAddContact(this,
                                                '{{ route('institutions.synapse-contact.store', $instId) }}',
                                                {{ json_encode(array_filter([
                                                    'job_title' => $cDept,
                                                    'email'     => $cType === 'email' ? $cValue : null,
                                                    'telephone' => $cType === 'phone' ? $cValue : null,
                                                ])) }}
                                            )"
                                            style="font-family:sans-serif;font-size:8pt;color:#059669;background:none;border:1px solid #a7f3d0;border-radius:4px;padding:3px 10px;cursor:pointer;">
                                            + Add to institution record
                                        </button>
                                    </div>
                                @endif
                            </div>
                            @endif
                            @endforeach
                        </div>
                        @else
                        <div style="border-top:1px solid #f3f4f6;padding-top:8px;margin-top:6px;font-family:sans-serif;font-size:8.5pt;color:#b45309;">
                            &#9888; Contact details not found — manual search required for this organisation's SAR/DSAR route.
                        </div>
                        @endif

                        {{-- Institution DB link --}}
                        <div style="margin-top:8px;display:flex;gap:8px;flex-wrap:wrap;" class="no-print">
                            @if($instId)
                                <a wire:navigate href="{{ route('institutions.show', $instId) }}"
                                   target="_blank"
                                   style="font-family:sans-serif;font-size:8pt;color:#7c3aed;text-decoration:none;border:1px solid #e9d5ff;border-radius:4px;padding:3px 10px;">
                                    &#8599; View institution record
                                </a>
                            @else
                                <a wire:navigate href="{{ route('institutions.create') }}?display_name={{ urlencode($target['organisation']) }}"
                                   target="_blank"
                                   style="font-family:sans-serif;font-size:8pt;color:#059669;text-decoration:none;border:1px solid #a7f3d0;border-radius:4px;padding:3px 10px;">
                                    + Add to institutions
                                </a>
                            @endif
                        </div>
                    </div>
                    @endforeach
                </section>
                @endif

                {{-- ===== G: STRATEGIC NOTES ===== --}}
                @if(!empty($cs['strategic_notes']))
                <section class="section">
                    <div class="section-heading">
                        <span class="section-letter">G</span> Strategic Notes
                    </div>
                    <p class="prose">{{ $cs['strategic_notes'] }}</p>
                </section>
                @endif

                {{-- ===== H: EVIDENCE PROBABILITY ASSESSMENT ===== --}}
                @if(!empty($cs['dsar_targets']))
                <section class="section">
                    <div class="section-heading">
                        <span class="section-letter">H</span> Evidence Probability Assessment
                    </div>
                    <table class="evidence-table">
                        <thead>
                            <tr>
                                <th style="width:32px;">#</th>
                                <th>DSAR Target</th>
                                <th>Records Exist</th>
                                <th>Usefulness</th>
                                <th>Retrieval Difficulty</th>
                                <th>Strategic Importance</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($cs['dsar_targets'] as $target)
                            <tr>
                                <td style="text-align:center;font-family:sans-serif;font-weight:600;">{{ $target['priority'] }}</td>
                                <td class="ev-org">{{ $target['organisation'] }}</td>
                                <td class="{{ $scoreClass($target['record_likelihood'] ?? '') }}" style="font-family:sans-serif;font-weight:600;">{{ $target['record_likelihood'] ?? '—' }}</td>
                                <td class="{{ $scoreClass($target['usefulness'] ?? '') }}" style="font-family:sans-serif;font-weight:600;">{{ $target['usefulness'] ?? '—' }}</td>
                                <td class="{{ $scoreClass($target['retrieval_difficulty'] ?? '') }}" style="font-family:sans-serif;font-weight:600;">{{ $target['retrieval_difficulty'] ?? '—' }}</td>
                                <td class="{{ $scoreClass($target['strategic_importance'] ?? '') }}" style="font-family:sans-serif;font-weight:600;">{{ $target['strategic_importance'] ?? '—' }}</td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </section>
                @endif

                {{-- ===== I: FALLBACK ROUTES ===== --}}
                @if(!empty($cs['fallback_routes']))
                <section class="section">
                    <div class="section-heading">
                        <span class="section-letter">I</span> Fallback / Advanced Evidence Routes
                    </div>
                    @foreach($cs['fallback_routes'] as $fb)
                    <div class="fallback-item">
                        <div class="fallback-route">{{ $fb['route'] }}</div>
                        <div class="fallback-rationale">{{ $fb['rationale'] }}</div>
                    </div>
                    @endforeach
                </section>
                @endif

            @else
                {{-- Strategic notes still shown even for test/unverifiable --}}
                @if(!empty($cs['strategic_notes']))
                <section class="section">
                    <div class="section-heading">
                        <span class="section-letter">Note</span> Analysis Notes
                    </div>
                    <p class="prose">{{ $cs['strategic_notes'] }}</p>
                </section>
                @endif
            @endif

            {{-- ===== J: CONFIDENCE ===== --}}
            <section class="section">
                <div class="section-heading">
                    <span class="section-letter">J</span> Confidence Level
                </div>
                <div class="confidence-banner">
                    <span class="confidence-badge {{ $csConfClass }}">{{ $cs['confidence'] ?? '—' }} Confidence</span>
                    <span class="confidence-explanation">{{ $cs['confidence_explanation'] ?? '' }}</span>
                </div>
            </section>

        </div>{{-- end care-setting-block --}}
        @endforeach

        {{-- ===== OVERALL STRATEGIC NOTES ===== --}}
        @if(!empty($result['overall_strategic_notes']))
        <section class="section page-break overall-section">
            <div class="section-heading">
                <span class="section-letter">&#9733;</span> Overall Strategic Recommendations
            </div>
            <p class="prose">{{ $result['overall_strategic_notes'] }}</p>
        </section>
        @endif

    @endif

    {{-- ===== DISCLAIMER ===== --}}
    <div class="disclaimer">
        <strong>Important Notice:</strong> This report was generated by Synapse, an AI-assisted legal intelligence system.
        It is intended to assist solicitors and caseworkers in planning DSAR strategy and should be reviewed critically before acting.
        Contact details, institution names, and record survival assessments are based on the case data provided and general knowledge;
        they must be independently verified. This report does not constitute legal advice.
        Confidence ratings reflect the quality of information available at the time of analysis and not a guarantee of outcome.
    </div>

</div>

{{-- Print / Back buttons --}}
<div class="print-bar no-print">
    <a wire:navigate href="javascript:history.back()" class="btn-back">&#8592; Back</a>
    <button class="btn-print" onclick="window.print()">Print / Save PDF</button>
</div>

{{-- Toast notification --}}
<div id="synapse-toast" class="no-print" style="
    position:fixed;bottom:24px;left:50%;transform:translateX(-50%);
    font-family:sans-serif;font-size:10pt;font-weight:600;
    padding:10px 20px;border-radius:6px;box-shadow:0 4px 12px rgba(0,0,0,.15);
    display:none;z-index:9999;white-space:nowrap;transition:opacity .2s;">
</div>

<script>
async function synapseAddContact(btn, url, data) {
    btn.disabled = true;
    btn.textContent = 'Adding…';

    try {
        const res = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
            },
            body: JSON.stringify(data),
        });

        const json = await res.json();

        if (json.success) {
            btn.textContent = '✓ Added';
            btn.style.color = '#059669';
            btn.style.borderColor = '#059669';
            showToast(json.message, true);
        } else {
            btn.disabled = false;
            btn.textContent = '+ Add contact details';
            showToast(json.message, false);
        }
    } catch (e) {
        btn.disabled = false;
        btn.textContent = '+ Add contact details';
        showToast('Network error — please try again.', false);
    }
}

function showToast(msg, success) {
    const t = document.getElementById('synapse-toast');
    t.textContent = msg;
    t.style.background = success ? '#166534' : '#991b1b';
    t.style.color = '#fff';
    t.style.display = 'block';
    t.style.opacity = '1';
    clearTimeout(t._timer);
    t._timer = setTimeout(() => {
        t.style.opacity = '0';
        setTimeout(() => t.style.display = 'none', 200);
    }, 3500);
}
</script>

</body>
</html>
