import { j as t, e as P } from "./externalizeComponent-Dc3fViZA.js";
import * as x from "three";
import { Matrix4 as w, Vector3 as T, 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 S, 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 Ge, { useRef as R, useEffect as _, useCallback as M, useState as G, Suspense as oe, useMemo as Se } from "react";
import { useTranslation as ke } from "react-i18next";
import { N as se, V as ie, c as ae, b as Z, M as v } from "./interpolation-baUmFLkh.js";
import { ErrorBoundary as le } from "react-error-boundary";
function Fe(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, i;
  const l = ((u = r.pose) == null ? void 0 : u.position) ?? [0, 0, 0], o = ((i = r.pose) == null ? void 0 : i.orientation) ?? [0, 0, 0];
  return r.margin && console.warn(`${e} margin is not supported`), /* @__PURE__ */ t.jsx(
    "mesh",
    {
      name: e,
      position: new x.Vector3(
        l[0],
        l[1],
        l[2]
      ).divideScalar(1e3),
      rotation: new x.Euler(o[0], o[1], o[2], "XYZ"),
      geometry: Fe(r.shape),
      children: n
    }
  );
}
function Ve({
  name: e,
  colliders: r,
  meshChildrenProvider: n,
  ...l
}) {
  return /* @__PURE__ */ t.jsx("group", { name: e, ...l, 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(Ie, {}) });
}
function Ie({ positions: e = [2, 0, 2, 0, 2, 0, 2, 0] }) {
  return /* @__PURE__ */ t.jsxs(t.Fragment, { children: [
    /* @__PURE__ */ t.jsx(
      S,
      {
        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(
      S,
      {
        form: "circle",
        intensity: 5,
        rotation: [Math.PI / 2, 0, 0],
        position: [r, 4, n * 4],
        scale: [3, 1, 1]
      },
      n
    )) }) }),
    /* @__PURE__ */ t.jsx(
      S,
      {
        intensity: 40,
        "rotation-y": Math.PI / 2,
        position: [-5, 1, -1],
        scale: [20, 0.1, 1]
      }
    ),
    /* @__PURE__ */ t.jsx(
      S,
      {
        intensity: 20,
        "rotation-y": -Math.PI,
        position: [-5, -2, -1],
        scale: [20, 0.1, 1]
      }
    ),
    /* @__PURE__ */ t.jsx(
      S,
      {
        "rotation-y": Math.PI / 2,
        position: [-5, -1, -1],
        scale: [20, 0.5, 1],
        intensity: 5
      }
    ),
    /* @__PURE__ */ t.jsx(
      S,
      {
        "rotation-y": -Math.PI / 2,
        position: [10, 1, 0],
        scale: [20, 1, 1],
        intensity: 10
      }
    ),
    /* @__PURE__ */ t.jsx(
      S,
      {
        form: "ring",
        color: "white",
        intensity: 5,
        scale: 10,
        position: [-15, 4, -18],
        target: [0, 0, 0]
      }
    )
  ] });
}
function Pe(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), l = new x.Vector3(e[2].x, e[2].y, e[2].z), o = new x.Vector3().subVectors(n, r), u = new x.Vector3().subVectors(l, r), i = new x.Vector3().crossVectors(o, u).normalize();
  for (let f = 3; f < e.length; f++) {
    const c = new x.Vector3(e[f].x, e[f].y, e[f].z), m = new x.Vector3().subVectors(c, r), d = i.dot(m);
    if (Math.abs(d) > 1e-6)
      return console.log("Vertices are not on the same plane"), { isCoplanar: !1 };
  }
  return { isCoplanar: !0, normal: i };
}
function ot({
  safetyZones: e,
  ...r
}) {
  return /* @__PURE__ */ t.jsx("group", { ...r, children: e.map((n, l) => {
    let o = [];
    return n.geometry && (n.geometry.compound ? o = n.geometry.compound.child_geometries : n.geometry.convex_hull && (o = [n.geometry])), o.map((u, i) => {
      if (!u.convex_hull) return null;
      const f = u.convex_hull.vertices.map(
        (d) => new x.Vector3(d.x / 1e3, d.y / 1e3, d.z / 1e3)
      ), c = Pe(f);
      if (c.isCoplanar && c.normal) {
        const s = new x.Vector3().addVectors(
          f[0],
          c.normal.multiplyScalar(1e-4)
        );
        f.push(s);
      }
      let m;
      try {
        m = new te(f);
      } catch (d) {
        return console.log("Error creating ConvexGeometry:", d), null;
      }
      return /* @__PURE__ */ t.jsx("mesh", { geometry: m, children: /* @__PURE__ */ t.jsx(
        "meshStandardMaterial",
        {
          attach: "material",
          color: "#009f4d",
          opacity: 0.2,
          depthTest: !1,
          depthWrite: !1,
          transparent: !0,
          polygonOffset: !0,
          polygonOffsetFactor: -i
        },
        l
      ) }, `${l}-${i}`);
    });
  }) });
}
function st({
  trajectory: e,
  ...r
}) {
  var l;
  const n = ((l = e.trajectory) == null ? void 0 : l.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 D = /* @__PURE__ */ new Map();
async function U(e) {
  if (D.has(e))
    return D.get(e);
  const r = (async () => {
    var u;
    const l = new se({ instanceUrl: "" }), o = l.api.motionGroupModels;
    (u = o.axios) != null && u.interceptors && o.axios.interceptors.request.use((i) => {
      var f;
      return (f = i.url) != null && f.includes("/glb") && (i.responseType = "blob"), i;
    });
    try {
      const i = await l.api.motionGroupModels.getMotionGroupGlbModel(e);
      return URL.createObjectURL(i);
    } catch (i) {
      throw console.error("Failed to fetch model:", i), i;
    }
  })();
  return D.set(e, r), r;
}
function ce(e) {
  function r(n) {
    return n.children.length === 0 ? [n] : [n, ...n.children.flatMap((l) => r(l))];
  }
  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 l(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(l);
  }
  if (l(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: l
}) {
  const o = R([]), u = R([]), i = R(null), { invalidate: f } = ne();
  _(() => {
    const s = e.joint_position.filter(
      (a) => a !== void 0
    );
    return i.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 a;
      (a = i.current) == null || a.destroy();
    };
  }, []), re((s, a) => {
    if (i.current) {
      const h = i.current.update(a);
      m(), h || f();
    }
  });
  function c(s) {
    s && (u.current = ce(s), m(), f());
  }
  function m() {
    var a;
    const s = ((a = i.current) == null ? void 0 : a.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 d = M(() => {
    const s = e.joint_position.filter(
      (a) => a !== void 0
    );
    requestAnimationFrame(() => {
      var a;
      o.current = s, (a = i.current) == null || a.setTarget(s);
    });
  }, [e]);
  return _(() => {
    d();
  }, [e, d]), ae(() => {
    d();
  }), /* @__PURE__ */ t.jsx("group", { ref: c, children: l });
}
const Ce = "line", De = "mesh";
function ze({
  rapidlyChangingMotionState: e,
  dhParameters: r,
  ...n
}) {
  const l = new w(), o = R([]), u = R([]);
  Ge.useEffect(() => {
    o.current = new Array(r.length).fill(null), u.current = new Array(r.length).fill(null);
  }, [r.length]);
  function i(m, d) {
    const s = new T(), a = new z(), h = new T();
    l.decompose(s, a, h);
    const g = s.clone(), p = new w().makeRotationY(
      m.theta + d * (m.reverse_rotation_direction ? -1 : 1)
    ).multiply(new w().makeTranslation(0, m.d / 1e3, 0)).multiply(new w().makeTranslation(m.a / 1e3, 0, 0)).multiply(new w().makeRotationX(m.alpha));
    return l.multiply(p), l.decompose(s, a, h), { a: g, b: s };
  }
  function f(m, d, s, a) {
    if (!r)
      return;
    const h = r[m];
    if (!h)
      return;
    const { a: g, b: p } = i(h, a);
    d.geometry.setPositions([g.toArray(), p.toArray()].flat()), s.position.set(p.x, p.y, p.z);
  }
  function c(m, d) {
    l.identity();
    for (let s = 0; s < Math.min(m.length, d.length); s++) {
      const a = o.current[s], h = u.current[s];
      a && h && f(s, a, h, d[s]);
    }
  }
  return /* @__PURE__ */ t.jsx(t.Fragment, { children: /* @__PURE__ */ t.jsx(
    de,
    {
      rapidlyChangingMotionState: e,
      dhParameters: r,
      onRotationChanged: c,
      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((m, d) => {
          const { a: s, b: a } = i(
            m,
            e.joint_position[d] ?? 0
          ), h = `dhrobot_J0${d}`;
          return /* @__PURE__ */ t.jsxs("group", { name: h, children: [
            /* @__PURE__ */ t.jsx(
              O,
              {
                ref: (g) => {
                  o.current[d] = g;
                },
                name: Ce,
                points: [s, a],
                color: "white",
                lineWidth: 5
              }
            ),
            /* @__PURE__ */ t.jsxs(
              "mesh",
              {
                ref: (g) => {
                  u.current[d] = g;
                },
                name: De,
                position: a,
                children: [
                  /* @__PURE__ */ t.jsx("sphereGeometry", { args: [0.01, 32, 32] }),
                  /* @__PURE__ */ t.jsx("meshStandardMaterial", { color: "black", depthTest: !0 })
                ]
              },
              "mesh_" + d
            )
          ] }, 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 We({
  url: e,
  flangeRef: r,
  postModelRender: n,
  ...l
}) {
  const o = Me(e);
  let u;
  try {
    u = Ue(o, "robot.glb").gltf;
  } catch (c) {
    throw c;
  }
  const i = M(
    (c) => {
      c && n && n();
    },
    [n]
  );
  function f(c) {
    try {
      return Ee(c) ? c.geometry ? /* @__PURE__ */ t.jsx(
        "mesh",
        {
          name: c.name,
          geometry: c.geometry,
          material: c.material,
          position: c.position,
          rotation: c.rotation
        },
        c.uuid
      ) : /* @__PURE__ */ t.jsx("group", { name: c.name, position: c.position, rotation: c.rotation }, c.uuid) : /* @__PURE__ */ t.jsx(
        "group",
        {
          name: c.name,
          position: c.position,
          rotation: c.rotation,
          ref: ue(c) ? r : void 0,
          children: c.children.map(f)
        },
        c.uuid
      );
    } catch (m) {
      return console.warn("Error rendering node", c.name, m), null;
    }
  }
  return /* @__PURE__ */ t.jsx("group", { ...l, dispose: null, ref: i, children: f(u.scene) });
}
function he({
  modelURL: e,
  flangeRef: r,
  postModelRender: n,
  ...l
}) {
  const [o, u] = G(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(
    We,
    {
      url: o,
      flangeRef: r,
      postModelRender: n,
      ...l
    }
  ) : 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 l = n.clone(), o = n.clone();
      l.material = new x.MeshStandardMaterial({
        depthTest: !0,
        depthWrite: !0,
        colorWrite: !1,
        polygonOffset: !0,
        polygonOffsetFactor: -1,
        side: x.DoubleSide
      }), l.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(l), n.parent.add(o));
    }
  }), e.userData.isGhost = !0);
}, xe = (e) => {
  if (!e.userData.isGhost) return;
  const r = [];
  e.traverse((n) => {
    var l;
    n instanceof x.Mesh && ((l = n.userData) != null && l.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 = P(
  ({
    rapidlyChangingMotionState: e,
    modelFromController: r,
    dhParameters: n,
    getModel: l = U,
    flangeRef: o,
    postModelRender: u,
    transparentColor: i,
    ...f
  }) => {
    const [c, m] = G(null), d = M((a) => {
      m(a);
    }, []);
    _(() => {
      c && (i ? pe(c, i) : xe(c));
    }, [c, i]);
    const s = /* @__PURE__ */ t.jsx(
      ze,
      {
        rapidlyChangingMotionState: e,
        dhParameters: n,
        ...f
      }
    );
    return /* @__PURE__ */ t.jsxs(
      le,
      {
        fallback: s,
        onError: (a) => {
          console.warn(a);
        },
        children: [
          /* @__PURE__ */ t.jsx(oe, { fallback: s, children: /* @__PURE__ */ t.jsx("group", { ref: d, children: /* @__PURE__ */ t.jsx(
            de,
            {
              rapidlyChangingMotionState: e,
              dhParameters: n,
              children: /* @__PURE__ */ t.jsx(
                he,
                {
                  modelURL: (() => {
                    const a = l(r);
                    if (!a) {
                      const h = new Blob([], { type: "model/gltf-binary" }), g = new File([h], `${r}.glb`, { type: "model/gltf-binary" });
                      return Promise.resolve(URL.createObjectURL(g));
                    }
                    return a;
                  })(),
                  postModelRender: u,
                  flangeRef: o,
                  ...f
                }
              )
            }
          ) }) }),
          /* @__PURE__ */ t.jsx(me, {})
        ]
      }
    );
  }
);
function Be({
  connectedMotionGroup: e,
  getModel: r = U,
  flangeRef: n,
  transparentColor: l,
  postModelRender: o,
  ...u
}) {
  return e.dhParameters ? /* @__PURE__ */ t.jsx(
    ge,
    {
      rapidlyChangingMotionState: e.rapidlyChangingMotionState,
      modelFromController: e.modelFromController || "",
      dhParameters: e.dhParameters,
      getModel: r,
      flangeRef: n,
      transparentColor: l,
      postModelRender: o,
      ...u
    }
  ) : null;
}
const it = P(
  Te(
    ({
      robotName: e,
      programState: r,
      safetyState: n,
      operationMode: l,
      driveToHomeEnabled: o = !1,
      onDriveToHomePress: u,
      onDriveToHomeRelease: i,
      connectedMotionGroup: f,
      robotComponent: c = Be,
      customContentComponent: m,
      className: d
    }) => {
      var B;
      const s = _e(), { t: a } = ke(), [h, g] = G(!1), p = R(null), j = R(null), [y, C] = G(!1), [k, be] = G({ width: 400, height: 600 }), [$e, Re] = G(0);
      _(() => {
        const I = () => {
          if (j.current) {
            const { offsetWidth: $, offsetHeight: J } = j.current;
            C($ > J), be({ width: $, height: J });
          }
        };
        I();
        const K = new ResizeObserver(I);
        return j.current && K.observe(j.current), () => {
          K.disconnect();
        };
      }, []);
      const E = M(() => {
        Re((I) => I + 1);
      }, []), F = M(() => {
        !o || !u || (g(!0), u());
      }, [o, u]), L = M(() => {
        !o || !i || (g(!1), i());
      }, [o, i]), W = M(() => {
        h && i && (g(!1), i());
      }, [h, i]), A = y ? k.width < 350 : k.height < 200, V = y ? k.height < 310 : k.height < 450;
      return /* @__PURE__ */ t.jsx(
        Ae,
        {
          ref: j,
          className: d,
          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: ((B = s.palette.backgroundPaperElevation) == null ? void 0 : B[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(
                        c,
                        {
                          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: l
                          }
                        )
                      ]
                    }
                  ),
                  /* @__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 && m && /* @__PURE__ */ t.jsxs(b, { children: [
                          /* @__PURE__ */ t.jsx(m, {}),
                          /* @__PURE__ */ t.jsx(
                            q,
                            {
                              sx: {
                                mt: 1,
                                mb: 0,
                                borderColor: s.palette.divider,
                                opacity: 0.5
                              }
                            }
                          )
                        ] }),
                        /* @__PURE__ */ t.jsx(
                          b,
                          {
                            sx: {
                              mt: !V && m ? "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: F,
                                    onMouseUp: L,
                                    onMouseLeave: W,
                                    onTouchStart: F,
                                    onTouchEnd: L,
                                    sx: {
                                      textTransform: "none",
                                      px: 1.5,
                                      py: 0.5
                                    },
                                    children: a("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: l
                    }
                  )
                ] }),
                /* @__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(
                            c,
                            {
                              connectedMotionGroup: f,
                              postModelRender: E
                            }
                          ) })
                        ]
                      }
                    )
                  }
                ),
                /* @__PURE__ */ t.jsxs(b, { children: [
                  !V && m && /* @__PURE__ */ t.jsxs(t.Fragment, { children: [
                    /* @__PURE__ */ t.jsx(m, {}),
                    /* @__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 && m ? { 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: F,
                          onMouseUp: L,
                          onMouseLeave: W,
                          onTouchStart: F,
                          onTouchEnd: L,
                          sx: {
                            textTransform: "none",
                            px: 1.5,
                            py: 0.5
                          },
                          children: a("RobotCard.DriveToHome.bt")
                        }
                      )
                    }
                  )
                ] })
              ]
            }
          ) })
        }
      );
    }
  )
), at = Array(6).fill(2 * Math.PI);
function ye({
  rapidlyChangingMotionState: e,
  dhParameters: r,
  onTranslationChanged: n,
  children: l
}) {
  const o = R([]), u = R([]), i = R(null), { invalidate: f } = ne();
  _(() => {
    const s = e.joint_position.filter(
      (a) => a !== void 0
    );
    return i.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 a;
      (a = i.current) == null || a.destroy();
    };
  }, []), re((s, a) => {
    if (i.current) {
      const h = i.current.update(a);
      m(), h || f();
    }
  });
  function c(s) {
    s && (u.current = ce(s), m(), f());
  }
  function m() {
    var a;
    const s = ((a = i.current) == null ? void 0 : a.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 d = M(() => {
    const s = e.joint_position.filter(
      (a) => a !== void 0
    );
    requestAnimationFrame(() => {
      var a;
      o.current = s, (a = i.current) == null || a.setTarget(s);
    });
  }, [e]);
  return _(() => {
    d();
  }, [e, d]), ae(() => {
    d();
  }), /* @__PURE__ */ t.jsx("group", { ref: c, children: l });
}
function je({
  rapidlyChangingMotionState: e,
  dhParameters: r,
  ...n
}) {
  const l = new w(), o = R(null), u = R(null);
  function i(m) {
    const d = new w();
    for (let g = 0; g < r.length; g++) {
      const p = r[g], j = m[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));
      d.multiply(y);
    }
    const s = new T(), a = new z(), h = new T();
    return d.decompose(s, a, h), s;
  }
  const f = i(e.joint_position);
  function c(m, d) {
    l.identity();
    let s = new T();
    for (let p = 0; p < r.length; p++) {
      const j = d[p] ?? 0, y = r[p], C = 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));
      l.multiply(C);
    }
    const a = new T(), h = new z(), g = new T();
    if (l.decompose(a, h, g), s = a, 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: c,
      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 T(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 = P(
  ({
    rapidlyChangingMotionState: e,
    modelFromController: r,
    dhParameters: n,
    getModel: l = U,
    flangeRef: o,
    postModelRender: u,
    transparentColor: i,
    ...f
  }) => {
    const [c, m] = G(null), d = M((a) => {
      m(a);
    }, []);
    _(() => {
      c && (i ? pe(c, i) : xe(c));
    }, [c, i]);
    const s = /* @__PURE__ */ t.jsx(
      je,
      {
        rapidlyChangingMotionState: e,
        dhParameters: n,
        ...f
      }
    );
    return /* @__PURE__ */ t.jsxs(
      le,
      {
        fallback: s,
        onError: (a) => {
          console.warn(a);
        },
        children: [
          /* @__PURE__ */ t.jsx(oe, { fallback: s, children: /* @__PURE__ */ t.jsx("group", { ref: d, children: /* @__PURE__ */ t.jsx(
            ye,
            {
              rapidlyChangingMotionState: e,
              dhParameters: n,
              children: /* @__PURE__ */ t.jsx(
                he,
                {
                  modelURL: (() => {
                    const a = l(r);
                    if (!a) {
                      const h = new Blob([], { type: "model/gltf-binary" }), g = new File([h], `${r}.glb`, { type: "model/gltf-binary" });
                      return Promise.resolve(URL.createObjectURL(g));
                    }
                    return a;
                  })(),
                  postModelRender: u,
                  flangeRef: o,
                  ...f
                }
              )
            }
          ) }) }),
          /* @__PURE__ */ t.jsx(me, {})
        ]
      }
    );
  }
);
function lt({
  connectedMotionGroup: e,
  getModel: r = U,
  flangeRef: n,
  transparentColor: l,
  postModelRender: o,
  ...u
}) {
  if (!e.dhParameters)
    return null;
  const i = e.modelFromController || "";
  return i && r(i) ? /* @__PURE__ */ t.jsx(
    we,
    {
      rapidlyChangingMotionState: e.rapidlyChangingMotionState,
      modelFromController: i,
      dhParameters: e.dhParameters,
      getModel: r,
      flangeRef: n,
      transparentColor: l,
      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 = P((e) => {
  const { inverseSolver: r, modelFromController: n, ...l } = e, [o, u] = G(r), i = "";
  console.log({ props: e });
  const f = M(async () => {
    const m = new se({ instanceUrl: i });
    try {
      const d = await m.api.motionGroupModels.getMotionGroupKinematicModel(
        n
      );
      console.log("FETCH"), u(d.inverse_solver);
    } catch {
      console.warn(`Failed to fetch kinematic model from API for ${n}, falling back to local config`);
    }
  }, [n, i]);
  _(() => {
  }, [r, n, f, i]);
  const c = Se(() => ["KUKA_DK250", "KUKA_DK500", "YASKAWA_TURN1", "YASKAWA_TURN2", "YASKAWA_TURN3"].includes(n), [n]);
  return o || c ? /* @__PURE__ */ t.jsx(ge, { modelFromController: n, ...l }) : o === null ? /* @__PURE__ */ t.jsx(we, { modelFromController: n, ...l }) : null;
});
export {
  rt as C,
  lt as L,
  ee as M,
  Q as P,
  Be 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-D41S2gx7.js.map
