// 存档广场 - 最简可渲染版本
// 确保页面打开就有内容，绝对不白屏

const { useState, Component } = React;

// ========== 静态文件数据（写死，兜底用） ==========
const STATIC_FILES = [
  {
    id: 1,
    file_name: '2024年度工作总结报告.docx',
    file_type: 'document',
    file_size: '2.4 MB',
    uploader: '行政小王',
    uploader_color: '#165DFF',
    created_at: '2026-09-18 14:30',
    visibility: 'public',
    downloads: 128,
    description: '包含全年工作回顾、数据统计和明年规划。',
  },
  {
    id: 2,
    file_name: '公司团建活动合影.jpg',
    file_type: 'image',
    file_size: '8.6 MB',
    uploader: '人事小李',
    uploader_color: '#10B981',
    created_at: '2026-09-17 09:15',
    visibility: 'public',
    downloads: 56,
    description: '上周六团建活动大合影，大家笑得很开心~',
    thumb_color: '#34D399',
  },
  {
    id: 3,
    file_name: '产品发布宣讲视频.mp4',
    file_type: 'video',
    file_size: '156 MB',
    uploader: '产品老张',
    uploader_color: '#F59E0B',
    created_at: '2026-09-15 16:45',
    visibility: 'public',
    downloads: 234,
    description: '新产品线上发布会完整录像，含Q&A环节。',
    thumb_color: '#FBBF24',
  },
  {
    id: 4,
    file_name: '技术架构设计文档.pdf',
    file_type: 'document',
    file_size: '5.1 MB',
    uploader: '架构师老刘',
    uploader_color: '#9333EA',
    created_at: '2026-09-14 11:20',
    visibility: 'public',
    downloads: 45,
    description: '系统整体架构图及各模块详细设计说明。',
  },
];

// ========== 错误边界 ==========
class ArchiveErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorInfo: '' };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, errorInfo: error?.message || '' };
  }
  componentDidCatch(error, errorInfo) {
    console.error('[ArchivePage] 渲染错误:', error, errorInfo);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div style={{
          minHeight: '100vh',
          padding: '16px',
          background: 'var(--bg-page)',
          color: 'var(--text-primary)',
          fontFamily: 'system-ui, -apple-system, sans-serif',
        }}>
          <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 12 }}>存档广场</div>
          <div style={{ fontSize: 14, color: '#EF4444', marginBottom: 8 }}>页面加载异常</div>
          <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 16 }}>
            {this.state.errorInfo || '内容暂时无法显示'}
          </div>
          <button
            onClick={() => this.setState({ hasError: false, errorInfo: '' })}
            style={{
              padding: '8px 20px',
              background: 'var(--primary)',
              color: '#fff',
              border: 'none',
              borderRadius: 16,
              fontSize: 13,
              cursor: 'pointer',
            }}
          >
            重新加载
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// ========== 文件类型图标 ==========
function FileIcon({ type = 'document', size = 40, color = '#165DFF' }) {
  const iconMap = {
    document: '📄',
    image: '🖼️',
    video: '🎬',
    audio: '🎵',
    archive: '📦',
    other: '📁',
  };
  const bgColors = {
    document: '#EFF6FF',
    image: '#ECFDF5',
    video: '#FFF7ED',
    audio: '#FDF4FF',
    archive: '#F3F4F6',
    other: '#F3F4F6',
  };
  return (
    <div style={{
      width: size,
      height: size,
      borderRadius: 8,
      background: bgColors[type] || bgColors.other,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontSize: size * 0.5,
      flexShrink: 0,
    }}>
      {iconMap[type] || iconMap.other}
    </div>
  );
}

