{{--
    Appointment-integrated AI — 4 staged clinical checkpoints.
    Included by VetClinic's appointment page (View::exists guard). $appointment is passed in.
--}}
@can('vet_ai.use_assistant')
@php
    // NB: no `use` statements — a compiled Blade view runs inside a method scope,
    // so imports must be fully-qualified class references instead.
    $vaiBiz      = session('user.business_id');
    $vaiSettings = \Modules\VetAI\Entities\VaiSetting::forBusiness($vaiBiz);

    $vaiSubjective = trim((string) ($appointment->soap_subjective ?: $appointment->reason));
    $vaiObjective  = trim((string) $appointment->soap_objective);
    $vaiAssessment = trim((string) $appointment->soap_assessment);
    $vaiPlan       = trim((string) $appointment->soap_plan);

    $vaiStages = [
        'exam_review' => [
            'title' => 'Examination Review', 'icon' => 'fa-stethoscope', 'color' => '#0ea5e9',
            'desc'  => 'Reviews the complaint + physical exam, then suggests a missed/more-specific exam, recommended investigations, or that you may proceed to diagnosis.',
            'ready' => ($vaiSubjective !== '' || $vaiObjective !== ''),
            'lock'  => 'Record the complaint or physical examination first.',
        ],
        'diagnosis' => [
            'title' => 'Expected Diagnoses', 'icon' => 'fa-search-plus', 'color' => '#8b5cf6',
            'desc'  => 'Ranked likely diagnoses from the history, examination and any uploaded investigation results.',
            'ready' => ($vaiObjective !== ''),
            'lock'  => 'Record the physical examination (Objective) first.',
        ],
        'treatment' => [
            'title' => 'Treatment Plan', 'icon' => 'fa-prescription-bottle-alt', 'color' => '#22c55e',
            'desc'  => 'Treatment plan for the approved diagnosis. Recommended drugs are checked against your defined medicine list.',
            'ready' => ($vaiAssessment !== ''),
            'lock'  => 'Enter the diagnosis in the Assessment field first — the doctor-approval gate.',
        ],
        'interaction' => [
            'title' => 'Interaction & Dose Check', 'icon' => 'fa-pills', 'color' => '#ef4444',
            'desc'  => 'Drug-interaction check and weight-based dosing for the planned medications.',
            'ready' => ($vaiPlan !== ''),
            'lock'  => 'Record the treatment plan first.',
        ],
    ];

    $vaiCached = \Modules\VetAI\Entities\VaiQuery::where('appointment_id', $appointment->id)
        ->where('status', 'success')->whereNotNull('stage')
        ->latest()->get()->groupBy('stage');
@endphp

<style>
.vai-ap-disc { background:#fffbeb; border:1px solid #fde68a; color:#92400e; border-radius:8px;
    padding:9px 13px; font-size:12px; margin-bottom:14px; }
