@extends('layouts.guest')

@push('styles')
    <style>
        /* ===== Map Pin Visualization ===== */
        .map-container {
            position: relative;
            width: 100%;
            overflow: hidden;
            border-radius: 0.75rem;
            background: #E2E8F0;
        }

        .map-container img {
            display: block;
            width: 100%;
            height: auto;
            opacity: 0.95;
        }

        /* Pin Pointer */
        .map-pin {
            position: absolute;
            transform: translate(-50%, -100%);
            z-index: 30;
            cursor: pointer;
            filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.25));
            transition: filter 0.3s ease;
        }

        .map-pin:hover {
            filter: drop-shadow(0 6px 14px rgba(227, 38, 54, 0.5));
            z-index: 40;
        }

        .map-pin.active {
            animation: pinBounce 1.5s infinite;
        }

        /* Pin Icon (red circle + triangle tail) */
        .map-pin__icon {
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .map-pin__circle {
            width: 32px;
            height: 32px;
            background: linear-gradient(135deg, #E32636, #c0392b);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 2.5px solid #fff;
            box-shadow: 0 2px 8px rgba(227, 38, 54, 0.4);
        }

        .map-pin__circle i {
            color: #fff;
            font-size: 13px;
        }

        .map-pin__tail {
            width: 0;
            height: 0;
            border-left: 7px solid transparent;
            border-right: 7px solid transparent;
            border-top: 10px solid #c0392b;
            margin-top: -2px;
        }

        /* Pin Label (tooltip di bawah) */
        .map-pin__label {
            position: absolute;
            top: calc(100% + 6px);
            left: 50%;
            transform: translateX(-50%);
            background: #0B5394;
            color: #fff;
            font-size: 9px;
            font-weight: 800;
            padding: 3px 8px;
            border-radius: 4px;
            white-space: nowrap;
            box-shadow: 0 2px 6px rgba(11, 83, 148, 0.4);
            border: 1px solid rgba(96, 165, 250, 0.4);
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.2s ease;
        }

        .map-pin:hover .map-pin__label,
        .map-pin.active .map-pin__label {
            opacity: 1;
        }

        /* Pulse dot di dasar pin */
        .map-pin__pulse {
            position: absolute;
            bottom: -4px;
            left: 50%;
            transform: translateX(-50%);
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: rgba(227, 38, 54, 0.35);
            z-index: -1;
        }

        .map-pin.active .map-pin__pulse {
            animation: pinPulse 2s infinite;
        }

        /* Overlay Not Found */
        .map-overlay-notfound {
            position: absolute;
            inset: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(6px);
            z-index: 50;
            border-radius: 0.75rem;
        }

        @keyframes pinBounce {

            0%,
            100% {
                transform: translate(-50%, -100%);
            }

            50% {
                transform: translate(-50%, calc(-100% - 8px));
            }
        }

        @keyframes pinPulse {
            0% {
                transform: translateX(-50%) scale(1);
                opacity: 0.6;
            }

            100% {
                transform: translateX(-50%) scale(3.5);
                opacity: 0;
            }
        }

        /* Responsive adjustments */
        @media (max-width: 640px) {
            .map-pin__circle {
                width: 24px;
                height: 24px;
            }

            .map-pin__circle i {
                font-size: 10px;
            }

            .map-pin__tail {
                border-left-width: 5px;
                border-right-width: 5px;
                border-top-width: 7px;
            }

            .map-pin__label {
                font-size: 8px;
                padding: 2px 6px;
            }
        }
    </style>
@endpush

@section('content')
    <div class="container mx-auto px-4 py-12 max-w-7xl">
        <!-- Header: Back button & Search Bar -->
        <div class="flex flex-col md:flex-row justify-between items-center mb-10 gap-6">
            <a href="{{ route('katalog.index') }}"
                class="text-gray-500 hover:text-blue-600 font-bold flex items-center transition-colors px-4 py-2 bg-white rounded-full shadow-sm border border-gray-100 hover:shadow-md">
                <i class="fas fa-arrow-left mr-2"></i> Kembali
            </a>

            <!-- Search Bar -->
            <form action="{{ route('katalog.index') }}" method="GET" class="w-full md:w-80 relative group">
                <input type="text" name="search" placeholder="Cari Buku..."
                    class="w-full pl-5 pr-14 py-3 bg-white border border-gray-200 rounded-full shadow-sm focus:ring-4 focus:ring-blue-500/20 focus:border-blue-500 text-sm font-medium transition-all outline-none">
                <button type="submit"
                    class="absolute right-1 top-1 bottom-1 w-10 flex items-center justify-center bg-gray-100 text-gray-600 rounded-full hover:bg-blue-600 hover:text-white transition-colors">
                    <i class="fas fa-search"></i>
                </button>
            </form>
        </div>

        <!-- Main Content Grid 3 Columns -->
        <div class="grid grid-cols-1 md:grid-cols-12 gap-10 items-start">

            <!-- Column 1: Book Cover Card -->
            <div class="md:col-span-12 lg:col-span-3">
                <div
                    class="bg-white rounded-3xl shadow-[0_10px_40px_-10px_rgba(0,0,0,0.08)] border border-gray-50 p-5 flex flex-col items-center text-center overflow-hidden transition-transform duration-500 hover:-translate-y-2">
                    @if ($buku->cover)
                        <img src="{{ asset('storage/' . $buku->cover) }}" alt="{{ $buku->judul }}"
                            class="w-full aspect-[3/4] object-cover rounded-2xl mb-6 shadow-md border border-gray-100">
                    @else
                        <div
                            class="w-full aspect-[3/4] bg-gradient-to-br from-indigo-50 to-blue-50 rounded-2xl flex items-center justify-center mb-6 overflow-hidden relative shadow-inner border border-blue-100/50">
                            <div
                                class="absolute inset-0 opacity-40 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAiIGhlaWdodD0iMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGNpcmNsZSBjeD0iMiIgY3k9IjIiIHI9IjIiIGZpbGw9IiMzYjgyZjYiIGZpbGwtb3BhY2l0eT0iMC4wNSIvPjwvc3ZnPg==')]">
                            </div>
                            <div class="relative z-10 flex flex-col items-center justify-center p-6 w-full h-full">
                                <div
                                    class="w-20 h-20 bg-white/80 backdrop-blur rounded-full flex items-center justify-center mb-4 shadow-sm text-blue-400">
                                    <i class="fas fa-book-open text-3xl"></i>
                                </div>
                                <h3
                                    class="text-sm font-black text-blue-900 leading-snug break-words drop-shadow-sm uppercase line-clamp-4">
                                    {{ $buku->judul }}</h3>
                                <div class="w-8 h-1 bg-blue-300/50 rounded-full my-3"></div>
                                <p class="text-[10px] text-blue-700 font-bold uppercase tracking-widest">
                                    {{ $buku->pengarang }}</p>
                            </div>
                        </div>
                    @endif
                    <h2 class="font-extrabold text-gray-900 uppercase tracking-widest text-xs leading-relaxed px-2 mb-2">
                        {{ $buku->judul }}</h2>
                </div>
            </div>

            <!-- Column 2: Details Description -->
            <div class="md:col-span-12 lg:col-span-5 flex flex-col gap-8 lg:px-4">
                <div class="text-center lg:text-left">
                    <h2 class="text-3xl font-black text-gray-900 mb-2 tracking-tight">Deskripsi Buku</h2>
                </div>

                <div class="space-y-6">
                    <!-- Data Row -->
                    <div class="flex flex-col sm:flex-row gap-2 border-b border-gray-100 pb-5">
                        <span class="text-gray-500 font-semibold text-sm w-full sm:w-1/3 flex-shrink-0">Kode Buku:</span>
                        <span
                            class="text-gray-900 font-bold text-sm bg-gray-100 px-3 py-1 rounded w-fit">{{ $buku->nomor_panggil ?? '-' }}</span>
                    </div>
                    <!-- Data Row -->
                    <div class="flex flex-col sm:flex-row gap-2 border-b border-gray-100 pb-5">
                        <span class="text-gray-500 font-semibold text-sm w-full sm:w-1/3 flex-shrink-0">Judul Buku:</span>
                        <span class="text-gray-900 font-bold text-sm">{{ $buku->judul }}</span>
                    </div>
                    <!-- Data Row -->
                    <div class="flex flex-col sm:flex-row gap-2 border-b border-gray-100 pb-5">
                        <span class="text-gray-500 font-semibold text-sm w-full sm:w-1/3 flex-shrink-0">Nama Penulis:</span>
                        <span class="text-gray-900 font-bold text-sm">{{ $buku->pengarang }}</span>
                    </div>
                    <!-- Data Row -->
                    <div class="flex flex-col sm:flex-row gap-2 border-b border-gray-100 pb-5">
                        <span class="text-gray-500 font-semibold text-sm w-full sm:w-1/3 flex-shrink-0">Deskripsi
                            Fisik:</span>
                        <span
                            class="text-gray-700 font-medium text-sm leading-relaxed">{{ $buku->deskripsi_fisik ?: 'Tidak ada deskripsi fisik.' }}</span>
                    </div>
                    <!-- Data Row -->
                    <div class="flex flex-col sm:flex-row gap-2 border-b border-gray-100 pb-5">
                        <span class="text-gray-500 font-semibold text-sm w-full sm:w-1/3 flex-shrink-0">Nama
                            Kategori:</span>
                        <span
                            class="text-blue-600 font-bold text-sm">{{ $buku->kategori->nama_kategori ?? $lokasi['area'] }}</span>
                    </div>
                    <!-- Data Row -->
                    <div class="flex flex-col sm:flex-row gap-2 pb-5">
                        <span class="text-gray-500 font-semibold text-sm w-full sm:w-1/3 flex-shrink-0">Detail
                            Kategori:</span>
                        <span class="text-gray-900 font-bold text-sm">{{ $lokasi['area'] }} (Rak
                            {{ $lokasi['rak'] }})</span>
                    </div>
                </div>
            </div>

            <div class="w-full lg:w-96 flex-shrink-0 flex flex-col gap-6 mx-auto relative">

                <!-- MAP CONTAINER -->
                <div class="map-container shadow-sm border-2 border-slate-300 select-none font-sans min-h-[300px]"
                    id="mapContainer">
                    <!-- Background Image Map -->
                    <img src="{{ asset('img/img 2.png') }}" alt="Denah Perpustakaan" id="mapImage">

                    <!-- Pin Container (JavaScript akan merender pin di sini) -->
                    <div id="pinContainer"></div>

                    @if (!$buku->lokasi_x || !$buku->lokasi_y)
                        <!-- Overlay Not Found -->
                        <div class="map-overlay-notfound">
                            <i class="fas fa-exclamation-triangle text-red-500 text-3xl mb-2 animate-pulse"></i>
                            <h4 class="font-bold text-red-600 text-sm sm:text-base">Lokasi Rak Belum Dipetakan</h4>
                            <p class="text-xs text-gray-500 mt-1">Silakan hubungi petugas perpustakaan untuk bantuan.</p>
                        </div>
                    @endif
                </div>

                <!-- Detail Mini location box directly below map -->
                <div
                    class="bg-blue-900 border border-blue-800 rounded-2xl p-5 text-center shadow-lg w-full relative z-20 transform transition hover:scale-[1.02]">
                    <span
                        class="text-[10px] text-blue-300 font-bold uppercase tracking-widest block mb-2 opacity-80">Informasi
                        Lokasi Fisik</span>
                    <span class="text-2xl font-black text-white block mb-1 drop-shadow-sm">{{ $lokasi['rak'] }}</span>
                    <span class="text-sm font-semibold text-blue-200">{{ $lokasi['area'] }}</span>
                </div>
            </div>
        </div>

        <!-- Riwayat Peminjaman -->
        <div class="mt-12 mb-8">
            <h2 class="text-2xl font-extrabold text-gray-900 mb-6 border-b-2 border-blue-500 inline-block pb-2">Riwayat
                Peminjaman</h2>
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                @if ($buku->peminjaman && $buku->peminjaman->count() > 0)
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-gray-50 border-b border-gray-200 text-gray-600 text-sm">
                                    <th class="py-4 px-6 font-semibold">Nama Peminjam</th>
                                    <th class="py-4 px-6 font-semibold">Tanggal Pinjam</th>
                                    <th class="py-4 px-6 font-semibold">Tanggal Kembali</th>
                                    <th class="py-4 px-6 font-semibold">Status</th>
                                </tr>
                            </thead>
                            <tbody class="text-gray-700 text-sm">
                                @foreach ($buku->peminjaman->sortByDesc('tanggal_pinjam') as $history)
                                    <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                                        <td class="py-4 px-6 font-medium text-gray-900">
                                            @php
                                                $nama = $history->user->name ?? 'Pengguna Tidak Diketahui';
                                                $disensor =
                                                    $nama !== 'Pengguna Tidak Diketahui' && strlen($nama) >= 3
                                                        ? substr($nama, 0, 3) . '***'
                                                        : ($nama !== 'Pengguna Tidak Diketahui'
                                                            ? substr($nama, 0, 1) . '***'
                                                            : $nama);
                                            @endphp
                                            {{ $disensor }}
                                        </td>
                                        <td class="py-4 px-6">
                                            {{ \Carbon\Carbon::parse($history->tanggal_pinjam)->translatedFormat('d F Y') }}
                                        </td>
                                        <td class="py-4 px-6">
                                            @if ($history->status_peminjaman === 'Dikembalikan' && $history->tanggal_dikembalikan)
                                                <span class="text-green-600 font-medium">
                                                    {{ \Carbon\Carbon::parse($history->tanggal_dikembalikan)->translatedFormat('d F Y') }}
                                                    (Dikembalikan)
                                                </span>
                                            @else
                                                <span class="text-gray-600">
                                                    Batas:
                                                    {{ \Carbon\Carbon::parse($history->tanggal_kembali)->translatedFormat('d F Y') }}
                                                </span>
                                            @endif
                                        </td>
                                        <td class="py-4 px-6">
                                            @if ($history->status_peminjaman === 'Dipinjam')
                                                <span
                                                    class="px-3 py-1 bg-yellow-100 text-yellow-700 font-bold rounded-full text-xs">Sedang
                                                    Dipinjam</span>
                                            @elseif($history->status_peminjaman === 'Dikembalikan')
                                                <span
                                                    class="px-3 py-1 bg-green-100 text-green-700 font-bold rounded-full text-xs">Selesai</span>
                                            @else
                                                <span
                                                    class="px-3 py-1 bg-gray-100 text-gray-700 font-bold rounded-full text-xs">{{ $history->status_peminjaman }}</span>
                                            @endif
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @else
                    <div class="p-8 text-center flex flex-col items-center justify-center bg-gray-50/50">
                        <div class="w-16 h-16 bg-blue-50 text-blue-300 rounded-full flex items-center justify-center mb-3">
                            <i class="fas fa-history text-2xl"></i>
                        </div>
                        <p class="text-gray-500 font-medium">Belum ada riwayat peminjaman untuk buku ini.</p>
                    </div>
                @endif
            </div>
        </div>

        @if ($rekomendasi->count() > 0)
            <div class="mt-12">
                <h2 class="text-2xl font-extrabold text-gray-900 mb-6 border-b-2 border-blue-500 inline-block pb-2">
                    Rekomendasi Buku Serupa</h2>
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                    @foreach ($rekomendasi as $rek)
                        <div
                            class="bg-white rounded-xl shadow-sm border border-gray-200 hover:shadow-md transition duration-300 flex flex-col overflow-hidden">
                            <div class="p-5 flex-grow">
                                <div class="flex justify-between items-start mb-2">
                                    <span
                                        class="text-xs font-bold text-blue-600 bg-blue-50 px-2 py-1 rounded">{{ $rek->nomor_panggil }}</span>
                                    <span class="text-xs font-semibold text-green-600">Skor:
                                        {{ number_format($rek->similarity_score, 1) }}</span>
                                </div>
                                <h3 class="text-lg font-bold text-gray-900 mb-1 line-clamp-2">{{ $rek->judul }}</h3>
                                <p class="text-sm text-gray-600 line-clamp-1">{{ $rek->pengarang }}</p>
                            </div>
                            <div class="px-5 py-3 bg-gray-50 border-t border-gray-100 mt-auto">
                                <a href="{{ route('katalog.show', $rek->id_buku) }}"
                                    class="text-sm font-semibold text-blue-600 hover:text-blue-800 flex items-center justify-center w-full">
                                    Lihat Detail
                                </a>
                            </div>
                        </div>
                    @endforeach
                </div>
            </div>
        @endif
    </div>
@endsection

@push('scripts')
    @php
        $pinDataJson = [
            'x' => $buku->lokasi_x,
            'y' => $buku->lokasi_y,
            'label' => $lokasi['rak'] . ' — ' . $lokasi['area'],
        ];
    @endphp
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Data koordinat dari Laravel
            const pinData = @json($pinDataJson);

            const container = document.getElementById('pinContainer');
            if (!container || !pinData.x || !pinData.y) return;

            /**
             * Membuat elemen pin pointer dan menambahkannya ke container.
             * @param {number} x - Posisi X dalam persentase (0-100)
             * @param {number} y - Posisi Y dalam persentase (0-100)
             * @param {string} label - Label teks untuk pin
             * @param {boolean} isActive - Apakah pin ini aktif (bounce + label visible)
             */
            function renderPin(x, y, label, isActive) {
                // Wrapper pin
                const pin = document.createElement('div');
                pin.className = 'map-pin' + (isActive ? ' active' : '');
                pin.style.left = x + '%';
                pin.style.top = y + '%';

                // Ikon pin (circle + tail)
                const icon = document.createElement('div');
                icon.className = 'map-pin__icon';

                const circle = document.createElement('div');
                circle.className = 'map-pin__circle';
                circle.innerHTML = '<i class="fas fa-map-marker-alt"></i>';

                const tail = document.createElement('div');
                tail.className = 'map-pin__tail';

                icon.appendChild(circle);
                icon.appendChild(tail);
                pin.appendChild(icon);

                // Pulse effect
                const pulse = document.createElement('div');
                pulse.className = 'map-pin__pulse';
                pin.appendChild(pulse);

                // Label tooltip
                if (label) {
                    const labelEl = document.createElement('span');
                    labelEl.className = 'map-pin__label';
                    labelEl.textContent = label;
                    pin.appendChild(labelEl);
                }

                container.appendChild(pin);
                return pin;
            }

            // Render pin utama buku ini
            renderPin(pinData.x, pinData.y, pinData.label, true);
        });
    </script>
@endpush
