<?php $this->layout('system::layout/default') ?>

<div class="max-w-4xl mx-auto">
    <!-- Alerts -->
    <?php if ($data['is_closed']): ?>
        <div class="bg-red-50 border border-red-200 rounded-xl p-4 mb-6 text-red-800">
            <?= __('The guestbook is closed') ?>
        </div>
    <?php endif; ?>

    <?php if (! empty($data['message'])): ?>
        <div class="bg-green-50 border border-green-200 rounded-xl p-4 mb-6 text-green-800">
            <?= $data['message'] ?>
        </div>
    <?php endif; ?>

    <!-- Write Form -->
    <?php if ($data['can_write']): ?>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
            <?php if (! empty($data['errors']['csrf_token'])): ?>
                <div class="bg-red-50 border border-red-200 rounded-lg p-4 mb-4 text-red-800">
                    <?= implode(', ', $data['errors']['csrf_token']) ?>
                </div>
            <?php endif ?>

            <form name="form" action="/guestbook/" method="post">
                <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>"/>
                
                <!-- Name Field for Guests -->
                <?php if (! $user->isValid()): ?>
                    <div class="mb-4">
                        <label for="name" class="block text-sm font-medium text-gray-700 mb-2"><?= __('Name') ?></label>
                        <input type="text"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors <?= ! empty($data['errors']['name']) ? 'border-red-500' : '' ?>"
                               maxlength="25"
                               name="name"
                               id="name"
                               required
                               value="<?= $this->e($data['form_data']['name']) ?>"
                               placeholder="<?= __('Name') ?>"
                        >
                        <?php if (! empty($data['errors']['name'])): ?>
                            <div class="text-red-600 text-sm mt-1"><?= implode(', ', $data['errors']['name']) ?></div>
                        <?php endif ?>
                    </div>
                <?php endif; ?>

                <!-- Message Editor -->
                <?= $this->fetch(
                    'guestbook::ckeditor',
                    [
                        'label'  => __('Message'),
                        'errors' => implode(', ', $data['errors']['message'] ?? []),
                        'value'  => $this->e($data['form_data']['message']),
                    ]
                ) ?>

                <!-- Captcha for Guests -->
                <?php if (! $user->isValid()): ?>
                    <div class="mb-4">
                        <div class="mb-3">
                            <img alt="<?= __('Verification code') ?>" src="<?= $data['captcha'] ?>" class="border border-gray-300 rounded-lg">
                        </div>
                        <label for="code" class="block text-sm font-medium text-gray-700 mb-2"><?= __('Symbols on the picture') ?></label>
                        <input type="text"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors <?= (isset($data['errors']['code']) ? 'border-red-500' : '') ?>"
                               maxlength="6"
                               name="code"
                               id="code"
                               autocomplete="off"
                               required
                               placeholder="<?= __('Symbols on the picture') ?>"
                        >
                        <?php if (isset($data['errors']['code'])): ?>
                            <div class="text-red-600 text-sm mt-1"><?= implode(', ', $data['errors']['code']) ?></div>
                        <?php endif ?>
                        <div class="text-gray-500 text-sm mt-1">
                            <?= __('If you cannot see the image code, enable graphics in your browser and refresh this page') ?>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Submit Button -->
                <button type="submit" class="px-6 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition-colors duration-200">
                    <?= __('Write') ?>
                </button>
            </form>
        </div>
    <?php else: ?>
        <!-- For Registered Users Only -->
        <?php if (! $user->isValid()): ?>
            <div class="bg-red-50 border border-red-200 rounded-xl p-4 mb-6 text-red-800">
                <?= __('For registered users only') ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>

    <!-- Posts List -->
    <div class="space-y-4">
        <?php if (empty($data['posts']['data'])): ?>
            <!-- Empty Guestbook -->
            <div class="bg-blue-50 border border-blue-200 rounded-xl p-8 text-center">
                <svg class="w-16 h-16 text-blue-400 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"/>
                </svg>
                <h3 class="text-lg font-semibold text-gray-900 mb-2"><?= __('The guestbook is empty') ?></h3>
                <p class="text-gray-600"><?= __('Be the first! :)') ?></p>
            </div>
        <?php else: ?>
            <!-- Posts -->
            <?php foreach ($data['posts']['data'] as $post): ?>
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                    <!-- Post Header -->
                    <div class="flex items-start space-x-4 mb-4">
                        <!-- Avatar -->
                        <div class="relative flex-shrink-0">
                            <?php if (! empty($post['user']) && ! empty($post['user']['profile_url'])): ?>
                                <a href="<?= $post['user']['profile_url'] ?>">
                                    <img src="<?= $this->avatar($post['user']['id'] ?? 0) ?>" class="w-12 h-12 rounded-full" alt="Avatar">
                                </a>
                            <?php else: ?>
                                <img src="<?= $this->avatar($post['user']['id'] ?? 0) ?>" class="w-12 h-12 rounded-full" alt="Avatar">
                            <?php endif; ?>
                            <span class="absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white <?= $post['is_online'] ? 'bg-green-500' : 'bg-gray-400' ?>"></span>
                            <?php if (! empty($post['user']['rights_name'])): ?>
                                <div class="absolute -top-1 -left-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center" 
                                     title="<?= $post['user']['rights_name'] ?>">
                                    <svg class="w-3 h-3 text-white" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
                                    </svg>
                                </div>
                            <?php endif ?>
                        </div>

                        <!-- User Info -->
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center flex-wrap mb-1">
                                <?php if (! empty($post['user']) && ! empty($post['user']['profile_url'])): ?>
                                    <a href="<?= $post['user']['profile_url'] ?>" class="font-medium text-gray-900 hover:text-blue-600 transition-colors duration-200 mr-2">
                                        <?= $post['name'] ?>
                                    </a>
                                <?php else: ?>
                                    <span class="font-medium text-gray-900 mr-2">
                                        <?= ! empty($post['user']) ? $post['name'] : (__('Guest') . ': ' . $post['name']) ?>
                                    </span>
                                <?php endif; ?>
                                
                                <span class="text-sm text-gray-500"><?= $post['created_at'] ?></span>
                                
                                <?php if (! empty($post['edit_count'])): ?>
                                    <span class="text-sm text-gray-500 cursor-help ml-2" 
                                          title="<?= __('Edited:') ?> <?= $post['edited_by'] ?> (<?= $post['edited_at'] ?>) [<?= $post['edit_count'] ?>]">
                                        <?= __('Edited') ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                            
                            <?php if (! empty($post['user']) && ! empty($post['user']['status'])): ?>
                                <div class="text-sm text-gray-600"><?= $post['user']['status'] ?></div>
                            <?php endif ?>
                        </div>
                    </div>

                    <!-- Post Content -->
                    <div class="prose prose-sm max-w-none mb-4">
                        <?= $post['text'] ?>
                    </div>

                    <!-- Reply -->
                    <?php if (! empty($post['reply_text'])): ?>
                        <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mt-4">
                            <div class="text-sm text-yellow-800">
                                <div class="font-semibold mb-1"><?= $post['reply_author'] ?> <?= $post['replied_at'] ?></div>
                                <?= $post['reply_text'] ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Post Footer -->
                    <div class="flex justify-between items-center pt-4 border-t border-gray-200">
                        <!-- Meta Info -->
                        <div class="text-xs text-gray-500">
                            <?php if ($post['meta']): ?>
                                <div class="flex items-center space-x-4">
                                    <span>
                                        <a href="<?= $post['meta']['search_ip_url'] ?>" class="hover:text-gray-700"><?= $post['meta']['ip'] ?></a>
                                    </span>
                                    <span><?= $post['meta']['user_agent'] ?></span>
                                </div>
                            <?php endif; ?>
                        </div>

                        <!-- Actions -->
                        <div class="flex items-center space-x-3">
                            <?php if ($data['can_write'] && $post['user_id'] !== $user->id): ?>
                                <button onclick="reply_to_post('<?= $post['name'] ?>')" 
                                        class="text-sm text-blue-600 hover:text-blue-800 transition-colors duration-200">
                                    <?= __('Reply') ?>
                                </button>
                            <?php endif; ?>
                            
                            <?php if (! empty($post['meta']['can_manage'])): ?>
                                <div class="relative">
                                    <button class="text-gray-400 hover:text-gray-600 p-1">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h.01M12 12h.01M19 12h.01M6 12a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0z"/>
                                        </svg>
                                    </button>
                                    <div class="absolute right-0 mt-1 w-48 bg-white rounded-md shadow-lg border border-gray-200 py-1 z-10 hidden">
                                        <?php if ($post['meta']['reply_url']): ?>
                                            <a href="<?= $post['meta']['reply_url'] ?>" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"><?= __('Reply') ?></a>
                                        <?php endif; ?>
                                        <a href="<?= $post['meta']['edit_url'] ?>" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"><?= __('Edit') ?></a>
                                        <a href="#" data-url="<?= $post['meta']['delete_url'] ?>" data-toggle="modal" data-target=".ajax_modal" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"><?= __('Delete') ?></a>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>

            <!-- Pagination -->
            <?php if (! empty($data['pagination'])): ?>
                <div class="mt-6"><?= $data['pagination'] ?></div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <!-- Clear Button -->
    <?php if ($data['can_clear']): ?>
        <div class="mt-6 pt-4 border-t border-gray-200">
            <button type="button" 
                    class="px-4 py-2 bg-red-600 text-white font-medium rounded-lg hover:bg-red-700 transition-colors duration-200"
                    data-url="/guestbook/clean" 
                    data-toggle="modal" 
                    data-target=".ajax_modal">
                <?= __('Clear') ?>
            </button>
        </div>
    <?php endif ?>
