<?php
class EagleLibraryViewer {
    private $libraryPath;
    private $libraryUrlPath;
    private $metadata;
    private $items = [];
    private $folders = [];

    // 文件类型定义
    private $imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'];
    private $videoTypes = ['mp4', 'mov', 'avi', 'mkv', 'flv', 'wmv', 'webm', 'm4v'];

    public function __construct($libraryPath, $libraryUrlPath = '') {
        $this->libraryPath = rtrim($libraryPath, '/');
        $this->libraryUrlPath = rtrim($libraryUrlPath, '/');
        $this->loadMetadata();
        $this->loadItems();
    }

    private function loadMetadata() {
        $metadataPath = $this->libraryPath . '/metadata.json';
        if (file_exists($metadataPath)) {
            $this->metadata = json_decode(file_get_contents($metadataPath), true);
            $this->folders = $this->metadata['folders'] ?? [];
        }
    }

    private function loadItems() {
        $imagesPath = $this->libraryPath . '/images';
        if (!is_dir($imagesPath)) {
            return;
        }

        $dirs = glob($imagesPath . '/*.info', GLOB_ONLYDIR);
        foreach ($dirs as $dir) {
            $metadataPath = $dir . '/metadata.json';
            if (file_exists($metadataPath)) {
                $itemData = json_decode(file_get_contents($metadataPath), true);
                // 获取相对路径
                $relativeDir = 'images/' . basename($dir);
                $itemData['path'] = $relativeDir;
                
                // 构建完整的URL路径
                $baseUrl = $this->libraryUrlPath ? $this->libraryUrlPath . '/' : '';
                $itemData['thumbnail'] = $baseUrl . $relativeDir . '/' . $itemData['name'] . '_thumbnail.png';
                $itemData['file'] = $baseUrl . $relativeDir . '/' . $itemData['name'] . '.' . $itemData['ext'];
                
                // 判断文件类型
                $itemData['type'] = $this->getFileType($itemData['ext']);
                
                $this->items[$itemData['id']] = $itemData;
            }
        }
    }

    private function getFileType($ext) {
        $ext = strtolower($ext);
        if (in_array($ext, $this->imageTypes)) {
            return 'image';
        } elseif (in_array($ext, $this->videoTypes)) {
            return 'video';
        } else {
            return 'file';
        }
    }

    private function getFileIcon($ext) {
        $ext = strtolower($ext);
        $icons = [
            'pdf' => '📄',
            'doc' => '📝', 'docx' => '📝',
            'xls' => '📊', 'xlsx' => '📊',
            'ppt' => '📊', 'pptx' => '📊',
            'zip' => '📦', 'rar' => '📦', '7z' => '📦',
            'txt' => '📃',
            'mp3' => '🎵', 'wav' => '🎵', 'flac' => '🎵',
            'psd' => '🎨', 'ai' => '🎨', 'sketch' => '🎨',
            'fig' => '🎨',
        ];
        return $icons[$ext] ?? '📎';
    }

