<template>
    <div class="component-registry">
        <div class="component-registry-header">
            <h1>Component Registry</h1>
            <p>Browse and preview all available Twig components</p>

            <div class="component-filters">
                <div class="search-wrapper">
                    <input
                        type="text"
                        placeholder="Search components..."
                        v-model="searchQuery"
                        @input="handleSearch"
                        class="search-input"
                    >
                </div>

                <div class="category-filters" v-if="categories.length > 0">
                    <button
                        @click="selectCategory('')"
                        :class="['filter-btn', selectedCategory === '' ? 'active' : '']"
                    >
                        All ({{ totalComponents }})
                    </button>
                    <button
                        v-for="category in categories"
                        :key="category.slug"
                        @click="selectCategory(category.slug)"
                        :class="['filter-btn', selectedCategory === category.slug ? 'active' : '']"
                    >
                        {{ category.name }} ({{ category.component_count }})
                    </button>
                </div>
            </div>
        </div>

        <loading-spinner v-if="loading"></loading-spinner>

        <div v-else-if="error" class="error-message">
            <h3>Error Loading Components</h3>
            <p>{{ error }}</p>
            <button @click="loadComponents" class="retry-btn">Try Again</button>
        </div>

        <div v-else-if="filteredComponents.length === 0" class="no-components">
            <h3>No Components Found</h3>
            <p v-if="searchQuery">No components match your search for "{{ searchQuery }}".</p>
            <p v-else-if="selectedCategory">No components found in the "{{ getCategoryName(selectedCategory) }}" category.</p>
            <p v-else>No components have been discovered yet.</p>
        </div>

        <div v-else class="components-grid">
            <div
                v-for="component in filteredComponents"
                :key="component.path"
                class="component-card"
                @click="previewComponent(component)"
            >
                <div class="component-card-header">
                    <h3>{{ component.name }}</h3>
                    <span class="component-category">{{ getCategoryName(component.category) }}</span>
                </div>

                <div class="component-card-body">
                    <p class="component-description">{{ component.description }}</p>

                    <div class="component-meta">
                        <span class="file-info">
                            {{ component.filename }} ({{ formatFileSize(component.file_size) }})
                        </span>
                        <span :class="['status', component.is_renderable ? 'renderable' : 'error']">
                            {{ component.is_renderable ? '✓ Renderable' : '⚠ Has Issues' }}
                        </span>
                    </div>

                    <div v-if="!component.is_renderable && component.error_message" class="error-details">
                        {{ component.error_message }}
                    </div>
                </div>
            </div>
        </div>

        <div v-if="filteredComponents.length > 0" class="components-summary">
            Showing {{ filteredComponents.length }} of {{ totalComponents }} components
        </div>
    </div>
</template>

<script>
export default {
    name: 'ComponentRegistry',

    data() {
        return {
            components: [],
            categories: [],
            loading: true,
            error: null,
            searchQuery: '',
            selectedCategory: '',
            totalComponents: 0,
        }
    },

    computed: {
        filteredComponents() {
            let filtered = this.components;

            // Filter by category
            if (this.selectedCategory) {
                const categoryPath = this.selectedCategory.replace('-', '/');
                filtered = filtered.filter(component => component.category === categoryPath);
            }

            // Filter by search query
            if (this.searchQuery.trim()) {
                const query = this.searchQuery.toLowerCase();
                filtered = filtered.filter(component =>
                    component.name.toLowerCase().includes(query) ||
                    component.description.toLowerCase().includes(query)
                );
            }

            return filtered;
        }
    },

    mounted() {
        this.loadComponents();
    },

    methods: {
        async loadComponents() {
            this.loading = true;
            this.error = null;

            try {
                const response = await fetch('/api/components');

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }

                const data = await response.json();

                this.components = data.data || [];
                this.categories = data.categories || [];
                this.totalComponents = data.meta?.total || this.components.length;

            } catch (error) {
                console.error('Error loading components:', error);
                this.error = error.message || 'Failed to load components';
            } finally {
                this.loading = false;
            }
        },

        handleSearch() {
            // Debounce search - could be enhanced with actual debouncing
            // For now, search happens immediately
        },

        selectCategory(categorySlug) {
            this.selectedCategory = categorySlug;
        },

        getCategoryName(categorySlug) {
            if (!categorySlug) return 'All';

            const category = this.categories.find(cat => cat.slug === categorySlug);
            return category ? category.name : categorySlug.replace('-', '/');
        },

        previewComponent(component) {
            const previewUrl = `/component/preview/${component.path}`;
            window.open(previewUrl, '_blank');
        },

        formatFileSize(bytes) {
            if (bytes === 0) return '0 B';

            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));

            return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
        }
    }
}
</script>

<style scoped>
.component-registry {
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;
}

.component-registry-header {
    margin-bottom: 2rem;
}

.component-registry-header h1 {
    margin: 0 0 0.5rem 0;
    color: #333;
}

.component-registry-header p {
    color: #666;
    margin: 0 0 2rem 0;
}

.component-filters {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.search-wrapper {
    max-width: 400px;
}

.search-input {
    width: 100%;
    padding: 0.75rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 1rem;
}

.search-input:focus {
    outline: none;
    border-color: #007bff;
}

.category-filters {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
}

.filter-btn {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;
}

.filter-btn:hover {
    background: #e9ecef;
}

.filter-btn.active {
    background: #007bff;
    color: white;
    border-color: #007bff;
}

.components-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.component-card {
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.2s;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.component-card:hover {
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    transform: translateY(-1px);
}

.component-card-header {
    padding: 1.5rem 1.5rem 1rem 1.5rem;
    border-bottom: 1px solid #f8f9fa;
}

.component-card-header h3 {
    margin: 0 0 0.5rem 0;
    color: #333;
    font-size: 1.25rem;
}

.component-category {
    background: #e9ecef;
    color: #495057;
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
    border-radius: 3px;
    text-transform: uppercase;
    font-weight: 500;
}

.component-card-body {
    padding: 0 1.5rem 1.5rem 1.5rem;
}

.component-description {
    color: #666;
    margin: 0 0 1rem 0;
    line-height: 1.4;
}

.component-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 0.875rem;
    gap: 1rem;
}

.file-info {
    color: #6c757d;
    flex: 1;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.status {
    font-weight: 500;
    flex-shrink: 0;
}

.status.renderable {
    color: #28a745;
}

.status.error {
    color: #dc3545;
}

.error-details {
    margin-top: 0.5rem;
    padding: 0.5rem;
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
    border-radius: 4px;
    font-size: 0.875rem;
}

.error-message {
    text-align: center;
    padding: 2rem;
    color: #dc3545;
}

.retry-btn {
    background: #dc3545;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    cursor: pointer;
    margin-top: 1rem;
}

.no-components {
    text-align: center;
    padding: 4rem 2rem;
    color: #6c757d;
}

.components-summary {
    text-align: center;
    color: #6c757d;
    font-size: 0.875rem;
    padding: 1rem 0;
}

@media (max-width: 768px) {
    .component-registry {
        padding: 1rem;
    }

    .components-grid {
        grid-template-columns: 1fr;
    }

    .component-filters {
        align-items: stretch;
    }

    .category-filters {
        flex-direction: column;
    }
}
</style>