import { j as t, e as I } from "./externalizeComponent-Dc3fViZA.js";
import * as x from "three";
import { Matrix4 as w, Vector3 as F, Quaternion as z } from "three";
import { ConvexGeometry as te } from "three-stdlib";
import { useThree as ne, useFrame as re, Canvas as N } from "@react-three/fiber";
import { Environment as ve, Lightformer as G, Line as O, useGLTF as Me, Bounds as H } from "@react-three/drei";
import { useTheme as _e, Card as Ae, Box as b, Typography as Y, Divider as q, Button as X } from "@mui/material";
import { observer as Te } from "mobx-react-lite";
import Fe, { useRef as R, useEffect as _, useCallback as M, useState as T, Suspense as oe, useMemo as Ge } from "react";
import { useTranslation as Se } from "react-i18next";
import { N as se, V as ie, c as ae, b as Z, M as v } from "./interpolation-6ZZN4S_x.js";
import { ErrorBoundary as le } from "react-error-boundary";
function ke(e) {
  switch (e.shape_type) {
    case "convex_hull":
      return new te(
        e.vertices.map(
          (n) => new x.Vector3(
            n[0] / 1e3,
            n[1] / 1e3,
            n[2] / 1e3
          )
        )
      );
    case "box":
      return new x.BoxGeometry(
        e.size_x / 1e3,
        e.size_y / 1e3,
        e.size_z / 1e3
      );
    case "sphere":
      return new x.SphereGeometry(e.radius / 1e3);
    case "capsule":
      return new x.CapsuleGeometry(
        e.radius / 1e3,
        e.cylinder_height / 1e3
      );
    case "cylinder":
      return new x.CylinderGeometry(
        e.radius / 1e3,
        e.radius / 1e3,
        e.height / 1e3
      );
    case "rectangle":
      return new x.BoxGeometry(e.size_x / 1e3, e.size_y / 1e3, 0);
    default:
      return console.warn(`${e.shape_type} is not supported`), new x.BufferGeometry();
  }
}
function Le({
  name: e,
  collider: r,
  children: n
}) {
  var u, a;
  const i = ((u = r.pose) == null ? void 0 : u.position) ?? [0, 0, 0], o = ((a = r.pose) == null ? void 0 : a.orientation) ?? [0, 0, 0];
  return r.margin && console.warn(`${e} margin is not supported`), /* @__PURE__ */ t.jsx(
    "mesh",
    {
      name: e,
      position: new x.Vector3(
        i[0],
        i[1],
        i[2]
      ).divideScalar(1e3),
      rotation: new x.Euler(o[0], o[1], o[2], "XYZ"),
      geometry: ke(r.shape),
      children: n
    }
  );
}
function Ve({
  name: e,
  colliders: r,
  meshChildrenProvider: n,
  ...i
}) {
  return /* @__PURE__ */ t.jsx("group", { name: e, ...i, children: Object.entries(r).map(([o, u]) => /* @__PURE__ */ t.jsx(
    Le,
    {
      name: o,
      collider: u,
      children: n(o, u)
    },
    o
  )) });
}
function rt({
  scene: e,
  meshChildrenProvider: r
}) {
  const n = e.colliders;
  return /* @__PURE__ */ t.jsx("group", { children: n && /* @__PURE__ */ t.jsx(
    Ve,
    {
      meshChildrenProvider: r,
      colliders: n
    }
  ) });
}
function Q() {
  return /* @__PURE__ */ t.jsx(ve, { children: /* @__PURE__ */ t.jsx(Pe, {}) });
}
function Pe({ positions: e = [2, 0, 2, 0, 2, 0, 2, 0] }) {
  return /* @__PURE__ */ t.jsxs(t.Fragment, { children: [
    /* @__PURE__ */ t.jsx(
      G,
      {
        intensity: 5,
        "rotation-x": Math.PI / 2,
        position: [0, 5, -9],
        scale: [10, 10, 1]
      }
    ),
    /* @__PURE__ */ t.jsx("group", { rotation: [0, 0.5, 0], children: /* @__PURE__ */ t.jsx("group", { children: e.map((r, n) => /* @__PURE__ */ t.jsx(
      G,
      {
        form: "circle",
        intensity: 5,
        rotation: [Math.PI / 2, 0, 0],
        position: [r, 4, n * 4],
        scale: [3, 1, 1]
      },
      n
    )) }) }),
    /* @__PURE__ */ t.jsx(
      G,
      {
        intensity: 40,
        "rotation-y": Math.PI / 2,
        position: [-5, 1, -1],
        scale: [20, 0.1, 1]
      }
    ),
    /* @__PURE__ */ t.jsx(
      G,
      {
        intensity: 20,
        "rotation-y": -Math.PI,
        position: [-5, -2, -1],
        scale: [20, 0.1, 1]
      }
    ),
    /* @__PURE__ */ t.jsx(
      G,
      {
        "rotation-y": Math.PI / 2,
        position: [-5, -1, -1],
        scale: [20, 0.5, 1],
        intensity: 5
      }
    ),
    /* @__PURE__ */ t.jsx(
      G,
      {
        "rotation-y": -Math.PI / 2,
        position: [10, 1, 0],
        scale: [20, 1, 1],
        intensity: 10
      }
    ),
    /* @__PURE__ */ t.jsx(
      G,
      {
        form: "ring",
        color: "white",
        intensity: 5,
        scale: 10,
        position: [-15, 4, -18],
        target: [0, 0, 0]
      }
    )
  ] });
}
function Ie(e) {
  if (e.length < 3)
    return console.log("Not enough vertices to define a plane"), { isCoplanar: !1 };
  const r = new x.Vector3(e[0].x, e[0].y, e[0].z), n = new x.Vector3(e[1].x, e[1].y, e[1].z), i = new x.Vector3(e[2].x, e[2].y, e[2].z), o = new x.Vector3().subVectors(n, r), u = new x.Vector3().subVectors(i, r), a = new x.Vector3().crossVectors(o, u).normalize();
  for (let f = 3; f < e.length; f++) {
    const l = new x.Vector3(e[f].x, e[f].y, e[f].z), d = new x.Vector3().subVectors(l, r), m = a.dot(d);
    if (Math.abs(m) > 1e-6)
      return console.log("Vertices are not on the same plane"), { isCoplanar: !1 };
  }
  return { isCoplanar: !0, normal: a };
}
function ot({
  safetyZones: e,
  ...r
}) {
  return /* @__PURE__ */ t.jsx("group", { ...r, children: e.map((n, i) => {
    let o = [];
    return n.geometry && (n.geometry.compound ? o = n.geometry.compound.child_geometries : n.geometry.convex_hull && (o = [n.geometry])), o.map((u, a) => {
      if (!u.convex_hull) return null;
      const f = u.convex_hull.vertices.map(
        (m) => new x.Vector3(m.x / 1e3, m.y / 1e3, m.z / 1e3)
      ), l = Ie(f);
      if (l.isCoplanar && l.normal) {
        const s = new x.Vector3().addVectors(
          f[0],
          l.normal.multiplyScalar(1e-4)
        );
        f.push(s);
      }
      let d;
      try {
        d = new te(f);
      } catch (m) {
        return console.log("Error creating ConvexGeometry:", m), null;
      }
      return /* @__PURE__ */ t.jsx("mesh", { geometry: d, children: /* @__PURE__ */ t.jsx(
        "meshStandardMaterial",
        {
          attach: "material",
          color: "#009f4d",
          opacity: 0.2,
          depthTest: !1,
          depthWrite: !1,
          transparent: !0,
          polygonOffset: !0,
          polygonOffsetFactor: -a
        },
        i
      ) }, `${i}-${a}`);
    });
  }) });
}
function st({
  trajectory: e,
  ...r
}) {
  var i;
  const n = ((i = e.trajectory) == null ? void 0 : i.map((o) => o.tcp_pose ? new x.Vector3(
    o.tcp_pose.position.x / 1e3,
    o.tcp_pose.position.z / 1e3,
    -o.tcp_pose.position.y / 1e3
  ) : null).filter((o) => o !== null)) || [];
  return /* @__PURE__ */ t.jsx("group", { ...r, children: n.length > 0 && /* @__PURE__ */ t.jsx(
    O,
    {
      points: n,
      lineWidth: 3,
      polygonOffset: !0,
      polygonOffsetFactor: 10,
      polygonOffsetUnits: 10
    }
  ) });
}
const C = /* @__PURE__ */ new Map();
async function U(e, r) {
  if (C.has(e))
    return C.get(e);
  const n = (async () => {
    var a;
    const i = r || "", o = new se({ instanceUrl: i }), u = o.api.motionGroupModels;
    (a = u.axios) != null && a.interceptors && u.axios.interceptors.request.use((f) => {
      var l;
      return (l = f.url) != null && l.includes("/glb") && (f.responseType = "blob"), f;
    });
    try {
      const f = await o.api.motionGroupModels.getMotionGroupGlbModel(e);
      return URL.createObjectURL(f);
    } catch (f) {
      throw console.error("Failed to fetch model:", f), f;
    }
  })();
  return C.set(e, n), n;
}
function ce(e) {
  function r(n) {
    return n.children.length === 0 ? [n] : [n, ...n.children.flatMap((i) => r(i))];
  }
  return r(e).filter((n) => fe(n));
}
function ue(e) {
  return e.name.endsWith("_FLG");
}
function fe(e) {
  return /_J[0-9]+$/.test(e.name);
}
function Ue(e, r) {
  let n;
  function i(o) {
    if (ue(o)) {
      if (n)
        throw Error(
          `Found multiple flange groups in robot model ${r}; first ${n.name} then ${o.name}. Only one _FLG group is allowed.`
        );
      n = o;
    }
    fe(o), o.children.map(i);
  }
  if (i(e.scene), !n)
    throw Error(
      `No flange group found in robot model ${r}. Flange must be identified with a name ending in _FLG.`
    );
  return { gltf: e };
}
function de({
  rapidlyChangingMotionState: e,
  dhParameters: r,
  onRotationChanged: n,
  children: i
}) {
  const o = R([]), u = R([]), a = R(null), { invalidate: f } = ne();
  _(() => {
    const s = e.joint_position.filter(
      (c) => c !== void 0
    );
    return a.current = new ie(s, {
      tension: 120,
      // Controls spring stiffness - higher values create faster, more responsive motion
      friction: 20,
      // Controls damping - higher values reduce oscillation and create smoother settling
      threshold: 1e-3
    }), () => {
      var c;
      (c = a.current) == null || c.destroy();
    };
  }, []), re((s, c) => {
    if (a.current) {
      const h = a.current.update(c);
      d(), h || f();
    }
  });
  function l(s) {
    s && (u.current = ce(s), d(), f());
  }
  function d() {
    var c;
    const s = ((c = a.current) == null ? void 0 : c.getCurrentValues()) || [];
    if (n)
      n(u.current, s);
    else
      for (const [h, g] of u.current.entries()) {
        const p = r[h], j = p.theta || 0, y = p.reverse_rotation_direction ? -1 : 1;
        g.rotation.y = y * (s[h] || 0) + j;
      }
  }
  const m = M(() => {
    const s = e.joint_position.filter(
      (c) => c !== void 0
    );
    requestAnimationFrame(() => {
      var c;
      o.current = s, (c = a.current) == null || c.setTarget(s);
    });
  }, [e]);
  return _(() => {
    m();
  }, [e, m]), ae(() => {
    m();
  }), /* @__PURE__ */ t.jsx("group", { ref: l, children: i });
}
const De = "line", Ce = "mesh";
function ze({
  rapidlyChangingMotionState: e,
  dhParameters: r,
  ...n
}) {
  const i = new w(), o = R([]), u = R([]);
  Fe.useEffect(() => {
    o.current = new Array(r.length).fill(null), u.current = new Array(r.length).fill(null);
  }, [r.length]);
  function a(d, m) {
    const s = new F(), c = new z(), h = new F();
    i.decompose(s, c, h);
    const g = s.clone(), p = new w().makeRotationY(
      d.theta + m * (d.reverse_rotation_direction ? -1 : 1)
    ).multiply(new w().makeTranslation(0, d.d / 1e3, 0)).multiply(new w().makeTranslation(d.a / 1e3, 0, 0)).multiply(new w().makeRotationX(d.alpha));
    return i.multiply(p), i.decompose(s, c, h), { a: g, b: s };
  }
  function f(d, m, s, c) {
    if (!r)
      return;
    const h = r[d];
    if (!h)
      return;
    const { a: g, b: p } = a(h, c);
    m.geometry.setPositions([g.toArray(), p.toArray()].flat()), s.position.set(p.x, p.y, p.z);
  }
  function l(d, m) {
    i.identity();
    for (let s = 0; s < Math.min(d.length, m.length); s++) {
      const c = o.current[s], h = u.current[s];
      c && h && f(s, c, h, m[s]);
    }
  }
  return /* @__PURE__ */ t.jsx(t.Fragment, { children: /* @__PURE__ */ t.jsx(
    de,
    {
      rapidlyChangingMotionState: e,
      dhParameters: r,
      onRotationChanged: l,
      children: /* @__PURE__ */ t.jsxs("group", { ...n, name: "Scene", children: [
        /* @__PURE__ */ t.jsxs("mesh", { children: [
          /* @__PURE__ */ t.jsx("sphereGeometry", { args: [0.01, 32, 32] }),
          /* @__PURE__ */ t.jsx("meshStandardMaterial", { color: "black", depthTest: !0 })
        ] }),
        r.map((d, m) => {
          const { a: s, b: c } = a(
            d,
            e.joint_position[m] ?? 0
          ), h = `dhrobot_J0${m}`;
          return /* @__PURE__ */ t.jsxs("group", { name: h, children: [
            /* @__PURE__ */ t.jsx(
              O,
              {
                ref: (g) => {
                  o.current[m] = g;
                },
                name: De,
                points: [s, c],
                color: "white",
                lineWidth: 5
              }
            ),
            /* @__PURE__ */ t.jsxs(
              "mesh",
              {
                ref: (g) => {
                  u.current[m] = g;
                },
                name: Ce,
                position: c,
                children: [
                  /* @__PURE__ */ t.jsx("sphereGeometry", { args: [0.01, 32, 32] }),
                  /* @__PURE__ */ t.jsx("meshStandardMaterial", { color: "black", depthTest: !0 })
                ]
              },
              "mesh_" + m
            )
          ] }, h);
        })
      ] })
    }
  ) });
}
const Oe = console.warn;
function me() {
  return _(() => {
    console.warn = (e) => {
      e !== "Cannot call the manual advancement of rafz whilst frameLoop is not set as demand" && Oe(e);
    };
  }, []), /* @__PURE__ */ t.jsx(t.Fragment, {});
}
function Ee(e) {
  return e.type === "Mesh";
}
function Be({
  url: e,
  flangeRef: r,
  postModelRender: n,
  ...i
}) {
  const o = Me(e);
  let u;
  try {
    u = Ue(o, "robot.glb").gltf;
  } catch (l) {
    throw l;
  }
  const a = M(
    (l) => {
      l && n && n();
    },
    [n]
  );
  function f(l) {
    try {
      return Ee(l) ? l.geometry ? /* @__PURE__ */ t.jsx(
        "mesh",
        {
          name: l.name,
          geometry: l.geometry,
          material: l.material,
          position: l.position,
          rotation: l.rotation
        },
        l.uuid
      ) : /* @__PURE__ */ t.jsx("group", { name: l.name, position: l.position, rotation: l.rotation }, l.uuid) : /* @__PURE__ */ t.jsx(
        "group",
        {
          name: l.name,
          position: l.position,
          rotation: l.rotation,
          ref: ue(l) ? r : void 0,
          children: l.children.map(f)
        },
        l.uuid
      );
    } catch (d) {
      return console.warn("Error rendering node", l.name, d), null;
    }
  }
  return /* @__PURE__ */ t.jsx("group", { ...i, dispose: null, ref: a, children: f(u.scene) });
}
function he({
  modelURL: e,
  flangeRef: r,
  postModelRender: n,
  ...i
}) {
  const [o, u] = T(null);
  return _(() => {
    (async () => {
      try {
        if (typeof e == "string")
          u(e);
        else {
          const f = await e;
          u(f);
        }
      } catch (f) {
        console.error("Failed to resolve model URL:", f);
      }
    })();
  }, [e]), o ? /* @__PURE__ */ t.jsx(
    Be,
    {
      url: o,
      flangeRef: r,
      postModelRender: n,
      ...i
    }
  ) : null;
}
const pe = (e, r) => {
  e.userData.isGhost || (e.traverse((n) => {
    if (n instanceof x.Mesh) {
      n.material instanceof x.Material && (n.material.colorWrite = !1);
      const i = n.clone(), o = n.clone();
      i.material = new x.MeshStandardMaterial({
        depthTest: !0,
        depthWrite: !0,
        colorWrite: !1,
        polygonOffset: !0,
        polygonOffsetFactor: -1,
        side: x.DoubleSide
      }), i.userData.isGhost = !0, o.material = new x.MeshStandardMaterial({
        color: r,
        opacity: 0.3,
        depthTest: !0,
        depthWrite: !1,
        transparent: !0,
        polygonOffset: !0,
        polygonOffsetFactor: -2,
        side: x.DoubleSide
      }), o.userData.isGhost = !0, n.parent && (n.parent.add(i), n.parent.add(o));
    }
  }), e.userData.isGhost = !0);
}, xe = (e) => {
  if (!e.userData.isGhost) return;
  const r = [];
  e.traverse((n) => {
    var i;
    n instanceof x.Mesh && ((i = n.userData) != null && i.isGhost ? r.push(n) : n.material instanceof x.Material && (n.material.colorWrite = !0));
  }), r.forEach((n) => {
    n.parent && n.parent.remove(n);
  }), e.userData.isGhost = !1;
}, ge = I(
  ({
    rapidlyChangingMotionState: e,
    modelFromController: r,
    dhParameters: n,
    getModel: i = U,
    flangeRef: o,
    postModelRender: u,
    transparentColor: a,
    instanceUrl: f,
    ...l
  }) => {
    const [d, m] = T(null), s = M((h) => {
      m(h);
    }, []);
    _(() => {
      d && (a ? pe(d, a) : xe(d));
    }, [d, a]);
    const c = /* @__PURE__ */ t.jsx(
      ze,
      {
        rapidlyChangingMotionState: e,
        dhParameters: n,
        ...l
      }
    );
    return /* @__PURE__ */ t.jsxs(
      le,
      {
        fallback: c,
        onError: (h) => {
          console.warn(h);
        },
        children: [
          /* @__PURE__ */ t.jsx(oe, { fallback: c, children: /* @__PURE__ */ t.jsx("group", { ref: s, children: /* @__PURE__ */ t.jsx(
            de,
            {
              rapidlyChangingMotionState: e,
              dhParameters: n,
              children: /* @__PURE__ */ t.jsx(
                he,
                {
                  modelURL: (() => {
                    const h = i(r, f);
                    if (!h) {
                      const g = new Blob([], { type: "model/gltf-binary" }), p = new File([g], `${r}.glb`, { type: "model/gltf-binary" });
                      return Promise.resolve(URL.createObjectURL(p));
                    }
                    return h;
                  })(),
                  postModelRender: u,
                  flangeRef: o,
                  ...l
                }
              )
            }
          ) }) }),
          /* @__PURE__ */ t.jsx(me, {})
        ]
      }
    );
  }
);
function We({
  connectedMotionGroup: e,
  getModel: r = U,
  flangeRef: n,
  transparentColor: i,
  postModelRender: o,
  ...u
}) {
  return e.dhParameters ? /* @__PURE__ */ t.jsx(
    ge,
    {
      rapidlyChangingMotionState: e.rapidlyChangingMotionState,
      modelFromController: e.modelFromController || "",
      dhParameters: e.dhParameters,
      getModel: r,
      flangeRef: n,
      transparentColor: i,
      postModelRender: o,
      ...u
    }
  ) : null;
}
const it = I(
  Te(
    ({
      robotName: e,
      programState: r,
      safetyState: n,
      operationMode: i,
      driveToHomeEnabled: o = !1,
      onDriveToHomePress: u,
      onDriveToHomeRelease: a,
      connectedMotionGroup: f,
      robotComponent: l = We,
      customContentComponent: d,
      className: m
    }) => {
      var W;
      const s = _e(), { t: c } = Se(), [h, g] = T(!1), p = R(null), j = R(null), [y, D] = T(!1), [S, be] = T({ width: 400, height: 600 }), [$e, Re] = T(0);
      _(() => {
        const P = () => {
          if (j.current) {
            const { offsetWidth: $, offsetHeight: J } = j.current;
            D($ > J), be({ width: $, height: J });
          }
        };
        P();
        const K = new ResizeObserver(P);
        return j.current && K.observe(j.current), () => {
          K.disconnect();
        };
      }, []);
      const E = M(() => {
        Re((P) => P + 1);
      }, []), k = M(() => {
        !o || !u || (g(!0), u());
      }, [o, u]), L = M(() => {
        !o || !a || (g(!1), a());
      }, [o, a]), B = M(() => {
        h && a && (g(!1), a());
      }, [h, a]), A = y ? S.width < 350 : S.height < 200, V = y ? S.height < 310 : S.height < 450;
      return /* @__PURE__ */ t.jsx(
        Ae,
        {
          ref: j,
          className: m,
          sx: {
            width: "100%",
            height: "100%",
            display: "flex",
            flexDirection: y ? "row" : "column",
            position: "relative",
            overflow: "hidden",
            minWidth: { xs: 180, sm: 220, md: 250 },
            minHeight: y ? { xs: 200, sm: 240, md: 260 } : { xs: 150, sm: 180, md: 220 },
            // Allow progressive hiding in portrait mode
            border: `1px solid ${s.palette.divider}`,
            borderRadius: "18px",
            boxShadow: "none",
            backgroundColor: ((W = s.palette.backgroundPaperElevation) == null ? void 0 : W[8]) || "#2A2A3F",
            backgroundImage: "none"
            // Override any gradient from elevation
          },
          children: y ? /* @__PURE__ */ t.jsxs(t.Fragment, { children: [
            /* @__PURE__ */ t.jsx(
              b,
              {
                sx: {
                  flex: "0 0 50%",
                  position: "relative",
                  height: "100%",
                  minHeight: "100%",
                  maxHeight: "100%",
                  borderRadius: 1,
                  m: { xs: 1.5, sm: 2, md: 3 },
                  mr: { xs: 0.75, sm: 1, md: 1.5 },
                  overflow: "hidden",
                  // Prevent content from affecting container size
                  display: A ? "none" : "block"
                },
                children: !A && /* @__PURE__ */ t.jsxs(
                  N,
                  {
                    orthographic: !0,
                    camera: {
                      position: [3, 2, 3],
                      zoom: 1
                    },
                    shadows: !0,
                    frameloop: "demand",
                    style: {
                      borderRadius: s.shape.borderRadius,
                      width: "100%",
                      height: "100%",
                      background: "transparent",
                      position: "absolute",
                      top: 0,
                      left: 0
                    },
                    dpr: [1, 2],
                    gl: { alpha: !0, antialias: !0 },
                    children: [
                      /* @__PURE__ */ t.jsx(Q, {}),
                      /* @__PURE__ */ t.jsx(H, { fit: !0, observe: !0, margin: 1, maxDuration: 1, children: /* @__PURE__ */ t.jsx(
                        l,
                        {
                          connectedMotionGroup: f,
                          postModelRender: E
                        }
                      ) })
                    ]
                  }
                )
              }
            ),
            /* @__PURE__ */ t.jsxs(
              b,
              {
                sx: {
                  flex: "1",
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "flex-start",
                  width: A ? "100%" : "50%"
                },
                children: [
                  /* @__PURE__ */ t.jsxs(
                    b,
                    {
                      sx: {
                        p: { xs: 1.5, sm: 2, md: 3 },
                        pb: { xs: 1, sm: 1.5, md: 2 },
                        textAlign: "left"
                      },
                      children: [
                        /* @__PURE__ */ t.jsx(Y, { variant: "h6", component: "h2", sx: { mb: 1 }, children: e }),
                        /* @__PURE__ */ t.jsx(
                          Z,
                          {
                            programState: r,
                            safetyState: n,
                            operationMode: i
                          }
                        )
                      ]
                    }
                  ),
                  /* @__PURE__ */ t.jsxs(
                    b,
                    {
                      sx: {
                        p: { xs: 1.5, sm: 2, md: 3 },
                        pt: 0,
                        flex: "1",
                        display: "flex",
                        flexDirection: "column",
                        justifyContent: "space-between"
                      },
                      children: [
                        !V && d && /* @__PURE__ */ t.jsxs(b, { children: [
                          /* @__PURE__ */ t.jsx(d, {}),
                          /* @__PURE__ */ t.jsx(
                            q,
                            {
                              sx: {
                                mt: 1,
                                mb: 0,
                                borderColor: s.palette.divider,
                                opacity: 0.5
                              }
                            }
                          )
                        ] }),
                        /* @__PURE__ */ t.jsx(
                          b,
                          {
                            sx: {
                              mt: !V && d ? "auto" : 0
                            },
                            children: /* @__PURE__ */ t.jsx(
                              b,
                              {
                                sx: {
                                  display: "flex",
                                  justifyContent: "flex-start",
                                  mt: { xs: 1, sm: 1.5, md: 2 },
                                  mb: { xs: 0.5, sm: 0.75, md: 1 }
                                },
                                children: /* @__PURE__ */ t.jsx(
                                  X,
                                  {
                                    ref: p,
                                    variant: "contained",
                                    color: "secondary",
                                    size: "small",
                                    disabled: !o,
                                    onMouseDown: k,
                                    onMouseUp: L,
                                    onMouseLeave: B,
                                    onTouchStart: k,
                                    onTouchEnd: L,
                                    sx: {
                                      textTransform: "none",
                                      px: 1.5,
                                      py: 0.5
                                    },
                                    children: c("RobotCard.DriveToHome.bt")
                                  }
                                )
                              }
                            )
                          }
                        )
                      ]
                    }
                  )
                ]
              }
            )
          ] }) : /* @__PURE__ */ t.jsx(t.Fragment, { children: /* @__PURE__ */ t.jsxs(
            b,
            {
              sx: {
                p: 3,
                height: "100%",
                display: "flex",
                flexDirection: "column"
              },
              children: [
                /* @__PURE__ */ t.jsxs(b, { children: [
                  /* @__PURE__ */ t.jsx(Y, { variant: "h6", component: "h2", sx: { mb: 1 }, children: e }),
                  /* @__PURE__ */ t.jsx(
                    Z,
                    {
                      programState: r,
                      safetyState: n,
                      operationMode: i
                    }
                  )
                ] }),
                /* @__PURE__ */ t.jsx(
                  b,
                  {
                    sx: {
                      flex: A ? 0 : 1,
                      position: "relative",
                      minHeight: A ? 0 : { xs: 120, sm: 150, md: 200 },
                      height: A ? 0 : "auto",
                      borderRadius: 1,
                      overflow: "hidden",
                      display: A ? "none" : "block"
                    },
                    children: !A && /* @__PURE__ */ t.jsxs(
                      N,
                      {
                        orthographic: !0,
                        camera: {
                          position: [3, 2, 3],
                          zoom: 1
                        },
                        shadows: !0,
                        frameloop: "demand",
                        style: {
                          borderRadius: s.shape.borderRadius,
                          width: "100%",
                          height: "100%",
                          background: "transparent",
                          position: "absolute"
                        },
                        dpr: [1, 2],
                        gl: { alpha: !0, antialias: !0 },
                        children: [
                          /* @__PURE__ */ t.jsx(Q, {}),
                          /* @__PURE__ */ t.jsx(H, { fit: !0, clip: !0, observe: !0, margin: 1, maxDuration: 1, children: /* @__PURE__ */ t.jsx(
                            l,
                            {
                              connectedMotionGroup: f,
                              postModelRender: E
                            }
                          ) })
                        ]
                      }
                    )
                  }
                ),
                /* @__PURE__ */ t.jsxs(b, { children: [
                  !V && d && /* @__PURE__ */ t.jsxs(t.Fragment, { children: [
                    /* @__PURE__ */ t.jsx(d, {}),
                    /* @__PURE__ */ t.jsx(
                      q,
                      {
                        sx: {
                          mt: 1,
                          mb: 0,
                          borderColor: s.palette.divider,
                          opacity: 0.5
                        }
                      }
                    )
                  ] }),
                  /* @__PURE__ */ t.jsx(
                    b,
                    {
                      sx: {
                        display: "flex",
                        justifyContent: "flex-start",
                        mt: !V && d ? { xs: 1, sm: 2, md: 5 } : { xs: 0.5, sm: 1, md: 2 },
                        mb: { xs: 0.5, sm: 0.75, md: 1 }
                      },
                      children: /* @__PURE__ */ t.jsx(
                        X,
                        {
                          ref: p,
                          variant: "contained",
                          color: "secondary",
                          size: "small",
                          disabled: !o,
                          onMouseDown: k,
                          onMouseUp: L,
                          onMouseLeave: B,
                          onTouchStart: k,
                          onTouchEnd: L,
                          sx: {
                            textTransform: "none",
                            px: 1.5,
                            py: 0.5
                          },
                          children: c("RobotCard.DriveToHome.bt")
                        }
                      )
                    }
                  )
                ] })
              ]
            }
          ) })
        }
      );
    }
  )
), at = Array(6).fill(2 * Math.PI);
function ye({
  rapidlyChangingMotionState: e,
  dhParameters: r,
  onTranslationChanged: n,
  children: i
}) {
  const o = R([]), u = R([]), a = R(null), { invalidate: f } = ne();
  _(() => {
    const s = e.joint_position.filter(
      (c) => c !== void 0
    );
    return a.current = new ie(s, {
      tension: 120,
      // Controls spring stiffness - higher values create faster, more responsive motion
      friction: 20,
      // Controls damping - higher values reduce oscillation and create smoother settling
      threshold: 1e-3
    }), () => {
      var c;
      (c = a.current) == null || c.destroy();
    };
  }, []), re((s, c) => {
    if (a.current) {
      const h = a.current.update(c);
      d(), h || f();
    }
  });
  function l(s) {
    s && (u.current = ce(s), d(), f());
  }
  function d() {
    var c;
    const s = ((c = a.current) == null ? void 0 : c.getCurrentValues()) || [];
    if (n)
      n(u.current, s);
    else
      for (const [h, g] of u.current.entries()) {
        const j = r[h].reverse_rotation_direction ? -1 : 1;
        g.position.y = j * (s[h] || 0) / 1e3;
      }
  }
  const m = M(() => {
    const s = e.joint_position.filter(
      (c) => c !== void 0
    );
    requestAnimationFrame(() => {
      var c;
      o.current = s, (c = a.current) == null || c.setTarget(s);
    });
  }, [e]);
  return _(() => {
    m();
  }, [e, m]), ae(() => {
    m();
  }), /* @__PURE__ */ t.jsx("group", { ref: l, children: i });
}
function je({
  rapidlyChangingMotionState: e,
  dhParameters: r,
  ...n
}) {
  const i = new w(), o = R(null), u = R(null);
  function a(d) {
    const m = new w();
    for (let g = 0; g < r.length; g++) {
      const p = r[g], j = d[g] ?? 0, y = new w().makeRotationY(p.theta).multiply(
        new w().makeTranslation(
          p.a / 1e3,
          (p.d + j * (p.reverse_rotation_direction ? -1 : 1)) / 1e3,
          0
        )
      ).multiply(new w().makeRotationX(p.alpha));
      m.multiply(y);
    }
    const s = new F(), c = new z(), h = new F();
    return m.decompose(s, c, h), s;
  }
  const f = a(e.joint_position);
  function l(d, m) {
    i.identity();
    let s = new F();
    for (let p = 0; p < r.length; p++) {
      const j = m[p] ?? 0, y = r[p], D = new w().makeRotationY(y.theta).multiply(
        new w().makeTranslation(
          y.a / 1e3,
          (y.d + j * (y.reverse_rotation_direction ? -1 : 1)) / 1e3,
          0
        )
      ).multiply(new w().makeRotationX(y.alpha));
      i.multiply(D);
    }
    const c = new F(), h = new z(), g = new F();
    if (i.decompose(c, h, g), s = c, o.current && o.current.position.set(s.x, s.y, s.z), u.current) {
      const p = u.current.geometry;
      p && p.setPositions && p.setPositions([0, 0, 0, s.x, s.y, s.z]);
    }
  }
  return /* @__PURE__ */ t.jsx(t.Fragment, { children: /* @__PURE__ */ t.jsx(
    ye,
    {
      rapidlyChangingMotionState: e,
      dhParameters: r,
      onTranslationChanged: l,
      children: /* @__PURE__ */ t.jsxs("group", { ...n, name: "Scene", children: [
        /* @__PURE__ */ t.jsxs("mesh", { name: "Base", position: [0, 0, 0], children: [
          /* @__PURE__ */ t.jsx("sphereGeometry", { args: [0.02, 32, 32] }),
          /* @__PURE__ */ t.jsx("meshStandardMaterial", { color: "green", depthTest: !0 })
        ] }),
        /* @__PURE__ */ t.jsx(
          O,
          {
            ref: u,
            points: [new F(0, 0, 0), f],
            color: "White",
            lineWidth: 5
          }
        ),
        /* @__PURE__ */ t.jsxs("mesh", { ref: o, name: "TCP", position: f, children: [
          /* @__PURE__ */ t.jsx("sphereGeometry", { args: [0.025, 32, 32] }),
          /* @__PURE__ */ t.jsx("meshStandardMaterial", { color: "red", depthTest: !0 })
        ] })
      ] })
    }
  ) });
}
const we = I(
  ({
    rapidlyChangingMotionState: e,
    modelFromController: r,
    dhParameters: n,
    getModel: i = U,
    flangeRef: o,
    postModelRender: u,
    transparentColor: a,
    instanceUrl: f,
    ...l
  }) => {
    const [d, m] = T(null), s = M((h) => {
      m(h);
    }, []);
    _(() => {
      d && (a ? pe(d, a) : xe(d));
    }, [d, a]);
    const c = /* @__PURE__ */ t.jsx(
      je,
      {
        rapidlyChangingMotionState: e,
        dhParameters: n,
        ...l
      }
    );
    return /* @__PURE__ */ t.jsxs(
      le,
      {
        fallback: c,
        onError: (h) => {
          console.warn(h);
        },
        children: [
          /* @__PURE__ */ t.jsx(oe, { fallback: c, children: /* @__PURE__ */ t.jsx("group", { ref: s, children: /* @__PURE__ */ t.jsx(
            ye,
            {
              rapidlyChangingMotionState: e,
              dhParameters: n,
              children: /* @__PURE__ */ t.jsx(
                he,
                {
                  modelURL: (() => {
                    const h = i(r, f);
                    if (!h) {
                      const g = new Blob([], { type: "model/gltf-binary" }), p = new File([g], `${r}.glb`, { type: "model/gltf-binary" });
                      return Promise.resolve(URL.createObjectURL(p));
                    }
                    return h;
                  })(),
                  postModelRender: u,
                  flangeRef: o,
                  ...l
                }
              )
            }
          ) }) }),
          /* @__PURE__ */ t.jsx(me, {})
        ]
      }
    );
  }
);
function lt({
  connectedMotionGroup: e,
  getModel: r = U,
  flangeRef: n,
  transparentColor: i,
  postModelRender: o,
  ...u
}) {
  if (!e.dhParameters)
    return null;
  const a = e.modelFromController || "";
  return a && r(a) ? /* @__PURE__ */ t.jsx(
    we,
    {
      rapidlyChangingMotionState: e.rapidlyChangingMotionState,
      modelFromController: a,
      dhParameters: e.dhParameters,
      getModel: r,
      flangeRef: n,
      transparentColor: i,
      postModelRender: o,
      ...u
    }
  ) : /* @__PURE__ */ t.jsx(
    je,
    {
      rapidlyChangingMotionState: e.rapidlyChangingMotionState,
      dhParameters: e.dhParameters,
      ...u
    }
  );
}
const ee = {
  [v.Abb]: [0, 0, 0, 0, Math.PI / 2, 0, 0],
  [v.Fanuc]: [0, 0, 0, 0, -Math.PI / 2, 0, 0],
  [v.Yaskawa]: [0, 0, 0, 0, -Math.PI / 2, 0, 0],
  [v.Kuka]: [
    0,
    -Math.PI / 2,
    Math.PI / 2,
    0,
    Math.PI / 2,
    0,
    0
  ],
  [v.Universalrobots]: [
    0,
    -Math.PI / 2,
    -Math.PI / 2,
    -Math.PI / 2,
    Math.PI / 2,
    -Math.PI / 2,
    0
  ]
};
function Ke(e) {
  const [r] = e.split("_");
  switch (r) {
    case "ABB":
      return v.Abb;
    case "FANUC":
      return v.Fanuc;
    case "YASKAWA":
      return v.Yaskawa;
    case "KUKA":
      return v.Kuka;
    case "UniversalRobots":
      return v.Universalrobots;
    default:
      return null;
  }
}
function ct(e, r) {
  const n = Ke(e);
  return n && n in ee ? ee[n] : r || null;
}
const ut = I((e) => {
  const {
    instanceUrl: r,
    inverseSolver: n,
    modelFromController: i,
    ...o
  } = e, [u, a] = T(
    n
  ), [, f] = T(!1), l = M(async () => {
    const m = new se({ instanceUrl: r });
    try {
      const s = await m.api.motionGroupModels.getMotionGroupKinematicModel(
        i
      );
      a(s.inverse_solver);
    } catch {
      console.warn(
        `Failed to fetch kinematic model from API for ${i}, falling back to local config`
      );
    } finally {
      setTimeout(() => f(!0), 0);
    }
  }, [i, r]);
  _(() => {
    n === void 0 && !!i && !!r && l();
  }, [n, i, l, r]);
  const d = Ge(() => [
    "KUKA_DKP250",
    "KUKA_DKP500_2",
    "YASKAWA_TURN1",
    "YASKAWA_TURN2",
    "YASKAWA_TURN3"
  ].includes(i), [i]);
  return u || d ? /* @__PURE__ */ t.jsx(
    ge,
    {
      instanceUrl: r,
      modelFromController: i,
      ...o
    }
  ) : u === null ? /* @__PURE__ */ t.jsx(
    we,
    {
      instanceUrl: r,
      modelFromController: i,
      ...o
    }
  ) : null;
});
export {
  rt as C,
  lt as L,
  ee as M,
  Q as P,
  We as R,
  ot as S,
  st as T,
  ut as a,
  it as b,
  we as c,
  ge as d,
  at as e,
  U as f,
  Ke as g,
  ct as h
};
//# sourceMappingURL=MotionGroupVisualizer-Ck631qIj.js.map
