{{-- Dermatology panel, injected into ClinicCore's patient show AND appointment
     screens via the SpecialtyDriverRegistry.
       - patient show fragment  -> receives $patient
       - appointment fragment   -> receives $patient + $appointment
     Contains: the at-a-glance skin profile (unchanged), an interactive body-map
     lesion editor with ABCDE checklist + biopsy hint, a per-lesion photo strip
     (reusing clc_clinical_photos), and PASI/EASI/DLQI/IGA severity scores with a
     lightweight trend. All writes go through the module's own AJAX endpoints. --}}
@php
    use Modules\DermatologyClinic\Entities\DermaLesion;
    use Modules\DermatologyClinic\Entities\DermaScore;

    $dermaProfile = \Modules\DermatologyClinic\Entities\DermaPatientProfile::where('clc_patient_id', $patient->id)->first();
    $dCanLesions  = auth()->user() && auth()->user()->can('derma.lesions.manage');
    $dCanScores   = auth()->user() && auth()->user()->can('derma.scores.manage');
    $dApptId      = isset($appointment) ? $appointment->id : null;

    $dLesions = DermaLesion::where('business_id', $patient->business_id)
        ->where('patient_id', $patient->id)
        ->orderByDesc('id')->get();

    // Photos available to link (this patient's shared clinical photos).
    $dPhotos = \Modules\ClinicCore\Entities\ClcClinicalPhoto::where('business_id', $patient->business_id)
        ->where('clc_patient_id', $patient->id)
        ->orderBy('taken_at')->orderBy('id')
        ->get(['id', 'taken_at', 'body_area', 'caption', 'file_path']);
    $dPhotoById = $dPhotos->keyBy('id');

    $dScores = DermaScore::where('business_id', $patient->business_id)
        ->where('patient_id', $patient->id)
        ->orderBy('recorded_at')->orderBy('id')->get();

    $dUid = 'derma' . $patient->id;
@endphp

{{-- ── At-a-glance skin profile (unchanged behaviour) ── --}}
@if($dermaProfile && $dermaProfile->fitzpatrick_type)
<div class="detail-row">
    <span class="dk"><i class="fas fa-sun fa-fw"></i> Fitzpatrick</span>
    <span class="dv"><span class="label label-info" style="font-size:11px;">Type {{ $dermaProfile->fitzpatrick_type }}</span></span>
</div>
@endif
@if($dermaProfile && $dermaProfile->skin_type)
<div class="detail-row">
    <span class="dk"><i class="fas fa-hand-dots fa-fw"></i> Skin Type</span>
    <span class="dv">{{ $dermaProfile->skin_type }}</span>
</div>
@endif

{{-- ── Skin lesions: body map + list + ABCDE ── --}}
<div class="detail-row" style="display:block;" id="{{ $dUid }}_lesions"
     data-store-url="{{ route('derma.lesions.store', $patient->id) }}"
     data-photos-base="{{ url('derma/patients/'.$patient->id.'/lesions') }}"
     data-appointment-id="{{ $dApptId }}">
    <span class="dk" style="display:block;margin-bottom:6px;"><i class="fas fa-hand-dots fa-fw"></i> {{ __('dermaClinic::lang.skin_lesions') }}</span>

    <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:flex-start;">
        {{-- Inline SVG body outline (front + back). Click stores region + x/y%. --}}
        <div style="flex:0 0 200px;">
            <div style="display:flex;gap:4px;margin-bottom:4px;font-size:10px;color:#64748b;">
                <span style="flex:1;text-align:center;">{{ __('dermaClinic::lang.front') }}</span>
                <span style="flex:1;text-align:center;">{{ __('dermaClinic::lang.back') }}</span>
            </div>
            <svg viewBox="0 0 200 220" width="200" height="220" class="derma-bodymap" style="border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;cursor:{{ $dCanLesions ? 'crosshair' : 'default' }};">
                {{-- FRONT figure (x 0-100) --}}
                <g data-face="front">
                    <circle cx="50" cy="24" r="14" fill="#e2e8f0" stroke="#cbd5e1" data-region="face"/>
                    <rect x="44" y="38" width="12" height="8" fill="#e2e8f0" stroke="#cbd5e1" data-region="neck"/>
                    <rect x="30" y="46" width="40" height="46" rx="8" fill="#e2e8f0" stroke="#cbd5e1" data-region="chest"/>
                    <rect x="30" y="92" width="40" height="34" rx="6" fill="#e2e8f0" stroke="#cbd5e1" data-region="abdomen"/>
                    <rect x="16" y="48" width="12" height="52" rx="6" fill="#e2e8f0" stroke="#cbd5e1" data-region="right_arm"/>
                    <rect x="72" y="48" width="12" height="52" rx="6" fill="#e2e8f0" stroke="#cbd5e1" data-region="left_arm"/>
                    <circle cx="22" cy="106" r="7" fill="#e2e8f0" stroke="#cbd5e1" data-region="right_hand"/>
                    <circle cx="78" cy="106" r="7" fill="#e2e8f0" stroke="#cbd5e1" data-region="left_hand"/>
                    <rect x="32" y="126" width="15" height="60" rx="6" fill="#e2e8f0" stroke="#cbd5e1" data-region="right_leg"/>
                    <rect x="53" y="126" width="15" height="60" rx="6" fill="#e2e8f0" stroke="#cbd5e1" data-region="left_leg"/>
                    <ellipse cx="39" cy="196" rx="8" ry="5" fill="#e2e8f0" stroke="#cbd5e1" data-region="right_foot"/>
                    <ellipse cx="61" cy="196" rx="8" ry="5" fill="#e2e8f0" stroke="#cbd5e1" data-region="left_foot"/>
                </g>
                {{-- BACK figure (x 100-200) --}}
                <g data-face="back">
                    <circle cx="150" cy="24" r="14" fill="#eef2f7" stroke="#cbd5e1" data-region="head"/>
                    <rect x="144" y="38" width="12" height="8" fill="#eef2f7" stroke="#cbd5e1" data-region="neck"/>
                    <rect x="130" y="46" width="40" height="80" rx="8" fill="#eef2f7" stroke="#cbd5e1" data-region="back"/>
                    <rect x="116" y="48" width="12" height="52" rx="6" fill="#eef2f7" stroke="#cbd5e1" data-region="left_arm"/>
                    <rect x="172" y="48" width="12" height="52" rx="6" fill="#eef2f7" stroke="#cbd5e1" data-region="right_arm"/>
                    <rect x="132" y="126" width="15" height="60" rx="6" fill="#eef2f7" stroke="#cbd5e1" data-region="left_leg"/>
                    <rect x="153" y="126" width="15" height="60" rx="6" fill="#eef2f7" stroke="#cbd5e1" data-region="right_leg"/>
                </g>
                {{-- lesion markers --}}
                @foreach($dLesions as $lz)
                    @php
                        $isBack = in_array($lz->body_region, ['back','head'], true);
                        $mx = $isBack ? 100 : 0;
                        $cx = $mx + (($lz->position_x ?? 50) / 100 * 100);
                        $cy = ($lz->position_y ?? 50) / 100 * 220;
                        $danger = $lz->suggestsBiopsy();
                    @endphp
                    <circle cx="{{ $cx }}" cy="{{ $cy }}" r="4" fill="{{ $danger ? '#dc3545' : '#0d6efd' }}"
                            stroke="#fff" stroke-width="1" class="derma-marker" data-lesion="{{ $lz->id }}">
                        <title>#{{ $lz->id }} {{ DermaLesion::MORPHOLOGIES[$lz->morphology] ?? $lz->morphology }} — {{ DermaLesion::BODY_REGIONS[$lz->body_region] ?? $lz->body_region }}</title>
                    </circle>
                @endforeach
            </svg>
        </div>

        {{-- Lesion list --}}
        <div style="flex:1 1 260px;min-width:240px;">
            <table style="width:100%;font-size:11px;border-collapse:collapse;" class="derma-lesion-table">
                <thead>
                    <tr style="color:#64748b;border-bottom:1px solid #e2e8f0;">
                        <th style="text-align:left;padding:2px 4px;">#</th>
                        <th style="text-align:left;padding:2px 4px;">Region</th>
                        <th style="text-align:left;padding:2px 4px;">Morphology</th>
                        <th style="text-align:left;padding:2px 4px;">ABCDE</th>
                        <th style="text-align:left;padding:2px 4px;">Status</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($dLesions as $lz)
                        @php $abCount = $lz->abcdeCount(); @endphp
                        <tr data-lesion-row="{{ $lz->id }}" style="border-bottom:1px solid #f1f5f9;">
                            <td style="padding:2px 4px;">{{ $lz->id }}</td>
                            <td style="padding:2px 4px;">{{ DermaLesion::BODY_REGIONS[$lz->body_region] ?? $lz->body_region }}</td>
                            <td style="padding:2px 4px;">{{ DermaLesion::MORPHOLOGIES[$lz->morphology] ?? $lz->morphology }}{{ $lz->size_mm ? ' · '.rtrim(rtrim(number_format($lz->size_mm,1),'0'),'.').'mm' : '' }}</td>
                            <td style="padding:2px 4px;">
                                <span class="label {{ $abCount >= 3 ? 'label-danger' : 'label-default' }}" style="font-size:10px;">{{ $abCount }}/5</span>
                                @if($lz->suggestsBiopsy())
                                    <span class="label label-danger" style="font-size:9px;" title="3+ ABCDE criteria — consider biopsy"><i class="fas fa-exclamation-triangle"></i> {{ __('dermaClinic::lang.suggest_biopsy') }}</span>
                                @endif
                            </td>
                            <td style="padding:2px 4px;">{{ DermaLesion::STATUSES[$lz->status] ?? $lz->status }}</td>
                            <td style="padding:2px 4px;text-align:right;">
                                @if(count($lz->photo_ids ?? []))
                                    <span title="{{ count($lz->photo_ids) }} photo(s)"><i class="fas fa-camera" style="color:#64748b;"></i> {{ count($lz->photo_ids) }}</span>
                                @endif
                                @if($dCanLesions)
                                    <button type="button" class="btn btn-xs btn-link derma-link-photos" data-lesion="{{ $lz->id }}" title="{{ __('dermaClinic::lang.link_photos') }}" style="padding:0 4px;color:#0d6efd;"><i class="fas fa-link"></i></button>
                                    <button type="button" class="btn btn-xs btn-link derma-del-lesion" data-lesion="{{ $lz->id }}" title="{{ __('dermaClinic::lang.delete') }}" style="padding:0 4px;color:#dc3545;"><i class="fas fa-trash"></i></button>
                                @endif
                            </td>
                        </tr>
                        {{-- Per-lesion "Link photos" picker (hidden until the link button is clicked).
                             Lists this patient's shared clinical photos with checkboxes; POSTs the
                             selected photo_ids[] to derma.lesions.photos (linkPhotos). --}}
                        @if($dCanLesions)
                        @php $lzLinked = collect($lz->photo_ids ?? [])->map(fn($v) => (int) $v)->all(); @endphp
                        <tr class="derma-photo-picker" data-lesion="{{ $lz->id }}"
                            data-photos-url="{{ url('derma/patients/'.$patient->id.'/lesions/'.$lz->id.'/photos') }}"
                            style="display:none;">
                            <td colspan="6" style="padding:0 4px 8px;">
                                <div style="padding:8px;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;">
                                    <div style="font-size:10px;color:#64748b;margin-bottom:4px;">{{ __('dermaClinic::lang.link_photos') }}</div>
                                    @if($dPhotos->count())
                                        <div style="display:flex;flex-wrap:wrap;gap:8px;">
                                            @foreach($dPhotos as $ph)
                                                <label style="font-weight:400;font-size:10px;text-align:center;cursor:pointer;margin:0;">
                                                    <img src="{{ \Illuminate\Support\Facades\Storage::disk('public')->url($ph->file_path) }}" alt="" style="display:block;height:46px;border-radius:4px;border:1px solid #e2e8f0;margin-bottom:2px;">
                                                    <input type="checkbox" class="d-photo-cb" value="{{ $ph->id }}" @checked(in_array((int) $ph->id, $lzLinked, true))>
                                                    <span style="display:block;color:#94a3b8;">{{ optional($ph->taken_at)->format('Y-m-d') }}</span>
                                                </label>
                                            @endforeach
                                        </div>
                                        <div style="margin-top:6px;text-align:right;">
                                            <button type="button" class="btn btn-xs btn-default derma-photos-cancel">Cancel</button>
                                            <button type="button" class="btn btn-xs btn-primary derma-photos-save" data-lesion="{{ $lz->id }}">{{ __('dermaClinic::lang.save') }}</button>
                                        </div>
                                    @else
                                        <div style="font-size:10px;color:#94a3b8;">
                                            {{ __('dermaClinic::lang.no_photos_upload_hint') }}
                                            <a href="{{ route('clinic.patients.photos.index', $patient->id) }}" target="_blank" rel="noopener">{{ __('dermaClinic::lang.open_photo_uploader') }}</a>
                                        </div>
                                    @endif
                                </div>
                            </td>
                        </tr>
                        @endif
                        {{-- Per-lesion chronological photo strip (side-by-side, dated) --}}
                        @php $lzPhotos = collect($lz->photo_ids ?? [])->map(fn($pid) => $dPhotoById->get($pid))->filter()->values(); @endphp
                        @if($lzPhotos->count())
                        <tr>
                            <td colspan="6" style="padding:0 4px 6px;">
                                <div style="display:flex;gap:6px;overflow-x:auto;">
                                    @foreach($lzPhotos as $ph)
                                        <figure style="margin:0;flex:0 0 auto;text-align:center;">
                                            <a href="{{ \Illuminate\Support\Facades\Storage::disk('public')->url($ph->file_path) }}" target="_blank" rel="noopener">
                                                <img src="{{ \Illuminate\Support\Facades\Storage::disk('public')->url($ph->file_path) }}" alt="" style="height:56px;border-radius:4px;border:1px solid #e2e8f0;">
                                            </a>
                                            <figcaption style="font-size:9px;color:#64748b;">{{ optional($ph->taken_at)->format('Y-m-d') }}</figcaption>
                                        </figure>
                                    @endforeach
                                </div>
                            </td>
                        </tr>
                        @endif
                    @empty
                        <tr><td colspan="6" style="padding:6px 4px;color:#94a3b8;">No lesions recorded.</td></tr>
                    @endforelse
                </tbody>
            </table>

            @if($dCanLesions)
                <button type="button" class="btn btn-xs btn-default derma-add-lesion" style="margin-top:6px;"><i class="fas fa-plus"></i> {{ __('dermaClinic::lang.add_lesion') }}</button>
            @endif
        </div>
    </div>

    {{-- Lesion editor (hidden until "Add lesion" or a marker/body click) --}}
    @if($dCanLesions)
    <div class="derma-lesion-editor" style="display:none;margin-top:10px;padding:10px;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;">
        <input type="hidden" class="d-lesion-id">
        <input type="hidden" class="d-pos-x">
        <input type="hidden" class="d-pos-y">
        <div class="row" style="margin:0 -5px;">
            <div class="col-xs-6" style="padding:0 5px;">
                <label style="font-size:11px;">Region</label>
                <select class="form-control input-sm d-region">
                    @foreach(DermaLesion::BODY_REGIONS as $val => $lbl)<option value="{{ $val }}">{{ $lbl }}</option>@endforeach
                </select>
            </div>
            <div class="col-xs-6" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('dermaClinic::lang.morphology') }}</label>
                <select class="form-control input-sm d-morphology">
                    @foreach(DermaLesion::MORPHOLOGIES as $val => $lbl)<option value="{{ $val }}">{{ $lbl }}</option>@endforeach
                </select>
            </div>
        </div>
        <div class="row" style="margin:6px -5px 0;">
            <div class="col-xs-4" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('dermaClinic::lang.size_mm') }}</label>
                <input type="number" step="0.1" min="0" class="form-control input-sm d-size" placeholder="mm">
            </div>
            <div class="col-xs-4" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('dermaClinic::lang.color') }}</label>
                <input type="text" class="form-control input-sm d-color" placeholder="e.g. brown">
            </div>
            <div class="col-xs-4" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('dermaClinic::lang.border') }}</label>
                <select class="form-control input-sm d-border">
                    <option value="">—</option>
                    @foreach(DermaLesion::BORDERS as $val => $lbl)<option value="{{ $val }}">{{ $lbl }}</option>@endforeach
                </select>
            </div>
        </div>
        <div class="row" style="margin:6px -5px 0;">
            <div class="col-xs-4" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('dermaClinic::lang.evolution') }}</label>
                <select class="form-control input-sm d-evolution">
                    <option value="">—</option>
                    @foreach(DermaLesion::EVOLUTIONS as $val => $lbl)<option value="{{ $val }}">{{ $lbl }}</option>@endforeach
                </select>
            </div>
            <div class="col-xs-4" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('dermaClinic::lang.status') }}</label>
                <select class="form-control input-sm d-status">
                    @foreach(DermaLesion::STATUSES as $val => $lbl)<option value="{{ $val }}">{{ $lbl }}</option>@endforeach
                </select>
            </div>
            <div class="col-xs-4" style="padding:0 5px;">
                <label style="font-size:11px;">{{ __('dermaClinic::lang.biopsy') }}</label>
                <select class="form-control input-sm d-biopsy-type">
                    <option value="">Not taken</option>
                    @foreach(DermaLesion::BIOPSY_TYPES as $val => $lbl)<option value="{{ $val }}">{{ $lbl }}</option>@endforeach
                </select>
            </div>
        </div>
        <div style="margin-top:8px;">
            <label style="font-size:11px;display:block;">{{ __('dermaClinic::lang.abcde') }} <small style="color:#94a3b8;">(3+ → suggests biopsy)</small></label>
            <div style="display:flex;flex-wrap:wrap;gap:10px;font-size:11px;">
                @foreach(DermaLesion::ABCDE_KEYS as $k => $lbl)
                    <label style="font-weight:400;"><input type="checkbox" class="d-abcde" data-key="{{ $k }}"> {{ $lbl }}</label>
                @endforeach
            </div>
            <span class="derma-biopsy-hint label label-danger" style="display:none;font-size:10px;margin-top:4px;"><i class="fas fa-exclamation-triangle"></i> {{ __('dermaClinic::lang.suggest_biopsy') }}</span>
        </div>
        <div style="margin-top:6px;">
            <label style="font-size:11px;">{{ __('dermaClinic::lang.dermoscopy_notes') }}</label>
            <input type="text" class="form-control input-sm d-dermoscopy" placeholder="Dermoscopy findings…">
        </div>
        <div style="margin-top:8px;text-align:right;">
            <button type="button" class="btn btn-xs btn-default derma-cancel-lesion">Cancel</button>
            <button type="button" class="btn btn-xs btn-primary derma-save-lesion">{{ __('dermaClinic::lang.save') }}</button>
        </div>
    </div>
    @endif
