---
import Button from '@/components/base/Button.astro';

interface Props {
    isAuthenticated: boolean;
}

const { isAuthenticated } = Astro.props;
---

<div class="bg-white rounded-2xl shadow-xl border border-gray-100 overflow-hidden sticky top-8">
    {/* Заголовок формы */}
    <div class="bg-gray-50 px-6 py-5 border-b border-gray-100 flex items-center gap-3">
        <div class="bg-blue-100 p-2 rounded-lg text-blue-600">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
            </svg>
        </div>
        <div>
            <h2 class="text-lg font-bold text-gray-900">Bewertung schreiben</h2>
            <p class="text-xs text-gray-500">Teilen Sie Ihre Erfahrung</p>
        </div>
    </div>

    <div class="p-6">
        {!isAuthenticated ? (
                <div class="text-center py-6">
                    <div class="bg-gray-100 w-12 h-12 rounded-full flex items-center justify-center mx-auto mb-3">
                        <svg class="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
                    </div>
                    <p class="text-gray-600 text-sm mb-4">Bitte melden Sie sich an.</p>
                    <Button href="/auth/login?callbackUrl=/bewertungen" variant="blue" size="md" fullWidth={true}>
                        Anmelden
                    </Button>
                </div>
        ) : (
                <form id="review-form" class="space-y-6">

                    {/* Скрытое поле для рейтинга */}
                    <input type="hidden" name="rating" id="rating-input" value="0" required>

                    {/* Звезды */}
                    <div class="flex flex-col items-center">
                        <label class="text-xs font-bold text-gray-500 uppercase tracking-wider mb-2">Ihre Bewertung</label>
                        <div class="flex gap-1" id="star-container">
                            {[1, 2, 3, 4, 5].map((star) => (
                                    <button type="button" class="star-btn transition-transform hover:scale-110 focus:outline-none cursor-pointer p-1" data-value={star}>
                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" class="h-10 w-10 text-gray-300 transition-colors duration-200 star-svg" fill="currentColor">
                                            <path d="M394 480a16 16 0 01-9.39-3L256 383.76 127.39 477a16 16 0 01-24.55-17.82l49.1-151.05-128.77-93.55a16 16 0 019.38-28.84l159.05-.29L240.79 31.81a16 16 0 0130.42 0l49.18 153.64 159.05.29a16 16 0 019.38 28.84l-128.77 93.55 49.1 151.05A16 16 0 01394 480z"/>
                                        </svg>
                                    </button>
                            ))}
                        </div>
                        <div id="rating-text" class="h-4 mt-1 text-xs font-bold text-[#FE9901]"></div>
                    </div>

                    {/* Поля ввода */}
                    <div>
                        <label for="title" class="block text-sm font-semibold text-gray-700 mb-1">Titel</label>
                        <input
                            type="text"
                            id="title"
                            name="title"
                            required
                            minlength="5"
                            maxlength="100"
                            placeholder="Z.B. Tolle Fahrt!"
                            class="w-full px-4 py-2.5 rounded-lg bg-gray-50 border border-gray-200 focus:bg-white focus:ring-2 focus:ring-blue-100 focus:border-blue-500 outline-none transition text-sm"
                        >
                        <div id="title-error" class="hidden text-red-500 text-xs mt-1"></div>
                        <div class="text-xs text-gray-500 mt-1">5-100 Zeichen</div>
                    </div>

                    <div>
                        <label for="content" class="block text-sm font-semibold text-gray-700 mb-1">Kommentar</label>
                        <textarea
                            id="content"
                            name="content"
                            rows="4"
                            required
                            minlength="10"
                            maxlength="1000"
                            placeholder="Erzählen Sie uns mehr..."
                            class="w-full px-4 py-2.5 rounded-lg bg-gray-50 border border-gray-200 focus:bg-white focus:ring-2 focus:ring-blue-100 focus:border-blue-500 outline-none transition text-sm resize-none"
                        ></textarea>
                        <div id="content-error" class="hidden text-red-500 text-xs mt-1"></div>
                        <div class="text-xs text-gray-500 mt-1">10-1000 Zeichen</div>
                    </div>

                    {/* Кнопка отправки */}
                    <button type="submit" id="submit-btn" disabled class="w-full bg-blue-600 text-white font-bold py-3 rounded-xl hover:bg-blue-700 transition shadow-md disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer flex justify-center items-center">
                        <span id="btn-text">Bewertung absenden</span>
                        <span id="btn-loader" class="hidden ml-2 h-4 w-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></span>
                    </button>

                    <div id="form-message" class="hidden text-sm text-center p-2 rounded-lg"></div>
                </form>
        )}
    </div>
</div>

