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 Le(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 Ve({
  name: e,
  collider: r,
  children: n
}) {
  var u, l;
  const o = ((u = r.pose) == null ? void 0 : u.position) ?? [0, 0, 0], s = ((l = r.pose) == null ? void 0 : l.orientation) ?? [0, 0, 0];
  return r.margin && console.warn(`${e} margin is not supported`), /* @__PURE__ */ t.jsx(
    "mesh",
    {
      name: e,
      position: new x.Vector3(
        o[0],
        o[1],
        o[2]
      ).divideScalar(1e3),
      rotation: new x.Euler(s[0], s[1], s[2], "XYZ"),
      geometry: Le(r.shape),
      children: n
    }
  );
}
function Fe({
  name: e,
  colliders: r,
  meshChildrenProvider: n,
  ...o
}) {
  return /* @__PURE__ */ t.jsx("group", { name: e, ...o, children: Object.entries(r).map(([s, u]) => /* @__PURE__ */ t.jsx(
    Ve,
    {
      name: s,
      collider: u,
      children: n(s, u)
    },
    s
  )) });
}
function rt({
  scene: e,
  meshChildrenProvider: r
}) {
  const n = e.colliders;
  return /* @__PURE__ */ t.jsx("group", { children: n && /* @__PURE__ */ t.jsx(
    Fe,
    {
      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), o = new x.Vector3(e[2].x, e[2].y, e[2].z), s = new x.Vector3().subVectors(n, r), u = new x.Vector3().subVectors(o, r), l = new x.Vector3().crossVectors(s, 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 = l.dot(m);
    if (Math.abs(d) > 1e-6)
      return console.log("Vertices are not on the same plane"), { isCoplanar: !1 };
  }
  return { isCoplanar: !0, normal: l };
}
function ot({
  safetyZones: e,
  ...r
}) {
  return /* @__PURE__ */ t.jsx("group", { ...r, children: e.map((n, o) => {
    let s = [];
    return n.geometry && (n.geometry.compound ? s = n.geometry.compound.child_geometries : n.geometry.convex_hull && (s = [n.geometry])), s.map((u, l) => {
      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 i = new x.Vector3().addVectors(
          f[0],
          c.normal.multiplyScalar(1e-4)
        );
        f.push(i);
      }
      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: -l
        },
        o
      ) }, `${o}-${l}`);
    });
  }) });
}
function st({
  trajectory: e,
  ...r
}) {
  var o;
  const n = ((o = e.trajectory) == null ? void 0 : o.map((s) => s.tcp_pose ? new x.Vector3(
    s.tcp_pose.position.x / 1e3,
    s.tcp_pose.position.z / 1e3,
    -s.tcp_pose.position.y / 1e3
  ) : null).filter((s) => s !== 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) {
  if (C.has(e))
    return C.get(e);
  const r = (async () => {
    var u;
    const o = new se({ instanceUrl: "" }), s = o.api.motionGroupModels;
    (u = s.axios) != null && u.interceptors && s.axios.interceptors.request.use((l) => {
      var f;
      return (f = l.url) != null && f.includes("/glb") && (l.responseType = "blob"), l;
    });
    try {
      const l = await o.api.motionGroupModels.getMotionGroupGlbModel(e);
      return URL.createObjectURL(l);
    } catch (l) {
      throw console.error("Failed to fetch model:", l), l;
    }
  })();
  return C.set(e, r), r;
}
function ce(e) {
  function r(n) {
    return n.children.length === 0 ? [n] : [n, ...n.children.flatMap((o) => r(o))];
  }
  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 o(s) {
    if (ue(s)) {
      if (n)
        throw Error(
          `Found multiple flange groups in robot model ${r}; first ${n.name} then ${s.name}. Only one _FLG group is allowed.`
        );
      n = s;
    }
    fe(s), s.children.map(o);
  }
  if (o(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: o
}) {
  const s = R([]), u = R([]), l = R(null), { invalidate: f } = ne();
  _(() => {
    const i = e.joint_position.filter(
      (a) => a !== void 0
    );
    return l.current = new ie(i, {
      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 = l.current) == null || a.destroy();
    };
  }, []), re((i, a) => {
    if (l.current) {
      const h = l.current.update(a);
      m(), h || f();
    }
  });
  function c(i) {
    i && (u.current = ce(i), m(), f());
  }
  function m() {
    var a;
    const i = ((a = l.current) == null ? void 0 : a.getCurrentValues()) || [];
    if (n)
      n(u.current, i);
    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 * (i[h] || 0) + j;
      }
  }
  const d = M(() => {
    const i = e.joint_position.filter(
      (a) => a !== void 0
    );
    requestAnimationFrame(() => {
      var a;
      s.current = i, (a = l.current) == null || a.setTarget(i);
    });
  }, [e]);
  return _(() => {
    d();
  }, [e, d]), ae(() => {
    d();
  }), /* @__PURE__ */ t.jsx("group", { ref: c, children: o });
}
const De = "line", Ce = "mesh";
function ze({
  rapidlyChangingMotionState: e,
  dhParameters: r,
  ...n
}) {
  const o = new w(), s = R([]), u = R([]);
  Ge.useEffect(() => {
    s.current = new Array(r.length).fill(null), u.current = new Array(r.length).fill(null);
  }, [r.length]);
  function l(m, d) {
    const i = new T(), a = new z(), h = new T();
    o.decompose(i, a, h);
    const g = i.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 o.multiply(p), o.decompose(i, a, h), { a: g, b: i };
  }
  function f(m, d, i, a) {
    if (!r)
      return;
    const h = r[m];
    if (!h)
      return;
    const { a: g, b: p } = l(h, a);
    d.geometry.setPositions([g.toArray(), p.toArray()].flat()), i.position.set(p.x, p.y, p.z);
  }
  function c(m, d) {
    o.identity();
    for (let i = 0; i < Math.min(m.length, d.length); i++) {
      const a = s.current[i], h = u.current[i];
      a && h && f(i, a, h, d[i]);
    }
  }
  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: i, b: a } = l(
            m,
            e.joint_position[d] ?? 0
          ), h = `dhrobot_J0${d}`;
          return /* @__PURE__ */ t.jsxs("group", { name: h, children: [
            /* @__PURE__ */ t.jsx(
              O,
              {
                ref: (g) => {
                  s.current[d] = g;
                },
                name: De,
                points: [i, a],
                color: "white",
                lineWidth: 5
              }
            ),
            /* @__PURE__ */ t.jsxs(
              "mesh",
              {
                ref: (g) => {
                  u.current[d] = g;
                },
                name: Ce,
                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,
  ...o
}) {
  const s = Me(e);
  let u;
  try {
    u = Ue(s, "robot.glb").gltf;
  } catch (c) {
    throw c;
  }
  const l = 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", { ...o, dispose: null, ref: l, children: f(u.scene) });
}
function he({
  modelURL: e,
  flangeRef: r,
  postModelRender: n,
  ...o
}) {
  const [s, 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]), s ? /* @__PURE__ */ t.jsx(
    We,
    {
      url: s,
      flangeRef: r,
      postModelRender: n,
      ...o
    }
  ) : 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 o = n.clone(), s = n.clone();
      o.material = new x.MeshStandardMaterial({
        depthTest: !0,
        depthWrite: !0,
        colorWrite: !1,
        polygonOffset: !0,
        polygonOffsetFactor: -1,
        side: x.DoubleSide
      }), o.userData.isGhost = !0, s.material = new x.MeshStandardMaterial({
        color: r,
        opacity: 0.3,
        depthTest: !0,
        depthWrite: !1,
        transparent: !0,
        polygonOffset: !0,
        polygonOffsetFactor: -2,
        side: x.DoubleSide
      }), s.userData.isGhost = !0, n.parent && (n.parent.add(o), n.parent.add(s));
    }
  }), e.userData.isGhost = !0);
}, xe = (e) => {
  if (!e.userData.isGhost) return;
  const r = [];
  e.traverse((n) => {
    var o;
    n instanceof x.Mesh && ((o = n.userData) != null && o.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: o = U,
    flangeRef: s,
    postModelRender: u,
    transparentColor: l,
    ...f
  }) => {
    const [c, m] = G(null), d = M((a) => {
      m(a);
    }, []);
    _(() => {
      c && (l ? pe(c, l) : xe(c));
    }, [c, l]);
    const i = /* @__PURE__ */ t.jsx(
      ze,
      {
        rapidlyChangingMotionState: e,
        dhParameters: n,
        ...f
      }
    );
    return /* @__PURE__ */ t.jsxs(
      le,
      {
        fallback: i,
        onError: (a) => {
          console.warn(a);
        },
        children: [
          /* @__PURE__ */ t.jsx(oe, { fallback: i, children: /* @__PURE__ */ t.jsx("group", { ref: d, children: /* @__PURE__ */ t.jsx(
            de,
            {
              rapidlyChangingMotionState: e,
              dhParameters: n,
              children: /* @__PURE__ */ t.jsx(
                he,
                {
                  modelURL: (() => {
                    const a = o(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: s,
                  ...f
                }
              )
            }
          ) }) }),
          /* @__PURE__ */ t.jsx(me, {})
        ]
      }
    );
  }
);
function Be({
  connectedMotionGroup: e,
  getModel: r = U,
  flangeRef: n,
  transparentColor: o,
  postModelRender: s,
  ...u
}) {
  return e.dhParameters ? /* @__PURE__ */ t.jsx(
    ge,
    {
      rapidlyChangingMotionState: e.rapidlyChangingMotionState,
      modelFromController: e.modelFromController || "",
      dhParameters: e.dhParameters,
      getModel: r,
      flangeRef: n,
      transparentColor: o,
      postModelRender: s,
      ...u
    }
  ) : null;
}
const it = P(
  Te(
    ({
      robotName: e,
      programState: r,
      safetyState: n,
      operationMode: o,
      driveToHomeEnabled: s = !1,
      onDriveToHomePress: u,
      onDriveToHomeRelease: l,
      connectedMotionGroup: f,
      robotComponent: c = Be,
      customContentComponent: m,
      className: d
    }) => {
      var B;
      const i = _e(), { t: a } = ke(), [h, g] = G(!1), p = R(null), j = R(null), [y, D] = G(!1), [k, be] = G({ width: 400, height: 600 }), [$e, Re] = G(0);
      _(() => {
        const I = () => {
          if (j.current) {
            const { offsetWidth: $, offsetHeight: J } = j.current;
            D($ > 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);
      }, []), L = M(() => {
        !s || !u || (g(!0), u());
      }, [s, u]), V = M(() => {
        !s || !l || (g(!1), l());
      }, [s, l]), W = M(() => {
        h && l && (g(!1), l());
      }, [h, l]), A = y ? k.width < 350 : k.height < 200, F = 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 ${i.palette.divider}`,
            borderRadius: "18px",
            boxShadow: "none",
            backgroundColor: ((B = i.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: i.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: o
                          }
                        )
                      ]
                    }
                  ),
                  /* @__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: [
                        !F && m && /* @__PURE__ */ t.jsxs(b, { children: [
                          /* @__PURE__ */ t.jsx(m, {}),
                          /* @__PURE__ */ t.jsx(
                            q,
                            {
                              sx: {
                                mt: 1,
                                mb: 0,
                                borderColor: i.palette.divider,
                                opacity: 0.5
                              }
                            }
                          )
                        ] }),
                        /* @__PURE__ */ t.jsx(
                          b,
                          {
                            sx: {
                              mt: !F && 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: !s,
                                    onMouseDown: L,
                                    onMouseUp: V,
                                    onMouseLeave: W,
                                    onTouchStart: L,
                                    onTouchEnd: V,
                                    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: o
                    }
                  )
                ] }),
                /* @__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: i.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: [
                  !F && m && /* @__PURE__ */ t.jsxs(t.Fragment, { children: [
                    /* @__PURE__ */ t.jsx(m, {}),
                    /* @__PURE__ */ t.jsx(
                      q,
                      {
                        sx: {
                          mt: 1,
                          mb: 0,
                          borderColor: i.palette.divider,
                          opacity: 0.5
                        }
                      }
                    )
                  ] }),
                  /* @__PURE__ */ t.jsx(
                    b,
                    {
                      sx: {
                        display: "flex",
                        justifyContent: "flex-start",
                        mt: !F && 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: !s,
                          onMouseDown: L,
                          onMouseUp: V,
                          onMouseLeave: W,
                          onTouchStart: L,
                          onTouchEnd: V,
                          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: o
}) {
  const s = R([]), u = R([]), l = R(null), { invalidate: f } = ne();
  _(() => {
    const i = e.joint_position.filter(
      (a) => a !== void 0
    );
    return l.current = new ie(i, {
      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 = l.current) == null || a.destroy();
    };
  }, []), re((i, a) => {
    if (l.current) {
      const h = l.current.update(a);
      m(), h || f();
    }
  });
  function c(i) {
    i && (u.current = ce(i), m(), f());
  }
  function m() {
    var a;
    const i = ((a = l.current) == null ? void 0 : a.getCurrentValues()) || [];
    if (n)
      n(u.current, i);
    else
      for (const [h, g] of u.current.entries()) {
        const j = r[h].reverse_rotation_direction ? -1 : 1;
        g.position.y = j * (i[h] || 0) / 1e3;
      }
  }
  const d = M(() => {
    const i = e.joint_position.filter(
      (a) => a !== void 0
    );
    requestAnimationFrame(() => {
      var a;
      s.current = i, (a = l.current) == null || a.setTarget(i);
    });
  }, [e]);
  return _(() => {
    d();
  }, [e, d]), ae(() => {
    d();
  }), /* @__PURE__ */ t.jsx("group", { ref: c, children: o });
}
function je({
  rapidlyChangingMotionState: e,
  dhParameters: r,
  ...n
}) {
  const o = new w(), s = R(null), u = R(null);
  function l(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 i = new T(), a = new z(), h = new T();
    return d.decompose(i, a, h), i;
  }
  const f = l(e.joint_position);
  function c(m, d) {
    o.identity();
    let i = new T();
    for (let p = 0; p < r.length; p++) {
      const j = d[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));
      o.multiply(D);
    }
    const a = new T(), h = new z(), g = new T();
    if (o.decompose(a, h, g), i = a, s.current && s.current.position.set(i.x, i.y, i.z), u.current) {
      const p = u.current.geometry;
      p && p.setPositions && p.setPositions([0, 0, 0, i.x, i.y, i.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: s, 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: o = U,
    flangeRef: s,
    postModelRender: u,
    transparentColor: l,
    ...f
  }) => {
    const [c, m] = G(null), d = M((a) => {
      m(a);
    }, []);
    _(() => {
      c && (l ? pe(c, l) : xe(c));
    }, [c, l]);
    const i = /* @__PURE__ */ t.jsx(
      je,
      {
        rapidlyChangingMotionState: e,
        dhParameters: n,
        ...f
      }
    );
    return /* @__PURE__ */ t.jsxs(
      le,
      {
        fallback: i,
        onError: (a) => {
          console.warn(a);
        },
        children: [
          /* @__PURE__ */ t.jsx(oe, { fallback: i, children: /* @__PURE__ */ t.jsx("group", { ref: d, children: /* @__PURE__ */ t.jsx(
            ye,
            {
              rapidlyChangingMotionState: e,
              dhParameters: n,
              children: /* @__PURE__ */ t.jsx(
                he,
                {
                  modelURL: (() => {
                    const a = o(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: s,
                  ...f
                }
              )
            }
          ) }) }),
          /* @__PURE__ */ t.jsx(me, {})
        ]
      }
    );
  }
);
function lt({
  connectedMotionGroup: e,
  getModel: r = U,
  flangeRef: n,
  transparentColor: o,
  postModelRender: s,
  ...u
}) {
  if (!e.dhParameters)
    return null;
  const l = e.modelFromController || "";
  return l && r(l) ? /* @__PURE__ */ t.jsx(
    we,
    {
      rapidlyChangingMotionState: e.rapidlyChangingMotionState,
      modelFromController: l,
      dhParameters: e.dhParameters,
      getModel: r,
      flangeRef: n,
      transparentColor: o,
      postModelRender: s,
      ...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 { instanceUrl: r, inverseSolver: n, modelFromController: o, ...s } = e, [u, l] = G(n), f = M(async () => {
    const m = new se({ instanceUrl: r });
    try {
      const d = await m.api.motionGroupModels.getMotionGroupKinematicModel(
        o
      );
      l(d.inverse_solver);
    } catch {
      console.warn(`Failed to fetch kinematic model from API for ${o}, falling back to local config`);
    }
  }, [o, r]);
  _(() => {
    console.log(n, o, r), console.log(n === void 0 && o && r), n === void 0 && o && r && f();
  }, [n, o, f, r]);
  const c = Se(() => ["KUKA_DK250", "KUKA_DK500", "YASKAWA_TURN1", "YASKAWA_TURN2", "YASKAWA_TURN3"].includes(o), [o]);
  return u || c ? /* @__PURE__ */ t.jsx(ge, { modelFromController: o, ...s }) : u === null ? /* @__PURE__ */ t.jsx(we, { modelFromController: o, ...s }) : 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-BC0FX5ed.js.map
