@extends('layouts.teknisi')

@section('title', 'Estimasi Pengerjaan - Teknisi')

@section('content')
<div class="space-y-6">
    <!-- Notifikasi -->
    @if (session('success'))
        <div x-data="{ show: true }" x-show="show" x-transition:enter="transition transform ease-out duration-500"
            x-transition:enter-start="-translate-y-10 opacity-0" x-transition:enter-end="translate-y-0 opacity-100"
            x-transition:leave="transition transform ease-in duration-500"
            x-transition:leave-start="translate-y-0 opacity-100" x-transition:leave-end="-translate-y-10 opacity-0"
            x-init="setTimeout(() => show = false, 4000)"
            class="fixed top-6 left-1/2 transform -translate-x-1/2 z-50 w-[90%] sm:w-[500px] bg-gradient-to-r from-green-500 to-emerald-600 text-white shadow-2xl rounded-xl px-6 py-4 flex items-center justify-between space-x-3">
            <div class="flex items-center space-x-3">
                <div class="flex items-center justify-center w-8 h-8 bg-white/20 rounded-full">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-white" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.707a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 10-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                    </svg>
                </div>
                <div class="flex-1 font-semibold text-sm sm:text-base">
                    {{ session('success') }}
                </div>
            </div>
            <button @click="show = false" class="hover:bg-white/20 rounded-full p-1 transition duration-200">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>
        </div>
    @endif

    @if (session('error'))
        <div x-data="{ show: true }" x-show="show" x-transition:enter="transition transform ease-out duration-500"
            x-transition:enter-start="-translate-y-10 opacity-0" x-transition:enter-end="translate-y-0 opacity-100"
            x-transition:leave="transition transform ease-in duration-500"
            x-transition:leave-start="translate-y-0 opacity-100" x-transition:leave-end="-translate-y-10 opacity-0"
            x-init="setTimeout(() => show = false, 4000)"
            class="fixed top-6 left-1/2 transform -translate-x-1/2 z-50 w-[90%] sm:w-[500px] bg-gradient-to-r from-red-500 to-pink-600 text-white shadow-2xl rounded-xl px-6 py-4 flex items-center justify-between space-x-3">
            <div class="flex items-center space-x-3">
                <div class="flex items-center justify-center w-8 h-8 bg-white/20 rounded-full">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-white" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                    </svg>
                </div>
                <div class="flex-1 font-semibold text-sm sm:text-base">
                    {{ session('error') }}
                </div>
            </div>
            <button @click="show = false" class="hover:bg-white/20 rounded-full p-1 transition duration-200">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
            </button>
        </div>
    @endif

    <!-- Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800 dark:text-white mb-2">Estimasi Pengerjaan</h1>
        <p class="text-gray-600 dark:text-gray-400">Berikan estimasi hari kerja dan biaya jasa untuk penawaran customer</p>
    </div>

    <!-- Quick Stats -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
            <div class="flex items-center">
                <div class="p-2 bg-blue-100 dark:bg-blue-900/40 rounded-lg">
                    <i class="fas fa-clipboard-list text-blue-600 dark:text-blue-400"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Total Penawaran</p>
                    <p class="text-lg font-semibold text-gray-900 dark:text-white">{{ $totalInquiries ?? $inquiries->total() }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
            <div class="flex items-center">
                <div class="p-2 bg-yellow-100 dark:bg-yellow-900/40 rounded-lg">
                    <i class="fas fa-eye-slash text-yellow-600 dark:text-yellow-400"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Belum Dibaca</p>
                    <p class="unread-count text-lg font-semibold text-gray-900 dark:text-white">{{ $unreadCount ?? 0 }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
            <div class="flex items-center">
                <div class="p-2 bg-green-100 dark:bg-green-900/40 rounded-lg">
                    <i class="fas fa-check-circle text-green-600 dark:text-green-400"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Sudah Dibaca</p>
                    <p class="text-lg font-semibold text-gray-900 dark:text-white">{{ $readCount ?? 0 }}</p>
                </div>
            </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
            <div class="flex items-center">
                <div class="p-2 bg-purple-100 dark:bg-purple-900/40 rounded-lg">
                    <i class="fas fa-clock text-purple-600 dark:text-purple-400"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm font-medium text-gray-500 dark:text-gray-400">Menunggu Estimasi</p>
                    <p class="text-lg font-semibold text-gray-900 dark:text-white">{{ $inquiries->count() }}</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Table Container -->
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden transition-colors duration-300">
        @if($inquiries->count() > 0)
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 dark:bg-gray-700/50 border-b border-gray-200 dark:border-gray-600">
                    <tr>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Produk & Customer</th>
                        <th class="px-6 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Range Harga</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Catatan Supervisor</th>
                        <th class="px-6 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Status</th>
                        <th class="px-6 py-3.5 text-center text-xs font-semibold uppercase tracking-wider text-gray-600 dark:text-gray-300">Aksi</th>
                    </tr>
                </thead>
                <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                    @foreach($inquiries as $inquiry)
                    <tr data-inquiry-id="{{ $inquiry->id }}" class="hover:bg-blue-50/50 dark:hover:bg-gray-700/80 transition-colors duration-200 {{ !$inquiry->is_read ? 'bg-yellow-50/30 dark:bg-yellow-900/10' : '' }}">
                        <td class="px-6 py-4">
                            <div class="flex items-start">
                                <div class="flex-1">
                                    <div class="flex items-center gap-2 mb-1">
                                        <div class="text-sm font-medium text-gray-900 dark:text-white">
                                            {{ $inquiry->product->product_title ?? 'N/A' }}
                                        </div>
                                        @if(!$inquiry->is_read)
                                            <span class="inline-flex items-center px-2 py-0.5 text-[10px] font-semibold rounded-full bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-200">
                                                <i class="fas fa-circle text-[6px] mr-1"></i>Baru
                                            </span>
                                        @endif
                                    </div>
                                    @php
                                        $rawMsg = $inquiry->message ?? '';
                                        $first = strtok($rawMsg, "\r\n");
                                        $type = null;
                                        if ($first && substr($first,0,14) === '[REQUEST_TYPE]') {
                                            $type = trim(substr($first,14));
                                        }
                                        $badgeText = $type === 'custom_addon' ? 'Custom Add-on' : ($type === 'custom_new' ? 'Custom Baru' : ($type ? 'Katalog' : null));
                                        $badgeCls = $type === 'custom_addon' ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/40 dark:text-yellow-200' : ($type === 'custom_new' ? 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-200' : 'bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-200');
                                    @endphp
                                    <div class="flex items-center gap-2 mt-1">
                                        <div class="text-xs text-gray-500 dark:text-gray-400">
                                            <i class="fas fa-user mr-1"></i>{{ $inquiry->name }}
                                        </div>
                                        @if($badgeText)
                                            <span class="inline-flex items-center px-2 py-0.5 text-[10px] font-semibold rounded-full {{ $badgeCls }}">
                                                {{ $badgeText }}
                                            </span>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 text-center">
                            <div class="text-sm font-semibold text-gray-900 dark:text-white">
                                Rp {{ number_format($inquiry->min_price ?? 0, 0, ',', '.') }}
                            </div>
                            <div class="text-xs text-gray-500 dark:text-gray-400 my-1">sampai</div>
                            <div class="text-sm font-semibold text-gray-900 dark:text-white">
                                Rp {{ number_format($inquiry->max_price ?? 0, 0, ',', '.') }}
                            </div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900 dark:text-white max-w-xs">
                                {{ Str::limit($inquiry->supervisor_note ?? '-', 80) }}
                            </div>
                        </td>
                        <td class="px-6 py-4 text-center">
                            @if($inquiry->is_read)
                                <span class="status-badge inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300">
                                    <i class="fas fa-check-circle text-xs"></i>
                                    <span>Dibaca</span>
                                </span>
                            @else
                                <span class="status-badge inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300">
                                    <i class="fas fa-eye-slash text-xs"></i>
                                    <span>Belum Dibaca</span>
                                </span>
                            @endif
                        </td>
                        <td class="px-6 py-4 text-center">
                            <div class="flex items-center justify-center gap-2">
                                @if(!$inquiry->is_read)
                                    <button type="button" 
                                        data-id="{{ $inquiry->id }}" 
                                        onclick="markAsReadFromBtn(this)"
                                        class="inline-flex items-center justify-center w-9 h-9 text-orange-600 dark:text-orange-400 hover:text-orange-700 dark:hover:text-orange-300 hover:bg-orange-50 dark:hover:bg-orange-900/20 rounded transition-colors duration-200"
                                        title="Tandai Dibaca">
                                        <i class="fas fa-check text-base"></i>
                                    </button>
                                @endif
                                <button type="button" 
                                    data-estimate-btn="1" 
                                    data-id="{{ $inquiry->id }}" 
                                    data-title='@json($inquiry->product->product_title ?? '')' 
                                    data-message='@json($inquiry->message ?? '')' 
                                    data-base='{{ (float)($inquiry->product->product_prices ?? 0) }}' 
                                    data-cname='{{ $inquiry->name }}' 
                                    data-cemail='{{ $inquiry->email }}' 
                                    data-cphone='{{ $inquiry->phone }}'
                                    onclick='openEstimateModal({{ $inquiry->id }}, @json($inquiry->product->product_title ?? ''), @json($inquiry->message ?? ''))' 
                                    class="inline-flex items-center justify-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors duration-200 text-sm font-medium">
                                    <i class="fas fa-calculator mr-2"></i> Buat Estimasi
                                </button>
                            </div>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if ($inquiries->hasPages())
            <div class="px-6 py-4 border-t border-gray-200 dark:border-gray-700">
                {{ $inquiries->onEachSide(4)->links() }}
            </div>
        @endif
        @else
        <div class="text-center py-12">
            <div class="mx-auto w-24 h-24 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mb-4">
                <i class="fas fa-inbox text-4xl text-gray-400 dark:text-gray-500"></i>
            </div>
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-2">Tidak Ada Penawaran</h3>
            <p class="text-gray-600 dark:text-gray-400">Tidak ada penawaran yang perlu estimasi saat ini</p>
        </div>
        @endif
    </div>
</div>

<!-- Estimate Modal -->
<div id="estimateModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden items-center justify-center" style="display: none;">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-4xl w-full max-h-[95vh] overflow-hidden flex flex-col">
            <!-- Modal Header -->
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-gray-800 dark:to-gray-700">
                <div class="flex justify-between items-center">
                    <div>
                        <h3 class="text-xl font-bold text-gray-900 dark:text-white">Estimasi Pengerjaan</h3>
                        <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">Lengkapi informasi estimasi untuk penawaran ini</p>
                    </div>
                    <button onclick="closeEstimateModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
            </div>

            <!-- Modal Body (Scrollable) -->
            <div class="flex-1 overflow-y-auto p-6">
                <form id="estimateForm" method="POST">
                    @csrf
                    <input type="hidden" name="inquiry_id" id="inquiry_id">

                    <div class="space-y-6">
                        <!-- Product & Customer Info -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-gray-800 dark:to-gray-700 rounded-lg p-4 border border-blue-200 dark:border-gray-600">
                                <div class="flex items-center mb-3">
                                    <div class="p-2 bg-blue-100 dark:bg-blue-900/40 rounded-lg mr-3">
                                        <i class="fas fa-box text-blue-600 dark:text-blue-400"></i>
                                    </div>
                                    <div>
                                        <div class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide">Produk</div>
                                        <div class="text-sm font-bold text-gray-900 dark:text-white mt-1" id="product_title_display">-</div>
                                    </div>
                                </div>
                                <div class="mt-3 pt-3 border-t border-blue-200 dark:border-gray-600">
                                    <div class="text-xs font-semibold text-gray-500 dark:text-gray-400 mb-2">Harga Base Produk</div>
                                    <div class="text-lg font-bold text-blue-700 dark:text-blue-300" id="base_price_view">Rp 0</div>
                                </div>
                            </div>

                            <div class="bg-gradient-to-br from-green-50 to-emerald-50 dark:from-gray-800 dark:to-gray-700 rounded-lg p-4 border border-green-200 dark:border-gray-600">
                                <div class="flex items-center mb-3">
                                    <div class="p-2 bg-green-100 dark:bg-green-900/40 rounded-lg mr-3">
                                        <i class="fas fa-user text-green-600 dark:text-green-400"></i>
                                    </div>
                                    <div>
                                        <div class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide">Customer</div>
                                    </div>
                                </div>
                                <div class="space-y-2 mt-3">
                                    <div class="flex items-center text-sm">
                                        <i class="fas fa-user-circle text-gray-400 dark:text-gray-500 mr-2 w-4"></i>
                                        <span class="text-gray-600 dark:text-gray-400">Nama:</span>
                                        <span class="ml-2 font-medium text-gray-900 dark:text-white" id="customer_name_view">-</span>
                                    </div>
                                    <div class="flex items-center text-sm">
                                        <i class="fas fa-envelope text-gray-400 dark:text-gray-500 mr-2 w-4"></i>
                                        <span class="text-gray-600 dark:text-gray-400">Email:</span>
                                        <span class="ml-2 font-medium text-gray-900 dark:text-white" id="customer_email_view">-</span>
                                    </div>
                                    <div class="flex items-center text-sm">
                                        <i class="fas fa-phone text-gray-400 dark:text-gray-500 mr-2 w-4"></i>
                                        <span class="text-gray-600 dark:text-gray-400">Telepon:</span>
                                        <span class="ml-2 font-medium text-gray-900 dark:text-white" id="customer_phone_view">-</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Customer Request -->
                        <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
                            <div class="flex items-center justify-between mb-3">
                                <div class="flex items-center">
                                    <i class="fas fa-file-alt text-gray-400 dark:text-gray-500 mr-2"></i>
                                    <span class="text-sm font-semibold text-gray-700 dark:text-gray-300">Permintaan Customer</span>
                                </div>
                                <span id="reqTypeBadge" class="hidden text-xs px-3 py-1 rounded-full font-medium"></span>
                            </div>
                            <div id="addonList" class="text-xs text-gray-700 dark:text-gray-300 space-y-1 mb-3"></div>
                            <div>
                                <label class="text-xs font-medium text-gray-600 dark:text-gray-400 mb-1 block">Pesan Customer</label>
                                <textarea id="customer_message" rows="3" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm" readonly></textarea>
                            </div>
                        </div>

                        <!-- Estimation Inputs -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
                                <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    <i class="fas fa-calendar-alt mr-2 text-blue-500"></i>Estimasi Hari Pengerjaan
                                </label>
                                <input type="number" name="estimated_days" id="estimated_days" min="1" 
                                    class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white text-lg font-semibold focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition" 
                                    required placeholder="Contoh: 5">
                                <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">
                                    <i class="fas fa-info-circle mr-1"></i>Berapa hari yang dibutuhkan untuk menyelesaikan pekerjaan ini?
                                </p>
                            </div>

                            <div class="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
                                <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    <i class="fas fa-dollar-sign mr-2 text-green-500"></i>Biaya Jasa (Labor Cost)
                                </label>
                                <div class="relative">
                                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400">Rp</span>
                                    <input type="number" name="labor_cost" id="labor_cost" step="0.01" 
                                        class="w-full pl-12 pr-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white text-lg font-semibold focus:ring-2 focus:ring-green-500 focus:border-green-500 transition" 
                                        required placeholder="0" oninput="updateTotalCost()">
                                </div>
                                <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">
                                    <i class="fas fa-info-circle mr-1"></i>Total biaya jasa yang diperlukan untuk pekerjaan ini
                                </p>
                            </div>
                        </div>

                        <input type="hidden" name="materials_breakdown" id="materials_breakdown">
                        <input type="hidden" name="spareparts_breakdown" id="spareparts_breakdown">

                        <!-- Materials Section -->
                        <div class="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
                            <div class="flex items-center justify-between mb-4">
                                <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300">
                                    <i class="fas fa-cube mr-2 text-indigo-500"></i>Bahan yang Diperlukan
                                </label>
                                <button type="button" onclick="addMaterialRow()" 
                                    class="px-3 py-1.5 text-xs rounded-md border border-indigo-200 dark:border-indigo-700 text-indigo-700 dark:text-indigo-300 bg-white dark:bg-gray-800 hover:bg-indigo-50 dark:hover:bg-indigo-900/30 transition-colors">
                                    <i class="fas fa-plus mr-1"></i>Tambah Bahan
                                </button>
                            </div>
                            <div class="overflow-x-auto border border-gray-200 dark:border-gray-700 rounded-lg">
                                <table class="min-w-full text-xs" id="materialsTable">
                                    <thead class="bg-gray-100 dark:bg-gray-800">
                                        <tr>
                                            <th class="px-3 py-2 text-left font-semibold text-gray-700 dark:text-gray-300">Nama Bahan</th>
                                            <th class="px-3 py-2 text-right font-semibold text-gray-700 dark:text-gray-300">Qty</th>
                                            <th class="px-3 py-2 text-center font-semibold text-gray-700 dark:text-gray-300">Unit</th>
                                            <th class="px-3 py-2 text-right font-semibold text-gray-700 dark:text-gray-300">Harga/Unit</th>
                                            <th class="px-3 py-2 text-right font-semibold text-gray-700 dark:text-gray-300">Total</th>
                                            <th class="px-3 py-2 text-center font-semibold text-gray-700 dark:text-gray-300">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody id="materialsBody"></tbody>
                                    <tfoot class="bg-gray-50 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700">
                                        <tr>
                                            <td colspan="4" class="px-3 py-2 text-right font-semibold text-gray-700 dark:text-gray-300">Subtotal Bahan:</td>
                                            <td class="px-3 py-2 text-right font-bold text-indigo-700 dark:text-indigo-300" id="materials_subtotal">Rp 0</td>
                                            <td></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>

                        <!-- Spareparts Section -->
                        <div class="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
                            <div class="flex items-center justify-between mb-4">
                                <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300">
                                    <i class="fas fa-cog mr-2 text-purple-500"></i>Sparepart yang Diperlukan
                                </label>
                                <button type="button" onclick="addSparepartRow()" 
                                    class="px-3 py-1.5 text-xs rounded-md border border-purple-200 dark:border-purple-700 text-purple-700 dark:text-purple-300 bg-white dark:bg-gray-800 hover:bg-purple-50 dark:hover:bg-purple-900/30 transition-colors">
                                    <i class="fas fa-plus mr-1"></i>Tambah Sparepart
                                </button>
                            </div>
                            <div class="overflow-x-auto border border-gray-200 dark:border-gray-700 rounded-lg">
                                <table class="min-w-full text-xs" id="sparepartsTable">
                                    <thead class="bg-gray-100 dark:bg-gray-800">
                                        <tr>
                                            <th class="px-3 py-2 text-left font-semibold text-gray-700 dark:text-gray-300">Nama Sparepart</th>
                                            <th class="px-3 py-2 text-right font-semibold text-gray-700 dark:text-gray-300">Qty</th>
                                            <th class="px-3 py-2 text-center font-semibold text-gray-700 dark:text-gray-300">Unit</th>
                                            <th class="px-3 py-2 text-right font-semibold text-gray-700 dark:text-gray-300">Harga/Unit</th>
                                            <th class="px-3 py-2 text-right font-semibold text-gray-700 dark:text-gray-300">Total</th>
                                            <th class="px-3 py-2 text-center font-semibold text-gray-700 dark:text-gray-300">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody id="sparepartsBody"></tbody>
                                    <tfoot class="bg-gray-50 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700">
                                        <tr>
                                            <td colspan="4" class="px-3 py-2 text-right font-semibold text-gray-700 dark:text-gray-300">Subtotal Sparepart:</td>
                                            <td class="px-3 py-2 text-right font-bold text-purple-700 dark:text-purple-300" id="spareparts_subtotal">Rp 0</td>
                                            <td></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>

                        <!-- Total Cost Summary -->
                        <div class="bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-gray-800 dark:to-gray-700 rounded-lg p-4 border-2 border-blue-200 dark:border-gray-600">
                            <div class="flex items-center justify-between mb-3">
                                <div class="flex items-center">
                                    <i class="fas fa-calculator text-blue-600 dark:text-blue-400 mr-2"></i>
                                    <span class="text-sm font-semibold text-gray-700 dark:text-gray-300">Ringkasan Biaya</span>
                                </div>
                            </div>
                            <div class="space-y-2">
                                <div class="flex justify-between text-sm">
                                    <span class="text-gray-600 dark:text-gray-400">Subtotal Bahan:</span>
                                    <span class="font-medium text-gray-900 dark:text-white" id="summary_materials">Rp 0</span>
                                </div>
                                <div class="flex justify-between text-sm">
                                    <span class="text-gray-600 dark:text-gray-400">Subtotal Sparepart:</span>
                                    <span class="font-medium text-gray-900 dark:text-white" id="summary_spareparts">Rp 0</span>
                                </div>
                                <div class="flex justify-between text-sm">
                                    <span class="text-gray-600 dark:text-gray-400">Biaya Jasa:</span>
                                    <span class="font-medium text-gray-900 dark:text-white" id="summary_labor">Rp 0</span>
                                </div>
                                <div class="pt-2 border-t border-blue-200 dark:border-gray-600">
                                    <div class="flex justify-between">
                                        <span class="text-base font-bold text-gray-900 dark:text-white">Total Biaya:</span>
                                        <span class="text-xl font-bold text-blue-700 dark:text-blue-300" id="summary_total">Rp 0</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Teknisi Note -->
                        <div class="bg-white dark:bg-gray-800 rounded-lg p-4 border border-gray-200 dark:border-gray-700">
                            <label class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                <i class="fas fa-sticky-note mr-2 text-amber-500"></i>Catatan Teknis
                            </label>
                            <textarea name="teknisi_note" id="teknisi_note" rows="4" 
                                class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-amber-500 focus:border-amber-500 transition" 
                                placeholder="Detail pengerjaan, bahan yang diperlukan, kesulitan teknis, catatan khusus, dll..."></textarea>
                            <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">
                                <i class="fas fa-info-circle mr-1"></i>Catatan ini akan dilihat oleh supervisor untuk review final
                            </p>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Modal Footer -->
            <div class="px-6 py-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800 flex justify-end space-x-3">
                <button type="button" onclick="closeEstimateModal()" 
                    class="px-6 py-2.5 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-200 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors font-medium">
                    <i class="fas fa-times mr-2"></i>Batal
                </button>
                <button type="submit" form="estimateForm" 
                    class="px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors font-medium shadow-lg">
                    <i class="fas fa-check mr-2"></i>Simpan Estimasi
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function fmt(n){ return new Intl.NumberFormat('id-ID').format(n||0); }

function openEstimateModal(inquiryId, productTitle, rawMessage) {
    document.getElementById('inquiry_id').value = inquiryId;
    document.getElementById('product_title_display').textContent = productTitle || '-';
    document.getElementById('estimateForm').action = '/teknisi/quotations/' + inquiryId + '/estimate';
    
    try {
        const typeMatch = (rawMessage||'').match(/\[REQUEST_TYPE\]\s*([^\r\n]+)/);
        const addMatch = (rawMessage||'').match(/\[ADDONS\]\s*(\[[\s\S]*?\])/);
        const type = typeMatch ? typeMatch[1].trim() : null;
        let addons = [];
        if (addMatch) { try { addons = JSON.parse(addMatch[1]); } catch(e){} }
        let plain = (rawMessage||'').replace(/\[REQUEST_TYPE\][^\r\n]*/,'').replace(/\[ADDONS\][^\r\n]*/,'').trim();
        const badge = document.getElementById('reqTypeBadge');
        const addonList = document.getElementById('addonList');
        const msg = document.getElementById('customer_message');
        msg.value = plain || (rawMessage||'');
        addonList.innerHTML = '';
        if (type){
            badge.classList.remove('hidden');
            badge.textContent = type === 'custom_addon' ? 'Custom Add-on' : (type === 'custom_new' ? 'Custom Baru' : 'Katalog');
            badge.className = 'text-xs px-3 py-1 rounded-full font-medium ' + (type==='custom_addon' ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/40 dark:text-yellow-200' : (type==='custom_new' ? 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-200' : 'bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-200'));
        } else {
            badge.classList.add('hidden');
        }
        if (Array.isArray(addons) && addons.length){
            addonList.innerHTML = '<div class="text-xs font-semibold mb-2 text-gray-900 dark:text-white">Spesifikasi Tambahan:</div>' + addons.map(a => `<div class="pl-2">• <span class="font-medium">${(a?.name||'-')}</span>: ${(a?.value||'-')}</div>`).join('');
        }
    } catch(_){ /* ignore */ }
    
    const modal = document.getElementById('estimateModal');
    if (modal){
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
    }
    try { document.body.style.overflow = 'hidden'; } catch(_){}
    
    // Clear previous data
    document.getElementById('materialsBody').innerHTML = '';
    document.getElementById('sparepartsBody').innerHTML = '';
    document.getElementById('estimated_days').value = '';
    document.getElementById('labor_cost').value = '';
    document.getElementById('teknisi_note').value = '';
    updateTotalCost();
}

