---
import ReviewCard from './ReviewCard.astro';

interface Props {
    reviews: any[];
    currentUserId?: string;
    isAdmin?: boolean;
}

const { reviews, currentUserId, isAdmin } = Astro.props;
---

<!-- 1. Список отзывов -->
<div class="grid grid-cols-1 gap-6 mb-12" id="reviews-list">
    {reviews.map((review) => (
            <ReviewCard
                    review={review}
                    currentUserId={currentUserId}
                    isAdmin={isAdmin}
            />
    ))}
</div>

<!-- 2. Модальное окно (по умолчанию скрыто классом hidden) -->
<div id="delete-modal" class="relative z-[150] hidden" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <!-- Затемнение фона -->
    <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity backdrop-blur-sm" id="modal-backdrop"></div>

    <div class="fixed inset-0 z-10 w-screen overflow-y-auto">
        <div class="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">

            <!-- Карточка модального окна -->
            <div class="relative transform overflow-hidden rounded-lg bg-white text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg">
                <div class="bg-white px-4 pb-4 pt-5 sm:p-6 sm:pb-4">
                    <div class="sm:flex sm:items-start">
                        <div class="mx-auto flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                            <svg class="h-6 w-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                            </svg>
                        </div>
                        <div class="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left">
                            <h3 class="text-base font-semibold leading-6 text-gray-900" id="modal-title">Bewertung löschen</h3>
                            <div class="mt-2">
                                <p class="text-sm text-gray-500">Möchten Sie diese Bewertung wirklich unwiderruflich löschen? Diese Aktion kann nicht rückgängig gemacht werden.</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Кнопки -->
                <div class="bg-gray-50 px-4 py-3 sm:flex sm:flex-row-reverse sm:px-6">
                    <button type="button" id="confirm-delete-btn" class="inline-flex w-full justify-center rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-500 sm:ml-3 sm:w-auto cursor-pointer transition-colors">
                        Löschen
                    </button>
                    <button type="button" id="cancel-delete-btn" class="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:mt-0 sm:w-auto cursor-pointer transition-colors">
                        Abbrechen
                    </button>
                </div>
            </div>

        </div>
    </div>
</div>

<script>
    // === 1. TOAST ФУНКЦИЯ ===
    function showToast(message: string, type: 'success' | 'error' = 'success') {
        const config = {
            success: { bg: 'bg-white border-green-500', text: 'text-gray-800', iconColor: 'text-green-500', iconPath: 'M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z' },
            error: { bg: 'bg-white border-red-500', text: 'text-gray-800', iconColor: 'text-red-500', iconPath: 'M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z' }
        };
        const currentConfig = config[type];

        // Удаляем старые тосты, если есть, чтобы не накладывались
        const oldToast = document.querySelector('.js-toast');
        if (oldToast) oldToast.remove();

        const toast = document.createElement('div');
        toast.className = `js-toast fixed top-5 left-1/2 transform -translate-x-1/2 z-[200] flex items-center w-full max-w-sm p-4 mb-4 text-gray-500 bg-white rounded-lg shadow-xl border-l-4 transition-all duration-500 ease-in-out opacity-0 -translate-y-full ${currentConfig.bg}`;
        toast.innerHTML = `
        <div class="inline-flex items-center justify-center flex-shrink-0 w-8 h-8 rounded-lg ${currentConfig.iconColor} bg-opacity-10">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="${currentConfig.iconPath}" clip-rule="evenodd"></path></svg>
        </div>
        <div class="ml-3 text-sm font-medium ${currentConfig.text}">${message}</div>
    `;
        document.body.appendChild(toast);

        requestAnimationFrame(() => {
            toast.classList.remove('opacity-0', '-translate-y-full');
            toast.classList.add('opacity-100', 'translate-y-0');
        });
        setTimeout(() => {
            toast.classList.add('opacity-0', '-translate-y-full');
            setTimeout(() => toast.remove(), 500);
        }, 4000);
    }

    // === 2. ОСНОВНАЯ ЛОГИКА ===
    document.addEventListener('DOMContentLoaded', () => {
        // Получаем элементы
        const modal = document.getElementById('delete-modal');
        const confirmBtn = document.getElementById('confirm-delete-btn');
        const cancelBtn = document.getElementById('cancel-delete-btn');
        const backdrop = document.getElementById('modal-backdrop');
        const reviewList = document.getElementById('reviews-list');

        // Проверка, что элементы найдены (важно для отладки)
        if (!modal || !confirmBtn || !cancelBtn || !reviewList) {
            console.error("Critical elements not found in DOM");
            return;
        }

        let deleteId: string | null = null;
        let deleteCard: HTMLElement | null = null;

        // --- ФУНКЦИИ ---

        // Открыть модалку
        const openModal = (id: string, card: HTMLElement) => {
            console.log('Opening modal for ID:', id);
            deleteId = id;
            deleteCard = card;
            modal.classList.remove('hidden');
        };

        // Закрыть модалку
        const closeModal = () => {
            console.log('Closing modal');
            modal.classList.add('hidden');
            deleteId = null;
            deleteCard = null;
        };

        // --- СЛУШАТЕЛИ СОБЫТИЙ ---

        // 1. Клик по кнопке корзины (делегирование)
        reviewList.addEventListener('click', (e) => {
            const target = e.target as HTMLElement;
            // Ищем ближайшую кнопку с классом delete-review-btn
            const btn = target.closest('.delete-review-btn');

            if (btn) {
                e.preventDefault();
                e.stopPropagation(); // Остановить всплытие

                const id = btn.getAttribute('data-id');
                const card = btn.closest('.review-card') as HTMLElement;

                if (id && card) {
                    openModal(id, card);
                } else {
                    console.error("ID or Card not found on button click");
                }
            }
        });

        // 2. Клик "Löschen" (Подтвердить)
        confirmBtn.addEventListener('click', async () => {
            if (!deleteId) return;

            console.log('Confirming delete for:', deleteId);

            // Блокируем кнопку
            const originalText = confirmBtn.innerText;
            confirmBtn.innerText = 'Wird gelöscht...';
            (confirmBtn as HTMLButtonElement).disabled = true;

            try {
                const res = await fetch(`/api/reviews/${deleteId}`, { method: 'DELETE' });

                if (res.ok) {
                    // Анимация удаления карточки
                    if (deleteCard) {
                        deleteCard.style.transition = 'all 0.5s ease';
                        deleteCard.style.opacity = '0';
                        deleteCard.style.transform = 'scale(0.9)';
                        setTimeout(() => deleteCard?.remove(), 500);
                    }

                    showToast('Bewertung erfolgreich gelöscht', 'success');
                    closeModal();
                } else {
                    const data = await res.json();
                    console.error('Server Error:', data);
                    showToast(data.error || 'Fehler beim Löschen', 'error');
                    closeModal();
                }
            } catch (error) {
                console.error('Network Error:', error);
                showToast('Verbindungsfehler', 'error');
                closeModal();
            } finally {
                confirmBtn.innerText = originalText;
                (confirmBtn as HTMLButtonElement).disabled = false;
            }
        });

        // 3. Клик "Отмена"
        cancelBtn.addEventListener('click', closeModal);

        // 4. Клик по фону (закрыть)
        backdrop?.addEventListener('click', closeModal);
    });
</script>