@if(empty($inspections))
    <div class="p-12 text-center text-gray-500">
        <p>점검 가능한 설비가 없습니다.</p>
        <p class="text-sm mt-2">설비 등록대장에서 해당 주기의 점검항목을 추가해주세요.</p>
    </div>
@else
    @php
        $cycle = $cycle ?? 'daily';
        $isDaily = $cycle === 'daily';
        // 첫 번째 설비의 labels 사용
        $labels = $inspections[0]['labels'] ?? [];
        $holidayDates = $holidayDates ?? [];
    @endphp

    <div class="overflow-x-auto">
        <table class="min-w-full border-collapse text-xs">
            <thead>
                <tr class="bg-gray-100">
                    <th class="border border-gray-300 px-2 py-1 text-center whitespace-nowrap sticky left-0 bg-gray-100 z-10" style="min-width: 80px;">설비</th>
                    <th class="border border-gray-300 px-2 py-1 text-center whitespace-nowrap sticky bg-gray-100 z-10" style="left: 80px; min-width: 80px;">점검항목</th>
                    @foreach($labels as $colIndex => $label)
                        @php
                            $colDate = \App\Enums\InspectionCycle::resolveCheckDate($cycle, $period, $colIndex);
                            $isOff = $isDaily && \App\Enums\InspectionCycle::isNonWorkingDay($colDate, $holidayDates);
                        @endphp
                        <th class="border border-gray-300 px-1 py-1 text-center {{ $isOff ? 'bg-red-50 text-red-600' : '' }}" style="min-width: 32px;">
                            {{ $label }}
                        </th>
                    @endforeach
                    <th class="border border-gray-300 px-2 py-1 text-center whitespace-nowrap" style="min-width: 60px;">판정</th>
                </tr>
            </thead>
            <tbody>
                @foreach($inspections as $item)
                    @php
                        $equipment = $item['equipment'];
                        $templates = $item['templates'];
                        $inspection = $item['inspection'];
                        $details = $item['details'];
                        $canInspect = $item['can_inspect'] ?? true;
                        $rowCount = $templates->count();
                    @endphp

                    @php
                    // 자동 판정: 비근무일(주말+휴일) 제외, 오늘까지 도래한 날짜만 검사
                    $today = now()->format('Y-m-d');
                    $totalChecks = 0;
                    $passedChecks = 0;
                    foreach ($templates as $tmpl) {
                        foreach ($labels as $ci => $lbl) {
                            $cd = \App\Enums\InspectionCycle::resolveCheckDate($cycle, $period, $ci);
                            if ($isDaily && \App\Enums\InspectionCycle::isNonWorkingDay($cd, $holidayDates)) {
                                continue;
                            }
                            if ($cd > $today) {
                                continue;
                            }
                            $totalChecks++;
                            $k = $tmpl->id . '_' . $cd;
                            $d = isset($details[$k]) ? $details[$k]->first() : null;
                            if ($d && in_array($d->result, ['good', 'repaired'])) {
                                $passedChecks++;
                            }
                        }
                    }
                    $autoJudgment = $totalChecks > 0 ? ($passedChecks === $totalChecks ? 'pass' : 'fail') : null;
                @endphp

                    @foreach($templates as $idx => $tmpl)
                        <tr class="{{ $idx === 0 ? 'border-t-2 border-gray-400' : '' }}">
                            @if($idx === 0)
                                <td class="border border-gray-300 px-2 py-1 text-center font-medium whitespace-nowrap sticky left-0 bg-white z-10"
                                    rowspan="{{ $rowCount }}" style="min-width: 80px;">
                                    <div class="text-xs text-blue-600">{{ $equipment->equipment_code }}</div>
                                    <div class="text-xs">{{ Str::limit($equipment->name, 8) }}</div>
                                    @if($canInspect)
                                        <button type="button" onclick="resetEquipment({{ $equipment->id }}, '{{ addslashes($equipment->equipment_code . ' ' . $equipment->name) }}')"
                                                class="mt-1 text-gray-400 hover:text-red-500 transition" title="점검 초기화">
                                            <svg class="w-3.5 h-3.5 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                                        </button>
                                    @endif
                                </td>
                            @endif
                            <td class="border border-gray-300 px-2 py-1 whitespace-nowrap sticky bg-white z-10" style="left: 80px; min-width: 80px;">
                                <span class="text-gray-600">{{ $tmpl->check_point }}</span>
                            </td>

                            @foreach($labels as $colIndex => $label)
                                @php
                                    $checkDate = \App\Enums\InspectionCycle::resolveCheckDate($cycle, $period, $colIndex);
                                    $key = $tmpl->id . '_' . $checkDate;
                                    $detail = isset($details[$key]) ? $details[$key]->first() : null;
                                    $symbol = $detail ? $detail->result_symbol : '';
                                    $color = $detail ? $detail->result_color : 'text-gray-400';
                                    $isOff = $isDaily && \App\Enums\InspectionCycle::isNonWorkingDay($checkDate, $holidayDates);
                                @endphp
                                @if($canInspect && !$isOff)
                                    <td class="border border-gray-300 text-center cursor-pointer select-none"
                                        style="min-width: 32px; padding: 2px;"
                                        onclick="toggleCell({{ $equipment->id }}, {{ $tmpl->id }}, '{{ $checkDate }}', this)">
                                        <span class="inspection-cell text-lg font-bold {{ $color }}">{{ $symbol }}</span>
                                    </td>
                                @else
                                    <td class="border border-gray-300 text-center select-none {{ $isOff ? 'bg-red-50' : 'cursor-not-allowed opacity-50' }}"
                                        style="min-width: 32px; padding: 2px;">
                                        <span class="inspection-cell text-lg font-bold {{ $color }}">{{ $symbol }}</span>
                                    </td>
                                @endif
                            @endforeach

                            @if($idx === 0)
                                <td class="border border-gray-300 px-2 py-1 text-center whitespace-nowrap"
                                    rowspan="{{ $rowCount }}">
                                    @if($autoJudgment === 'pass')
                                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">합격</span>
                                    @elseif($autoJudgment === 'fail')
                                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">불합격</span>
                                    @else
                                        <span class="text-gray-400">-</span>
                                    @endif
                                </td>
                            @endif
                        </tr>
                    @endforeach
                @endforeach
            </tbody>
        </table>
    </div>

    <!-- 범례 -->
    <div class="p-4 border-t flex flex-wrap gap-4 text-sm text-gray-600">
        <span><span class="text-green-600 font-bold text-lg">○</span> 양호</span>
        <span><span class="text-red-600 font-bold text-lg">X</span> 이상</span>
        <span><span class="text-yellow-600 font-bold text-lg">△</span> 수리완료</span>
        <span class="text-gray-400">셀 클릭: 빈칸 → ○ → X → △ → 빈칸</span>
        <span class="text-red-400">■ 휴일/주말 (점검 불가)</span>
    </div>
@endif
