import React, { useMemo } from 'react';
import { useApp } from '../context/AppContext';
import { NODE_TYPES } from '../utils/fileUtils';
import './Sidebar.css';

function TreeNode({ node, level = 0 }) {
  const { selectFile, toggleNodeExpansion, currentFile } = useApp();

  // 计算当前目录下的直接文章数量
  const articleCount = useMemo(() => {
    if (node.type !== NODE_TYPES.FOLDER || !node.children) {
      return 0;
    }
    return node.children.filter(child => 
      child.type === NODE_TYPES.FILE && child.name.endsWith('.md')
    ).length;
  }, [node]);

  const handleClick = () => {
    if (node.type === NODE_TYPES.FOLDER) {
      toggleNodeExpansion(node.path);
    } else {
      selectFile(node.path);
    }
  };

  const isSelected = currentFile === node.path;
  const hasChildren = node.children && node.children.length > 0;
  const paddingLeft = `${level * 18 + 14}px`;
  const contentClass = isSelected ? 'tree-node-content selected' : 'tree-node-content';
  const folderIconClass = `tree-node-icon${node.isExpanded ? ' expanded' : ''}`;

  return (
    <div className="tree-node">
      <div
        className={contentClass}
        style={{ paddingLeft }}
        onClick={handleClick}
        role="button"
        tabIndex={0}
        onKeyDown={(event) => {
          if (event.key === 'Enter' || event.key === ' ') {
            event.preventDefault();
            handleClick();
          }
        }}
      >
        {node.type === NODE_TYPES.FOLDER && (
          <span className={folderIconClass} aria-hidden>
            {hasChildren ? (node.isExpanded ? '📂' : '📁') : '📁'}
          </span>
        )}
        {node.type === NODE_TYPES.FILE && (
          <span className="tree-node-icon" aria-hidden>📄</span>
        )}
        <span className="tree-node-name">
          {node.type === NODE_TYPES.FILE && node.name.endsWith('.md') 
            ? node.name.slice(0, -3) 
            : node.name}
        </span>
        {node.type === NODE_TYPES.FOLDER && articleCount > 0 && (
          <span className="article-count-badge">[{articleCount}]</span>
        )}
      </div>

      {node.type === NODE_TYPES.FOLDER && node.isExpanded && hasChildren && (
        <div className="tree-node-children">
          {node.children.map((child) => (
            <TreeNode key={child.path} node={child} level={level + 1} />
          ))}
        </div>
      )}
    </div>
  );
}

export default function Sidebar() {
  const { directoryTree, isLoading, error, sidebarOpen, toggleSidebar } = useApp();

  return (
    <>
      <aside className={sidebarOpen ? 'sidebar open' : 'sidebar closed'} aria-hidden={!sidebarOpen}>
        <div className="sidebar-header">
          <h2>📚 文章目录</h2>
          <button
            type="button"
            onClick={toggleSidebar}
            className="toggle-button"
            aria-label={sidebarOpen ? '隐藏目录' : '展开目录'}
            title={sidebarOpen ? '隐藏目录' : '展开目录'}
          >
            {sidebarOpen ? '◀' : '▶'}
          </button>
        </div>

        <div className="sidebar-content">
          {isLoading && (
            <div className="loading">
              <div className="loading-spinner" aria-hidden />
              <span>加载中...</span>
            </div>
          )}

          {error && (
            <div className="error">
              <span>目录加载失败: {error}</span>
            </div>
          )}

          {!isLoading && !error && (
            <div className="directory-tree">
              {directoryTree.map((node) => (
                <TreeNode key={node.path} node={node} />
              ))}
            </div>
          )}
        </div>
      </aside>
    </>
  );
}