function closeEstimateModal() {
    const modal = document.getElementById('estimateModal');
    if (modal){
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
    try { document.body.style.overflow = ''; } catch(_){}
}

// Format number inputs
const ed = document.getElementById('estimated_days');
if (ed) ed.addEventListener('input', function(){ this.value = this.value.replace(/[^0-9]/g,''); });
const lc = document.getElementById('labor_cost');
if (lc) lc.addEventListener('input', function(){ 
    this.value = this.value.replace(/[^0-9.]/g,'');
    updateTotalCost();
});

@php
    $materialsPayload = collect($materials ?? [])->map(function($m){
        return [
            'id' => $m->id,
            'name' => $m->name,
            'unit' => $m->unit,
            'price' => (float) $m->price,
            'stock' => (float) $m->stock,
        ];
    })->values();
    $sparepartsPayload = collect($spareparts ?? [])->map(function($s){
        return [
            'id' => $s->id,
            'name' => $s->name,
            'unit' => $s->unit,
            'price' => (float) $s->price,
            'stock' => (float) $s->stock,
        ];
    })->values();
@endphp
const MATERIALS = @json($materialsPayload);
const SPAREPARTS = @json($sparepartsPayload);

function buildOptions(list, placeholder){
    let html = `<option value="">-- ${placeholder} --</option>`;
    list.forEach(function(it){
        const unit = it.unit || '';
        const stockStatus = it.stock <= 0 ? ' (Stok Habis!)' : (it.stock <= 5 ? ' (Stok Rendah!)' : '');
        html += `<option value="${it.id}" data-name="${String(it.name).replace(/"/g,'&quot;')}" data-unit="${String(unit).replace(/"/g,'&quot;')}" data-price="${it.price}" data-stock="${it.stock}">${it.name}${stockStatus} - Stock: ${it.stock} ${unit} - Rp ${fmt(it.price)}</option>`;
    });
    return html;
}

function rowTemplateSelect(kind){
    const rowId = 'rs_' + Math.random().toString(36).slice(2);
    const options = kind === 'material' ? buildOptions(MATERIALS, 'Pilih Bahan') : buildOptions(SPAREPARTS, 'Pilih Sparepart');
    return `<tr data-kind="${kind}" data-row-id="${rowId}" class="hover:bg-gray-50 dark:hover:bg-gray-700/50">
        <td class="px-3 py-2">
            <select class="w-full px-2 py-1.5 border dark:border-gray-600 rounded text-xs dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-blue-500" data-field="select" onchange="onSelectChange('${rowId}', this)">
                ${options}
            </select>
            <input type="hidden" data-field="item_id">
            <input type="hidden" data-field="name">
        </td>
        <td class="px-3 py-2 text-right">
            <input type="number" step="0.01" min="0" class="w-full px-2 py-1.5 border dark:border-gray-600 rounded text-xs text-right dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-blue-500" data-field="qty" oninput="recalc(this)" placeholder="0">
        </td>
        <td class="px-3 py-2 text-center">
            <input class="w-full px-2 py-1.5 border dark:border-gray-600 rounded text-xs text-center dark:bg-gray-700 dark:text-white bg-gray-50 dark:bg-gray-800" data-field="unit" readonly>
        </td>
        <td class="px-3 py-2 text-right">
            <input type="number" step="0.01" class="w-full px-2 py-1.5 border dark:border-gray-600 rounded text-xs text-right dark:bg-gray-700 dark:text-white bg-gray-50 dark:bg-gray-800" data-field="unit_cost" readonly>
        </td>
        <td class="px-3 py-2 text-right">
            <span class="font-semibold text-gray-900 dark:text-white" data-field="total">Rp 0</span>
        </td>
        <td class="px-3 py-2 text-center">
            <button type="button" class="text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 transition-colors" onclick="removeRow(this)" title="Hapus">
                <i class="fas fa-trash"></i>
            </button>
        </td>
    </tr>`;
}

function onSelectChange(rowId, selectEl){
    const tr = document.querySelector(`tr[data-row-id="${rowId}"]`);
    if(!tr) return;
    const opt = selectEl.selectedOptions[0];
    if(!opt || !opt.value){
        tr.querySelector('[data-field="item_id"]').value = '';
        tr.querySelector('[data-field="name"]').value = '';
        tr.querySelector('[data-field="unit"]').value = '';
        tr.querySelector('[data-field="unit_cost"]').value = '';
        tr.querySelector('[data-field="qty"]').value = '';
        recalc(selectEl);
        return;
    }
    tr.querySelector('[data-field="item_id"]').value = opt.value;
    tr.querySelector('[data-field="name"]').value = opt.getAttribute('data-name')||'';
    tr.querySelector('[data-field="unit"]').value = opt.getAttribute('data-unit')||'';
    tr.querySelector('[data-field="unit_cost"]').value = parseFloat(opt.getAttribute('data-price')||0);
    const stock = parseFloat(opt.getAttribute('data-stock')||0);
    if(stock <= 0) {
        alert('Peringatan: Stok bahan/sparepart ini habis!');
    } else if(stock <= 5) {
        alert('Peringatan: Stok bahan/sparepart ini rendah!');
    }
    recalc(selectEl);
}

function recalc(el){
    const tr = el.closest('tr');
    if(!tr) return;
    const qty = parseFloat(tr.querySelector('[data-field="qty"]').value||0);
    const unitCost = parseFloat(tr.querySelector('[data-field="unit_cost"]').value||0);
    const total = qty * unitCost;
    tr.querySelector('[data-field="total"]').innerText = 'Rp ' + fmt(total);
    updateTotalCost();
}

function updateTotalCost(){
    // Calculate materials subtotal
    let materialsTotal = 0;
    Array.from(document.querySelectorAll('#materialsBody tr')).forEach(tr => {
        const qty = parseFloat(tr.querySelector('[data-field="qty"]')?.value || 0);
        const unitCost = parseFloat(tr.querySelector('[data-field="unit_cost"]')?.value || 0);
        materialsTotal += qty * unitCost;
    });
    
    // Calculate spareparts subtotal
    let sparepartsTotal = 0;
    Array.from(document.querySelectorAll('#sparepartsBody tr')).forEach(tr => {
        const qty = parseFloat(tr.querySelector('[data-field="qty"]')?.value || 0);
        const unitCost = parseFloat(tr.querySelector('[data-field="unit_cost"]')?.value || 0);
        sparepartsTotal += qty * unitCost;
    });
    
    // Get labor cost
    const laborCost = parseFloat(document.getElementById('labor_cost')?.value || 0);
    
    // Calculate total
    const total = materialsTotal + sparepartsTotal + laborCost;
    
    // Update displays
    document.getElementById('materials_subtotal').textContent = 'Rp ' + fmt(materialsTotal);
    document.getElementById('spareparts_subtotal').textContent = 'Rp ' + fmt(sparepartsTotal);
    document.getElementById('summary_materials').textContent = 'Rp ' + fmt(materialsTotal);
    document.getElementById('summary_spareparts').textContent = 'Rp ' + fmt(sparepartsTotal);
    document.getElementById('summary_labor').textContent = 'Rp ' + fmt(laborCost);
    document.getElementById('summary_total').textContent = 'Rp ' + fmt(total);
}

function removeRow(btn){ 
    btn.closest('tr').remove();
    updateTotalCost();
}

window.addMaterialRow = function(){ 
    document.getElementById('materialsBody').insertAdjacentHTML('beforeend', rowTemplateSelect('material')); 
};
window.addSparepartRow = function(){ 
    document.getElementById('sparepartsBody').insertAdjacentHTML('beforeend', rowTemplateSelect('sparepart')); 
};

// Mark as Read Function
function markAsReadFromBtn(btn) {
    const inquiryId = Number(btn.getAttribute('data-id'));
    markAsRead(inquiryId);
}

function markAsRead(inquiryId) {
    Swal.fire({
        title: 'Tandai sebagai Dibaca?',
        text: 'Penawaran ini akan ditandai sebagai sudah dibaca.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3b82f6',
        cancelButtonColor: '#6b7280',
        confirmButtonText: '<i class="fas fa-check mr-2"></i>Ya, Tandai Dibaca',
        cancelButtonText: '<i class="fas fa-times mr-2"></i>Batal',
        reverseButtons: true
    }).then((result) => {
        if (result.isConfirmed) {
            fetch(`/teknisi/quotations/${inquiryId}/mark-read`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Update badge immediately
                    if (window.notificationSystem && typeof window.notificationSystem.checkNotifications === 'function') {
                        window.notificationSystem.checkNotifications();
                    }
                    
                    // Update local badge count
                    const quotationsBadge = document.getElementById('sidebar-quotations-badge');
                    if (quotationsBadge) {
                        const currentCount = parseInt(quotationsBadge.textContent) || 0;
                        const newCount = Math.max(0, currentCount - 1);
                        if (newCount > 0) {
                            quotationsBadge.textContent = newCount > 99 ? '99+' : newCount.toString();
                            quotationsBadge.classList.remove('hidden');
                            quotationsBadge.removeAttribute('hidden');
                            quotationsBadge.style.cssText = 'display: inline-flex !important; visibility: visible !important; opacity: 1 !important;';
                        } else {
                            quotationsBadge.classList.add('hidden');
                            quotationsBadge.setAttribute('hidden', 'true');
                            quotationsBadge.style.cssText = 'display: none !important; visibility: hidden !important;';
                        }
                    }
                    
                    // Update row styling
                    const row = document.querySelector(`tr[data-inquiry-id="${inquiryId}"]`);
                    if (row) {
                        row.classList.remove('bg-yellow-50/30', 'dark:bg-yellow-900/10');
                    }
                    
                    // Update status badge in row
                    const statusBadge = document.querySelector(`tr[data-inquiry-id="${inquiryId}"] .status-badge`);
                    if (statusBadge) {
                        statusBadge.innerHTML = '<i class="fas fa-check-circle text-green-500 mr-1"></i><span>Dibaca</span>';
                    }
                    
                    // Update unread count in stats
                    const unreadCountEl = document.querySelector('.unread-count');
                    if (unreadCountEl) {
                        const currentUnread = parseInt(unreadCountEl.textContent) || 0;
                        const newUnread = Math.max(0, currentUnread - 1);
                        unreadCountEl.textContent = newUnread;
                    }
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        text: data.message || 'Penawaran ditandai sebagai dibaca.',
                        timer: 2000,
                        showConfirmButton: false
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: data.message || 'Gagal menandai sebagai dibaca.',
                        timer: 3000,
                        showConfirmButton: true
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: 'Terjadi kesalahan saat memproses permintaan.',
                    timer: 3000,
                    showConfirmButton: true
                });
            });
        }
    });
}

