@php
    $user = auth()->user();
    $allowGuest = config('reviews.allow_guest_reviews', false);
    $requireApproval = config('reviews.require_approval', true);
@endphp

<div class="review-form-container mt-4">
    <h4 class="mb-3">
        <i class="bi bi-pencil-square"></i> Write a Review
    </h4>

    @if(!$user && !$allowGuest)
        <div class="alert alert-info">
            <i class="bi bi-info-circle"></i> Please <a href="{{ route('login') }}">login</a> to write a review.
        </div>
    @else
        <form id="reviewForm" action="{{ route('api.products.reviews.store', $product->id) }}" method="POST">
            @csrf
            
            @if(!$user && $allowGuest)
                <div class="mb-3">
                    <label for="reviewer_name" class="form-label">Your Name</label>
                    <input type="text" class="form-control" id="reviewer_name" name="reviewer_name" required>
                </div>
                <div class="mb-3">
                    <label for="reviewer_email" class="form-label">Your Email</label>
                    <input type="email" class="form-control" id="reviewer_email" name="reviewer_email" required>
                </div>
            @endif

            <div class="mb-3">
                <label class="form-label">Rating <span class="text-danger">*</span></label>
                <div class="rating-input">
                    @for($i = 5; $i >= 1; $i--)
                        <input type="radio" name="rating" id="rating{{ $i }}" value="{{ $i }}" required>
                        <label for="rating{{ $i }}" class="star-label">
                            <i class="bi bi-star-fill"></i>
                        </label>
                    @endfor
                </div>
                <div class="invalid-feedback">Please select a rating.</div>
            </div>

            <div class="mb-3">
                <label for="review_title" class="form-label">Review Title (Optional)</label>
                <input type="text" class="form-control" id="review_title" name="title" maxlength="255" placeholder="Brief summary of your experience">
            </div>

            <div class="mb-3">
                <label for="review_body" class="form-label">Your Review (Optional)</label>
                <textarea class="form-control" id="review_body" name="body" rows="5" maxlength="5000" placeholder="Share your experience with this product..."></textarea>
                <small class="text-muted"><span id="charCount">0</span>/5000 characters</small>
            </div>

            @if(config('reviews.verified_purchase_only', false))
                <div class="mb-3">
                    <label for="order_id" class="form-label">Order ID <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="order_id" name="order_id" required placeholder="Enter your order ID">
                    <small class="text-muted">Only verified purchases can leave reviews.</small>
                </div>
            @endif

            <div class="mb-3">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-check-circle"></i> Submit Review
                </button>
            </div>
        </form>

        <div id="reviewFormMessage" class="mt-3" style="display: none;"></div>
    @endif
</div>

<style>
.rating-input {
    display: flex;
    flex-direction: row-reverse;
    justify-content: flex-end;
    gap: 5px;
}

.rating-input input[type="radio"] {
    display: none;
}

.rating-input .star-label {
    cursor: pointer;
    font-size: 1.5rem;
    color: #ddd;
    transition: color 0.2s;
}

.rating-input .star-label:hover,
.rating-input .star-label:hover ~ .star-label {
    color: #ffc107;
}

.rating-input input[type="radio"]:checked ~ .star-label {
    color: #ffc107;
}

.rating-input input[type="radio"]:checked ~ .star-label ~ .star-label {
    color: #ffc107;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('reviewForm');
    const bodyTextarea = document.getElementById('review_body');
    const charCount = document.getElementById('charCount');
    
    if (bodyTextarea && charCount) {
        bodyTextarea.addEventListener('input', function() {
            charCount.textContent = this.value.length;
        });
    }
    
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(form);
            const submitBtn = form.querySelector('button[type="submit"]');
            const messageDiv = document.getElementById('reviewFormMessage');
            
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> Submitting...';
            
            fetch(form.action, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || formData.get('_token'),
                    'Accept': 'application/json',
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    messageDiv.className = 'alert alert-success';
                    messageDiv.innerHTML = '<i class="bi bi-check-circle"></i> ' + data.message;
                    messageDiv.style.display = 'block';
                    form.reset();
                    if (charCount) charCount.textContent = '0';
                    
                    // Reload reviews after a short delay
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else {
                    messageDiv.className = 'alert alert-danger';
                    messageDiv.innerHTML = '<i class="bi bi-exclamation-circle"></i> ' + (data.message || 'Failed to submit review.');
                    messageDiv.style.display = 'block';
                }
            })
            .catch(error => {
                messageDiv.className = 'alert alert-danger';
                messageDiv.innerHTML = '<i class="bi bi-exclamation-circle"></i> An error occurred. Please try again.';
                messageDiv.style.display = 'block';
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="bi bi-check-circle"></i> Submit Review';
            });
        });
    }
});
</script>

