// 文字量子纠缠演示
// 输入核心汉字 → 展示与其他文明符号的量子纠缠关联
// 以古风星图/连线形式可视化

const { useState, useEffect } = React;

function EntanglementTool({ onNavigate }) {
  const [inputChar, setInputChar] = useState("龙");
  const [displayChar, setDisplayChar] = useState("龙");
  const [hoveredPair, setHoveredPair] = useState(null);
  const [showAll, setShowAll] = useState(true);

  const pairs = entanglementData[displayChar]?.pairs || [];
  
  // 生成星图坐标
  const generatePositions = (pairs) => {
    const positions = [];
    const centerX = 250;
    const centerY = 220;
    const radius = 150;
    
    pairs.forEach((pair, idx) => {
      const angle = (idx / pairs.length) * Math.PI * 2 - Math.PI / 2;
      const x = centerX + Math.cos(angle) * radius;
      const y = centerY + Math.sin(angle) * radius * 0.75;
      positions.push({ x, y, angle });
    });
    
    return positions;
  };

  const positions = generatePositions(pairs);
  const centerX = 250;
  const centerY = 220;

  const handleGenerate = () => {
    if (!inputChar || inputChar.length === 0) return;
    const char = inputChar[0];
    if (!/[\u4e00-\u9fa5]/.test(char)) return;
    setDisplayChar(char);
    setShowAll(false);
    setTimeout(() => setShowAll(true), 100);
  };

  const handleKeyPress = (e) => {
    if (e.key === "Enter") handleGenerate();
  };

  const quickChars = ["龙", "鼎", "仁", "天", "文"];

  // 古风装饰星点
  const starPoints = Array.from({ length: 40 }, (_, i) => ({
    x: Math.random() * 500,
    y: Math.random() * 440,
    size: Math.random() * 2 + 1,
    opacity: Math.random() * 0.5 + 0.2,
    delay: Math.random() * 2
  }));

  return (
    <div className="tool-container">
      <ToolHeader
        icon="綴"
        title="文字量子纠缠"
        subtitle="输入某文明核心字符，系统自动生成其他文明相关符号。此现象首见于己亥年「鼎」字与古埃及圣书体关联实验。"
      />

      {/* 输入区 */}
      <div className="tool-panel">
        <h3 className="tool-panel-title">核心字符</h3>
        <div style={{ display: "flex", gap: "16px", alignItems: "center", flexWrap: "wrap" }}>
          <input
            type="text"
            className="form-input"
            style={{ flex: "1", minWidth: "200px", fontSize: "24px", fontFamily: "var(--font-brush)" }}
            value={inputChar}
            onChange={(e) => setInputChar(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="请输入一个汉字..."
            maxLength={1}
          />
          <button className="btn btn-seal" onClick={handleGenerate}>
            探赜索隐
          </button>
        </div>
        <div style={{ marginTop: "16px", display: "flex", gap: "8px", flexWrap: "wrap" }}>
          <span style={{ fontFamily: "var(--font-body)", color: "var(--ink-faint)", fontSize: "14px" }}>试字：</span>
          {quickChars.map(c => (
            <button
              key={c}
              onClick={() => { setInputChar(c); setDisplayChar(c); setShowAll(false); setTimeout(() => setShowAll(true), 100); }}
              style={{
                padding: "6px 14px",
                background: displayChar === c ? "var(--seal)" : "transparent",
                color: displayChar === c ? "var(--paper-light)" : "var(--ink-soft)",
                border: "1px solid var(--line-strong)",
                borderRadius: "2px",
                fontFamily: "var(--font-brush)",
                fontSize: "16px",
                cursor: "pointer",
                transition: "all 0.2s"
              }}
            >
              {c}
            </button>
          ))}
        </div>
      </div>

      {/* 星图可视化 */}
      <div className="tool-panel">
        <h3 className="tool-panel-title">
          量子纠缠星图
          <span style={{ 
            fontSize: "13px", 
            fontFamily: "var(--font-body)", 
            color: "var(--ink-faint)", 
            marginLeft: "auto",
            fontWeight: "normal"
          }}>
            共 {pairs.length} 对纠缠态
          </span>
        </h3>

        <div style={{ 
          position: "relative", 
          width: "100%", 
          maxWidth: "500px", 
          margin: "0 auto",
          aspectRatio: "500/440"
        }}>
          <svg viewBox="0 0 500 440" style={{ width: "100%", height: "100%" }}>
            {/* 背景装饰圈 */}
            <circle cx={centerX} cy={centerY} r="180" fill="none" stroke="var(--line)" strokeWidth="1" strokeDasharray="4 6" opacity="0.5" />
            <circle cx={centerX} cy={centerY} r="120" fill="none" stroke="var(--line)" strokeWidth="1" strokeDasharray="2 4" opacity="0.3" />
            
            {/* 装饰星点 */}
            {starPoints.map((star, idx) => (
              <circle
                key={idx}
                cx={star.x}
                cy={star.y}
                r={star.size}
                fill="var(--ink)"
                opacity={star.opacity}
              >
                <animate
                  attributeName="opacity"
                  values={`${star.opacity};${star.opacity * 0.3};${star.opacity}`}
                  dur={`${2 + star.delay}s`}
                  repeatCount="indefinite"
                />
              </circle>
            ))}

            {/* 连线 */}
            {pairs.map((pair, idx) => {
              if (!positions[idx]) return null;
              const isActive = hoveredPair === idx;
              const strength = pair.strength;
              return (
                <g key={`line-${idx}`}>
                  {/* 主线 */}
                  <line
                    x1={centerX}
                    y1={centerY}
                    x2={positions[idx].x}
                    y2={positions[idx].y}
                    stroke={isActive ? "var(--seal)" : "var(--ochre)"}
                    strokeWidth={isActive ? 2.5 : 1 + strength}
                    opacity={showAll ? (isActive ? 1 : 0.4 + strength * 0.5) : 0}
                    strokeDasharray={strength > 0.7 ? "none" : "6 4"}
                    style={{ transition: "all 0.4s", transitionDelay: `${idx * 0.1}s` }}
                  />
                  {/* 流光粒子 */}
                  {isActive && (
                    <circle r="4" fill="var(--seal)">
                      <animateMotion
                        dur="1.5s"
                        repeatCount="indefinite"
                        path={`M${centerX},${centerY} L${positions[idx].x},${positions[idx].y}`}
                      />
                    </circle>
                  )}
                </g>
              );
            })}

            {/* 中心字符 */}
            <g>
              <circle
                cx={centerX}
                cy={centerY}
                r="45"
                fill="var(--seal)"
                opacity="0.15"
              >
                <animate attributeName="r" values="45;52;45" dur="3s" repeatCount="indefinite" />
                <animate attributeName="opacity" values="0.15;0.25;0.15" dur="3s" repeatCount="indefinite" />
              </circle>
              <circle
                cx={centerX}
                cy={centerY}
                r="38"
                fill="var(--seal)"
                opacity="0.9"
              />
              <text
                x={centerX}
                y={centerY + 8}
                textAnchor="middle"
                fill="var(--paper-light)"
                fontFamily="var(--font-brush)"
                fontSize="36"
                fontWeight="700"
              >
                {displayChar}
              </text>
              <text
                x={centerX}
                y={centerY + 60}
                textAnchor="middle"
                fill="var(--ink-light)"
                fontFamily="var(--font-kai)"
                fontSize="12"
                letterSpacing="2"
              >
                核心字符
              </text>
            </g>

            {/* 外围文明符号 */}
            {pairs.map((pair, idx) => {
              if (!positions[idx]) return null;
              const isActive = hoveredPair === idx;
              return (
                <g 
                  key={`node-${idx}`}
                  style={{ 
                    cursor: "pointer",
                    opacity: showAll ? 1 : 0,
                    transition: `opacity 0.5s ease ${idx * 0.15}s`
                  }}
                  onMouseEnter={() => setHoveredPair(idx)}
                  onMouseLeave={() => setHoveredPair(null)}
                >
                  {/* 节点光晕 */}
                  <circle
                    cx={positions[idx].x}
                    cy={positions[idx].y}
                    r={isActive ? 28 : 22}
                    fill="var(--paper-light)"
                    stroke={isActive ? "var(--seal)" : "var(--line-strong)"}
                    strokeWidth={isActive ? 2 : 1}
                    style={{ transition: "all 0.3s" }}
                  />
                  {/* 符号文字 */}
                  <text
                    x={positions[idx].x}
                    y={positions[idx].y + 5}
                    textAnchor="middle"
                    fill="var(--ink)"
                    fontFamily="var(--font-brush)"
                    fontSize={isActive ? "16" : "14"}
                    style={{ transition: "all 0.3s" }}
                  >
                    {pair.symbol.slice(0, 2)}
                  </text>
                  {/* 强度指示 */}
                  <circle
                    cx={positions[idx].x + 18}
                    cy={positions[idx].y - 18}
                    r="5"
                    fill={pair.strength > 0.8 ? "var(--seal)" : pair.strength > 0.6 ? "var(--ochre)" : "var(--ink-faint)"}
                  />
                </g>
              );
            })}
          </svg>
        </div>

        {/* 纠缠对列表 */}
        <div style={{ marginTop: "24px" }}>
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))",
            gap: "12px"
          }}>
            {pairs.map((pair, idx) => (
              <div
                key={idx}
                onMouseEnter={() => setHoveredPair(idx)}
                onMouseLeave={() => setHoveredPair(null)}
                style={{
                  padding: "14px 18px",
                  background: hoveredPair === idx ? "rgba(184, 58, 42, 0.06)" : "var(--paper)",
                  border: `1px solid ${hoveredPair === idx ? "var(--seal)" : "var(--line)"}`,
                  borderRadius: "4px",
                  cursor: "pointer",
                  transition: "all 0.25s",
                  display: "flex",
                  alignItems: "center",
                  gap: "14px"
                }}
              >
                <div style={{
                  width: "44px",
                  height: "44px",
                  borderRadius: "50%",
                  background: "var(--paper-light)",
                  border: "1px solid var(--line-strong)",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontFamily: "var(--font-brush)",
                  fontSize: "16px",
                  color: "var(--seal)",
                  flexShrink: "0"
                }}>
                  {pair.symbol.slice(0, 2)}
                </div>
                <div style={{ flex: "1", minWidth: "0" }}>
                  <div style={{
                    fontFamily: "var(--font-brush)",
                    fontSize: "16px",
                    color: "var(--ink)",
                    marginBottom: "2px"
                  }}>
                    {pair.symbol}
                  </div>
                  <div style={{
                    fontSize: "12px",
                    color: "var(--ink-faint)",
                    fontFamily: "var(--font-kai)"
                  }}>
                    {pair.culture}
                  </div>
                </div>
                <div style={{ textAlign: "right", flexShrink: "0" }}>
                  <div style={{
                    fontFamily: "var(--font-brush)",
                    fontSize: "18px",
                    color: pair.strength > 0.8 ? "var(--seal)" : "var(--ochre)"
                  }}>
                    {Math.round(pair.strength * 100)}
                  </div>
                  <div style={{
                    fontSize: "10px",
                    color: "var(--ink-faint)",
                    fontFamily: "var(--font-kai)"
                  }}>
                    纠缠度
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 选中项详情 */}
        {hoveredPair !== null && pairs[hoveredPair] && (
          <div style={{
            marginTop: "20px",
            padding: "20px 24px",
            background: "var(--paper)",
            border: "1px solid var(--seal)",
            borderLeft: "4px solid var(--seal)",
            borderRadius: "0 4px 4px 0",
            animation: "fadeInUp 0.3s ease-out"
          }}>
            <div style={{
              fontFamily: "var(--font-brush)",
              fontSize: "20px",
              color: "var(--seal)",
              marginBottom: "8px",
              letterSpacing: "0.1em"
            }}>
              「{displayChar}」↔ {pairs[hoveredPair].symbol}
            </div>
            <div style={{
              fontFamily: "var(--font-body)",
              fontSize: "14px",
              color: "var(--ink-faint)",
              marginBottom: "10px"
            }}>
              {pairs[hoveredPair].culture} · 纠缠度 {Math.round(pairs[hoveredPair].strength * 100)}%
            </div>
            <p style={{
              fontFamily: "var(--font-body)",
              fontSize: "15px",
              color: "var(--ink-soft)",
              lineHeight: "2"
            }}>
              {pairs[hoveredPair].relation}
            </p>
          </div>
        )}
      </div>

      <BackButton onNavigate={onNavigate} />
    </div>
  );
}

window.EntanglementTool = EntanglementTool;