</div>

{{-- ── Severity scores (PASI / EASI / DLQI / IGA) with a lightweight trend ── --}}
<div class="detail-row" style="display:block;" id="{{ $dUid }}_scores" data-store-url="{{ route('derma.scores.store', $patient->id) }}">
    <span class="dk" style="display:block;margin-bottom:6px;"><i class="fas fa-chart-line fa-fw"></i> {{ __('dermaClinic::lang.severity_scores') }}</span>
    @php $dByType = $dScores->groupBy('score_type'); @endphp
    @if($dScores->count())
        <table style="width:100%;font-size:11px;border-collapse:collapse;">
            <thead><tr style="color:#64748b;"><th style="text-align:left;">Type</th><th style="text-align:left;">Trend</th><th style="text-align:right;">Latest</th></tr></thead>
            <tbody>
            @foreach(DermaScore::SCORE_TYPES as $type => [$lbl, $max])
                @php $series = $dByType->get($type); @endphp
                @if($series && $series->count())
                    <tr style="border-bottom:1px solid #f1f5f9;">
                        <td style="padding:2px 4px;font-weight:600;">{{ $lbl }}</td>
                        <td style="padding:2px 4px;">
                            {{-- inline SVG sparkline (table fallback friendly) --}}
                            @php
                                $pts = [];
                                $n = $series->count();
                                foreach ($series->values() as $i => $s) {
                                    $x = $n > 1 ? ($i / ($n - 1) * 100) : 0;
                                    $y = 20 - min(1, $s->value / max(1, $max)) * 18;
                                    $pts[] = round($x,1).','.round($y,1);
                                }
                            @endphp
                            @if($n > 1)
                                <svg viewBox="0 0 100 20" width="100" height="20" preserveAspectRatio="none"><polyline points="{{ implode(' ', $pts) }}" fill="none" stroke="#0d6efd" stroke-width="1.5"/></svg>
                            @else
                                <span style="color:#94a3b8;">single point</span>
                            @endif
                            <span style="color:#94a3b8;">({{ $series->count() }})</span>
                        </td>
                        <td style="padding:2px 4px;text-align:right;font-weight:600;">{{ rtrim(rtrim(number_format($series->last()->value,2),'0'),'.') }} <small style="color:#94a3b8;">{{ optional($series->last()->recorded_at)->format('Y-m-d') }}</small></td>
                    </tr>
                @endif
            @endforeach
            </tbody>
        </table>
    @else
        <div style="font-size:11px;color:#94a3b8;">No scores recorded.</div>
    @endif

    @if($dCanScores)
        <div style="margin-top:6px;display:flex;gap:6px;align-items:flex-end;flex-wrap:wrap;">
            <div>
                <label style="font-size:10px;display:block;color:#64748b;">Type</label>
                <select class="form-control input-sm derma-score-type" style="width:auto;">
                    @foreach(DermaScore::SCORE_TYPES as $type => [$lbl, $max])<option value="{{ $type }}">{{ $lbl }}</option>@endforeach
                </select>
            </div>
            <div>
                <label style="font-size:10px;display:block;color:#64748b;">{{ __('dermaClinic::lang.value') }}</label>
                <input type="number" step="0.01" min="0" class="form-control input-sm derma-score-value" style="width:90px;" placeholder="0.00">
            </div>
            <button type="button" class="btn btn-xs btn-primary derma-add-score">{{ __('dermaClinic::lang.record_score') }}</button>
        </div>
    @endif