// ========== 存档卡片 ==========
function ArchiveCard({ item }) {
  const isImage = item.file_type === 'image';
  const isVideo = item.file_type === 'video';

  return (
    <div style={{
      background: 'var(--bg-card)',
      borderRadius: 12,
      padding: 14,
      marginBottom: 10,
      display: 'flex',
      gap: 12,
      border: '1px solid var(--border)',
    }}>
      {isImage || isVideo ? (
        <div style={{
          width: 80,
          height: 80,
          borderRadius: 8,
          background: item.thumb_color || '#E5E7EB',
          flexShrink: 0,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: 28,
          position: 'relative',
        }}>
          {isVideo && (
            <div style={{
              position: 'absolute',
              bottom: 6,
              right: 6,
              padding: '2px 6px',
              background: 'rgba(0,0,0,0.6)',
              color: '#fff',
              fontSize: 10,
              borderRadius: 4,
            }}>
              ▶
            </div>
          )}
          {isImage ? '🖼️' : '🎬'}
        </div>
      ) : (
        <FileIcon type={item.file_type} size={48} />
      )}

      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
        <div style={{
          fontSize: 14,
          fontWeight: 600,
          color: 'var(--text-primary)',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
        }}>
          {item.file_name}
        </div>
        <div style={{
          fontSize: 12,
          color: 'var(--text-secondary)',
          display: '-webkit-box',
          WebkitLineClamp: 2,
          WebkitBoxOrient: 'vertical',
          overflow: 'hidden',
          lineHeight: 1.5,
        }}>
          {item.description}
        </div>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          marginTop: 'auto',
        }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: 6,
            fontSize: 11,
            color: 'var(--text-tertiary)',
          }}>
            <div style={{
              width: 16,
              height: 16,
              borderRadius: '50%',
              background: item.uploader_color || '#9CA3AF',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: '#fff',
              fontSize: 9,
              fontWeight: 600,
            }}>
              {item.uploader?.charAt(0) || '?'}
            </div>
            <span>{item.uploader}</span>
            <span>·</span>
            <span>{item.file_size}</span>
          </div>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: 4,
            fontSize: 11,
            color: 'var(--text-tertiary)',
          }}>
            <span>⬇️</span>
            <span>{item.downloads}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ========== 存档页面 ==========
function ArchivePage() {
  const [activeTab, setActiveTab] = useState('all');

  const tabs = [
    { key: 'all', label: '全部' },
    { key: 'document', label: '文档' },
    { key: 'image', label: '图片' },
    { key: 'video', label: '视频' },
  ];

  const filtered = activeTab === 'all'
    ? STATIC_FILES
    : STATIC_FILES.filter(f => f.file_type === activeTab);

  return (
    <ArchiveErrorBoundary>
      <PageWrapper>
        <AppHeader title="存档广场" subtitle="知识沉淀 · 永久保存" showActions={true} />
        {/* 分类 Tab */}
        <div style={{
          display: 'flex',
          padding: '0 8px',
          borderBottom: '1px solid var(--border)',
          overflowX: 'auto',
          background: 'var(--bg-card)',
          position: 'sticky',
          top: 49,
          zIndex: 15,
        }}>
            {tabs.map((tab) => (
              <div
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                style={{
                  padding: '10px 14px',
                  fontSize: 13,
                  fontWeight: activeTab === tab.key ? 600 : 400,
                  color: activeTab === tab.key ? 'var(--primary)' : 'var(--text-secondary)',
                  borderBottom: activeTab === tab.key
                    ? '2px solid var(--primary)'
                    : '2px solid transparent',
                  whiteSpace: 'nowrap',
                  cursor: 'pointer',
                  transition: 'all 0.2s',
                }}
              >
                {tab.label}
              </div>
          ))}
        </div>

        {/* 统计信息条 */}
        <div style={{
          padding: '10px 16px',
          background: 'var(--bg-card)',
          borderBottom: '1px solid var(--border)',
          display: 'flex',
          gap: 20,
          fontSize: 12,
          color: 'var(--text-secondary)',
        }}>
          <span>
            共 <span style={{ color: 'var(--primary)', fontWeight: 600 }}>{filtered.length}</span> 个存档
          </span>
          <span>
            今日新增 <span style={{ color: '#10B981', fontWeight: 600 }}>12</span>
          </span>
        </div>

        {/* 文件列表 */}
        <div style={{ padding: '12px 14px 24px' }}>
          {filtered.length === 0 ? (
            <div style={{
              background: 'var(--bg-card)',
              borderRadius: 12,
              padding: '40px 20px',
              textAlign: 'center',
              color: 'var(--text-tertiary)',
              border: '1px solid var(--border)',
            }}>
              <div style={{ fontSize: 32, marginBottom: 12 }}>📁</div>
              <div style={{ fontSize: 13 }}>
                暂无{tabs.find(t => t.key === activeTab)?.label}存档
              </div>
            </div>
          ) : (
            filtered.map((item, idx) => (
              <ArchiveCard key={item.id || idx} item={item} />
            ))
          )}
        </div>
      </PageWrapper>
    </ArchiveErrorBoundary>
  );
}

Object.assign(window, { ArchivePage });
