/* OrchEcomm website — the orchestration node diagram (signature brand graphic).
 * Central hub + orbiting module nodes, animated data-flow pulses, hover tooltips.
 * Modes: default (light, on white), decorative (dark slice background),
 *        enhanced (larger + richer animation, for the Solution hero). */
function OrchestrationDiagram({ decorative = false, enhanced = false, onDark = false }) {
  const I = window.OcWebIcons;
  const [hover, setHover] = React.useState(null);
  const reduce = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  const cfg = enhanced
    ? { VW: 700, VH: 580, cx: 350, cy: 290, rx: 290, ry: 215, nodeR: 35, hubR: 54, icon: 25, font: 13, maxW: 940 }
    : { VW: 620, VH: 500, cx: 310, cy: 250, rx: 250, ry: 180, nodeR: 30, hubR: 46, icon: 22, font: 12, maxW: 620 };
  const { VW, VH, cx, cy, rx, ry, nodeR, hubR } = cfg;

  const nodes = [
    { id: "pay", label: "Payments", icon: "Card", desc: "Smart routing across every processor.", a: 0 },
    { id: "ship", label: "Shipping", icon: "Truck", desc: "Compare rates and print labels.", a: 45 },
    { id: "orders", label: "Orders", icon: "Cart", desc: "One queue for every platform's orders.", a: 90 },
    { id: "analytics", label: "Analytics", icon: "Chart", desc: "Every metric, unified in one view.", a: 135 },
    { id: "stock", label: "Stock", icon: "Package", desc: "Real-time inventory across platforms.", a: 180 },
    { id: "suppliers", label: "Suppliers", icon: "Factory", desc: "Source and order from verified suppliers.", a: 225 },
    { id: "visual", label: "Visual Content", icon: "Image", desc: "On-brand graphics, generated automatically.", a: 270 },
    { id: "email", label: "Email", icon: "Mail", desc: "Triggered flows that recover revenue.", a: 315 },
  ].map((n) => ({ ...n, x: cx + rx * Math.cos((n.a * Math.PI) / 180), y: cy + ry * Math.sin((n.a * Math.PI) / 180) }));

  const dark = decorative || onDark;
  const lineCol = dark ? "rgba(149,213,178,0.34)" : "rgba(82,183,136,0.40)";
  const pulseCol = dark ? "#95D5B2" : "#52B788";
  const labelCol = dark ? "var(--green-200)" : "var(--text-secondary)";

  // mid-orbit ellipse path for orbiting satellites (clockwise)
  const orbR1x = rx * 0.62, orbR1y = ry * 0.62;
  const ellipsePath = (ex, ey) => `M${cx - ex},${cy} a${ex},${ey} 0 1,0 ${ex * 2},0 a${ex},${ey} 0 1,0 ${-ex * 2},0`;

  return (
    <div style={{ position: "relative", width: "100%", maxWidth: decorative ? "none" : cfg.maxW, margin: "0 auto", height: decorative ? "100%" : "auto" }}>
      <svg viewBox={`0 0 ${VW} ${VH}`} width="100%" height={decorative ? "100%" : "auto"} preserveAspectRatio={decorative ? "xMidYMid slice" : "xMidYMid meet"} style={{ display: "block", overflow: "visible" }}>
        <defs>
          <radialGradient id="hubGlow" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor={dark ? "rgba(149,213,178,0.55)" : "rgba(82,183,136,0.35)"} />
            <stop offset="100%" stopColor="transparent" />
          </radialGradient>
        </defs>

        {/* enhanced: slowly counter-rotating dashed orbit rings */}
        {enhanced ? (
          <g>
            <ellipse cx={cx} cy={cy} rx={rx} ry={ry} fill="none" stroke={dark ? "rgba(149,213,178,0.22)" : "rgba(82,183,136,0.20)"} strokeWidth="1.3" strokeDasharray="2 9">
              {!reduce ? <animateTransform attributeName="transform" type="rotate" from={`0 ${cx} ${cy}`} to={`360 ${cx} ${cy}`} dur="60s" repeatCount="indefinite" /> : null}
            </ellipse>
            <ellipse cx={cx} cy={cy} rx={rx * 0.78} ry={ry * 0.78} fill="none" stroke={dark ? "rgba(149,213,178,0.16)" : "rgba(82,183,136,0.16)"} strokeWidth="1.3" strokeDasharray="2 11">
              {!reduce ? <animateTransform attributeName="transform" type="rotate" from={`360 ${cx} ${cy}`} to={`0 ${cx} ${cy}`} dur="46s" repeatCount="indefinite" /> : null}
            </ellipse>
          </g>
        ) : null}

        {/* connection lines */}
        {nodes.map((n) => {
          const on = hover === n.id;
          return <path key={"l" + n.id} d={`M${cx},${cy} L${n.x.toFixed(1)},${n.y.toFixed(1)}`} fill="none"
            stroke={on ? pulseCol : lineCol} strokeWidth={on ? 2.4 : 1.6} style={{ transition: "stroke 0.2s, stroke-width 0.2s" }} />;
        })}

        {/* data-flow pulses along each line */}
        {!reduce && nodes.map((n, i) => {
          const dur = enhanced ? 1.8 + (i % 3) * 0.4 : 2.2 + (i % 3) * 0.5;
          return (
            <circle key={"p" + n.id} r={hover === n.id ? 4.8 : enhanced ? 3.4 : 3} fill={pulseCol} opacity={dark ? 0.95 : 1}>
              <animateMotion dur={`${dur}s`} begin={`${(i * 0.26).toFixed(2)}s`} repeatCount="indefinite" path={`M${cx},${cy} L${n.x.toFixed(1)},${n.y.toFixed(1)}`} />
              <animate attributeName="opacity" values="0;1;1;0" dur={`${dur}s`} begin={`${(i * 0.26).toFixed(2)}s`} repeatCount="indefinite" />
            </circle>
          );
        })}

        {/* enhanced: satellites orbiting the hub */}
        {enhanced && !reduce ? [0, 1, 2].map((k) => (
          <circle key={"sat" + k} r={k === 1 ? 3.2 : 2.4} fill={pulseCol} opacity={dark ? 0.8 : 0.7}>
            <animateMotion dur={`${14 + k * 5}s`} begin={`${k * 3}s`} repeatCount="indefinite" rotate="auto" path={ellipsePath(orbR1x + k * 16, orbR1y + k * 12)} />
          </circle>
        )) : null}

        {/* glow halo behind hub */}
        <circle cx={cx} cy={cy} r={hubR + 34} fill="url(#hubGlow)" />

        {/* module nodes */}
        {nodes.map((n) => {
          const on = hover === n.id;
          return (
            <g key={n.id} transform={`translate(${n.x},${n.y})`} style={{ cursor: decorative ? "default" : "pointer" }}
              onMouseEnter={() => !decorative && setHover(n.id)} onMouseLeave={() => !decorative && setHover(null)}>
              {/* soft active glow ring */}
              {on ? <circle r={nodeR + 7} fill="none" stroke={pulseCol} strokeWidth="1.5" opacity="0.5" /> : null}
              <circle r={nodeR} fill={dark ? (on ? "#52B788" : "#fff") : "#fff"}
                stroke={dark ? (on ? "#52B788" : "rgba(255,255,255,0.7)") : on ? "#52B788" : "var(--border-default)"} strokeWidth={on ? 2.2 : 1.4}
                style={{ transition: "all 0.2s", filter: on ? "drop-shadow(0 6px 18px rgba(45,106,79,0.30))" : "none" }}>
                {enhanced && !reduce ? <animate attributeName="r" values={`${nodeR};${nodeR + 1.6};${nodeR}`} dur="3.4s" begin={`${(n.a / 360) * 2}s`} repeatCount="indefinite" /> : null}
              </circle>
              <g transform={`translate(${-cfg.icon / 2},${-cfg.icon / 2})`} style={{ color: dark ? (on ? "#fff" : "var(--green-700)") : "var(--green-700)", transition: "color 0.2s" }}>
                {React.createElement(I[n.icon], { size: cfg.icon })}
              </g>
              {!decorative ? <text y={nodeR + 18} textAnchor="middle" style={{ font: "var(--font-sans)", fontSize: cfg.font, fontWeight: 600, fill: on ? (dark ? "#fff" : "var(--green-800)") : labelCol }}>{n.label}</text> : null}
            </g>
          );
        })}

        {/* central hub */}
        <g transform={`translate(${cx},${cy})`}>
          {/* expanding rings */}
          {!reduce ? [0, 1].map((k) => (
            <circle key={"hr" + k} r={hubR} fill="none" stroke={pulseCol} strokeWidth="2" opacity={dark ? 0.45 : 0.5}>
              <animate attributeName="r" values={`${hubR};${hubR + (enhanced ? 30 : 16)}`} dur={enhanced ? "3.2s" : "3s"} begin={`${k * 1.6}s`} repeatCount="indefinite" />
              <animate attributeName="opacity" values={`${dark ? 0.45 : 0.5};0`} dur={enhanced ? "3.2s" : "3s"} begin={`${k * 1.6}s`} repeatCount="indefinite" />
            </circle>
          )) : null}
          <circle r={hubR} fill={dark ? "#fff" : "var(--green-800)"} stroke={dark ? "rgba(255,255,255,0.6)" : "var(--green-900)"} strokeWidth="2" style={{ filter: "drop-shadow(0 8px 26px rgba(27,67,50,0.34))" }} />
        </g>
      </svg>

      {/* hub logo overlay (HTML for crisp SVG logo) */}
      <div style={{ position: "absolute", left: `${(cx / VW) * 100}%`, top: `${(cy / VH) * 100}%`, transform: "translate(-50%,-50%)", pointerEvents: "none", textAlign: "center" }}>
        <img src="../../assets/orchecomm-mark.svg" height={enhanced ? 38 : decorative ? 30 : 34} alt="" />
      </div>

      {/* hover tooltip */}
      {!decorative && hover ? (() => {
        const n = nodes.find((x) => x.id === hover);
        const leftPct = (n.x / VW) * 100, topPct = (n.y / VH) * 100;
        const flip = n.x > cx;
        return (
          <div style={{ position: "absolute", left: `${leftPct}%`, top: `${topPct}%`, transform: `translate(${flip ? "-108%" : "8%"}, -130%)`, background: "var(--ink-900)", color: "#fff", borderRadius: "var(--radius-md)", padding: "10px 13px", boxShadow: "var(--shadow-lg)", width: 210, pointerEvents: "none", zIndex: 5 }}>
            <div style={{ font: "var(--type-card-title)", color: "#fff" }}>{n.label}</div>
            <div style={{ font: "var(--type-caption)", color: "var(--green-200)", marginTop: 3, lineHeight: 1.4 }}>{n.desc}</div>
          </div>
        );
      })() : null}
    </div>
  );
}
window.OrchestrationDiagram = OrchestrationDiagram;