// Event delegation for estimate button
document.addEventListener('click', function(ev){
    const btn = ev.target.closest('[data-estimate-btn]');
    if (!btn) return;
    ev.preventDefault();
    try {
        const id = Number(btn.getAttribute('data-id'));
        const title = JSON.parse(btn.getAttribute('data-title')||'""');
        const msg = JSON.parse(btn.getAttribute('data-message')||'""');
        openEstimateModal(id, title, msg);
        const base = Number(btn.getAttribute('data-base')||0);
        const cname = btn.getAttribute('data-cname')||'-';
        const cemail = btn.getAttribute('data-cemail')||'-';
        const cphone = btn.getAttribute('data-cphone')||'-';
        document.getElementById('base_price_view').innerText = 'Rp ' + fmt(base||0);
        document.getElementById('customer_name_view').innerText = cname;
        document.getElementById('customer_email_view').innerText = cemail;
        document.getElementById('customer_phone_view').innerText = cphone;
    } catch(_){
        const id = Number(btn.getAttribute('data-id'));
        const title = btn.getAttribute('data-title')||'';
        const msg = btn.getAttribute('data-message')||'';
        openEstimateModal(id, title, msg);
        const base = Number(btn.getAttribute('data-base')||0);
        const cname = btn.getAttribute('data-cname')||'-';
        const cemail = btn.getAttribute('data-cemail')||'-';
        const cphone = btn.getAttribute('data-cphone')||'-';
        document.getElementById('base_price_view').innerText = 'Rp ' + fmt(base||0);
        document.getElementById('customer_name_view').innerText = cname;
        document.getElementById('customer_email_view').innerText = cemail;
        document.getElementById('customer_phone_view').innerText = cphone;
    }
});

