// ChildSwitcher：子女切换组件（MF 暴露 ./ChildSwitcher）
// 依据：02-architecture-design.md §15.1 ChildSwitcher 设计、F10 MF 暴露粒度
// - 多子女：下拉选择器
// - 单子女：仅显示子女名称（不可切换）
// - 无子女：显示空状态提示
// - ISSUE-009：纯前端切换，不调后端

"use client";

import { useState, useRef, useEffect, type KeyboardEvent } from "react";
// 修正：onKeyDown 绑定到 <button>，需用 HTMLButtonElement
import { useChildSwitcher } from "@/hooks/useChildSwitcher";
import { cn } from "@/lib/utils";

export function ChildSwitcher() {
  const { children, currentChild, currentChildId, switchChild, loading } =
    useChildSwitcher();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  // 点击外部关闭
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, []);

  if (loading) {
    return (
      <span className="skeleton h-8 w-32 rounded" aria-label="加载子女列表" />
    );
  }

  if (children.length === 0) {
    return (
      <span className="text-sm text-ink-muted" aria-label="未绑定子女">
        未绑定子女
      </span>
    );
  }

  // 单子女：仅显示
  if (children.length === 1) {
    return (
      <span className="font-serif text-base" aria-label="当前子女">
        {children[0]?.name}
      </span>
    );
  }

  // 多子女：下拉选择器
  function handleKeyDown(e: KeyboardEvent<HTMLButtonElement>) {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      setOpen((v) => !v);
    }
    if (e.key === "Escape") setOpen(false);
  }

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label="选择子女"
        onClick={() => setOpen((v) => !v)}
        onKeyDown={handleKeyDown}
        className="flex items-center gap-2 rounded border border-rule bg-paper px-3 py-1.5 text-sm transition-colors hover:bg-paper-elevated"
      >
        <span className="font-serif text-base">{currentChild?.name}</span>
        <svg
          className={cn("h-4 w-4 transition-transform", open && "rotate-180")}
          viewBox="0 0 20 20"
          fill="currentColor"
          aria-hidden="true"
        >
          <path
            fillRule="evenodd"
            d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
            clipRule="evenodd"
          />
        </svg>
      </button>

      {open && (
        <ul
          role="listbox"
          aria-label="子女列表"
          className="absolute right-0 z-50 mt-1 min-w-48 rounded border border-rule bg-paper-elevated py-1 shadow-lg"
        >
          {children.map((child) => (
            <li
              key={child.id}
              role="option"
              aria-selected={child.id === currentChildId}
            >
              <button
                type="button"
                onClick={() => {
                  switchChild(child.id);
                  setOpen(false);
                }}
                className={cn(
                  "block w-full px-4 py-2 text-left text-sm transition-colors hover:bg-accent-soft",
                  child.id === currentChildId && "bg-accent-soft font-medium",
                )}
              >
                <span className="font-serif">{child.name}</span>
                {child.className && (
                  <span className="ml-2 text-xs text-ink-muted">
                    {child.className}
                  </span>
                )}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default ChildSwitcher;
