<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Buat Permintaan Barang</title>
    <link rel="icon" type="image/svg+xml" href="{{ asset('favicon.svg') }}">

    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

    <style>
        :root {
            --bg: #eef4ff;
            --panel: rgba(255, 255, 255, 0.9);
            --text: #172554;
            --muted: #64748b;
            --line: #dbe6f7;
            --primary: #4f46e5;
            --secondary: #2563eb;
            --cyan: #38bdf8;
            --shadow-soft: 0 28px 55px rgba(59, 84, 145, 0.10);
            --shadow-card: 0 18px 32px rgba(148, 163, 184, 0.12);
        }

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            color: var(--text);
            background:
                radial-gradient(circle at top left, rgba(79, 70, 229, 0.08), transparent 20%),
                radial-gradient(circle at top right, rgba(56, 189, 248, 0.08), transparent 22%),
                linear-gradient(180deg, #f8fbff 0%, var(--bg) 100%);
            -webkit-font-smoothing: antialiased;
        }

        .app {
            display: flex;
            min-height: 100vh;
        }

        .content {
            flex: 1;
            width: 100%;
            padding: 28px;
        }

        .shell {
            max-width: 1480px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .glass-card {
            background: var(--panel);
            border: 1px solid rgba(255, 255, 255, 0.82);
            box-shadow: var(--shadow-soft);
            backdrop-filter: blur(16px);
        }

        .hero-card {
            overflow: hidden;
            border-radius: 32px;
            padding: 24px;
            background:
                radial-gradient(circle at top right, rgba(99, 102, 241, 0.14), transparent 22%),
                linear-gradient(135deg, rgba(255, 255, 255, 0.98) 0%, rgba(243, 247, 255, 0.96) 100%);
        }

        .pill {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 8px 14px;
            border-radius: 999px;
            background: linear-gradient(135deg, rgba(79, 70, 229, 0.10), rgba(37, 99, 235, 0.08));
            color: var(--primary);
            font-size: 11px;
            font-weight: 800;
            letter-spacing: 0.14em;
            text-transform: uppercase;
            border: 1px solid rgba(99, 102, 241, 0.10);
        }

        .hero-title {
            margin: 16px 0 8px;
            font-size: clamp(30px, 4vw, 44px);
            line-height: 0.98;
            letter-spacing: -0.05em;
            font-weight: 900;
        }

        .hero-text {
            margin: 0;
            color: var(--muted);
            line-height: 1.8;
            font-size: 14px;
            max-width: 760px;
        }

        .form-shell {
            overflow: hidden;
            border-radius: 32px;
            background:
                radial-gradient(circle at top right, rgba(99, 102, 241, 0.12), transparent 22%),
                linear-gradient(135deg, rgba(255, 255, 255, 0.98) 0%, rgba(243, 247, 255, 0.96) 100%);
        }

        .form-head {
            padding: 22px 24px;
            border-bottom: 1px solid rgba(219, 230, 247, 0.95);
            background: rgba(255, 255, 255, 0.58);
        }

        .form-title {
            margin: 0;
            color: #172554;
            font-size: 20px;
            font-weight: 900;
            letter-spacing: -0.04em;
        }

        .form-subtitle {
            margin: 6px 0 0;
            color: var(--muted);
            font-size: 13px;
            line-height: 1.6;
        }

        .inner-panel {
            border-radius: 26px;
            border: 1px solid rgba(219, 230, 247, 0.95);
            background: linear-gradient(180deg, rgba(248, 251, 255, 0.96), rgba(255, 255, 255, 0.98));
            box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.78);
        }

        .section-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
        }

        .section-title {
            margin: 0;
            font-size: 12px;
            font-weight: 800;
            letter-spacing: 0.14em;
            text-transform: uppercase;
            color: var(--muted);
        }

        .section-dot {
            width: 10px;
            height: 10px;
            border-radius: 999px;
            background: linear-gradient(135deg, var(--primary) 0%, var(--cyan) 100%);
            box-shadow: 0 0 0 6px rgba(79, 70, 229, 0.08);
            flex-shrink: 0;
        }

        .field,
        .field-box {
            width: 100%;
            border: 1px solid var(--line);
            border-radius: 18px;
            background: #ffffff;
            color: var(--text);
            padding: 14px 16px;
            outline: none;
            font-size: 14px;
            transition: all 0.2s ease;
            box-shadow: 0 12px 24px rgba(148, 163, 184, 0.08);
        }

        .field:focus {
            border-color: rgba(79, 70, 229, 0.38);
            box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.10);
        }

        .field[type="date"],
        .field[type="datetime-local"] {
            min-height: 58px;
            padding: 16px 18px;
            font-size: 16px;
            font-weight: 900;
            cursor: pointer;
            background: linear-gradient(180deg, #ffffff, #f8fbff);
        }

        .field[type="date"]::-webkit-calendar-picker-indicator,
        .field[type="datetime-local"]::-webkit-calendar-picker-indicator {
            width: 28px;
            height: 28px;
            padding: 6px;
            border-radius: 12px;
            cursor: pointer;
            background-color: #eef2ff;
        }

        .preview-panel {
            display: flex;
            flex-direction: column;
            gap: 16px;
            border-radius: 26px;
            border: 1px solid rgba(219, 230, 247, 0.95);
            background:
                radial-gradient(circle at top left, rgba(79, 70, 229, 0.10), transparent 26%),
                radial-gradient(circle at bottom right, rgba(56, 189, 248, 0.10), transparent 28%),
                linear-gradient(180deg, rgba(248, 251, 255, 0.96), rgba(255, 255, 255, 0.98));
            box-shadow: var(--shadow-card);
        }

        .request-entry-grid {
            display: grid;
            grid-template-columns: 1fr;
            gap: 24px;
            align-items: start;
        }

        .request-input-panel {
            display: flex;
            flex-direction: column;
        }

        .request-input-fields {
            display: grid;
            grid-template-columns: 1fr;
            gap: 20px;
        }

        .request-action-row {
            margin-top: 20px;
        }

        .preview-box {
            width: 100%;
            height: 220px;
            min-height: 220px;
            max-height: 220px;
            border-radius: 24px;
            overflow: hidden;
            border: 1px solid rgba(219, 230, 247, 0.92);
            background:
                radial-gradient(circle at top left, rgba(79, 70, 229, 0.14), transparent 22%),
                radial-gradient(circle at bottom right, rgba(56, 189, 248, 0.12), transparent 24%),
                linear-gradient(180deg, #f8fbff 0%, #eef4ff 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }

        .preview-box img {
            width: 100%;
            height: 100%;
            min-height: 0;
            object-fit: contain;
            background: #ffffff;
        }

        .preview-placeholder {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 10px;
            color: #94a3b8;
            text-align: center;
            padding: 18px;
        }

        .submit-primary {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            box-shadow: 0 18px 28px rgba(79, 70, 229, 0.24);
        }

        .submit-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 22px 30px rgba(79, 70, 229, 0.28);
        }

        @media (max-width:1024px) {
            .app {
                display: block;
            }

            .content {
                padding: 20px;
                padding-top: 80px;
            }
        }

        @media (min-width:768px) {
            .request-input-fields {
                grid-template-columns: repeat(2, minmax(0, 1fr));
            }
        }

        @media (min-width:1024px) {
            .request-entry-grid {
                grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
            }
        }

        @media (max-width:640px) {
            .content {
                padding: 16px;
                padding-top: 80px;
            }

            .hero-card,
            .form-shell {
                border-radius: 24px;
            }
        }
    </style>
</head>

<body>
    <div class="app">
        @include('partials.sidebar')

        <main class="content">
            <div class="shell">
                <section class="hero-card glass-card">
                    <div>
                        <div class="pill">
                            <i data-lucide="file-plus-2" class="w-3.5 h-3.5"></i>
                            Form Pengajuan
                        </div>

                        <h1 class="hero-title">Buat Permintaan Barang</h1>
                        <p class="hero-text">
                            Tambahkan barang ke daftar permintaan, upload surat pengajuan PDF, lalu kirim seluruh list sekaligus ke Sipian.
                        </p>
                    </div>
                </section>

                @if($errors->any())
                <div class="rounded-2xl border border-rose-200 bg-rose-50 px-5 py-4 text-rose-700 shadow-sm">
                    <div class="flex items-start gap-3">
                        <i data-lucide="alert-triangle" class="w-5 h-5 mt-0.5"></i>
                        <div>
                            <div class="font-semibold">Permintaan belum bisa dikirim.</div>
                            <ul class="mt-2 text-sm space-y-1 list-disc list-inside">
                                @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    </div>
                </div>
                @endif

                <form action="{{ route('item-requests.store') }}" method="POST" enctype="multipart/form-data" class="space-y-6">
                    @csrf

                    <div class="grid grid-cols-1 gap-6">
                        <div class="form-shell glass-card">
                            <div class="form-head">
                                <h2 class="form-title">Form Permintaan Barang</h2>
                                <p class="form-subtitle">Pilih barang, cek preview singkatnya, lalu tambahkan ke daftar list barang.</p>
                            </div>

                            <div class="p-6 space-y-6">
                                <div class="request-entry-grid">
                                    <div class="inner-panel p-5 request-input-panel">
                                        <div class="request-input-fields">
                                        <div class="md:col-span-2">
                                            <label class="block text-sm font-semibold text-slate-700 mb-2">Nama Barang</label>
                                            <select id="request_item_id"
                                                class="field">
                                                <option value="">-- Pilih Barang --</option>
                                                @foreach($items as $item)
                                                <option
                                                    value="{{ $item->id }}"
                                                    data-unit="{{ $item->unit }}"
                                                    data-image="{{ $item->image_url }}"
                                                    data-stock="{{ $item->stock }}"
                                                    data-description="{{ $item->description }}"
                                                    data-name="{{ $item->display_name }}">
                                                    {{ $item->display_name }}{{ (float) $item->stock <= 0 ? ' - Stok habis' : '' }}
                                                </option>
                                                @endforeach
                                            </select>
                                        </div>

                                        <div>
                                            <label class="block text-sm font-semibold text-slate-700 mb-2">Jumlah Barang</label>
                                            <div class="flex gap-3">
                                                <input
                                                    type="number"
                                                    id="quantity"
                                                    min="0.01"
                                                    step="1"
                                                    class="field"
                                                    placeholder="Masukkan jumlah">
                                                <div id="unit_badge" class="min-w-[100px] px-4 py-3 rounded-2xl bg-slate-100 text-slate-700 font-semibold text-center border border-slate-200">
                                                    satuan
                                                </div>
                                            </div>
                                            <p id="quantity_hint" class="text-xs text-slate-500 mt-2">Pilih barang terlebih dahulu untuk menyesuaikan jumlah.</p>
                                            <p id="quantity_stock_warning" class="hidden text-rose-600 text-sm mt-2 font-medium"></p>
                                        </div>

                                        <div>
                                            <label class="block text-sm font-semibold text-slate-700 mb-2">Stok Tersedia</label>
                                            <div id="stock_info" class="field-box bg-slate-50 text-slate-700 font-medium">
                                                Pilih barang dulu
                                            </div>
                                        </div>

                                        <div id="stock_unavailable_notice" class="md:col-span-2 hidden rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm font-medium text-rose-700">
                                            Barang yang dipilih sedang habis. Silakan pilih barang lain.
                                        </div>
                                        </div>

                                        <div class="request-action-row">
                                            <button id="add_item_button" type="button"
                                                class="submit-primary inline-flex w-full justify-center items-center gap-2 px-6 py-3 rounded-2xl text-white font-semibold transition shadow-sm">
                                                <i data-lucide="plus" class="w-4 h-4"></i>
                                                Tambah Barang
                                            </button>
                                        </div>
                                    </div>

                                    <div class="preview-panel p-5">
                                        <div class="section-head mb-0">
                                            <h3 class="section-title">Preview Barang</h3>
                                            <span class="section-dot" aria-hidden="true"></span>
                                        </div>

                                        <div class="preview-box">
                                            <img
                                                id="item_preview_image"
                                                src=""
                                                alt="Preview Barang"
                                                class="hidden"
                                                onerror="this.classList.add('hidden'); document.getElementById('item_preview_placeholder').classList.remove('hidden');">
                                            <div id="item_preview_placeholder" class="preview-placeholder">
                                                <i data-lucide="image" class="w-10 h-10"></i>
                                                <div>
                                                    <div class="font-semibold text-slate-600">Preview</div>
                                                    <div class="text-xs text-slate-500 mt-1">Belum ada foto.</div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="hidden">
                                            <span id="item_preview_name">Belum dipilih</span>
                                            <span id="item_preview_description">Pilih barang terlebih dahulu untuk melihat deskripsi.</span>
                                            <span id="item_preview_unit">-</span>
                                            <span id="item_preview_stock">-</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-shell glass-card">
                        <div class="form-head">
                            <h2 class="form-title">Form List Barang</h2>
                            <p class="form-subtitle">Daftar barang yang ingin diminta akan tampil di tabel berikut. Lengkapi surat, tanggal realisasi, lalu kirim permintaan.</p>
                        </div>

                        <div class="p-6 space-y-6">
                            <div class="overflow-x-auto hidden md:block">
                                <table class="min-w-full border-separate border-spacing-0">
                                    <thead>
                                        <tr class="bg-slate-50 text-slate-500">
                                            <th class="px-4 py-3 text-left text-xs font-bold uppercase tracking-[0.14em] rounded-tl-2xl border border-slate-200">Barang</th>
                                            <th class="px-4 py-3 text-left text-xs font-bold uppercase tracking-[0.14em] border-y border-slate-200">Jumlah</th>
                                            <th class="px-4 py-3 text-left text-xs font-bold uppercase tracking-[0.14em] border-y border-slate-200">Satuan</th>
                                            <th class="px-4 py-3 text-left text-xs font-bold uppercase tracking-[0.14em] border-y border-slate-200">Stok</th>
                                            <th class="px-4 py-3 text-right text-xs font-bold uppercase tracking-[0.14em] rounded-tr-2xl border border-slate-200">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody id="request_list_table_body"></tbody>
                                </table>
                            </div>

                            <div id="request_list_mobile" class="md:hidden space-y-3"></div>

                            <div id="request_list_empty" class="rounded-2xl border border-dashed border-slate-300 bg-slate-50 px-6 py-10 text-center text-slate-500">
                                Belum ada barang di dalam list permintaan.
                            </div>

                            <div id="request_items_inputs"></div>

                            <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
                                <div class="lg:col-span-2">
                                    <label class="block text-sm font-semibold text-slate-700 mb-2">Upload Surat Pengajuan (PDF)</label>
                                    <label for="letter_file" class="flex items-center justify-between gap-4 rounded-2xl border border-slate-300 bg-white px-4 py-4 cursor-pointer hover:border-blue-400 transition">
                                        <div class="flex items-center gap-3 min-w-0">
                                            <div class="w-11 h-11 rounded-2xl bg-red-50 border border-red-100 text-red-600 flex items-center justify-center shrink-0">
                                                <i data-lucide="file-text" class="w-5 h-5"></i>
                                            </div>
                                            <div class="min-w-0">
                                                <div class="text-sm font-semibold text-slate-800">Pilih file surat pengajuan</div>
                                                <div id="letter_file_name" class="text-xs text-slate-500 truncate">Belum ada file dipilih</div>
                                            </div>
                                        </div>
                                        <span class="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-slate-100 text-slate-700 text-sm font-semibold">
                                            <i data-lucide="upload" class="w-4 h-4"></i>
                                            Upload PDF
                                        </span>
                                    </label>
                                    <input id="letter_file" name="letter_file" type="file" accept="application/pdf,.pdf" class="hidden" required>
                                    <p class="text-xs text-slate-500 mt-2">Gunakan file PDF yang rapi dan jelas. Ukuran surat tidak boleh lebih dari 2MB agar upload tetap cepat.</p>
                                    <div id="letter_file_actions" class="hidden mt-3">
                                        <button id="view_letter_button" type="button"
                                            class="inline-flex items-center gap-2 px-4 py-2 rounded-2xl bg-red-50 text-red-700 border border-red-200 text-sm font-semibold hover:bg-red-100 transition">
                                            <i data-lucide="file-search" class="w-4 h-4"></i>
                                            View PDF
                                        </button>
                                    </div>
                                </div>

                                <div>
                                    <label class="block text-sm font-semibold text-slate-700 mb-2">Tanggal Permintaan</label>
                                    <input
                                        type="date"
                                        value="{{ now()->format('Y-m-d') }}"
                                        readonly
                                        class="field bg-slate-50">
                                    <p class="text-xs text-slate-500 mt-2">Otomatis mengikuti tanggal hari ini.</p>
                                </div>

                                <div>
                                    <label class="block text-sm font-semibold text-slate-700 mb-2">Tanggal Realisasi</label>
                                    <input
                                        type="date"
                                        id="realization_date"
                                        name="realization_date"
                                        value="{{ old('realization_date', now()->format('Y-m-d')) }}"
                                        min="{{ now()->format('Y-m-d') }}"
                                        class="field"
                                        required>
                                    <p class="text-xs text-slate-500 mt-2">Bisa hari ini atau tanggal setelahnya, tetapi tidak boleh tanggal kemarin.</p>
                                </div>

                                <div class="lg:col-span-2">
                                    <label class="block text-sm font-semibold text-slate-700 mb-2">Keterangan</label>
                                    <textarea
                                        id="purpose"
                                        name="purpose"
                                        rows="4"
                                        placeholder="Contoh: Digunakan untuk kegiatan operasional rapat koordinasi bidang..."
                                        class="field resize-none"
                                        required>{{ old('purpose') }}</textarea>
                                </div>
                            </div>
                        </div>

                        <div class="px-6 pb-6 flex flex-col sm:flex-row gap-3">
                            <button id="submit_request_button" type="submit" disabled
                                class="inline-flex justify-center items-center gap-2 px-6 py-3 rounded-2xl bg-slate-300 text-white font-semibold cursor-not-allowed transition shadow-sm">
                                <i data-lucide="send" class="w-4 h-4"></i>
                                <span id="submit_request_label">Kirim Permintaan</span>
                            </button>

                            <a href="{{ route('item-requests.index') }}"
                                class="inline-flex justify-center items-center gap-2 px-6 py-3 rounded-2xl border border-slate-300 text-slate-700 font-semibold hover:bg-slate-50 transition">
                                <i data-lucide="x" class="w-4 h-4"></i>
                                Cancel
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </main>
    </div>

    @php
        $requestItemsCatalog = $items->map(function ($item) {
            return [
                'id' => $item->id,
                'name' => $item->display_name,
                'unit' => $item->unit,
                'stock' => (float) $item->stock,
                'description' => $item->description,
                'image' => $item->image_url,
            ];
        })->values();
    @endphp

    <script>
        const requestItemsCatalog = @json($requestItemsCatalog);
        const oldRequestItems = @json(array_values(old('items', [])));
    </script>

    <script>
        const itemMap = Object.fromEntries(requestItemsCatalog.map((item) => [String(item.id), item]));
        const selectedItems = [];

        const itemSelect = document.getElementById('request_item_id');
        const quantityInput = document.getElementById('quantity');
        const addItemButton = document.getElementById('add_item_button');
        const stockInfo = document.getElementById('stock_info');
        const unitBadge = document.getElementById('unit_badge');
        const quantityHint = document.getElementById('quantity_hint');
        const quantityWarning = document.getElementById('quantity_stock_warning');
        const stockNotice = document.getElementById('stock_unavailable_notice');
        const tableBody = document.getElementById('request_list_table_body');
        const mobileList = document.getElementById('request_list_mobile');
        const emptyState = document.getElementById('request_list_empty');
        const hiddenInputs = document.getElementById('request_items_inputs');
        const submitButton = document.getElementById('submit_request_button');
        const letterFileInput = document.getElementById('letter_file');
        const letterFileName = document.getElementById('letter_file_name');
        const letterFileActions = document.getElementById('letter_file_actions');
        const viewLetterButton = document.getElementById('view_letter_button');

        const previewImage = document.getElementById('item_preview_image');
        const previewPlaceholder = document.getElementById('item_preview_placeholder');
        const previewName = document.getElementById('item_preview_name');
        const previewUnit = document.getElementById('item_preview_unit');
        const previewStock = document.getElementById('item_preview_stock');
        const previewDescription = document.getElementById('item_preview_description');

        function formatNumber(value) {
            return new Intl.NumberFormat('id-ID', {
                minimumFractionDigits: 0,
                maximumFractionDigits: 2,
            }).format(Number(value));
        }

        function selectedCatalogItem() {
            return itemMap[itemSelect.value] || null;
        }

        function syncPreview() {
            const item = selectedCatalogItem();

            if (!item) {
                previewImage.src = '';
                previewImage.classList.add('hidden');
                previewPlaceholder.classList.remove('hidden');
                previewName.textContent = 'Belum dipilih';
                previewUnit.textContent = '-';
                previewStock.textContent = '-';
                previewDescription.textContent = 'Pilih barang terlebih dahulu untuk melihat deskripsi.';
                stockInfo.textContent = 'Pilih barang dulu';
                unitBadge.textContent = 'satuan';
                quantityInput.step = '1';
                quantityHint.textContent = 'Pilih barang terlebih dahulu untuk menyesuaikan jumlah.';
                quantityWarning.classList.add('hidden');
                stockNotice.classList.add('hidden');
                addItemButton.disabled = false;
                addItemButton.className = 'submit-primary inline-flex w-full justify-center items-center gap-2 px-6 py-3 rounded-2xl text-white font-semibold transition shadow-sm';
                return;
            }

            if (item.image) {
                previewImage.src = item.image;
                previewImage.classList.remove('hidden');
                previewPlaceholder.classList.add('hidden');
            } else {
                previewImage.src = '';
                previewImage.classList.add('hidden');
                previewPlaceholder.classList.remove('hidden');
            }
            previewName.textContent = item.name;
            previewUnit.textContent = item.unit;
            previewStock.textContent = `${formatNumber(item.stock)} ${item.unit}`;
            previewDescription.textContent = item.description || 'Tidak ada deskripsi barang.';
            stockInfo.textContent = `${formatNumber(item.stock)} ${item.unit}`;
            unitBadge.textContent = item.unit;
            quantityInput.step = item.unit === 'meter' ? '0.01' : '1';
            quantityHint.textContent = item.unit === 'meter'
                ? 'Barang satuan meter boleh memakai angka desimal.'
                : 'Barang satuan pcs atau unit harus menggunakan angka bulat.';

            if (item.stock <= 0) {
                quantityWarning.textContent = 'Stok barang ini habis.';
                quantityWarning.classList.remove('hidden');
                stockNotice.classList.remove('hidden');
                addItemButton.disabled = true;
                addItemButton.className = 'inline-flex w-full justify-center items-center gap-2 px-6 py-3 rounded-2xl bg-slate-300 text-white font-semibold cursor-not-allowed transition shadow-sm';
            } else {
                quantityWarning.classList.add('hidden');
                stockNotice.classList.add('hidden');
                addItemButton.disabled = false;
                addItemButton.className = 'submit-primary inline-flex w-full justify-center items-center gap-2 px-6 py-3 rounded-2xl text-white font-semibold transition shadow-sm';
            }
        }

        function renderSelectedItems() {
            tableBody.innerHTML = '';
            mobileList.innerHTML = '';
            hiddenInputs.innerHTML = '';

            if (!selectedItems.length) {
                emptyState.classList.remove('hidden');
            } else {
                emptyState.classList.add('hidden');
            }

            selectedItems.forEach((row, index) => {
                tableBody.insertAdjacentHTML('beforeend', `
                    <tr class="bg-white">
                        <td class="px-4 py-4 border-x border-b border-slate-200 align-top">
                            <div class="flex items-center gap-3 min-w-[280px]">
                                <img src="${row.image || 'https://via.placeholder.com/80x80?text=No+Image'}" alt="${row.name}" class="w-14 h-14 rounded-2xl object-cover border border-slate-200 bg-slate-50">
                                <div>
                                    <div class="font-semibold text-slate-900">${row.name}</div>
                                    <div class="text-xs text-slate-500 mt-1">${row.description || 'Tanpa deskripsi.'}</div>
                                </div>
                            </div>
                        </td>
                        <td class="px-4 py-4 border-b border-slate-200 text-slate-800 font-semibold">${formatNumber(row.quantity)}</td>
                        <td class="px-4 py-4 border-b border-slate-200 text-slate-600">${row.unit}</td>
                        <td class="px-4 py-4 border-b border-slate-200 text-slate-600">${formatNumber(row.stock)} ${row.unit}</td>
                        <td class="px-4 py-4 border-x border-b border-slate-200 text-right">
                            <button type="button" data-remove-index="${index}" class="inline-flex items-center gap-2 px-3 py-2 rounded-xl border border-rose-200 text-rose-600 hover:bg-rose-50 text-sm font-semibold">
                                <i data-lucide="trash-2" class="w-4 h-4"></i>
                                Hapus
                            </button>
                        </td>
                    </tr>
                `);

                mobileList.insertAdjacentHTML('beforeend', `
                    <div class="rounded-3xl border border-slate-200 bg-white p-4 shadow-sm">
                        <div class="flex gap-3">
                            <img src="${row.image || 'https://via.placeholder.com/80x80?text=No+Image'}" alt="${row.name}" class="w-16 h-16 rounded-2xl object-cover border border-slate-200 bg-slate-50">
                            <div class="flex-1 min-w-0">
                                <div class="font-semibold text-slate-900">${row.name}</div>
                                <div class="text-xs text-slate-500 mt-1">${row.description || 'Tanpa deskripsi.'}</div>
                                <div class="mt-3 flex flex-wrap gap-2 text-xs">
                                    <span class="inline-flex px-3 py-1 rounded-full bg-blue-100 text-blue-700 border border-blue-200">${formatNumber(row.quantity)} ${row.unit}</span>
                                    <span class="inline-flex px-3 py-1 rounded-full bg-slate-100 text-slate-700 border border-slate-200">Stok ${formatNumber(row.stock)} ${row.unit}</span>
                                </div>
                                <button type="button" data-remove-index="${index}" class="mt-3 inline-flex items-center gap-2 px-3 py-2 rounded-xl border border-rose-200 text-rose-600 hover:bg-rose-50 text-sm font-semibold">
                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                    Hapus
                                </button>
                            </div>
                        </div>
                    </div>
                `);

                hiddenInputs.insertAdjacentHTML('beforeend', `
                    <input type="hidden" name="items[${index}][request_item_id]" value="${row.id}">
                    <input type="hidden" name="items[${index}][quantity]" value="${row.quantity}">
                `);
            });

            lucide.createIcons();
            syncSubmitState();
        }

        function syncSubmitState() {
            const ready = selectedItems.length > 0 && letterFileInput.files.length > 0;

            submitButton.disabled = !ready;
            submitButton.className = ready
                ? 'submit-primary inline-flex justify-center items-center gap-2 px-6 py-3 rounded-2xl text-white font-semibold transition shadow-sm'
                : 'inline-flex justify-center items-center gap-2 px-6 py-3 rounded-2xl bg-slate-300 text-white font-semibold cursor-not-allowed transition shadow-sm';
        }

        function resetItemForm() {
            itemSelect.value = '';
            quantityInput.value = '';
            syncPreview();
        }

        function addSelectedItem() {
            const item = selectedCatalogItem();
            const quantityValue = quantityInput.value.trim();

            if (!item) {
                quantityWarning.textContent = 'Pilih barang terlebih dahulu.';
                quantityWarning.classList.remove('hidden');
                return;
            }

            if (selectedItems.some((row) => String(row.id) === String(item.id))) {
                quantityWarning.textContent = 'Barang ini sudah ada di list permintaan.';
                quantityWarning.classList.remove('hidden');
                return;
            }

            if (!quantityValue) {
                quantityWarning.textContent = 'Isi jumlah barang terlebih dahulu.';
                quantityWarning.classList.remove('hidden');
                return;
            }

            const quantity = Number(quantityValue);

            if (Number.isNaN(quantity) || quantity <= 0) {
                quantityWarning.textContent = 'Jumlah barang harus lebih dari nol.';
                quantityWarning.classList.remove('hidden');
                return;
            }

            if (item.unit !== 'meter' && !Number.isInteger(quantity)) {
                quantityWarning.textContent = 'Untuk barang satuan pcs atau unit, jumlah harus angka bulat.';
                quantityWarning.classList.remove('hidden');
                return;
            }

            if (quantity > Number(item.stock)) {
                quantityWarning.textContent = `Jumlah melebihi stok tersedia. Maksimal ${formatNumber(item.stock)} ${item.unit}.`;
                quantityWarning.classList.remove('hidden');
                return;
            }

            quantityWarning.classList.add('hidden');
            selectedItems.push({
                id: item.id,
                name: item.name,
                unit: item.unit,
                stock: item.stock,
                description: item.description,
                image: item.image,
                quantity: item.unit === 'meter' ? quantity.toFixed(2) : String(quantity),
            });
            renderSelectedItems();
            resetItemForm();
        }

        itemSelect.addEventListener('change', syncPreview);
        addItemButton.addEventListener('click', addSelectedItem);
        letterFileInput.addEventListener('change', () => {
            letterFileName.textContent = letterFileInput.files.length ? letterFileInput.files[0].name : 'Belum ada file dipilih';
            letterFileActions.classList.toggle('hidden', !letterFileInput.files.length);
            syncSubmitState();
            lucide.createIcons();
        });

        viewLetterButton.addEventListener('click', () => {
            if (!letterFileInput.files.length) {
                return;
            }

            const file = letterFileInput.files[0];
            const fileUrl = URL.createObjectURL(file);
            window.open(fileUrl, '_blank', 'noopener,noreferrer');
        });

        document.addEventListener('click', (event) => {
            const removeButton = event.target.closest('[data-remove-index]');
            if (!removeButton) {
                return;
            }

            const index = Number(removeButton.dataset.removeIndex);
            selectedItems.splice(index, 1);
            renderSelectedItems();
        });

        oldRequestItems.forEach((row) => {
            const item = itemMap[String(row.request_item_id)];

            if (!item) {
                return;
            }

            selectedItems.push({
                id: item.id,
                name: item.name,
                unit: item.unit,
                stock: item.stock,
                description: item.description,
                image: item.image,
                quantity: row.quantity,
            });
        });

        syncPreview();
        renderSelectedItems();
        lucide.createIcons();
    </script>
    @include('partials.custom-calendar')
</body>

</html>
