// 仓颉Ⅲ型文字生成器
// 输入汉字 → 展示文字基因链解构（甲骨文→金文→篆文→隶书→楷书演变）
// 以及十万维度基因链可视化

const { useState, useEffect } = React;

function CangjieTool({ onNavigate }) {
  const [inputChar, setInputChar] = useState("龙");
  const [displayChar, setDisplayChar] = useState("龙");
  const [activeStage, setActiveStage] = useState(4);
  const [isGenerating, setIsGenerating] = useState(false);
  const [geneBars, setGeneBars] = useState([]);

  const stages = [
    { name: "甲骨文", era: "商", color: "#8B4513" },
    { name: "金  文", era: "周", color: "#A0522D" },
    { name: "篆  文", era: "秦", color: "#6B4423" },
    { name: "隶  书", era: "汉", color: "#4A3728" },
    { name: "楷  书", era: "唐", color: "#2A241E" }
  ];

  // 生成基因链数据
  const generateGeneChain = (char) => {
    const charData = cangjieData.characters[char];
    const baseDim = charData ? charData.dimension : 10000 + Math.floor(Math.random() * 5000);
    
    const bars = [];
    const categories = [
      { name: "形义基因", count: 12, color: "#B83A2A" },
      { name: "音韵基因", count: 10, color: "#A65D2F" },
      { name: "结构基因", count: 14, color: "#3A6B8C" },
      { name: "文化基因", count: 12, color: "#5B8C6A" },
      { name: "演变基因", count: 10, color: "#8B4513" }
    ];
    
    categories.forEach(cat => {
      for (let i = 0; i < cat.count; i++) {
        bars.push({
          category: cat.name,
          color: cat.color,
          height: 30 + Math.random() * 70,
          width: 4 + Math.random() * 6,
          opacity: 0.4 + Math.random() * 0.6
        });
      }
    });
    
    // 打乱顺序
    for (let i = bars.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [bars[i], bars[j]] = [bars[j], bars[i]];
    }
    
    return { bars, dimension: baseDim };
  };

  useEffect(() => {
    const { bars, dimension } = generateGeneChain(displayChar);
    setGeneBars(bars);
  }, [displayChar]);

  const handleGenerate = () => {
    if (!inputChar || inputChar.length === 0) return;
    const char = inputChar[0];
    // 只处理中文字符
    if (!/[\u4e00-\u9fa5]/.test(char)) return;
    
    setIsGenerating(true);
    setActiveStage(0);
    
    // 模拟演变过程
    let stage = 0;
    const interval = setInterval(() => {
      stage++;
      setActiveStage(stage);
      if (stage >= 4) {
        clearInterval(interval);
        setDisplayChar(char);
        setIsGenerating(false);
      }
    }, 400);
  };

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

  const charData = cangjieData.characters[displayChar];
  const stageNames = ["oracleDesc", "bronzeDesc", "sealDesc", "clericalDesc", "regularDesc"];
  const currentDesc = charData ? charData[stageNames[activeStage]] : "文字基因链解析中...";
  const dimension = charData ? charData.dimension : (10000 + displayChar.charCodeAt(0) % 5000);

  // 快速选择字符
  const quickChars = ["龙", "鼎", "仁", "天", "文"];

  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}
            disabled={isGenerating}
          >
            {isGenerating ? "生成中..." : "基因解构"}
          </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); setActiveStage(4); }}
              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">文字演变 · 五体同观</h3>
        
        <div className="cj-stages-grid" style={{ 
          display: "grid", 
          gridTemplateColumns: "repeat(5, 1fr)", 
          gap: "12px",
          marginBottom: "24px"
        }}>
          {stages.map((stage, idx) => (
            <div
              key={idx}
              onClick={() => setActiveStage(idx)}
              style={{
                textAlign: "center",
                padding: "20px 12px",
                background: activeStage === idx ? "rgba(184, 58, 42, 0.08)" : "var(--paper)",
                border: `2px solid ${activeStage === idx ? "var(--seal)" : "var(--line)"}`,
                borderRadius: "4px",
                cursor: "pointer",
                transition: "all 0.3s",
                position: "relative"
              }}
              className="char-evolve"
            >
              <div style={{
                fontSize: "clamp(32px, 6vw, 56px)",
                fontFamily: idx === 0 ? "var(--font-brush)" : "var(--font-serif-body)",
                color: stage.color,
                marginBottom: "8px",
                fontWeight: idx === 4 ? "700" : "400",
                textShadow: idx < 2 ? "2px 2px 0 rgba(139, 69, 19, 0.1)" : "none",
                transform: idx === 0 ? "rotate(-3deg)" : idx === 1 ? "rotate(1deg)" : "none",
                filter: isGenerating && idx > activeStage ? "blur(2px)" : "none",
                opacity: isGenerating && idx > activeStage ? "0.3" : "1"
              }}>
                {displayChar}
              </div>
              <div style={{
                fontFamily: "var(--font-body)",
                fontSize: "14px",
                color: activeStage === idx ? "var(--seal)" : "var(--ink-light)",
                letterSpacing: "0.15em",
                marginBottom: "4px"
              }}>
                {stage.name}
              </div>
              <div style={{
                fontSize: "11px",
                color: "var(--ink-faint)",
                fontFamily: "var(--font-song)"
              }}>
                {stage.era}代
              </div>
              {activeStage === idx && (
                <div style={{
                  position: "absolute",
                  bottom: "-8px",
                  left: "50%",
                  transform: "translateX(-50%)",
                  width: "12px",
                  height: "12px",
                  background: "var(--seal)",
                  borderRadius: "50%",
                  border: "2px solid var(--paper-light)"
                }}></div>
              )}
            </div>
          ))}
        </div>

        {/* 当前阶段描述 */}
        <div style={{
          padding: "20px 24px",
          background: "var(--paper)",
          border: "1px solid var(--line)",
          borderLeft: "4px solid var(--seal)",
          borderRadius: "0 4px 4px 0"
        }}>
          <div style={{
            fontFamily: "var(--font-brush)",
            fontSize: "18px",
            color: "var(--seal)",
            marginBottom: "8px",
            letterSpacing: "0.1em"
          }}>
            {stages[activeStage].name} · 形态解析
          </div>
          <p style={{
            fontFamily: "var(--font-body)",
            fontSize: "15px",
            color: "var(--ink-soft)",
            lineHeight: "2"
          }}>
            {currentDesc}
          </p>
        </div>
      </div>

      {/* 基因链可视化 */}
      <div className="tool-panel">
        <h3 className="tool-panel-title">
          十万维度基因链
          <span style={{ 
            fontSize: "14px", 
            fontFamily: "var(--font-body)", 
            color: "var(--ink-faint)", 
            marginLeft: "auto",
            fontWeight: "normal"
          }}>
            解析维度：<span style={{ color: "var(--seal)", fontFamily: "var(--font-brush)", fontSize: "18px" }}>{dimension.toLocaleString()}</span> 维
          </span>
        </h3>

        {/* 基因链卷轴可视化 */}
        <div className="gene-chain-wrap" style={{
          background: "linear-gradient(to right, rgba(166, 93, 47, 0.05), transparent, rgba(166, 93, 47, 0.05))",
          border: "1px solid var(--line)",
          borderRadius: "4px",
          padding: "24px 16px",
          marginBottom: "20px",
          overflowX: "auto"
        }}>
          <div style={{
            display: "flex",
            alignItems: "flex-end",
            justifyContent: "center",
            gap: "3px",
            height: "140px",
            marginBottom: "16px",
            minWidth: "480px"
          }}>
            {geneBars.slice(0, 58).map((bar, idx) => (
              <div
                key={idx}
                style={{
                  width: `${bar.width}px`,
                  height: `${bar.height}%`,
                  background: bar.color,
                  opacity: bar.opacity,
                  borderRadius: "2px 2px 0 0",
                  animation: `fadeInUp 0.5s ease-out ${idx * 0.01}s both`
                }}
                title={`${bar.category} · 基因位点 ${idx + 1}`}
              ></div>
            ))}
          </div>
          
          {/* 基因链标注线 */}
          <div style={{
            display: "flex",
            justifyContent: "space-between",
            padding: "0 20px",
            borderTop: "1px dashed var(--line-strong)",
            paddingTop: "12px",
            minWidth: "480px"
          }}>
            {["形义", "音韵", "结构", "文化", "演变"].map((name, idx) => (
              <div key={idx} style={{ textAlign: "center" }}>
                <div style={{
                  width: "10px",
                  height: "10px",
                  background: ["var(--seal)", "var(--ochre)", "var(--azure)", "var(--jade)", "var(--ink-light)"][idx],
                  borderRadius: "50%",
                  margin: "0 auto 6px"
                }}></div>
                <span style={{
                  fontFamily: "var(--font-body)",
                  fontSize: "12px",
                  color: "var(--ink-light)",
                  letterSpacing: "0.2em"
                }}>
                  {name}基因
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* 全息元胞信息 */}
        <div className="holo-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "12px" }}>
          <div style={{
            padding: "16px",
            border: "1px solid var(--line)",
            borderRadius: "4px",
            textAlign: "center"
          }}>
            <div style={{ fontFamily: "var(--font-body)", fontSize: "12px", color: "var(--ink-faint)", marginBottom: "6px" }}>本义</div>
            <div style={{ fontFamily: "var(--font-body)", fontSize: "14px", color: "var(--ink-soft)", lineHeight: "1.7" }}>
              {charData ? charData.meaning : "待考"}
            </div>
          </div>
          <div style={{
            padding: "16px",
            border: "1px solid var(--line)",
            borderRadius: "4px",
            textAlign: "center"
          }}>
            <div style={{ fontFamily: "var(--font-body)", fontSize: "12px", color: "var(--ink-faint)", marginBottom: "6px" }}>构件</div>
            <div style={{ fontFamily: "var(--font-brush)", fontSize: "20px", color: "var(--seal)" }}>
              {charData ? charData.components.join(" + ") : "—"}
            </div>
          </div>
          <div style={{
            padding: "16px",
            border: "1px solid var(--line)",
            borderRadius: "4px",
            textAlign: "center"
          }}>
            <div style={{ fontFamily: "var(--font-body)", fontSize: "12px", color: "var(--ink-faint)", marginBottom: "6px" }}>基因维度</div>
            <div style={{ fontFamily: "var(--font-brush)", fontSize: "22px", color: "var(--azure)" }}>
              {dimension.toLocaleString()} 维
            </div>
          </div>
        </div>
      </div>

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

window.CangjieTool = CangjieTool;
