{{-- Interactive dental tooth chart. Extracted so both the patient show screen
     and the appointment screen can render it. Receives $patient (ClcPatient).
     Storage stays universal 1-32; the chart optionally shows FDI/Palmer labels
     from the module config. The editor now also captures periodontal/endodontic
     findings additively (probing depth, BOP, mobility, endo status, implant). --}}
@php
    use Modules\DentalClinic\Entities\DentalToothFinding;
    $findings = DentalToothFinding::where('clc_patient_id', $patient->id)->get()->keyBy('tooth_number');
    $palette  = DentalToothFinding::CONDITIONS;
    $canEdit  = auth()->user()->can('clinic.manage_pets');
    $chartId  = 'clcTooth' . $patient->id;
    $notation = config('dentalclinic.tooth_numbering_system', config('dentalClinic.tooth_numbering_system', 'universal'));
    $notation = in_array($notation, DentalToothFinding::NOTATION_SYSTEMS, true) ? $notation : 'universal';
    $endoStatuses = DentalToothFinding::ENDO_STATUSES;
    $dark = DentalToothFinding::DARK_CONDITIONS;
@endphp
<div class="detail-row" style="display:block;">
    <span class="dk" style="display:block;margin-bottom:6px;"><i class="fas fa-tooth fa-fw"></i> {{ __('dentalClinic::lang.tooth_chart') }}
        <small class="text-muted">({{ strtoupper($notation) }})</small></span>
    <div id="{{ $chartId }}" class="clc-tooth-chart" data-url="{{ route('dental.toothchart.update', $patient->id) }}"
         style="display:flex;flex-direction:column;gap:4px;">
        @foreach([['Upper', range(1,16)], ['Lower', range(17,32)]] as [$arch, $teeth])
            <div style="display:flex;flex-wrap:wrap;gap:2px;">
                @foreach($teeth as $n)
                    @php
                        $f = $findings->get($n);
                        $cond = $f->condition ?? 'healthy';
                        $colour = $palette[$cond][1] ?? '#e9ecef';
                        $label = $palette[$cond][0] ?? 'Healthy';
                        $isDark = in_array($cond, $dark, true);
                        $shown = DentalToothFinding::convertNotation($n, $notation);
                    @endphp
                    <button type="button" class="clc-tooth" data-tooth="{{ $n }}" data-cond="{{ $cond }}"
                            title="Tooth {{ $shown }} — {{ $label }}{{ $f && $f->surfaces ? ' ('.$f->surfaces.')' : '' }}"
                            {{ $canEdit ? '' : 'disabled' }}
                            style="width:24px;height:28px;display:inline-flex;align-items:center;justify-content:center;
                                   font-size:9px;border:1px solid #ccc;border-radius:3px;padding:0;cursor:{{ $canEdit ? 'pointer' : 'default' }};
                                   background:{{ $colour }};color:{{ $isDark ? '#fff' : '#333' }};">{{ $shown }}</button>
                @endforeach
            </div>
        @endforeach
    </div>
    <div style="margin-top:6px;display:flex;flex-wrap:wrap;gap:6px;font-size:9px;">
        @foreach($palette as $key => [$lbl, $colour])
            @if(!in_array($key, ['caries','crown','extraction_needed'], true)) {{-- hide legacy aliases from legend --}}
            <span style="display:inline-flex;align-items:center;gap:3px;">
                <span style="width:10px;height:10px;border-radius:2px;border:1px solid #ccc;background:{{ $colour }};display:inline-block;"></span>{{ $lbl }}
            </span>
            @endif
        @endforeach
    </div>
    @if($canEdit)
        <div id="{{ $chartId }}_editor" style="display:none;margin-top:8px;padding:8px;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;">
            <div style="font-size:11px;font-weight:700;margin-bottom:6px;">Tooth <span class="clc-tooth-no"></span> — set condition</div>
            <div style="display:flex;flex-wrap:wrap;gap:4px;">
                @foreach($palette as $key => [$lbl, $colour])
                    @if(!in_array($key, ['caries','crown','extraction_needed'], true))
                    <button type="button" class="clc-cond-btn" data-cond="{{ $key }}"
                            style="font-size:10px;padding:3px 8px;border:1px solid #ccc;border-radius:4px;cursor:pointer;
                                   background:{{ $colour }};color:{{ in_array($key,$dark,true) ? '#fff' : '#333' }};">{{ $lbl }}</button>
                    @endif
                @endforeach
            </div>
            {{-- Periodontal / endodontic / implant findings (additive; optional) --}}
            <div style="display:flex;flex-wrap:wrap;gap:6px;margin-top:8px;">
                <label style="font-size:10px;margin:0;">{{ __('dentalClinic::lang.probing_depth') }}
                    <input type="number" min="0" max="20" class="form-control input-sm clc-perio" data-field="probing_depth_mm" style="width:70px;display:inline-block;"></label>
                <label style="font-size:10px;margin:0;">{{ __('dentalClinic::lang.mobility') }}
                    <input type="number" min="0" max="3" class="form-control input-sm clc-perio" data-field="mobility" style="width:60px;display:inline-block;"></label>
                <label style="font-size:10px;margin:0;"><input type="checkbox" class="clc-perio" data-field="bleeding_on_probing"> {{ __('dentalClinic::lang.bleeding_on_probing') }}</label>
                <label style="font-size:10px;margin:0;">{{ __('dentalClinic::lang.endo_status') }}
                    <select class="form-control input-sm clc-perio" data-field="endo_status" style="width:110px;display:inline-block;">
                        @foreach($endoStatuses as $es)<option value="{{ $es }}">{{ ucfirst($es) }}</option>@endforeach
                    </select></label>
                <input class="form-control input-sm clc-perio" data-field="implant_note" placeholder="{{ __('dentalClinic::lang.implant_note') }}" style="flex:1;min-width:120px;">
            </div>
            <div style="margin-top:8px;">
                <button type="button" class="btn btn-xs btn-success clc-perio-save">Save findings</button>
                <span class="clc-perio-hint text-muted" style="font-size:9px;margin-left:6px;">Pick a condition button, or edit perio/endo then Save.</span>
            </div>
        </div>
    @endif
