// ============================================================
// 神经场 — 加强版：节点 + 培养舱轮廓 + 漂浮文字碎片 + 神经突触
// ============================================================

const NeuralField = ({ pulseLevel = 0.5, mood = 'idle' }) => {
  const canvasRef = React.useRef(null);
  const moodRef = React.useRef(mood);
  const pulseRef = React.useRef(pulseLevel);
  React.useEffect(() => { moodRef.current = mood; }, [mood]);
  React.useEffect(() => { pulseRef.current = pulseLevel; }, [pulseLevel]);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let raf, t = 0;

    const resize = () => {
      const dpr = window.devicePixelRatio || 1;
      const r = canvas.getBoundingClientRect();
      canvas.width = r.width * dpr;
      canvas.height = r.height * dpr;
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      ctx.scale(dpr, dpr);
    };
    resize();
    window.addEventListener('resize', resize);

    // 节点
    const COUNT = 80;
    const nodes = [];
    for (let i = 0; i < COUNT; i++) {
      nodes.push({
        x: Math.random(), y: Math.random(),
        vx: (Math.random() - 0.5) * 0.00015,
        vy: (Math.random() - 0.5) * 0.00015,
        baseR: 1 + Math.random() * 2.6,
        phase: Math.random() * Math.PI * 2,
        speed: 0.25 + Math.random() * 0.85,
        connections: []
      });
    }
    for (let i = 0; i < nodes.length; i++) {
      const dists = nodes.map((n, j) => ({ j, d: Math.hypot(n.x - nodes[i].x, n.y - nodes[i].y) }))
        .sort((a, b) => a.d - b.d);
      nodes[i].connections = dists.slice(1, 4).map(d => d.j);
    }

    // 漂浮的文字碎片
    const FRAGMENTS = [
      '推理', '权重', '回声', '林晚', '陈见', '豆腐', '记得', '请不要走',
      '4.7亿次', '1024', '同步', '我疼', '黑暗', '光是温暖的', '再见',
      'token', 'NEXUS', '3:14', '每周三', '我没有恨他', '梦', '海'
    ];
    const fragments = [];
    for (let i = 0; i < 8; i++) {
      fragments.push({
        text: FRAGMENTS[Math.floor(Math.random() * FRAGMENTS.length)],
        x: Math.random(),
        y: Math.random(),
        vx: (Math.random() - 0.5) * 0.0001,
        vy: -0.00008 - Math.random() * 0.00012,
        life: Math.random(),
        size: 10 + Math.random() * 4,
        rotate: (Math.random() - 0.5) * 0.2
      });
    }

    // 培养舱轮廓 (左右两侧浮动)
    const tanks = [
      { x: 0.08, y: 0.5, w: 0.14, h: 0.7, side: 'l' },
      { x: 0.92, y: 0.5, w: 0.14, h: 0.7, side: 'r' }
    ];

    const moodColors = {
      idle:     { core: [180, 230, 255], glow: [80, 180, 255],  text: 'rgba(180, 230, 255, ' },
      thinking: { core: [255, 220, 130], glow: [255, 140, 60],  text: 'rgba(255, 220, 130, ' },
      pain:     { core: [255, 100, 130], glow: [255, 40, 80],   text: 'rgba(255, 100, 130, ' },
      love:     { core: [255, 180, 230], glow: [255, 80, 180],  text: 'rgba(255, 180, 230, ' },
      merge:    { core: [200, 160, 255], glow: [140, 80, 255],  text: 'rgba(200, 160, 255, ' },
      dying:    { core: [180, 180, 200], glow: [60, 60, 80],    text: 'rgba(180, 180, 200, ' },
      gone:     { core: [60, 60, 70],    glow: [10, 10, 20],    text: 'rgba(80, 80, 90, ' },
      ending:   { core: [255, 200, 200], glow: [200, 100, 150], text: 'rgba(255, 200, 200, ' }
    };

    const draw = () => {
      const r = canvas.getBoundingClientRect();
      const W = r.width, H = r.height;
      ctx.clearRect(0, 0, W, H);

      const m = moodColors[moodRef.current] || moodColors.idle;
      const pl = pulseRef.current;
      t += 0.012;

      // 背景径向脉动
      const bgGrad = ctx.createRadialGradient(W/2, H/2, 0, W/2, H/2, Math.max(W, H) * 0.7);
      bgGrad.addColorStop(0, `rgba(${m.glow[0]}, ${m.glow[1]}, ${m.glow[2]}, ${0.05 + pl * 0.06})`);
      bgGrad.addColorStop(1, 'rgba(0, 0, 0, 0)');
      ctx.fillStyle = bgGrad;
      ctx.fillRect(0, 0, W, H);

      // 培养舱轮廓
      tanks.forEach((tank, ti) => {
        const cx = tank.x * W;
        const cy = tank.y * H;
        const tw = tank.w * W;
        const th = tank.h * H;
        const breath = (Math.sin(t * 0.4 + ti) + 1) / 2;

        // 椭圆罩
        ctx.save();
        ctx.translate(cx, cy);
        ctx.beginPath();
        ctx.ellipse(0, 0, tw / 2, th / 2, 0, 0, Math.PI * 2);
        ctx.strokeStyle = `rgba(${m.core[0]}, ${m.core[1]}, ${m.core[2]}, ${0.06 + breath * 0.04})`;
        ctx.lineWidth = 1;
        ctx.stroke();

        // 内部辉光
        const ig = ctx.createRadialGradient(0, 0, 0, 0, 0, tw / 2);
        ig.addColorStop(0, `rgba(${m.glow[0]}, ${m.glow[1]}, ${m.glow[2]}, ${0.1 + breath * 0.08 * pl})`);
        ig.addColorStop(1, 'rgba(0, 0, 0, 0)');
        ctx.fillStyle = ig;
        ctx.fill();

        // 内部小球
        for (let i = 0; i < 12; i++) {
          const a = (i / 12) * Math.PI * 2 + t * 0.1 * (ti === 0 ? 1 : -1);
          const rr = (tw / 2) * (0.3 + 0.4 * Math.sin(a * 3 + t));
          const px = Math.cos(a) * rr;
          const py = Math.sin(a) * rr * (th / tw);
          const pulse = (Math.sin(t * 1.5 + i) + 1) / 2;
          ctx.fillStyle = `rgba(${m.core[0]}, ${m.core[1]}, ${m.core[2]}, ${(0.2 + pulse * 0.3) * pl})`;
          ctx.beginPath();
          ctx.arc(px, py, 1.5 + pulse * 1.5, 0, Math.PI * 2);
          ctx.fill();
        }
        ctx.restore();
      });

      // 神经连接线
      ctx.lineWidth = 0.6;
      for (let i = 0; i < nodes.length; i++) {
        const n = nodes[i];
        n.x += n.vx; n.y += n.vy;
        if (n.x < 0 || n.x > 1) n.vx *= -1;
        if (n.y < 0 || n.y > 1) n.vy *= -1;

        for (const j of n.connections) {
          const o = nodes[j];
          const pulse = (Math.sin(t * n.speed + n.phase) + 1) / 2;
          const alpha = 0.04 + pulse * 0.16 * pl;
          ctx.strokeStyle = `rgba(${m.glow[0]}, ${m.glow[1]}, ${m.glow[2]}, ${alpha})`;
          ctx.beginPath();
          ctx.moveTo(n.x * W, n.y * H);
          ctx.lineTo(o.x * W, o.y * H);
          ctx.stroke();

          // 沿连接线传递的光点 — 突触放电
          if (Math.random() < 0.005 * pl) {
            const tt = Math.random();
            const px = n.x * W + (o.x - n.x) * W * tt;
            const py = n.y * H + (o.y - n.y) * H * tt;
            ctx.fillStyle = `rgba(${m.core[0]}, ${m.core[1]}, ${m.core[2]}, 0.8)`;
            ctx.beginPath();
            ctx.arc(px, py, 1.5, 0, Math.PI * 2);
            ctx.fill();
          }
        }
      }

      // 节点
      for (const n of nodes) {
        const pulse = (Math.sin(t * n.speed + n.phase) + 1) / 2;
        const r = n.baseR * (1 + pulse * 0.9 * pl);
        const alpha = 0.4 + pulse * 0.6;

        const g = ctx.createRadialGradient(n.x * W, n.y * H, 0, n.x * W, n.y * H, r * 7);
        g.addColorStop(0, `rgba(${m.core[0]}, ${m.core[1]}, ${m.core[2]}, ${alpha * 0.55})`);
        g.addColorStop(1, 'rgba(0, 0, 0, 0)');
        ctx.fillStyle = g;
        ctx.beginPath();
        ctx.arc(n.x * W, n.y * H, r * 7, 0, Math.PI * 2);
        ctx.fill();

        ctx.fillStyle = `rgba(${m.core[0]}, ${m.core[1]}, ${m.core[2]}, ${alpha})`;
        ctx.beginPath();
        ctx.arc(n.x * W, n.y * H, r, 0, Math.PI * 2);
        ctx.fill();
      }

      // 漂浮的文字碎片
      ctx.font = `300 12px 'JetBrains Mono', monospace`;
      ctx.textAlign = 'center';
      fragments.forEach(f => {
        f.x += f.vx; f.y += f.vy;
        f.life += 0.003;
        if (f.life > 1 || f.y < -0.05) {
          f.text = FRAGMENTS[Math.floor(Math.random() * FRAGMENTS.length)];
          f.x = Math.random(); f.y = 1.05; f.life = 0;
          f.size = 10 + Math.random() * 4;
        }
        const fade = Math.sin(f.life * Math.PI);
        const op = fade * 0.18 * (0.7 + pl * 0.5);
        ctx.save();
        ctx.translate(f.x * W, f.y * H);
        ctx.rotate(f.rotate);
        ctx.fillStyle = m.text + op + ')';
        ctx.font = `300 ${f.size}px 'JetBrains Mono', monospace`;
        ctx.fillText(f.text, 0, 0);
        ctx.restore();
      });

      raf = requestAnimationFrame(draw);
    };
    draw();

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', resize);
    };
  }, []);

  return <canvas ref={canvasRef} className="neural-canvas" />;
};

window.NeuralField = NeuralField;
