import React, { useMemo } from 'react'
import { useStatusBarStore, type StatusBarItem } from '../../stores/statusBarStore'

/**
 * StatusBar — 纯渲染层
 *
 * 不包含任何业务逻辑。所有状态栏项由各功能模块通过
 * useStatusBarStore.register() 注入，本组件按 alignment + priority 排序渲染。
 * 每个 item.Component 是独立 React 组件，可自由使用 hooks。
 */

export const StatusBar = React.memo(function StatusBar() {
  const items = useStatusBarStore(s => s.items)

  const sorted = useMemo(() => {
    const list = Object.values(items)
    if (list.length === 0) return { left: [] as StatusBarItem[], right: [] as StatusBarItem[] }
    const byAlignment = (a: 'left' | 'right') =>
      list.filter(i => i.alignment === a).sort((x, y) => x.priority - y.priority)
    return { left: byAlignment('left'), right: byAlignment('right') }
  }, [items])

  return (
    <div id="statusbar" role="status" aria-live="polite">
      <div className="status-left">
        {sorted.left.map(({ id, Component }) => (
          <Component key={id} />
        ))}
      </div>
      <div className="status-right">
        {sorted.right.map(({ id, Component }, i) => (
          <React.Fragment key={id}>
            {i > 0 && <span className="status-divider">|</span>}
            <Component />
          </React.Fragment>
        ))}
      </div>
    </div>
  )
})

StatusBar.displayName = 'StatusBar'