// Serialize before submit
const estimateForm = document.getElementById('estimateForm');
if (estimateForm){
    estimateForm.addEventListener('submit', function(e){
        const mRowsAll = Array.from(document.querySelectorAll('#materialsBody tr')).map(tr=>({
            item_id: tr.querySelector('[data-field="item_id"]').value || null,
            name: tr.querySelector('[data-field="name"]').value,
            qty: parseFloat(tr.querySelector('[data-field="qty"]').value||0),
            unit: tr.querySelector('[data-field="unit"]').value,
            unit_cost: parseFloat(tr.querySelector('[data-field="unit_cost"]').value||0),
            type: 'material',
        }));
        const sRowsAll = Array.from(document.querySelectorAll('#sparepartsBody tr')).map(tr=>({
            item_id: tr.querySelector('[data-field="item_id"]').value || null,
            name: tr.querySelector('[data-field="name"]').value,
            qty: parseFloat(tr.querySelector('[data-field="qty"]').value||0),
            unit: tr.querySelector('[data-field="unit"]').value,
            unit_cost: parseFloat(tr.querySelector('[data-field="unit_cost"]').value||0),
            type: 'sparepart',
        }));
        // Filter baris kosong
        const mRows = mRowsAll.filter(r => (r.name && r.name.trim() !== '') && r.qty > 0);
        const sRows = sRowsAll.filter(r => (r.name && r.name.trim() !== '') && r.qty > 0);
        
        if (mRowsAll.length > 0 && mRows.length === 0 && sRowsAll.length === 0) {
            e.preventDefault();
            alert('Isi nama dan qty untuk bahan/sparepart yang ditambahkan, atau hapus baris kosong.');
            return;
        }
        
        document.getElementById('materials_breakdown').value = JSON.stringify(mRows);
        document.getElementById('spareparts_breakdown').value = JSON.stringify(sRows);
    });
}

