<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ artifact.manifest.name or 'Application' }} - Hypha</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
    <style>
        .file-tree {
            font-family: 'Courier New', monospace;
        }
        .file-item {
            transition: background-color 0.2s ease;
            position: relative;
        }
        .file-item:hover {
            background-color: rgba(59, 130, 246, 0.1);
        }
        .file-item-buttons {
            opacity: 0;
            transition: opacity 0.2s ease;
        }
        .file-item:hover .file-item-buttons {
            opacity: 1;
        }
        .file-card {
            transition: all 0.2s ease;
        }
        .file-card:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
    </style>
</head>
<body class="bg-gradient-to-br from-gray-50 to-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-7xl">
        <!-- Header -->
        <header class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-4xl font-bold text-gray-800 mb-2">
                        <i class="fas fa-cube text-blue-500 mr-3"></i>
                        {{ artifact.manifest.name or 'Application' }}
                    </h1>
                    <p class="text-xl text-gray-600">
                        {{ artifact.manifest.description or 'Application details and files' }}
                    </p>
                </div>
                <div class="flex gap-2">
                    <span class="px-3 py-2 bg-blue-100 text-blue-700 rounded-full text-sm font-medium">
                        <i class="fas fa-tag mr-1"></i> v{{ artifact.manifest.version or '1.0.0' }}
                    </span>
                    <span class="px-3 py-2 bg-purple-100 text-purple-700 rounded-full text-sm font-medium">
                        <i class="fas fa-cogs mr-1"></i> {{ artifact.manifest.type or 'application' }}
                    </span>
                </div>
            </div>
        </header>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Manifest Summary Card -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-lg p-6 sticky top-8">
                    <h2 class="text-2xl font-bold text-gray-800 mb-4">
                        <i class="fas fa-info-circle text-blue-500 mr-2"></i>
                        Application Info
                    </h2>
                    
                    <!-- Basic Information -->
                    <div class="space-y-4">
                        <div class="border-b border-gray-200 pb-4">
                            <h3 class="font-semibold text-gray-700 mb-2">Basic Details</h3>
                            <div class="space-y-2">
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Name:</span>
                                    <span class="font-medium">{{ artifact.manifest.name or 'N/A' }}</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Version:</span>
                                    <span class="font-medium">{{ artifact.manifest.version or 'N/A' }}</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Type:</span>
                                    <span class="font-medium">{{ artifact.manifest.type or 'N/A' }}</span>
                                </div>
                                {% if artifact.manifest.license %}
                                <div class="flex justify-between">
                                    <span class="text-gray-600">License:</span>
                                    <span class="font-medium">{{ artifact.manifest.license }}</span>
                                </div>
                                {% endif %}
                            </div>
                        </div>

                        <!-- Author Information -->
                        {% if artifact.manifest.author %}
                        <div class="border-b border-gray-200 pb-4">
                            <h3 class="font-semibold text-gray-700 mb-2">Author</h3>
                            {% if artifact.manifest.author is string %}
                                <p class="text-gray-800">{{ artifact.manifest.author }}</p>
                            {% else %}
                                <div class="space-y-1">
                                    {% if artifact.manifest.author.name %}
                                        <p class="font-medium">{{ artifact.manifest.author.name }}</p>
                                    {% endif %}
                                    {% if artifact.manifest.author.email %}
                                        <p class="text-sm text-gray-600">{{ artifact.manifest.author.email }}</p>
                                    {% endif %}
                                    {% if artifact.manifest.author.url %}
                                        <a href="{{ artifact.manifest.author.url }}" target="_blank" class="text-blue-600 hover:text-blue-800 text-sm">
                                            <i class="fas fa-external-link-alt mr-1"></i>{{ artifact.manifest.author.url }}
                                        </a>
                                    {% endif %}
                                </div>
                            {% endif %}
                        </div>
                        {% endif %}

                        <!-- Keywords/Tags -->
                        {% if artifact.manifest.keywords %}
                        <div class="border-b border-gray-200 pb-4">
                            <h3 class="font-semibold text-gray-700 mb-2">Keywords</h3>
                            <div class="flex flex-wrap gap-1">
                                {% for keyword in artifact.manifest.keywords %}
                                <span class="px-2 py-1 bg-gray-100 text-gray-700 rounded text-xs">{{ keyword }}</span>
                                {% endfor %}
                            </div>
                        </div>
                        {% endif %}

                        <!-- Entry Point -->
                        {% if artifact.manifest.entry_point %}
                        <div class="border-b border-gray-200 pb-4">
                            <h3 class="font-semibold text-gray-700 mb-2">Entry Point</h3>
                            <code class="text-sm bg-gray-100 px-2 py-1 rounded block">{{ artifact.manifest.entry_point }}</code>
                        </div>
                        {% endif %}

                        <!-- Configuration -->
                        {% if artifact.manifest.config %}
                        <div class="border-b border-gray-200 pb-4">
                            <h3 class="font-semibold text-gray-700 mb-2">Configuration</h3>
                            <details class="cursor-pointer">
                                <summary class="text-sm text-blue-600 hover:text-blue-800">View Configuration</summary>
                                <pre class="text-xs bg-gray-100 p-2 rounded mt-2 overflow-x-auto">{{ artifact.manifest.config | tojson(indent=2) }}</pre>
                            </details>
                        </div>
                        {% endif %}

                        <!-- Statistics -->
                        <div>
                            <h3 class="font-semibold text-gray-700 mb-2">Statistics</h3>
                            <div class="grid grid-cols-2 gap-4">
                                <div class="text-center bg-blue-50 rounded-lg p-3">
                                    <div class="text-2xl font-bold text-blue-600">{{ artifact.view_count|int }}</div>
                                    <div class="text-xs text-gray-600">Views</div>
                                </div>
                                <div class="text-center bg-green-50 rounded-lg p-3">
                                    <div class="text-2xl font-bold text-green-600">{{ artifact.download_count|int }}</div>
                                    <div class="text-xs text-gray-600">Downloads</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- File Tree -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h2 class="text-2xl font-bold text-gray-800 mb-4">
                        <i class="fas fa-folder-open text-yellow-500 mr-2"></i>
                        Application Files
                    </h2>
                    
                    <div id="fileTree" class="file-tree">
                        <!-- File tree will be populated by JavaScript -->
                        <div class="text-center py-8 text-gray-500">
                            <i class="fas fa-spinner fa-spin text-2xl mb-2"></i>
                            <p>Loading files...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // File tree state
        let fileTreeData = null;
        let expandedDirs = {};
        let loadingDirs = {};

        // Fetch initial file tree from server
        async function fetchFileTree() {
            try {
                const response = await fetch(`{{artifact_base_url}}/files/`);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                fileTreeData = await response.json();
                renderFileTree();
            } catch (error) {
                console.error('Failed to fetch file tree:', error);
                document.getElementById('fileTree').innerHTML = `
                    <div class="text-center py-8 text-red-500">
                        <i class="fas fa-exclamation-triangle text-2xl mb-2"></i>
                        <p>Failed to load files</p>
                        <p class="text-sm">${error.message}</p>
                    </div>
                `;
            }
        }

        // Fetch files in a specific directory
        async function listFiles(path) {
            try {
                const url = path ? `{{artifact_base_url}}/files/${path}/` : `{{artifact_base_url}}/files/`;
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return await response.json();
            } catch (error) {
                console.error('Failed to fetch directory contents:', error);
                throw error;
            }
        }

        // Render the initial file tree
        function renderFileTree() {
            const container = document.getElementById('fileTree');
            if (!fileTreeData || fileTreeData.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-8 text-gray-500">
                        <i class="fas fa-folder-open text-4xl mb-4"></i>
                        <p>No files found</p>
                    </div>
                `;
                return;
            }

            container.innerHTML = '';
            renderFileTreeLevel(fileTreeData, container, '');
        }

        // Render a level of the file tree recursively
        function renderFileTreeLevel(files, container, parentPath) {
            // Sort files: directories first, then files
            const sortedFiles = [...files].sort((a, b) => {
                if (a.type === 'directory' && b.type !== 'directory') return -1;
                if (a.type !== 'directory' && b.type === 'directory') return 1;
                return a.name.localeCompare(b.name);
            });

            sortedFiles.forEach(file => {
                const fullPath = parentPath ? `${parentPath}/${file.name}` : file.name;
                const fileCard = createFileCard(file, fullPath, container, parentPath);
                container.appendChild(fileCard);
            });
        }

        // Create file card element
        function createFileCard(file, fullPath, parentContainer, parentPath) {
            const isDirectory = file.type === 'directory';
            const isExpanded = !!expandedDirs[fullPath];
            const isLoading = !!loadingDirs[fullPath];
            
            const div = document.createElement('div');
            div.className = 'file-card flex flex-col justify-between items-start p-3 bg-gray-700 shadow-md transition-colors duration-200 mb-2 rounded';
            
            div.innerHTML = `
                <div class="file-item flex items-center w-full justify-between relative">
                    <div class="flex items-center">
                        ${isDirectory ? `
                            <button class="mr-2 min-w-[20px] text-center" 
                                    onclick="handleToggle('${fullPath}')" 
                                    ${isLoading ? 'disabled style="opacity: 0.7"' : ''}>
                                ${isLoading ? 
                                    '<i class="fas fa-spinner fa-spin text-blue-400"></i>' : 
                                    (isExpanded ? '-' : '+')
                                }
                            </button>
                        ` : ''}
                        <i class="fas ${isDirectory ? 'fa-folder' : 'fa-file-alt'} mr-2 ${isDirectory ? 'text-yellow-400' : 'text-gray-400'}"></i>
                        <span class="flex-1 text-white">${file.name}</span>
                    </div>
                    <div class="file-item-buttons">
                        ${!isDirectory ? `
                            <button onclick="downloadFile('${fullPath}')" 
                                    class="bg-blue-600 hover:bg-blue-500 text-white font-bold py-1 px-2 rounded transition duration-300 mr-1"
                                    title="Download file">
                                <i class="fas fa-download"></i>
                            </button>
                            <button onclick="viewFile('${fullPath}')" 
                                    class="bg-green-600 hover:bg-green-500 text-white font-bold py-1 px-2 rounded transition duration-300"
                                    title="View file">
                                <i class="fas fa-eye"></i>
                            </button>
                        ` : ''}
                    </div>
                </div>
                ${isExpanded ? '<div class="w-full mt-3 ml-3" id="children-' + fullPath.replace(/[^a-zA-Z0-9]/g, '_') + '"></div>' : ''}
            `;

            // If expanded and has children, render them
            if (isExpanded && expandedDirs[fullPath]) {
                const childrenContainer = div.querySelector('#children-' + fullPath.replace(/[^a-zA-Z0-9]/g, '_'));
                if (childrenContainer) {
                    renderFileTreeLevel(expandedDirs[fullPath], childrenContainer, fullPath);
                }
            }

            return div;
        }

        // Handle directory toggle
        async function handleToggle(fullPath) {
            const isExpanded = !!expandedDirs[fullPath];
            
            if (isExpanded) {
                // Collapse
                delete expandedDirs[fullPath];
            } else {
                // Expand - set loading state
                loadingDirs[fullPath] = true;
                
                try {
                    const children = await listFiles(fullPath);
                    expandedDirs[fullPath] = children;
                } catch (error) {
                    console.error('Error loading directory:', error);
                    alert(`Failed to load directory: ${error.message}`);
                } finally {
                    delete loadingDirs[fullPath];
                }
            }
            
            // Re-render the entire tree to reflect changes
            renderFileTree();
        }

        // Download file
        function downloadFile(filePath) {
            const downloadUrl = `{{artifact_base_url}}/files/${filePath}`;
            window.open(downloadUrl, '_blank');
        }

        // View file (open in new tab)
        function viewFile(filePath) {
            const viewUrl = `{{artifact_base_url}}/files/${filePath}`;
            window.open(viewUrl, '_blank');
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            fetchFileTree();
        });
    </script>
</body>
</html>