.vai-ap-stage { border:1px solid #e5e9f0; border-radius:10px; margin-bottom:12px; overflow:hidden; }
.vai-ap-head { padding:10px 14px; display:flex; align-items:center; gap:9px; background:#f8fafc;
    border-bottom:1px solid #f0f2f5; }
.vai-ap-head .t { font-weight:700; color:#1e293b; }
.vai-ap-head .badge-step { width:22px;height:22px;border-radius:50%;color:#fff;font-size:11px;font-weight:700;
    display:inline-flex;align-items:center;justify-content:center; }
.vai-ap-body { padding:12px 14px; }
.vai-ap-desc { font-size:12px; color:#64748b; margin-bottom:9px; }
.vai-ap-result { font-size:13px; line-height:1.6; color:#1e293b; background:#f8fafc;
    border:1px solid #e8ecf0; border-radius:8px; padding:12px 14px; margin-top:9px; display:none; }
.vai-ap-result.show { display:block; }
.vai-ap-result p { margin:0 0 9px; }
.vai-ap-result ul,.vai-ap-result ol { padding-left:22px; margin:0 0 9px; }
.vai-ap-result h1,.vai-ap-result h2,.vai-ap-result h3,.vai-ap-result h4 { font-size:14px; font-weight:700; margin:12px 0 6px; }
.vai-ap-result code { background:#eef2f7; padding:1px 5px; border-radius:4px; }
.vai-ap-result em { color:#b45309; }
.vai-medchk { margin-top:10px; border-top:1px dashed #e2e8f0; padding-top:8px; }
.vai-medchk .pill { display:inline-block; font-size:11px; font-weight:600; padding:3px 9px;
    border-radius:12px; margin:2px 4px 2px 0; }
.vai-medchk .in  { background:#dcfce7; color:#15803d; }
.vai-medchk .out { background:#fef3c7; color:#92400e; }
.vai-ap-meta { font-size:11px; color:#94a3b8; margin-top:6px; }
.vai-ap-locked { font-size:11.5px; color:#b45309; }
</style>

<div style="max-width:900px;">
    <div class="vai-ap-disc">
        <i class="fa fa-shield-alt"></i> <strong>Advisory only.</strong>
        Every suggestion must be verified by the attending veterinarian. The AI never finalises a diagnosis or prescription.
    </div>

    @unless($vaiSettings->isConfigured())
        <div class="callout callout-warning" style="font-size:12px;">
            <i class="fa fa-exclamation-triangle"></i> The AI assistant is not configured.
            @can('vet_ai.manage_settings')<a href="{{ route('vai.settings.index') }}">Open AI Settings</a>.@endcan
        </div>
    @endunless

    @php $vaiStep = 0; @endphp
    @foreach($vaiStages as $key => $st)
        @php
            $vaiStep++;
            $last = optional($vaiCached->get($key))->first();
            $cachedText = $last ? preg_replace('/^[ \t]*MEDICINES:.*$/im', '', (string) $last->response) : '';
        @endphp
        <div class="vai-ap-stage" data-stage="{{ $key }}">
            <div class="vai-ap-head">
                <span class="badge-step" style="background:{{ $st['color'] }};">{{ $vaiStep }}</span>
                <i class="fa {{ $st['icon'] }}" style="color:{{ $st['color'] }};"></i>
                <span class="t">{{ $st['title'] }}</span>
            </div>
            <div class="vai-ap-body">
                <div class="vai-ap-desc">{{ $st['desc'] }}</div>

                @if($st['ready'])
                    <button class="btn btn-sm btn-primary vai-ap-btn" data-stage="{{ $key }}"
                            {{ $vaiSettings->isConfigured() ? '' : 'disabled' }}>
                        <i class="fa fa-robot"></i> {{ $last ? 'Regenerate' : 'Generate AI advice' }}
                    </button>
                @else
                    <button class="btn btn-sm btn-default" disabled>
                        <i class="fa fa-lock"></i> Locked
                    </button>
                    <span class="vai-ap-locked"><i class="fa fa-info-circle"></i> {{ $st['lock'] }}</span>
                @endif

                <div class="vai-ap-result {{ $last ? 'show' : '' }}" id="vai-res-{{ $key }}">
                    @if($last){!! \Modules\VetAI\Entities\VaiQuery::renderMarkdown($cachedText) !!}@endif
                </div>
                <div class="vai-medchk" id="vai-med-{{ $key }}" style="display:none;"></div>
                <div class="vai-ap-meta" id="vai-meta-{{ $key }}">
                    @if($last)Last generated {{ optional($last->created_at)->format('d M Y H:i') }} · model {{ $last->model }}@endif
                </div>
            </div>
        </div>
    @endforeach
</div>

<script>
// The panel is rendered mid-page; defer until jQuery (loaded at page end) is ready.
window.addEventListener('load', function () {
    var VAI_URL   = '{{ route('vai.appointment.generate', $appointment->id) }}';
    var VAI_TOKEN = '{{ csrf_token() }}';

    function renderMedCheck($box, rows) {
        if (!rows || !rows.length) { $box.hide().empty(); return; }
        var html = '<strong style="font-size:11.5px;color:#475569;">Medicine-list check:</strong><br>';
        rows.forEach(function (r) {
            if (r.in_list) {
                html += '<span class="pill in"><i class="fa fa-check"></i> ' + $('<i>').text(r.drug).html()
                      + (r.matched ? ' → ' + $('<i>').text(r.matched).html() : '') + '</span>';
            } else {
                html += '<span class="pill out"><i class="fa fa-exclamation-triangle"></i> '
                      + $('<i>').text(r.drug).html() + ' — not in your medicine list</span>';
            }
        });
        $box.html(html).show();
    }

    $(document).on('click', '.vai-ap-btn', function () {
        var stage = $(this).data('stage');
        var $btn  = $(this);
        var $res  = $('#vai-res-' + stage);
        var $med  = $('#vai-med-' + stage);
        var $meta = $('#vai-meta-' + stage);

        $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Thinking…');
        $res.addClass('show').html('<span class="text-muted"><i class="fa fa-spinner fa-spin"></i> Contacting the AI model…</span>');
        $med.hide().empty();

        $.post(VAI_URL, { _token: VAI_TOKEN, stage: stage })
            .done(function (d) {
                if (d.success) {
                    $res.html(d.response_html);
                    renderMedCheck($med, d.medicine_check);
                    $meta.text('Last generated ' + d.generated_at + ' · ~' + d.tokens + ' tokens');
                } else {
                    $res.html('<span style="color:#dc2626;">' + $('<i>').text(d.msg || 'Failed').html() + '</span>');
                }
            })
            .fail(function (xhr) {
                var m = (xhr.responseJSON && xhr.responseJSON.msg) ? xhr.responseJSON.msg : 'AI request failed.';
                $res.html('<span style="color:#dc2626;">' + $('<i>').text(m).html() + '</span>');
            })
            .always(function () {
                $btn.prop('disabled', false).html('<i class="fa fa-robot"></i> Regenerate');
            });
    });
});
</script>
@endcan
