// Animated workflow diagram. Two variants:
//   HeroDiagram   — Start → Condition → WaitUntil → Action → End
//   TruckDiagram  — Speeding truck monitor demo with event stream

const NODE_KIND_STYLES = {
  start:    { fill: "#0F1322", stroke: "#22D3EE", glow: "#22D3EE", icon: "▶" },
  trigger:  { fill: "#0F1322", stroke: "#22D3EE", glow: "#22D3EE", icon: "↯" },
  cond:     { fill: "#13162A", stroke: "#818CF8", glow: "#6366F1", icon: "?" },
  wait:     { fill: "#13162A", stroke: "#A78BFA", glow: "#8B5CF6", icon: "⧗" },
  counter:  { fill: "#13162A", stroke: "#A78BFA", glow: "#8B5CF6", icon: "Σ" },
  action:   { fill: "#0F1F1C", stroke: "#34D399", glow: "#34D399", icon: "⚡" },
  end:      { fill: "#1F1216", stroke: "#F87171", glow: "#F87171", icon: "■" },
};

function DiagramNode({ x, y, w = 132, h = 56, kind, label, sub, active, fired }) {
  const s = NODE_KIND_STYLES[kind] || NODE_KIND_STYLES.cond;
  return (
    <g transform={`translate(${x} ${y})`}>
      {/* glow halo */}
      <rect
        x={-6} y={-6} width={w+12} height={h+12} rx={14}
        fill={s.glow}
        style={{
          opacity: active ? 0.22 : 0,
          filter: "blur(10px)",
          transition: "opacity .4s ease",
        }}
      />
      <rect
        x={0} y={0} width={w} height={h} rx={10}
        fill={s.fill}
        stroke={active ? s.stroke : "rgba(255,255,255,0.10)"}
        strokeWidth={active ? 1.5 : 1}
        style={{ transition: "stroke .25s ease, stroke-width .25s ease" }}
      />
      {/* left status bar */}
      <rect x={0} y={0} width={4} height={h} rx={2}
            fill={s.stroke}
            style={{ opacity: active ? 1 : 0.45, transition: "opacity .3s" }}/>
      {/* icon */}
      <g transform={`translate(14 ${h/2})`}>
        <circle r={11} fill={`${s.stroke}22`} stroke={`${s.stroke}66`} />
        <text textAnchor="middle" dominantBaseline="central"
              fill={s.stroke} fontSize={11} fontFamily="Geist Mono, monospace"
              fontWeight={600}>
          {s.icon}
        </text>
      </g>
      {/* label */}
      <text x={36} y={h/2 - 2} fill="#EDEFF7" fontSize={12} fontWeight={500}
            fontFamily="Geist, sans-serif" dominantBaseline="alphabetic">
        {label}
      </text>
      <text x={36} y={h/2 + 14} fill="#5B6378" fontSize={10}
            fontFamily="Geist Mono, monospace" dominantBaseline="alphabetic">
        {sub}
      </text>
      {/* fired pulse */}
      {fired && (
        <rect x={-1} y={-1} width={w+2} height={h+2} rx={11}
              fill="none" stroke={s.stroke} strokeWidth={1.5}
              style={{ animation: "node-fire 1s ease-out" }}/>
      )}
    </g>
  );
}

// Edge: animated path with a flowing particle when active
function DiagramEdge({ d, active, color = "#6366F1", reverse }) {
  return (
    <g>
      <path d={d} fill="none"
            stroke="rgba(255,255,255,0.12)" strokeWidth={1.25}
            strokeDasharray="3 4" />
      <path d={d} fill="none"
            stroke={color} strokeWidth={1.5}
            style={{
              opacity: active ? 0.9 : 0,
              transition: "opacity .35s ease",
            }} />
      {active && (
        <circle r={3.5} fill={color}>
          <animateMotion dur="1.1s" repeatCount="indefinite"
                         path={d}
                         keyPoints={reverse ? "1;0" : "0;1"}
                         keyTimes="0;1"/>
          <animate attributeName="opacity"
                   values="0;1;1;0" keyTimes="0;0.15;0.85;1"
                   dur="1.1s" repeatCount="indefinite"/>
        </circle>
      )}
    </g>
  );
}

