'use client'
import React from 'react'

export type MenuItem = {key: string, label: string, desc?: string, icon?: string}
export type Section = {title: string, items: MenuItem[]}

export const MENU: Section[] = [
  {
    title: '官网教程',
    items: [
      {key: 'browser-proxy', label: '浏览器设置代理教程'},
      {key: 'code-download', label: '代码下载'},
      {key: 'api-docs', label: 'API 文档'},
    ],
  },
  {
    title: '客户端教程',
    items: [
      {key: 'client-install', label: '客户端安装与配置'},
      {key: 'client-usage', label: '客户端使用指南'},
    ],
  },
  {
    title: '操作指南',
    items: [
      {key: 'faq', label: '常见问题', desc: '常见问题与解答'},
      {key: 'troubleshoot', label: '故障排查', desc: '排查与解决常见故障'},
    ],
  },
]

type Props = {
  collapsed?: boolean
  selected?: string
  onSelect?: (key: string) => void
  onToggle?: () => void
}

export default function Sidebar({collapsed = false, selected, onSelect, onToggle}: Props) {
  const [expanded, setExpanded] = React.useState<Record<string, boolean>>(() => {
    const s: Record<string, boolean> = {}
    MENU.forEach((section, idx) => (s[section.title] = idx === 0))
    return s
  })

  const toggleSection = (title: string) => {
    setExpanded(prev => ({...prev, [title]: !prev[title]}))
  }

  return (
    <aside className={`bg-white border rounded p-3 transition-all duration-200 flex-shrink-0 ${collapsed ? 'w-20' : 'w-72'}`}>
      <nav className="space-y-2">
        {MENU.map(section => (
          <div key={section.title}>
            <div
              onClick={() => toggleSection(section.title)}
              className={`flex items-center gap-2 cursor-pointer px-3 py-2 rounded-sm transition-colors ${expanded[section.title] && !collapsed ? 'bg-blue-50' : 'hover:bg-slate-50'}`}
            >
              <div className={`w-4 flex items-center justify-center text-sm text-slate-400 transform transition-transform ${expanded[section.title] ? 'rotate-90' : ''}`}>
                ▸
              </div>

              {!collapsed && (
                <div className="text-lg font-semibold text-slate-900">
                  {section.title}
                </div>
              )}
            </div>

            {expanded[section.title] && (
              <ul className={`mt-1 text-base ${collapsed ? 'hidden' : 'block'}`}>
                {section.items.map((item) => {
                  const active = selected === item.key
                  return (
                    <li
                      key={item.key}
                      onClick={() => onSelect?.(item.key)}
                      className={`pl-8 py-2 text-base cursor-pointer transition-colors ${active ? 'text-blue-600 font-semibold' : 'text-slate-700 hover:text-slate-900'}`}
                    >
                      {item.label}
                    </li>
                  )
                })}
              </ul>
            )}
          </div>
        ))}
      </nav>
    </aside>
  )
}
