/* global React */
const { useState, useEffect, useRef } = React;

// ============================================
// AUTOMATION FLOW HERO VISUAL
// 5 nodes connected in a workflow, animated activation cycle.
// ============================================
window.AutomationFlow = function AutomationFlow({ t }) {
  const [activeIdx, setActiveIdx] = useState(0);
  const [logs, setLogs] = useState([]);
  const [dotPos, setDotPos] = useState(null);

  const positions = [
    { x: 8,  y: 8 },
    { x: 56, y: 8 },
    { x: 8,  y: 35 },
    { x: 56, y: 35 },
    { x: 30, y: 62 },
  ];

  useEffect(() => {
    const i = setInterval(() => {
      setActiveIdx(prev => {
        const next = (prev + 1) % t.flow.nodes.length;
        setLogs(l => {
          const newLog = t.flow.logs[next];
          const out = [...l, { id: Date.now() + next, text: newLog }];
          return out.slice(-3);
        });
        return next;
      });
    }, 1700);
    return () => clearInterval(i);
  }, [t]);

  useEffect(() => {
    setLogs([]);
  }, [t]);

  useEffect(() => {
    const prev = (activeIdx - 1 + positions.length) % positions.length;
    const from = positions[prev];
    const to = positions[activeIdx];
    let start;
    let raf;
    const dur = 600;
    const animate = (ts) => {
      if (!start) start = ts;
      const p = Math.min(1, (ts - start) / dur);
      const eased = p < 0.5 ? 2*p*p : 1 - Math.pow(-2*p + 2, 2) / 2;
      setDotPos({
        x: from.x + (to.x - from.x) * eased + 9,
        y: from.y + (to.y - from.y) * eased + 4,
      });
      if (p < 1) raf = requestAnimationFrame(animate);
      else setDotPos(null);
    };
    raf = requestAnimationFrame(animate);
    return () => cancelAnimationFrame(raf);
  }, [activeIdx]);

  const connections = positions.map((p, i) => {
    const next = positions[(i + 1) % positions.length];
    return { from: p, to: next, id: i };
  });

  const pathFor = (from, to) => {
    const fx = from.x + 18, fy = from.y + 5.5;
    const tx = to.x + 18, ty = to.y + 5.5;
    const midX = (fx + tx) / 2;
    return `M ${fx} ${fy} L ${midX} ${fy} L ${midX} ${ty} L ${tx} ${ty}`;
  };

  return (
    <div className="flow-container" data-magnet>
      <div className="flow-header">
        <span>{t.flow.header}</span>
        <span className="led">
          <i className="on"/><i className={activeIdx >= 1 ? "on" : ""}/><i className={activeIdx >= 3 ? "on" : ""}/>
          <span style={{marginLeft: 8, color: "var(--accent)"}}>{t.flow.status}</span>
        </span>
      </div>
      <div className="flow-canvas">
        <svg className="flow-svg" viewBox="0 0 100 70" preserveAspectRatio="none">
          {connections.map((c, i) => (
            <path
              key={c.id}
              d={pathFor(c.from, c.to)}
              fill="none"
              stroke={i === (activeIdx - 1 + connections.length) % connections.length ? "var(--accent)" : "var(--line-strong)"}
              strokeWidth="0.25"
              strokeDasharray={i === (activeIdx - 1 + connections.length) % connections.length ? "0" : "0.6 0.6"}
              style={{transition: "stroke .3s ease"}}
            />
          ))}
          {dotPos && (
            <circle cx={dotPos.x} cy={dotPos.y} r="0.8" fill="var(--accent)" style={{filter: "drop-shadow(0 0 1.5px var(--accent))"}}/>
          )}
        </svg>
        {t.flow.nodes.map((n, i) => (
          <div
            key={i}
            className={`flow-node ${i === activeIdx ? "active" : ""}`}
            style={{ left: positions[i].x + "%", top: positions[i].y + "%" }}
          >
            <div className="nh">
              <span>{n.code}</span>
              <span className="nd"/>
            </div>
            <div className="nv">{n.label}</div>
          </div>
        ))}
      </div>
      <div className="flow-log">
        {logs.map((l, i) => (
          <span key={l.id} className="ll" style={{opacity: 0.35 + 0.65 * (i / Math.max(1, logs.length - 1))}}>
            <span className="t">›</span>{l.text}
          </span>
        ))}
      </div>
    </div>
  );
};