/* ──────────────────────────────────────────────────────────────
   HeroDiagram — runs a looping animation across the 5 nodes
   ────────────────────────────────────────────────────────────── */
function HeroDiagram() {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => (t + 1) % 6), 1200);
    return () => clearInterval(id);
  }, []);

  // Geometry
  const W = 560, H = 360;
  const nodes = [
    { id: "trigger", kind: "trigger", label: "Webhook",   sub: "POST /events",   x: 24,  y: 50 },
    { id: "cond",    kind: "cond",    label: "Condition", sub: "if speed > 80",  x: 220, y: 50 },
    { id: "wait",    kind: "wait",    label: "WaitUntil", sub: "count == 3",     x: 220, y: 160 },
    { id: "action",  kind: "action",  label: "API Call",  sub: "issue.ticket()", x: 410, y: 160 },
    { id: "end",     kind: "end",     label: "End",       sub: "instance done",  x: 410, y: 270 },
  ];

  // Right-angle edges (rounded corners via arc)
  const edges = [
    { id: "e1", from: "trigger", to: "cond",
      d: "M 156 78 L 220 78" },
    { id: "e2", from: "cond", to: "wait",
      d: "M 286 106 L 286 160" },
    { id: "e3", from: "wait", to: "action",
      d: "M 352 188 L 410 188" },
    { id: "e4", from: "action", to: "end",
      d: "M 476 216 L 476 270" },
  ];

  // simple step-based activation
  const activeNodeIdx = tick - 1;
  const activeEdgeIdx = tick - 1;

  return (
    <div className="hero-diagram-wrap" style={{ position: "relative", width: "100%" }}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block", overflow: "visible" }}>
        <defs>
          <linearGradient id="edgeGrad" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor="#6366F1" />
            <stop offset="100%" stopColor="#22D3EE" />
          </linearGradient>
          <pattern id="dots" width="22" height="22" patternUnits="userSpaceOnUse">
            <circle cx="1" cy="1" r="1" fill="rgba(255,255,255,0.08)" />
          </pattern>
        </defs>

        {/* Dot grid bg behind the diagram */}
        <rect x={0} y={0} width={W} height={H} fill="url(#dots)" rx={16}/>
        <rect x={0} y={0} width={W} height={H} fill="none"
              stroke="rgba(255,255,255,0.05)" rx={16}/>

        {edges.map((e, i) => (
          <DiagramEdge key={e.id} d={e.d}
                       active={activeEdgeIdx === i || tick === 5}
                       color={i === 1 ? "#A78BFA" : i === 2 ? "#34D399" : "#6366F1"} />
        ))}

        {nodes.map((n, i) => (
          <DiagramNode key={n.id} {...n}
                       active={activeNodeIdx >= i}
                       fired={activeNodeIdx === i} />
        ))}

        {/* labels: floating */}
        <text x={W-12} y={H-12} textAnchor="end"
              fill="#3a4054" fontSize={10} fontFamily="Geist Mono, monospace">
          diagram.v1 · instance_4f3a
        </text>
      </svg>
      <style>{`
        @keyframes node-fire {
          0%   { opacity: 0.9; transform: scale(1); }
          100% { opacity: 0;   transform: scale(1.08); transform-origin: center; }
        }
      `}</style>
    </div>
  );
}

/* ──────────────────────────────────────────────────────────────
   StepViz — small diagrams in How-It-Works cards
   ────────────────────────────────────────────────────────────── */