</div>

@if($dCanLesions || $dCanScores)
@once
<script>
(function () {
    var CSRF = '{{ csrf_token() }}';
    function post(url, body) {
        return fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json' },
            body: JSON.stringify(body || {})
        }).then(function (r) { return r.json(); });
    }
    function del(url) {
        return fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, 'Accept': 'application/json', 'X-HTTP-Method-Override': 'DELETE' }, body: JSON.stringify({ _method: 'DELETE' }) }).then(function (r) { return r.json(); });
    }

    document.addEventListener('click', function (e) {
        var root = e.target.closest('[id$="_lesions"]');

        // Body-map click -> open editor prefilled with region + x/y%.
        var svgEl = e.target.closest('svg.derma-bodymap');
        var marker = e.target.closest('.derma-marker');
        if (marker) { return; } // markers just show their <title> tooltip
        if (svgEl && root) {
            var editor = root.querySelector('.derma-lesion-editor');
            if (!editor) return;
            var shape = e.target.closest('[data-region]');
            var rect = svgEl.getBoundingClientRect();
            var isBack = (e.clientX - rect.left) > rect.width / 2;
            var localX = (e.clientX - rect.left) / rect.width * 100;   // 0-100 across whole svg
            var px = isBack ? (localX - 50) * 2 : localX * 2;           // 0-100 within the half
            px = Math.max(0, Math.min(100, Math.round(px)));
            var py = Math.max(0, Math.min(100, Math.round((e.clientY - rect.top) / rect.height * 100)));
            openEditor(editor, {
                region: shape ? shape.getAttribute('data-region') : (isBack ? 'back' : 'other'),
                x: px, y: py
            });
            return;
        }

        if (e.target.closest('.derma-add-lesion')) {
            var r1 = e.target.closest('[id$="_lesions"]');
            openEditor(r1.querySelector('.derma-lesion-editor'), {});
            return;
        }
        if (e.target.closest('.derma-cancel-lesion')) {
            e.target.closest('.derma-lesion-editor').style.display = 'none';
            return;
        }
        if (e.target.closest('.derma-save-lesion')) {
            var r2 = e.target.closest('[id$="_lesions"]');
            var ed = r2.querySelector('.derma-lesion-editor');
            var abcde = {};
            ed.querySelectorAll('.d-abcde').forEach(function (c) { abcde[c.dataset.key] = c.checked; });
            var bt = ed.querySelector('.d-biopsy-type').value;
            post(r2.dataset.storeUrl, {
                id: ed.querySelector('.d-lesion-id').value || null,
                appointment_id: r2.dataset.appointmentId || null,
                body_region: ed.querySelector('.d-region').value,
                position_x: ed.querySelector('.d-pos-x').value || null,
                position_y: ed.querySelector('.d-pos-y').value || null,
                morphology: ed.querySelector('.d-morphology').value,
                size_mm: ed.querySelector('.d-size').value || null,
                color: ed.querySelector('.d-color').value || null,
                border: ed.querySelector('.d-border').value || null,
                evolution: ed.querySelector('.d-evolution').value || null,
                status: ed.querySelector('.d-status').value,
                biopsy_taken: bt ? 1 : 0,
                biopsy_type: bt || null,
                dermoscopy_notes: ed.querySelector('.d-dermoscopy').value || null,
                abcde: abcde
            }).then(function (d) { if (d.success) location.reload(); });
            return;
        }
        var delLes = e.target.closest('.derma-del-lesion');
        if (delLes) {
            if (!confirm('Delete lesion #' + delLes.dataset.lesion + '?')) return;
            var r3 = e.target.closest('[id$="_lesions"]');
            del(r3.dataset.photosBase.replace(/\/lesions$/, '/lesions/') + delLes.dataset.lesion)
                .then(function (d) { if (d.success) location.reload(); });
            return;
        }

        // Link-photos: toggle this lesion's photo picker.
        var linkBtn = e.target.closest('.derma-link-photos');
        if (linkBtn) {
            var picker = document.querySelector('.derma-photo-picker[data-lesion="' + linkBtn.dataset.lesion + '"]');
            if (picker) picker.style.display = (picker.style.display === 'none' || !picker.style.display) ? 'table-row' : 'none';
            return;
        }
        if (e.target.closest('.derma-photos-cancel')) {
            var pk = e.target.closest('.derma-photo-picker');
            if (pk) pk.style.display = 'none';
            return;
        }
        var saveP = e.target.closest('.derma-photos-save');
        if (saveP) {
            var pk2 = e.target.closest('.derma-photo-picker');
            if (!pk2) return;
            var ids = [];
            pk2.querySelectorAll('.d-photo-cb:checked').forEach(function (c) { ids.push(parseInt(c.value, 10)); });
            post(pk2.dataset.photosUrl, { photo_ids: ids }).then(function (d) { if (d.success) location.reload(); });
            return;
        }

        // Scores
        if (e.target.closest('.derma-add-score')) {
            var sr = e.target.closest('[id$="_scores"]');
            var val = sr.querySelector('.derma-score-value').value;
            if (val === '' || val === null) return;
            post(sr.dataset.storeUrl, {
                score_type: sr.querySelector('.derma-score-type').value,
                value: val,
                appointment_id: {{ $dApptId ? $dApptId : 'null' }}
            }).then(function (d) { if (d.success) location.reload(); });
            return;
        }
    });

    // Live ABCDE hint (3+ flags).
    document.addEventListener('change', function (e) {
        if (e.target.classList && e.target.classList.contains('d-abcde')) {
            var ed = e.target.closest('.derma-lesion-editor');
            var n = ed.querySelectorAll('.d-abcde:checked').length;
            var hint = ed.querySelector('.derma-biopsy-hint');
            if (hint) hint.style.display = n >= 3 ? 'inline-block' : 'none';
        }
    });

    function openEditor(ed, opts) {
        if (!ed) return;
        ed.style.display = 'block';
        ed.querySelector('.d-lesion-id').value = opts.id || '';
        ed.querySelector('.d-pos-x').value = (opts.x != null ? opts.x : '');
        ed.querySelector('.d-pos-y').value = (opts.y != null ? opts.y : '');
        if (opts.region) ed.querySelector('.d-region').value = opts.region;
        ed.querySelectorAll('.d-abcde').forEach(function (c) { c.checked = false; });
        var hint = ed.querySelector('.derma-biopsy-hint');
        if (hint) hint.style.display = 'none';
        ed.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }
})();
</script>
@endonce
@endif
