<div>
    {{-- هدر صفحه --}}
    <link href="https://cdn.jsdelivr.net/npm/jodit@latest/es2021/jodit.fat.min.css" rel="stylesheet">
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            افزودن یادداشت جدید برای طرح: <span class="font-bold text-blue-600 dark:text-blue-400">{{ $project->title }}</span>
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            {{-- نمایش پیام‌های موفقیت یا خطا --}}
            @if (session()->has('message'))
                <div class="mb-6 p-4 text-sm text-green-800 bg-green-100 rounded-lg dark:bg-green-900 dark:text-green-300 shadow-md" role="alert">
                    <span class="font-medium">موفقیت!</span> {{ session('message') }}
                </div>
            @endif

            <form wire:submit.prevent="save">
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

                    {{-- ستون اصلی (دو سوم) برای فرم و ویرایشگر --}}
                    <div class="md:col-span-2">
                        <div
                            class="bg-white dark:bg-gray-800 overflow-hidden shadow-xl sm:rounded-lg p-6"
                            x-data="{
                                editor: null,
                                initEditor() {
                                    Alpine.nextTick(() => {
                                        if (typeof Jodit === 'undefined') { return; }
                                        if (this.editor) this.editor.destruct();
                                        this.editor = Jodit.make(this.$refs.editor, {
                                            direction: 'rtl',
                                            language: 'fa',
                                            height: 400,
                                        });
                                        this.editor.value = @this.get('body');
                                        this.editor.events.on('change', (newValue) => {
                                            @this.set('body', newValue, false);
                                        });
                                    });
                                },
                                // [FIXED] This function now correctly listens for the event
                                updateEditor(content) {
                                    if (this.editor) {
                                        this.editor.setEditorValue(content);
                                    }
                                }
                            }"
                            x-init="initEditor()"
                            {{-- [FIXED] The event listener is now correctly placed here --}}
                            @update-editor-content.window="updateEditor($event.detail.content)"
                            @insert-text-in-editor.window="if(editor) { editor.s.insertHTML($event.detail.text); }"

                        >
                            <div class="p-6 sm:p-8 space-y-6">
                                {{-- [NEW] Template Selection --}}
                                @if($templates->isNotEmpty())
                                    <div class="p-4 bg-gray-50 dark:bg-gray-900/50 rounded-lg border dark:border-gray-700">
                                        <h3 class="font-semibold text-gray-800 dark:text-gray-200">استفاده از قالب آماده</h3>
                                        <div class="mt-2 grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
                                            <div class="md:col-span-2">
                                                <select wire:model="selectedTemplateId" class="mt-1 block w-full border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 rounded-md shadow-sm">
                                                    <option value="">-- انتخاب کنید --</option>
                                                    @foreach($templates as $template)
                                                        <option value="{{ $template->id }}">{{ $template->title }}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            <div>
                                                <x-secondary-button type="button" wire:click="applyTemplate" class="w-full justify-center">
                                                    اعمال قالب
                                                </x-secondary-button>
                                            </div>
                                        </div>
                                    </div>
                                @endif
                                {{-- Title --}}
                                <div>
                                    <x-label for="title" value="عنوان یادداشت" />
                                    <x-input id="title" type="text" class="mt-1 block w-full" wire:model.defer="title" placeholder="مثال: نتایج آزمایش فاز اول" />
                                    <x-input-error for="title" class="mt-2" />
                                </div>

                                <div>
                                    <x-label for="entry_date" value="تاریخ انجام آزمایش" />
                                    <x-jalali-date-picker id="entry_date" wire:model="entry_date" />
                                    <x-input-error for="entry_date" class="mt-2" />
                                </div>
                                {{-- [NEW] Custom Editor Toolbar --}}
                                <div class="flex justify-between items-center border-b dark:border-gray-700 pb-2">
                                    <x-label for="body" value="{{ __('محتوای یادداشت') }}" />
                                    <div class="flex items-center gap-2">
                                        {{-- [NEW] Preview Content Button --}}
                                        <button type="button" wire:click="generatePreview" class="p-2 text-white/50 hover:text-cyan-600 rounded-full hover:bg-cyan-100 dark:hover:bg-cyan-900/50 transition" title="پیش‌نمایش محتوا">
                                            <x-lucide-eye class="w-5 h-5"/>
                                        </button>
                                        <button type="button" wire:click="openEntrySelector" class="p-2 text-white/50 hover:text-purple-600 rounded-full hover:bg-purple-100 dark:hover:bg-purple-900/50 transition" title="درج ارجاع به یادداشت">
                                            <x-lucide-link-2 class="w-5 h-5"/>
                                        </button>
                                    </div>
                                </div>
                                {{-- Jodit Editor Container --}}
                                <div wire:ignore>
                                    <x-label for="body" value="محتوای یادداشت"/>
                                    <textarea x-ref="editor" id="body_note"></textarea>
                                </div>
                                <x-input-error for="body" class="mt-2" />
                                {{-- [NEW] Attachments Section --}}
                                {{-- [REWRITTEN] بخش آپلود فایل با قابلیت Drag & Drop --}}
                                <div
                                    x-data="{ isDragging: false }"
                                    class="border-t dark:border-gray-700 pt-4"
                                >
                                    <x-label for="attachments" value="پیوست فایل‌ها (PDF, JPG, PNG)" />

                                    <div
                                        @dragover.prevent="isDragging = true"
                                        @dragleave.prevent="isDragging = false"
                                        @drop.prevent="isDragging = false; @this.uploadMultiple('newAttachments', $event.dataTransfer.files)"
                                        :class="{'border-blue-500 bg-blue-50 dark:bg-blue-900/20': isDragging}"
                                        class="mt-1 flex justify-center rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-600 px-6 py-10 transition-colors"
                                    >
                                        <div class="text-center">
                                            <x-lucide-upload-cloud class="mx-auto h-12 w-12 text-gray-400" />
                                            <div class="mt-4 flex text-sm leading-6 text-gray-600 dark:text-gray-400">
                                                <label for="attachments-input" class="relative cursor-pointer rounded-md font-semibold text-indigo-600 dark:text-indigo-400 focus-within:outline-none hover:text-indigo-500">
                                                    <span>فایل‌های خود را انتخاب کنید</span>
                                                    {{-- [CORRECTED] اتصال به پراپرتی جدید --}}
                                                    <input id="attachments-input" wire:model="newAttachments" type="file" class="sr-only" multiple>
                                                </label>
                                                <p class="pl-1">یا آن‌ها را بکشید و در اینجا رها کنید</p>
                                            </div>
                                            <p class="text-xs leading-5 text-gray-500">PDF, PNG, JPG up to 10MB</p>
                                        </div>
                                    </div>
                                    <x-input-error for="newAttachments.*" class="mt-2" />

                                    {{-- نمایش لیست فایل‌های پیوست شده --}}
                                    @if ($attachments)
                                        <div class="mt-4 border-t dark:border-gray-700 pt-4">
                                            <div class="flex justify-between items-center">
                                                <p class="text-sm font-medium">فایل‌های پیوست شده:</p>
                                                <button type="button" wire:click="editAttachments" class="text-sm font-semibold text-indigo-600 hover:underline">
                                                    ویرایش کپشن‌ها
                                                </button>
                                            </div>
                                            <ul class="mt-2 space-y-3">
                                                @foreach ($attachments as $index => $file)
                                                    <li class="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg flex items-center justify-between">
                                                        <div class="flex items-center gap-3">
                                                            @if(Str::startsWith($file->getMimeType(), 'image'))
                                                                <img src="{{ $file->temporaryUrl() }}" class="w-12 h-12 object-cover rounded-md">
                                                            @else
                                                                <div class="w-12 h-12 bg-gray-200 rounded-md flex items-center justify-center">
                                                                    <x-lucide-file-text class="w-6 h-6 text-gray-400"/>
                                                                </div>
                                                            @endif
                                                            <div class="flex-1">
                                                                <p class="text-sm font-semibold">{{ $file->getClientOriginalName() }}</p>
                                                                <p class="text-xs text-gray-500">{{ $attachmentCaptions[$index] ?? 'بدون کپشن' }}</p>
                                                            </div>
                                                        </div>
                                                        <button type="button" wire:click="removeAttachment({{ $index }})" class="text-red-500 hover:text-red-700">
                                                            <x-lucide-x class="w-4 h-4"/>
                                                        </button>
                                                    </li>
                                                @endforeach
                                            </ul>
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>


                        {{-- کارت مواد و معرف‌های مصرفی --}}
                        {{-- کارت مواد و معرف‌های مصرفی --}}
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg border-t-4 border-blue-600">
                            <div class="p-6 sm:p-8">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-1">
                                    مواد و معرف‌های مصرفی
                                </h3>
                                <p class="text-sm text-gray-500 dark:text-gray-400 mb-6">مواد مصرفی مجاز در این طرح را از لیست بودجه جستجو و اضافه کنید.</p>
                                <div class="space-y-6">
                                    <div class="relative">
                                        <x-label for="materialSearch" value="جستجوی آیتم انبار" />
                                        <div class="relative mt-1">
                                            <x-input id="materialSearch" type="text" class="w-full pl-10"
                                                     wire:model.live.debounce.300ms="materialSearch"
                                                     placeholder="جستجو بر اساس نام یا کد شناسایی..."
                                                     autocomplete="off" />
                                            <div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                                                <x-lucide-search class="w-5 h-5 text-gray-400" />
                                            </div>
                                        </div>
                                        @if(count($materialSearchResults) > 0)
                                            <ul class="absolute z-20 w-full bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md mt-1 max-h-56 overflow-auto shadow-lg">
                                                @foreach($materialSearchResults as $result)
                                                    <li class="px-4 py-3 cursor-pointer hover:bg-blue-50 dark:hover:bg-blue-900/50"
                                                        wire:click="addMaterial({{ $result->id }})">
                                                        <div class="font-bold text-gray-800 dark:text-gray-200">{{ $result->name }}</div>
                                                        <div class="text-sm text-gray-500 dark:text-gray-400">شناسه: {{ $result->sku }} | موجودی: {{ $result->quantity }} {{ $result->unit }}</div>
                                                    </li>
                                                @endforeach
                                            </ul>
                                        @endif
                                    </div>

                                    <div class="space-y-3">
                                        @forelse ($usedMaterials as $index => $material)
                                            <div class="flex items-center gap-4 p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700">
                                                <div class="flex-grow">
                                                    <p class="font-medium text-gray-900 dark:text-gray-200">{{ $material['name'] }}</p>
                                                    <p class="text-xs text-gray-500 dark:text-gray-400">شناسه: {{ $material['sku'] }}</p>
                                                </div>
                                                <div class="w-32">
                                                    <x-input type="number" step="any" class="block w-full text-center"
                                                             placeholder="مقدار"
                                                             wire:model.defer="usedMaterials.{{ $index }}.quantity_used" />
                                                </div>
                                                <span class="text-sm text-gray-600 dark:text-gray-300 w-12 text-right">{{ $material['unit'] }}</span>
                                                <button type="button" wire:click="removeMaterial({{ $material['id'] }})" class="text-gray-400 hover:text-red-600 transition duration-150">
                                                    <x-lucide-trash-2 class="w-5 h-5" />
                                                </button>
                                            </div>
                                        @empty
                                            <div class="text-center py-8 border-2 border-dashed border-gray-300 dark:border-gray-700 rounded-lg">
                                                <x-lucide-beaker class="mx-auto h-12 w-12 text-gray-400" />
                                                <h3 class="mt-2 text-sm font-medium text-gray-900 dark:text-white">هیچ ماده‌ای اضافه نشده</h3>
                                                <p class="mt-1 text-sm text-gray-500">برای شروع، یک آیتم را جستجو کنید.</p>
                                            </div>
                                        @endforelse
                                        <x-input-error for="usedMaterials.*.quantity_used" class="mt-2" />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- ستون کناری (یک سوم) برای دکمه‌ها و اطلاعات --}}
                    <div class="lg:col-span-1 space-y-8">
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg border-t-4 border-blue-600 p-6">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                                شناسه یادداشت
                            </h3>
                            <div class="flex items-center justify-center h-12 w-full bg-gray-100 dark:bg-gray-900/50 rounded-lg border border-gray-300 dark:border-gray-700">
                                <span class="text-gray-700 dark:text-gray-300 font-mono text-lg tracking-widest">{{ $generatedSku }}</span>
                            </div>
                        </div>
                        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg border-t-4 border-blue-600 p-6 sticky top-24">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                                عملیات
                            </h3>
                            <div class="mt-4 space-y-4">
                                <button type="submit" class="w-full inline-flex items-center justify-center px-4 py-3 bg-blue-600 border border-transparent rounded-lg font-semibold text-sm text-white uppercase tracking-widest hover:bg-blue-700 active:bg-blue-800 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition ease-in-out duration-150 shadow-md">
                                    <x-lucide-save class="w-5 h-5 ml-2" />
                                    ذخیره یادداشت
                                </button>
                                <a href="{{ route('projects.show', $project) }}" class="w-full inline-flex items-center justify-center px-4 py-3 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg font-semibold text-sm text-gray-800 dark:text-gray-200 uppercase tracking-widest hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition ease-in-out duration-150">
                                    انصراف
                                </a>
                            </div>
                        </div>
                    </div>

                </div>
            </form>
        </div>
    </div>
    {{-- [NEW] مودال مدیریت پیوست‌ها و کپشن‌ها --}}
    <x-dialog-modal wire:model.live="confirmingAttachments" maxWidth="2xl">
        <x-slot name="title">
            مدیریت پیوست‌ها
        </x-slot>
        <x-slot name="content">
            <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
                در صورت تمایل، می‌توانید برای هر فایل یک کپشن (توضیح کوتاه) بنویسید.
            </p>
            <div class="space-y-4 max-h-96 overflow-y-auto">
                @foreach($attachments as $index => $attachment)
                    <div class="p-4 border rounded-lg flex items-start gap-4">
                        @if(Str::startsWith($attachment->getMimeType(), 'image'))
                            <img src="{{ $attachment->temporaryUrl() }}" class="w-24 h-24 object-cover rounded-md">
                        @else
                            <div class="w-24 h-24 bg-gray-100 rounded-md flex items-center justify-center">
                                <x-lucide-file-text class="w-10 h-10 text-gray-400"/>
                            </div>
                        @endif
                        <div class="flex-1">
                            <p class="text-sm font-semibold">{{ $attachment->getClientOriginalName() }}</p>
                            <x-input type="text" class="w-full mt-2" wire:model="attachmentCaptions.{{ $index }}" placeholder="کپشن (اختیاری)..." />
                        </div>
                    </div>
                @endforeach
            </div>
        </x-slot>
        <x-slot name="footer">
            <x-button @click="show = false">
                تایید و ادامه
            </x-button>
        </x-slot>
    </x-dialog-modal>

    {{-- [REWRITTEN] مودال هوشمند برای خطاها و هشدارها --}}
    <x-dialog-modal wire:model.live="confirmingStockError">
        <x-slot name="title">
            <span class="flex items-center {{ $hasHardErrors ? 'text-red-600' : 'text-yellow-500' }}">
                @if($hasHardErrors)
                    <x-lucide-ban class="w-6 h-6 ml-2"/>
                    خطای اعتبارسنجی
                @else
                    <x-lucide-alert-triangle class="w-6 h-6 ml-2"/>
                    هشدار موجودی انبار
                @endif
            </span>
        </x-slot>
        <x-slot name="content">
            <div class="mt-4 text-sm text-gray-700 dark:text-gray-300 space-y-2">
                {!! $stockErrorMessage !!}
            </div>
        </x-slot>
        <x-slot name="footer">
            @if($hasHardErrors)
                <x-secondary-button wire:click="$set('confirmingStockError', false)" class="ms-3">
                    {{ __('متوجه شدم') }}
                </x-secondary-button>
            @else
                <x-secondary-button wire:click="$set('confirmingStockError', false)" wire:loading.attr="disabled">
                    {{ __('انصراف') }}
                </x-secondary-button>
                <x-button class="ms-3" wire:click="proceedWithSave" wire:loading.attr="disabled">
                    {{ __('ادامه و ارسال درخواست') }}
                </x-button>
            @endif
        </x-slot>
    </x-dialog-modal>

    <!-- [NEW] Modal to select an entry for cross-linking -->
    <x-dialog-modal wire:model.live="showEntrySelectorModal" maxWidth="2xl">
        <x-slot name="title">
            <div class="flex items-center">
                <x-lucide-link-2 class="w-6 h-6 ml-2 text-purple-500"/>
                <span class="text-lg font-bold">انتخاب یادداشت برای ارجاع</span>
            </div>
        </x-slot>
        <x-slot name="content">
            <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
                روی یادداشت مورد نظر کلیک کنید تا شناسه‌ی آن (`[[identityId]]`) در ویرایشگر درج شود.
            </p>
            <div class="space-y-2 max-h-[60vh] overflow-y-auto border-t border-b dark:border-gray-700 py-2">
                @forelse($projectEntries as $projectEntry)
                    <div wire:click="insertEntrySku('{{ $projectEntry->sku }}')"
                         class="p-3 rounded-lg hover:bg-purple-50 dark:hover:bg-purple-900/50 cursor-pointer transition">
                        <p class="font-semibold text-gray-800 dark:text-black">{{ $projectEntry->title }}</p>
                        <p class="text-xs text-gray-500 dark:text-blue-500 font-mono">{{ $projectEntry->sku }}</p>
                    </div>
                @empty
                    <div class="text-center py-8 text-gray-500">
                        <p>یادداشتی برای ارجاع در این طرح یافت نشد.</p>
                    </div>
                @endforelse
            </div>
        </x-slot>
        <x-slot name="footer">
            <x-secondary-button wire:click="$set('showEntrySelectorModal', false)">
                {{ __('انصراف') }}
            </x-secondary-button>
        </x-slot>
    </x-dialog-modal>
    <!-- [NEW] Modal for Content Preview -->
    <x-dialog-modal wire:model.live="showContentPreviewModal" maxWidth="2xl">
        <x-slot name="title">
            <div class="flex items-center">
                <x-lucide-eye class="w-6 h-6 ml-2 text-cyan-500"/>
                <span class="text-lg font-bold">پیش‌نمایش محتوا</span>
            </div>
        </x-slot>
        <x-slot name="content">
            <div class="prose dark:prose-invert max-w-none mt-4 max-h-[70vh] overflow-y-auto pr-2 jodit-container">
                {!! $previewHtml !!}
            </div>
        </x-slot>
        <x-slot name="footer">
            <x-secondary-button wire:click="$set('showContentPreviewModal', false)">
                {{ __('بستن') }}
            </x-secondary-button>
        </x-slot>
    </x-dialog-modal>

    <!-- [NEW] Modal for Linked Entry Preview -->
    <x-dialog-modal wire:model.live="showPreviewModal" maxWidth="2xl">
        <x-slot name="title">
            <div class="flex items-center">
                <x-lucide-file-search class="w-6 h-6 ml-2 text-blue-500"/>
                <span class="text-lg font-bold">پیش‌نمایش یادداشت ارجاع داده شده</span>
            </div>
        </x-slot>
        <x-slot name="content">
            @if ($previewingEntry)
                <div class="space-y-4">
                    <h2 class="text-2xl font-bold text-gray-900 dark:text-white">{{ $previewingEntry->title }}</h2>
                    <div class="text-sm text-gray-500 dark:text-gray-400 border-b dark:border-gray-700 pb-3">
                        <span>ثبت توسط: {{ $previewingEntry->user->full_name }}</span>
                        <span class="mx-2">|</span>
                        <span>شناسه: {{ $previewingEntry->sku }}</span>
                    </div>
                    <div class="prose dark:prose-invert max-w-none mt-4 max-h-[60vh] overflow-y-auto pr-2 jodit-container">
                        {!! $previewingEntry->processed_body !!}
                    </div>
                </div>
            @endif
        </x-slot>
        <x-slot name="footer">
            <x-secondary-button wire:click="$set('showPreviewModal', false)">
                {{ __('بستن') }}
            </x-secondary-button>
        </x-slot>
    </x-dialog-modal>

    <script src="https://cdn.jsdelivr.net/npm/jodit@latest/es2021/jodit.fat.min.js"></script>
</div>