function StepVizDefine() {
  return (
    <svg viewBox="0 0 280 92" width="100%" height="100%" style={{ display: "block" }}>
      <defs>
        <pattern id="sv1-dots" width="14" height="14" patternUnits="userSpaceOnUse">
          <circle cx="1" cy="1" r="0.7" fill="rgba(255,255,255,0.07)" />
        </pattern>
      </defs>
      <rect width="280" height="92" fill="url(#sv1-dots)"/>
      <rect x="22" y="26" width="60" height="40" rx="7" fill="#13162A"
            stroke="#22D3EE" strokeOpacity=".5"/>
      <text x="52" y="50" textAnchor="middle" fontSize="10" fill="#EDEFF7"
            fontFamily="Geist Mono, monospace">trigger</text>
      <rect x="110" y="26" width="60" height="40" rx="7" fill="#13162A"
            stroke="#818CF8" strokeOpacity=".5"/>
      <text x="140" y="50" textAnchor="middle" fontSize="10" fill="#EDEFF7"
            fontFamily="Geist Mono, monospace">if/else</text>
      <rect x="198" y="26" width="60" height="40" rx="7" fill="#13162A"
            stroke="#34D399" strokeOpacity=".5" strokeDasharray="3 3"/>
      <text x="228" y="50" textAnchor="middle" fontSize="10" fill="#5B6378"
            fontFamily="Geist Mono, monospace">drop…</text>
      <line x1="82" y1="46" x2="110" y2="46" stroke="#6366F1" strokeWidth="1.2"/>
      <line x1="170" y1="46" x2="198" y2="46" stroke="rgba(255,255,255,.15)" strokeDasharray="2 3" strokeWidth="1"/>
    </svg>
  );
}

function StepVizWebhook() {
  return (
    <svg viewBox="0 0 280 92" width="100%" height="100%" style={{ display: "block" }}>
      <rect x="14" y="20" width="120" height="52" rx="8" fill="#0C0E1A" stroke="rgba(255,255,255,.1)"/>
      <text x="24" y="40" fill="#22D3EE" fontSize="10" fontFamily="Geist Mono, monospace">POST /v1/events</text>
      <text x="24" y="54" fill="#9CA3B7" fontSize="9" fontFamily="Geist Mono, monospace">{`{ "type": "ping" }`}</text>
      <text x="24" y="66" fill="#5B6378" fontSize="9" fontFamily="Geist Mono, monospace">x-tenant: acme</text>
      {/* arrow */}
      <path d="M 140 46 L 170 46" stroke="#6366F1" strokeWidth="1.5" fill="none"/>
      <path d="M 170 46 L 163 42 L 163 50 Z" fill="#6366F1"/>
      {/* fluentra side */}
      <rect x="178" y="20" width="88" height="52" rx="8" fill="#11131F"
            stroke="#6366F1" strokeOpacity=".5"/>
      <circle cx="222" cy="40" r="6" fill="#6366F1" opacity=".3"/>
      <circle cx="222" cy="40" r="3" fill="#22D3EE"/>
      <text x="222" y="60" textAnchor="middle" fill="#9CA3B7" fontSize="9"
            fontFamily="Geist Mono, monospace">routed</text>
    </svg>
  );
}

function StepVizRuntime() {
  return (
    <svg viewBox="0 0 280 92" width="100%" height="100%" style={{ display: "block" }}>
      {/* row of instances */}
      {[0,1,2,3,4].map((i) => {
        const y = 20 + i*0; // not used, but stacked horizontally
        const cx = 30 + i*52;
        const states = ["running","waiting","running","done","running"];
        const color = {running:"#22D3EE", waiting:"#A78BFA", done:"#34D399"}[states[i]];
        return (
          <g key={i} transform={`translate(${cx} 26)`}>
            <rect width="40" height="40" rx="7" fill="#0F1322"
                  stroke={color} strokeOpacity=".5"/>
            <circle cx="20" cy="14" r="4" fill={color}>
              {states[i] !== "done" &&
                <animate attributeName="opacity" values="1;.3;1" dur="1.6s"
                         begin={`${i*0.2}s`} repeatCount="indefinite"/>}
            </circle>
            <text x="20" y="30" textAnchor="middle" fontSize="8" fill="#9CA3B7"
                  fontFamily="Geist Mono, monospace">#{1000+i}</text>
          </g>
        );
      })}
      <text x="14" y="82" fill="#5B6378" fontSize="9" fontFamily="Geist Mono, monospace">
        5 instances · 1 waiting · stateful
      </text>
    </svg>
  );
}