<script>
    // Логика формы на чистом JS
    document.addEventListener('DOMContentLoaded', () => {
        const form = document.getElementById('review-form') as HTMLFormElement;
        if (!form) return;

        const stars = document.querySelectorAll('.star-btn');
        const ratingInput = document.getElementById('rating-input') as HTMLInputElement;
        const ratingText = document.getElementById('rating-text');
        const submitBtn = document.getElementById('submit-btn') as HTMLButtonElement;
        const btnText = document.getElementById('btn-text');
        const btnLoader = document.getElementById('btn-loader');
        const messageBox = document.getElementById('form-message');

        const ratingLabels = ["Ungenügend", "Mangelhaft", "Befriedigend", "Gut", "Ausgezeichnet"];
        let currentRating = 0;

        // 1. Логика звезд
        stars.forEach((btn, index) => {
            const starValue = index + 1;

            // Наведение
            btn.addEventListener('mouseenter', () => updateStars(starValue));
            // Уход курсора
            btn.addEventListener('mouseleave', () => updateStars(currentRating));
            // Клик
            btn.addEventListener('click', () => {
                currentRating = starValue;
                ratingInput.value = starValue.toString();
                updateStars(currentRating);
                submitBtn.disabled = false; // Разблокировать кнопку
            });
        });

        function updateStars(value: number) {
            stars.forEach((btn, index) => {
                const svg = btn.querySelector('.star-svg');
                if (index < value) {
                    svg?.classList.remove('text-gray-300');
                    svg?.classList.add('text-[#FE9901]');
                } else {
                    svg?.classList.add('text-gray-300');
                    svg?.classList.remove('text-[#FE9901]');
                }
            });
            if (ratingText) {
                ratingText.textContent = value > 0 ? ratingLabels[value - 1] : '';
            }
        }

        // 3. Валидация полей
        const titleInput = document.getElementById('title') as HTMLInputElement;
        const contentInput = document.getElementById('content') as HTMLTextAreaElement;
        const titleError = document.getElementById('title-error');
        const contentError = document.getElementById('content-error');

        // Функция для проверки и отображения ошибок
        function validateField(input: HTMLInputElement | HTMLTextAreaElement, errorElement: HTMLElement, fieldName: string): boolean {
            let isValid = true;
            let errorMessage = '';

            // Проверка на минимальную длину
            if (input.value.length < parseInt(input.minLength || '0')) {
                errorMessage = `${fieldName} muss mindestens ${input.minLength} Zeichen enthalten.`;
                isValid = false;
            }
            // Проверка на максимальную длину
            else if (input.value.length > parseInt(input.maxLength || '9999')) {
                errorMessage = `${fieldName} darf höchstens ${input.maxLength} Zeichen enthalten.`;
                isValid = false;
            }
            // Проверка на HTML теги (для заголовка)
            else if (input.id === 'title' && /<[^>]*>/.test(input.value)) {
                errorMessage = 'HTML-Tags sind im Titel nicht erlaubt.';
                isValid = false;
            }

            if (!isValid && errorElement) {
                errorElement.textContent = errorMessage;
                errorElement.classList.remove('hidden');
                input.classList.add('border-red-500');
            } else if (errorElement) {
                errorElement.classList.add('hidden');
                input.classList.remove('border-red-500');
            }

            return isValid;
        }

        // Валидация в реальном времени
        titleInput.addEventListener('input', () => {
            validateField(titleInput, titleError, 'Titel');
        });

        contentInput.addEventListener('input', () => {
            validateField(contentInput, contentError, 'Kommentar');
        });

        // Валидация перед отправкой
        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            // Проверяем валидность полей
            const isTitleValid = validateField(titleInput, titleError, 'Titel');
            const isContentValid = validateField(contentInput, contentError, 'Kommentar');

            if (!isTitleValid || !isContentValid) {
                return; // Не отправляем форму, если есть ошибки
            }

            // UI: Загрузка
            submitBtn.disabled = true;
            if (btnText) btnText.classList.add('hidden');
            if (btnLoader) btnLoader.classList.remove('hidden');

            const formData = new FormData(form);
            const data = Object.fromEntries(formData);

            try {
                const res = await fetch('/api/reviews', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });

                const result = await res.json();

                if (res.ok) {
                    // Успех: перезагружаем страницу, чтобы увидеть новый отзыв
                    window.location.href = '/bewertungen?success=true';
                } else {
                    throw new Error(result.error || 'Fehler');
                }
            } catch (err: any) {
                if (messageBox) {
                    messageBox.textContent = err.message || 'Fehler beim Senden';
                    messageBox.className = 'text-sm text-center p-2 rounded-lg bg-red-50 text-red-600 block mt-2';
                    messageBox.classList.remove('hidden');
                }
                // Возвращаем кнопку
                submitBtn.disabled = false;
                if (btnText) btnText.classList.remove('hidden');
                if (btnLoader) btnLoader.classList.add('hidden');
            }
        });
    });
</script>