// Initialize sidebar badge on page load
document.addEventListener('DOMContentLoaded', function() {
    const unreadCount = {{ $unreadCount ?? 0 }};
    const quotationsBadge = document.getElementById('sidebar-quotations-badge');
    
    if (quotationsBadge) {
        if (unreadCount > 0) {
            quotationsBadge.textContent = unreadCount > 99 ? '99+' : unreadCount.toString();
            quotationsBadge.classList.remove('hidden');
            quotationsBadge.removeAttribute('hidden');
            quotationsBadge.style.cssText = 'display: inline-flex !important; visibility: visible !important; opacity: 1 !important;';
            console.log('[Quotations Page] Badge initialized with count:', unreadCount);
        } else {
            quotationsBadge.classList.add('hidden');
            quotationsBadge.setAttribute('hidden', 'true');
            quotationsBadge.style.cssText = 'display: none !important; visibility: hidden !important;';
            console.log('[Quotations Page] Badge hidden (no unread)');
        }
    } else {
        console.warn('[Quotations Page] Badge element not found');
    }
    
    // Also update badge via notification system if available
    if (window.notificationSystem && typeof window.notificationSystem.updateBadge === 'function') {
        // Trigger immediate update
        setTimeout(() => {
            if (window.notificationSystem.checkNotifications) {
                window.notificationSystem.checkNotifications();
            }
        }, 500);
    }
});
</script>

@endsection