</div>
@if($canEdit)
@once
<script>
(function () {
    const DARK = @json(array_values(DentalToothFinding::DARK_CONDITIONS));
    const NOTATION = '{{ $notation }}';

    function csrf() { return document.querySelector('meta[name="csrf-token"]') ? document.querySelector('meta[name="csrf-token"]').getAttribute('content') : '{{ csrf_token() }}'; }

    function post(chart, payload, onOk) {
        fetch(chart.dataset.url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf(), 'Accept': 'application/json' },
            body: JSON.stringify(payload)
        }).then(r => r.json()).then(d => { if (d.success && onOk) onOk(d); }).catch(() => {});
    }

    document.addEventListener('click', function (e) {
        const tooth = e.target.closest('.clc-tooth');
        if (tooth) {
            const chart = tooth.closest('.clc-tooth-chart');
            const editor = document.getElementById(chart.id + '_editor');
            if (!editor) return;
            editor.style.display = 'block';
            editor.dataset.tooth = tooth.dataset.tooth;
            editor.dataset.chart = chart.id;
            editor.querySelector('.clc-tooth-no').textContent = tooth.dataset.tooth;
            editor.dataset.cond = tooth.dataset.cond || 'healthy';
            chart.querySelectorAll('.clc-tooth').forEach(t => t.style.outline = '');
            tooth.style.outline = '2px solid #0d6efd';
            return;
        }

        const cond = e.target.closest('.clc-cond-btn');
        if (cond) {
            const editor = cond.closest('[id$="_editor"]');
            const chart = document.getElementById(editor.dataset.chart);
            const toothNo = editor.dataset.tooth;
            const condition = cond.dataset.cond;
            editor.dataset.cond = condition;
            post(chart, { tooth_number: toothNo, condition: condition, notation_system: NOTATION }, function (d) {
                const btn = chart.querySelector('.clc-tooth[data-tooth="' + toothNo + '"]');
                btn.style.background = d.colour;
                btn.style.color = DARK.includes(d.condition) ? '#fff' : '#333';
                btn.dataset.cond = d.condition;
                editor.style.display = 'none';
                chart.querySelectorAll('.clc-tooth').forEach(t => t.style.outline = '');
            });
            return;
        }

        const save = e.target.closest('.clc-perio-save');
        if (save) {
            const editor = save.closest('[id$="_editor"]');
            const chart = document.getElementById(editor.dataset.chart);
            const toothNo = editor.dataset.tooth;
            const payload = { tooth_number: toothNo, condition: editor.dataset.cond || 'healthy', notation_system: NOTATION };
            editor.querySelectorAll('.clc-perio').forEach(function (el) {
                const field = el.dataset.field;
                if (el.type === 'checkbox') { payload[field] = el.checked ? 1 : 0; }
                else if (el.value !== '') { payload[field] = el.value; }
            });
            post(chart, payload, function (d) {
                const btn = chart.querySelector('.clc-tooth[data-tooth="' + toothNo + '"]');
                btn.style.background = d.colour;
                btn.style.color = DARK.includes(d.condition) ? '#fff' : '#333';
                btn.dataset.cond = d.condition;
                editor.style.display = 'none';
                chart.querySelectorAll('.clc-tooth').forEach(t => t.style.outline = '');
            });
        }
    });
})();
</script>
@endonce
@endif