    public function getFolderTree($folders = null, $level = 0) {
        if ($folders === null) {
            $folders = $this->folders;
        }

        $html = '';
        foreach ($folders as $folder) {
            $indent = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $level);
            $html .= '<div class="folder-item">';
            $html .= '<a href="?folder=' . htmlspecialchars($folder['id']) . '" class="folder-link">';
            $html .= $indent . '📁 ' . htmlspecialchars($folder['name']);
            $html .= '</a>';
            
            if (!empty($folder['children'])) {
                $html .= $this->getFolderTree($folder['children'], $level + 1);
            }
            $html .= '</div>';
        }
        return $html;
    }

    public function getItemsByFolder($folderId) {
        $items = [];
        foreach ($this->items as $item) {
            if (in_array($folderId, $item['folders'] ?? [])) {
                $items[] = $item;
            }
        }
        return $items;
    }

    public function getAllItems() {
        return array_values($this->items);
    }

    public function getItemById($itemId) {
        return $this->items[$itemId] ?? null;
    }

    public function getFolderName($folderId) {
        return $this->findFolderName($this->folders, $folderId);
    }

    private function findFolderName($folders, $folderId) {
        foreach ($folders as $folder) {
            if ($folder['id'] === $folderId) {
                return $folder['name'];
            }
            if (!empty($folder['children'])) {
                $name = $this->findFolderName($folder['children'], $folderId);
                if ($name) {
                    return $name;
                }
            }
        }
        return null;
    }

    public function renderGallery($folderId = null) {
        $items = $folderId ? $this->getItemsByFolder($folderId) : $this->getAllItems();
        
        $html = '<div class="gallery">';
        if (empty($items)) {
            $html .= '<p class="no-items">暂无内容</p>';
        } else {
            foreach ($items as $item) {
                $html .= $this->renderGalleryItem($item);
            }
        }
        $html .= '</div>';
        return $html;
    }

    private function renderGalleryItem($item) {
        $type = $item['type'];
        $thumbnail = file_exists($item['thumbnail']) ? $item['thumbnail'] : '';
        
        $html = '<div class="gallery-item" data-type="' . $type . '">';
        $html .= '<a href="?item=' . htmlspecialchars($item['id']) . '" class="item-link">';
        
        // 缩略图区域
        $html .= '<div class="thumbnail-wrapper">';
        if ($type === 'image') {
            if ($thumbnail) {
                $html .= '<img src="' . htmlspecialchars($thumbnail) . '" alt="' . htmlspecialchars($item['name']) . '" class="thumbnail">';
            } else {
                $html .= '<div class="thumbnail-placeholder">🖼️</div>';
            }
        } elseif ($type === 'video') {
            if ($thumbnail) {
                $html .= '<img src="' . htmlspecialchars($thumbnail) . '" alt="' . htmlspecialchars($item['name']) . '" class="thumbnail">';
                $html .= '<div class="video-overlay">▶️</div>';
            } else {
                $html .= '<div class="thumbnail-placeholder video-placeholder">🎬</div>';
            }
        } else {
            $icon = $this->getFileIcon($item['ext']);
            $html .= '<div class="thumbnail-placeholder file-placeholder">' . $icon . '</div>';
        }
        $html .= '</div>';
        
        // 信息区域
        $html .= '<div class="item-info">';
        $html .= '<p class="item-name">' . htmlspecialchars($item['name']) . '</p>';
        if ($type === 'image') {
            $html .= '<p class="item-meta">' . $item['width'] . ' x ' . $item['height'] . '</p>';
        } elseif ($type === 'video') {
            $duration = isset($item['duration']) ? $this->formatDuration($item['duration']) : '';
            $html .= '<p class="item-meta">' . $duration . '</p>';
        } else {
            $html .= '<p class="item-meta">' . strtoupper($item['ext']) . '</p>';
        }
        $html .= '</div>';
        
        $html .= '</a>';
        $html .= '</div>';
        return $html;
    }

    private function formatDuration($seconds) {
        $minutes = floor($seconds / 60);
        $secs = floor($seconds % 60);
        return sprintf('%d:%02d', $minutes, $secs);
    }

    public function renderItemDetail($itemId) {
        $item = $this->getItemById($itemId);
        if (!$item) {
            return '<p class="error">项目不存在</p>';
        }

        $folderNames = [];
        foreach ($item['folders'] ?? [] as $folderId) {
            $name = $this->getFolderName($folderId);
            if ($name) {
                $folderNames[] = $name;
            }
        }

        $type = $item['type'];
        
        $html = '<div class="item-detail">';
        $html .= '<div class="detail-header">';
        $html .= '<a href="?folder=' . htmlspecialchars($item['folders'][0] ?? '') . '" class="back-link">← 返回</a>';
        $html .= '<h2>' . htmlspecialchars($item['name']) . '</h2>';
        $html .= '</div>';
        
        $html .= '<div class="detail-content">';
        $html .= '<div class="detail-preview">';
        $html .= $this->renderPreview($item);
        $html .= '</div>';
        
        $html .= '<div class="detail-info">';
        $html .= '<h3>文件信息</h3>';
        $html .= '<table class="info-table">';
        $html .= '<tr><th>类型:</th><td>' . $this->getTypeLabel($type) . '</td></tr>';
        if ($type === 'image' || $type === 'video') {
            $html .= '<tr><th>尺寸:</th><td>' . ($item['width'] ?? '-') . ' x ' . ($item['height'] ?? '-') . ' px</td></tr>';
        }
        if ($type === 'video' && isset($item['duration'])) {
            $html .= '<tr><th>时长:</th><td>' . $this->formatDuration($item['duration']) . '</td></tr>';
        }
        $html .= '<tr><th>文件大小:</th><td>' . $this->formatFileSize($item['size']) . '</td></tr>';
        $html .= '<tr><th>格式:</th><td>' . strtoupper($item['ext']) . '</td></tr>';
        $html .= '<tr><th>文件夹:</th><td>' . implode(', ', $folderNames) . '</td></tr>';
        $html .= '<tr><th>创建时间:</th><td>' . date('Y-m-d H:i:s', $item['btime'] / 1000) . '</td></tr>';
        $html .= '<tr><th>修改时间:</th><td>' . date('Y-m-d H:i:s', $item['mtime'] / 1000) . '</td></tr>';
        $html .= '</table>';

        // 下载按钮
        $html .= '<div class="download-section">';
        $html .= '<a href="' . htmlspecialchars($item['file']) . '" download class="download-btn">⬇️ 下载文件</a>';
        $html .= '</div>';

        if (!empty($item['palettes'])) {
            $html .= '<h3>调色板</h3>';
            $html .= '<div class="palettes">';
            foreach ($item['palettes'] as $palette) {
                $color = sprintf('rgb(%d,%d,%d)', $palette['color'][0], $palette['color'][1], $palette['color'][2]);
                $html .= '<div class="palette-item" title="' . $color . ' - ' . $palette['ratio'] . '%" style="background-color: ' . $color . '">';
                $html .= '<span>' . $palette['ratio'] . '%</span>';
                $html .= '</div>';
            }
            $html .= '</div>';
        }

        if (!empty($item['annotation'])) {
            $html .= '<h3>注释</h3>';
            $html .= '<p class="annotation">' . htmlspecialchars($item['annotation']) . '</p>';
        }

        $html .= '</div>';
        $html .= '</div>';
        $html .= '</div>';
        
        return $html;
    }

    private function getTypeLabel($type) {
        $labels = [
            'image' => '🖼️ 图片',
            'video' => '🎬 视频',
            'file' => '📎 文件'
        ];
        return $labels[$type] ?? '📎 文件';
    }

    private function renderPreview($item) {
        $type = $item['type'];
        
        if ($type === 'image') {
            return '<img src="' . htmlspecialchars($item['file']) . '" alt="' . htmlspecialchars($item['name']) . '">';
        } elseif ($type === 'video') {
            return '<video controls poster="' . htmlspecialchars($item['thumbnail']) . '">
                <source src="' . htmlspecialchars($item['file']) . '" type="video/' . $item['ext'] . '">
                您的浏览器不支持视频播放
            </video>';
        } else {
            $icon = $this->getFileIcon($item['ext']);
            return '<div class="file-preview">
                <div class="file-icon">' . $icon . '</div>
                <p class="file-name">' . htmlspecialchars($item['name']) . '.' . $item['ext'] . '</p>
                <p class="file-size">' . $this->formatFileSize($item['size']) . '</p>
            </div>';
        }
    }

    private function formatFileSize($bytes) {
        $units = ['B', 'KB', 'MB', 'GB'];
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1024, $pow);
        return round($bytes, 2) . ' ' . $units[$pow];
    }

    public function render() {
        $folderId = $_GET['folder'] ?? null;
        $itemId = $_GET['item'] ?? null;

        $html = '<!DOCTYPE html>';
        $html .= '<html lang="zh-CN">';
        $html .= '<head>';
        $html .= '<meta charset="UTF-8">';
        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
        $html .= '<title>Eagle 素材库查看器</title>';
        $html .= '<style>';
        $html .= '* { margin: 0; padding: 0; box-sizing: border-box; }';
        $html .= 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background: #f5f5f5; }';
        $html .= '.container { display: flex; min-height: 100vh; }';
        $html .= '.sidebar { width: 280px; background: #2c3e50; color: #ecf0f1; padding: 20px; overflow-y: auto; }';
        $html .= '.sidebar h2 { margin-bottom: 20px; font-size: 18px; border-bottom: 1px solid #34495e; padding-bottom: 10px; }';
        $html .= '.folder-link { color: #ecf0f1; text-decoration: none; display: block; padding: 8px 0; transition: color 0.3s; }';
        $html .= '.folder-link:hover { color: #3498db; }';
        $html .= '.main-content { flex: 1; padding: 20px; overflow-y: auto; }';
        $html .= '.gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 20px; }';
        $html .= '.gallery-item { background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: transform 0.3s, box-shadow 0.3s; }';
        $html .= '.gallery-item:hover { transform: translateY(-5px); box-shadow: 0 4px 16px rgba(0,0,0,0.15); }';
        $html .= '.thumbnail-wrapper { position: relative; width: 100%; height: 150px; overflow: hidden; }';
        $html .= '.thumbnail { width: 100%; height: 100%; object-fit: cover; display: block; }';
        $html .= '.thumbnail-placeholder { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-size: 48px; background: #ecf0f1; }';
        $html .= '.video-placeholder { background: #2c3e50; }';
        $html .= '.file-placeholder { background: #95a5a6; }';
        $html .= '.video-overlay { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 36px; opacity: 0.9; }';
        $html .= '.item-info { padding: 12px; }';
        $html .= '.item-name { font-size: 14px; font-weight: 500; margin-bottom: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }';
        $html .= '.item-meta { font-size: 12px; color: #7f8c8d; }';
        $html .= '.no-items { text-align: center; color: #7f8c8d; padding: 40px; }';
        $html .= '.item-detail { background: white; border-radius: 8px; padding: 20px; }';
        $html .= '.detail-header { margin-bottom: 20px; border-bottom: 1px solid #ecf0f1; padding-bottom: 15px; }';
        $html .= '.back-link { color: #3498db; text-decoration: none; margin-bottom: 10px; display: inline-block; }';
        $html .= '.detail-content { display: flex; gap: 30px; }';
        $html .= '.detail-preview { flex: 1; }';
        $html .= '.detail-preview img { max-width: 100%; height: auto; border-radius: 4px; }';
        $html .= '.detail-preview video { max-width: 100%; height: auto; border-radius: 4px; }';
        $html .= '.file-preview { text-align: center; padding: 60px 40px; background: #f8f9fa; border-radius: 8px; }';
        $html .= '.file-icon { font-size: 72px; margin-bottom: 20px; }';
        $html .= '.file-name { font-size: 18px; font-weight: 500; margin-bottom: 10px; }';
        $html .= '.file-size { font-size: 14px; color: #7f8c8d; }';
        $html .= '.detail-info { flex: 0 0 300px; }';
        $html .= '.detail-info h3 { margin: 20px 0 10px; font-size: 16px; }';
        $html .= '.info-table { width: 100%; border-collapse: collapse; }';
        $html .= '.info-table th { text-align: left; padding: 8px 0; color: #7f8c8d; font-weight: normal; }';
        $html .= '.info-table td { padding: 8px 0; }';
        $html .= '.download-section { margin: 20px 0; }';
        $html .= '.download-btn { display: inline-block; padding: 10px 20px; background: #3498db; color: white; text-decoration: none; border-radius: 4px; transition: background 0.3s; }';
        $html .= '.download-btn:hover { background: #2980b9; }';
        $html .= '.palettes { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }';
        $html .= '.palette-item { width: 40px; height: 40px; border-radius: 4px; display: flex; align-items: center; justify-content: center; color: white; font-size: 10px; font-weight: bold; text-shadow: 0 1px 2px rgba(0,0,0,0.5); }';
        $html .= '.annotation { color: #34495e; line-height: 1.6; }';
        $html .= '.error { color: #e74c3c; text-align: center; padding: 40px; }';
        $html .= '@media (max-width: 768px) { .container { flex-direction: column; } .sidebar { width: 100%; } .detail-content { flex-direction: column; } .detail-info { flex: 1; } }';
        $html .= '</style>';
        $html .= '</head>';
        $html .= '<body>';
        $html .= '<div class="container">';
        $html .= '<div class="sidebar">';
        $html .= '<h2>📚 文件夹</h2>';
        $html .= '<a href="?" class="folder-link">📁 全部内容</a>';
        $html .= $this->getFolderTree();
        $html .= '</div>';
        $html .= '<div class="main-content">';
        
        if ($itemId) {
            $html .= $this->renderItemDetail($itemId);
        } else {
            $folderName = $folderId ? $this->getFolderName($folderId) : '全部内容';
            $html .= '<h1>' . htmlspecialchars($folderName) . '</h1>';
            $html .= $this->renderGallery($folderId);
        }
        
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</body>';
        $html .= '</html>';
        
        return $html;
    }
}

$libraryPath = __DIR__;
$libraryUrlPath = '';

// 配置：指定资源库的相对路径（默认为当前目录）
$libraryRelativePath = '案例公开.library'; // 例如：'eagle-library'
if (!empty($libraryRelativePath)) {
    $libraryPath = __DIR__ . '/' . $libraryRelativePath;
    $libraryUrlPath = $libraryRelativePath;
}

$viewer = new EagleLibraryViewer($libraryPath, $libraryUrlPath);
echo $viewer->render();
