@extends('layouts.app')
@section('title', __('Dental chart').' — '.$patient->full_name)

@section('content')
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-2">
    <h1 class="h4 fw-bold mb-0">🦷 {{ $patient->full_name }}</h1>
    <span class="mb-muted small">FDI 11–48</span>
</div>
@include('patients._tabs')

@if($patient->allergies)
    <div class="alert alert-warning py-2">⚠ {{ __('Allergies') }}: {{ $patient->allergies }}</div>
@endif

<div class="row g-3">
    {{-- ===== Chart ===== --}}
    <div class="col-lg-8">
        <div class="mb-card p-3 p-md-4">
            <div class="chart-legend mb-3">
                @foreach($conditions as $key => $c)
                    <span><i style="background: {{ $c['color'] }}"></i>{{ __($c['label']) }}</span>
                @endforeach
                <span><i style="border:2px dashed var(--mb-amber); background:transparent"></i>{{ __('Planned') }}</span>
            </div>

            <p class="text-center mb-muted small mb-1">{{ __('Upper arch') }}</p>
            <div class="chart-arch upper" id="upperArch"></div>
            <hr style="border-color: var(--mb-line)">
            <div class="chart-arch lower" id="lowerArch"></div>
            <p class="text-center mb-muted small mt-1 mb-0">{{ __('Lower arch') }}</p>

            <p class="mb-muted small text-center mt-3 mb-0">
                {{ __("Tap any tooth to view its history and record findings. The patient's right side appears on the screen's left, as in clinical charts.") }}
            </p>
        </div>
    </div>

    {{-- ===== Tooth panel ===== --}}
    <div class="col-lg-4">
        <div class="mb-card p-4 sticky-lg-top" style="top: 70px" id="toothPanel">
            <div id="panelEmpty" class="text-center mb-muted py-5">
                <div style="font-size:2.5rem">🦷</div>
                {{ __('Select a tooth to begin.') }}
            </div>

            <div id="panelBody" class="d-none">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h2 class="h5 fw-bold mb-0">{{ __('Tooth') }} <span id="panelTooth"></span></h2>
                    <span id="panelCurrent" class="status-chip"></span>
                </div>

                @can('chart.manage')
                <form id="recordForm" class="mb-3">
                    <label class="form-label small fw-semibold">{{ __('Surfaces') }}</label>
                    <div class="surface-grid mb-3" id="surfaceGrid">
                        {{-- cross: B / M O D / L --}}
                        <span></span><button type="button" class="surface-btn" data-s="B">B</button><span></span>
                        <button type="button" class="surface-btn" data-s="M">M</button>
                        <button type="button" class="surface-btn" data-s="O">O</button>
                        <button type="button" class="surface-btn" data-s="D">D</button>
                        <span></span><button type="button" class="surface-btn" data-s="L">L</button><span></span>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-semibold">{{ __('Condition') }}</label>
                        <select class="form-select" id="recCondition" required>
                            @foreach($conditions as $key => $c)
                                <option value="{{ $key }}">{{ __($c['label']) }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-semibold">{{ __('State') }}</label>
                        <div class="btn-group w-100" role="group">
                            @foreach(['existing' => __('Existing'), 'planned' => __('Planned'), 'completed' => __('Completed')] as $val => $label)
                                <input type="radio" class="btn-check" name="recState" id="st-{{ $val }}" value="{{ $val }}" @checked($val === 'existing')>
                                <label class="btn btn-sm mb-btn-ghost" for="st-{{ $val }}">{{ $label }}</label>
                            @endforeach
                        </div>
                    </div>

                    <div class="mb-3">
                        <input class="form-control form-control-sm" id="recNote" maxlength="500" placeholder="{{ __('Note (optional)') }}">
                    </div>

                    <button class="btn mb-btn-primary w-100" id="recSubmit">{{ __('Record finding') }}</button>
                </form>
                <hr style="border-color: var(--mb-line)">
                @endcan

                <h3 class="h6 fw-semibold">{{ __('Tooth history') }}</h3>
                <div class="tl" id="panelHistory"></div>
            </div>
        </div>
    </div>
</div>

@push('page-scripts')
<script>
const CHART_URL = @json(route('tenant.patients.chart.data', $patient));
const STORE_URL = @json(route('tenant.patients.chart.store', $patient));
const CSRF = @json(csrf_token());
const UPPER = @json($upperArch);
const LOWER = @json($lowerArch);
const CAN_MANAGE = @json(auth()->user()->can('chart.manage'));
const I18N = {
    healthy: @json(__('Healthy')),
    deleted: @json(__('Record deleted.')),
    confirmDelete: @json(__('Delete this record?')),
    fromPlan: @json(__('from plan')),
    wholeTooth: @json(__('Whole tooth')),
};

let chart = @json($chart);
let selected = null;

function buildArch(el, teeth) {
    el.innerHTML = '';
    teeth.forEach((t, i) => {
        if (i === teeth.length / 2) {
            const mid = document.createElement('div');
            mid.className = 'chart-midline';
            el.appendChild(mid);
        }
        const d = chart[t] ?? { tooth: t, records: [] };
        const btn = document.createElement('button');
        btn.type = 'button';
        btn.className = 'chart-tooth';
        btn.dataset.tooth = t;
        btn.setAttribute('aria-label', 'Tooth ' + t);
        if (d.condition === 'missing' || d.condition === 'extraction') btn.classList.add('missing');
        if (d.has_planned) btn.classList.add('has-planned');
        if (selected === t) btn.classList.add('selected');
        btn.innerHTML = (d.color ? `<span class="dot" style="background:${d.color}"></span>` : '') + t;
        btn.onclick = () => selectTooth(t);
        el.appendChild(btn);
    });
}

function render() {
    buildArch(document.getElementById('upperArch'), UPPER);
    buildArch(document.getElementById('lowerArch'), LOWER);
}

function selectTooth(t) {
    selected = t;
    render();
    document.getElementById('panelEmpty').classList.add('d-none');
    document.getElementById('panelBody').classList.remove('d-none');
    document.getElementById('panelTooth').textContent = t;

    const d = chart[t] ?? { records: [] };
    const cur = document.getElementById('panelCurrent');
    if (d.condition) {
        cur.textContent = conditionLabel(d.condition);
        cur.style.background = d.color;
        cur.classList.remove('d-none');
    } else {
        cur.textContent = I18N.healthy;
        cur.style.background = '#22C55E';
    }

    const hist = document.getElementById('panelHistory');
    hist.innerHTML = d.records.length ? '' : `<p class="mb-muted small">—</p>`;
    d.records.forEach(r => {
        const item = document.createElement('div');
        item.className = 'tl-item';
        item.innerHTML = `
            <div class="d-flex justify-content-between gap-2">
                <strong style="color:${r.color}">${r.condition_label}</strong>
                <span class="mb-muted small">${r.recorded_at_human}</span>
            </div>
            <div class="small">
                <span class="badge text-bg-light">${r.state_label}</span>
                ${r.surfaces?.length ? `<span class="mb-muted">· ${r.surfaces.join(',')}</span>` : `<span class="mb-muted">· ${I18N.wholeTooth}</span>`}
                ${r.from_plan ? `<span class="mb-muted">· 📋 ${I18N.fromPlan}</span>` : ''}
            </div>
            ${r.note ? `<div class="mb-muted small">${escapeHtml(r.note)}</div>` : ''}
            ${r.recorded_by ? `<div class="mb-muted small">${escapeHtml(r.recorded_by)}</div>` : ''}`;
        hist.appendChild(item);
    });

    if (CAN_MANAGE) {
        document.querySelectorAll('.surface-btn').forEach(b => b.classList.remove('on'));
    }
}

function conditionLabel(key) {
    const map = @json(collect($conditions)->map(fn ($c) => __($c['label'])));
    return map[key] ?? key;
}
function escapeHtml(s) {
    return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}

// Surface toggles
document.querySelectorAll('.surface-btn').forEach(b => {
    b.addEventListener('click', () => b.classList.toggle('on'));
});

// Record a finding
document.getElementById('recordForm')?.addEventListener('submit', async (e) => {
    e.preventDefault();
    if (!selected) return;
    const btn = document.getElementById('recSubmit');
    btn.disabled = true;
    const surfaces = [...document.querySelectorAll('.surface-btn.on')].map(b => b.dataset.s);
    const res = await fetch(STORE_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF, Accept: 'application/json' },
        body: JSON.stringify({
            tooth: selected,
            condition: document.getElementById('recCondition').value,
            state: document.querySelector('input[name="recState"]:checked').value,
            surfaces,
            note: document.getElementById('recNote').value || null,
        }),
    });
    btn.disabled = false;
    if (res.ok) {
        document.getElementById('recNote').value = '';
        const { data } = await fetch(CHART_URL, { headers: { Accept: 'application/json' } }).then(r => r.json());
        chart = data;
        selectTooth(selected);
    } else {
        const body = await res.json().catch(() => null);
        alert(body?.message ?? 'Error');
    }
});

render();
</script>
@endpush
@endsection