/* ──────────────────────────────────────────────────────────────
   TruckDiagram — speeding truck monitor demo
   ────────────────────────────────────────────────────────────── */
function TruckDiagram({ events = [], count = 0, fired = false }) {
  // Layout: trigger → counter → cond(=3) → action / else loop
  const W = 580, H = 380;
  const trig    = { x: 28,  y: 165, w: 132, h: 56 };
  const counter = { x: 198, y: 165, w: 140, h: 56 };
  const cond    = { x: 376, y: 165, w: 140, h: 56 };
  const action  = { x: 376, y: 64,  w: 170, h: 56 };
  const wait    = { x: 376, y: 274, w: 170, h: 56 };

  // recent firing - last event drives node activation flow
  const lastTime = events[0]?.t ?? 0;
  const recent = Date.now() - lastTime < 700;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block", overflow: "visible" }}>
      <defs>
        <pattern id="tk-dots" width="22" height="22" patternUnits="userSpaceOnUse">
          <circle cx="1" cy="1" r="1" fill="rgba(255,255,255,0.06)" />
        </pattern>
      </defs>
      <rect width={W} height={H} fill="url(#tk-dots)" rx={14}/>

      {/* edges */}
      <DiagramEdge d={`M ${trig.x+trig.w} ${trig.y+trig.h/2} L ${counter.x} ${counter.y+counter.h/2}`}
                   active={recent} color="#22D3EE" />
      <DiagramEdge d={`M ${counter.x+counter.w} ${counter.y+counter.h/2} L ${cond.x} ${cond.y+cond.h/2}`}
                   active={recent} color="#A78BFA" />
      {/* yes branch up */}
      <DiagramEdge d={`M ${cond.x+cond.w/2} ${cond.y} L ${cond.x+cond.w/2} ${action.y+action.h}`}
                   active={fired} color="#34D399" />
      {/* no branch down (loop back) */}
      <DiagramEdge d={`M ${cond.x+cond.w/2} ${cond.y+cond.h} L ${cond.x+cond.w/2} ${wait.y}`}
                   active={recent && !fired} color="#6366F1" />

      <DiagramNode {...trig}    kind="trigger"  label="Truck event"     sub="POST /speeding" active={recent} fired={recent} />
      <DiagramNode {...counter} kind="counter"  label={`Counter`}       sub={`count = ${count}`} active={recent} fired={recent} />
      <DiagramNode {...cond}    kind="cond"     label="If count == 3"   sub={fired ? "→ yes" : "→ no"}  active={recent} fired={recent} />
      <DiagramNode {...action}  kind="action"   label="Issue ticket"    sub="POST /tickets" active={fired} fired={fired} />
      <DiagramNode {...wait}    kind="wait"     label="Wait 1h window"  sub="reset if idle"
                                active={recent && !fired} fired={recent && !fired} />

      {/* yes/no labels */}
      <text x={cond.x+cond.w/2 + 8} y={action.y+action.h + 16}
            fill="#34D399" fontSize={10} fontFamily="Geist Mono, monospace">yes</text>
      <text x={cond.x+cond.w/2 + 8} y={cond.y+cond.h + 14}
            fill="#6366F1" fontSize={10} fontFamily="Geist Mono, monospace">no</text>

      <text x={W-12} y={H-10} textAnchor="end"
            fill="#3a4054" fontSize={10} fontFamily="Geist Mono, monospace">
        speeding-truck-monitor.v3
      </text>
    </svg>
  );
}

Object.assign(window, {
  HeroDiagram,
  TruckDiagram,
  StepVizDefine,
  StepVizWebhook,
  StepVizRuntime,
  DiagramNode,
  DiagramEdge,
});