</div>

<?php $this->push('scripts') ?>
<script>
    function reply_to_post(user_name)
    {
        event.preventDefault();
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
        
        // Assuming CKEditor is available as 'editor'
        if (typeof editor !== 'undefined') {
            editor.editing.view.focus();
            editor.model.change(writer => {
                const insertPosition = editor.model.document.selection.getFirstPosition();
                writer.insertText(user_name + ', ', {}, insertPosition);
                writer.setSelection(writer.createPositionAt(editor.model.document.getRoot(), 'end'));
            });
        }
    }

    // Initialize dropdown menus
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.relative button').forEach(button => {
            button.addEventListener('click', function(e) {
                e.stopPropagation();
                const menu = this.nextElementSibling;
                menu.classList.toggle('hidden');
            });
        });

        // Close dropdowns when clicking outside
        document.addEventListener('click', function() {
            document.querySelectorAll('.absolute .hidden').forEach(menu => {
                menu.classList.add('hidden');
            });
        });
    });
</script>
<?php $this->stop(); ?>

<style>
.prose {
    color: #374151;
    line-height: 1.75;
}

.prose p {
    margin-bottom: 1em;
}

.prose ul, .prose ol {
    margin-bottom: 1em;
    padding-left: 1.5em;
}

.prose li {
    margin-bottom: 0.5em;
}

.prose a {
    color: #2563eb;
    text-decoration: underline;
}

.prose a:hover {
    color: #1d4ed8;
}

.prose img {
    max-width: 100%;
    height: auto;
    border-radius: 0.5rem;
}
</style>