import { ac as X, u as Y, ad as Z, ae as ee, af as te, ag as re, ah as se, ai as ae, o as V, aj as oe } from "./index-CPyEi9gS.js";
import { H as ne, E as ie, u as b, G as H, I as ce } from "./switch-Dkx2qEOr.js";
import { useState as z, useEffect as de, useCallback as A } from "react";
function le(e) {
  const [a, s] = z(null), [r, t] = z(null), o = X();
  return de(() => {
    if (!e || e.trim() === "") {
      s(null), t(null);
      return;
    }
    if (!o)
      return;
    (async () => {
      try {
        if (!e.startsWith("http://") && !e.startsWith("https://"))
          throw new Error(`Invalid URL format: ${e}`);
        try {
          new URL(e);
        } catch {
          throw new Error(`Invalid URL: ${e}`);
        }
        const i = `${e.endsWith("/") ? e : `${e}/`}index.js`;
        try {
          if (!(await fetch(i, { method: "HEAD" })).ok)
            throw new Error(`Module not found at ${i}`);
        } catch {
        }
        const f = await import(
          /* @vite-ignore */
          /* webpackIgnore: true */
          i
        );
        if (typeof f.useChartStore != "function")
          throw new Error("useChartStore is not a function");
        s(() => f.useChartStore), t(null);
      } catch (n) {
        const i = n instanceof Error ? n.message : "Unknown error";
        console.error("Failed to load remote chart store:", i), t(i), s(null);
      }
    })();
  }, [e, o]), a;
}
function ue(e, a) {
  if (e.length === 0)
    return "";
  const s = e.find(
    (r) => {
      var t, o;
      return ((t = r.customCardPreferences) == null ? void 0 : t.visualType) === "multiple" || !!((o = r.customCardPreferences) != null && o.dataInputCardIds);
    }
  );
  if (s)
    return s.id;
  if (a) {
    const r = e.find((t) => t.id === a);
    if (r) {
      const t = r.tabTitle;
      if (t == "All__Header")
        return e[0].id;
      if (t && t.endsWith("__Header")) {
        const l = t.split("__")[0], n = e.find(
          (i) => i.tabTitle === l
        );
        return n ? n.id : e[0].id;
      }
      return a;
    }
  }
  return e[0].id;
}
const M = /* @__PURE__ */ new Set();
function we(e) {
  return M.add(e), () => {
    M.delete(e);
  };
}
function fe() {
  M.forEach((e) => {
    e();
  });
}
const he = (e) => {
  if (!e || !("detailTableBackup" in e))
    return e;
  const { detailTableBackup: a, ...s } = e;
  return s;
};
async function Q(e, a, s, r) {
  if (!a || !s)
    throw new Error("Missing auth token or visual ID");
  const t = ["resource-by-id", "visual", s], o = r.getQueryData(t);
  if (o)
    return console.log("Using cached visual data for:", s), { data: o, fromCache: !0 };
  console.log("Fetching visual data from network for:", s);
  const l = V.loading("Loading visual...", {
    position: "top-center"
  });
  try {
    const n = await fetch(
      `${e}/management/v1/visuals/${s}`,
      {
        headers: {
          Authorization: `Bearer ${a}`
        }
      }
    );
    if (!n.ok)
      throw new Error("Failed to load visual");
    const i = await n.json();
    return r.setQueryData(t, i), V.dismiss(l), { data: i, fromCache: !1 };
  } catch (n) {
    throw V.dismiss(l), n;
  }
}
function q(e) {
  if (typeof e == "string")
    return JSON.parse(e);
  if (typeof e == "object")
    return e;
  throw new Error("Invalid frame object format");
}
function me(e, a) {
  var o, l;
  const s = (e == null ? void 0 : e.frameObject) ?? ((o = e == null ? void 0 : e.visual) == null ? void 0 : o.frameObject);
  if (!s)
    return !1;
  const r = q(s);
  if (!(r != null && r.cards) || r.cards.length === 0)
    return !1;
  const t = (l = r.cards) == null ? void 0 : l.find(
    (n) => n.id === r.activeCardId
  );
  return t ? (oe({
    ...a,
    frame: r,
    card: t,
    visualId: (e == null ? void 0 : e.id) || r.visualId
  }), !0) : !1;
}
function pe() {
  const e = H(
    (r) => {
      var t;
      return ((t = r.card.customCardPreferences) == null ? void 0 : t.url) || "";
    }
  ), a = le(e);
  return { getUpdatedFrame: A(() => {
    var p;
    fe();
    const {
      frame: r,
      card: t,
      isDevMode: o,
      isShowingVisual: l,
      selectedSchemaName: n,
      selectedDatamodelId: i,
      selectedDatabaseName: f,
      selectedTableName: h,
      selectedConnectionId: F
    } = H.getState(), C = t.sql, y = (p = a == null ? void 0 : a.getState()) == null ? void 0 : p.settings, I = ce(t, {
      isDevMode: o,
      cardSql: C,
      isShowingVisual: l,
      selectedSchemaName: n,
      selectedDatamodelId: i,
      selectedDatabaseName: f,
      selectedTableName: h,
      selectedConnectionId: F,
      remoteChartSettings: y,
      stripConfig: he
    }), m = r.cards.map(
      (g) => g.id === t.id ? I : g
    );
    return {
      ...r,
      cards: m,
      activeCardId: ue(m, r.activeCardId)
    };
  }, [a]) };
}
function be() {
  const { authToken: e, tokenProps: a } = Y(), s = Z(), r = ee(), t = te(), { selectVisual: o } = re(), {
    setFrame: l,
    setCard: n,
    setIsDevMode: i,
    initializeModeDrafts: f,
    setActiveTabCardId: h,
    updateDataSource: F,
    setQueryResultColumns: C,
    setSelectedConnectionId: y,
    setSelectedDatabaseName: I,
    setSelectedSchemaName: m,
    setSelectedTableName: p,
    setSelectedDatamodelId: g,
    setFilterValues: P,
    setInlineFilterValuesMap: j,
    setApplyFilters: D,
    clearEditorContext: L
  } = ne(), {
    setIsDashboardEditing: U,
    setIsVisualEditing: T,
    setSelectedFrameId: k,
    clearSelectedFrameId: N,
    setIsDashboardPanelOpen: W
  } = ie(), E = b((c) => c.selectedSheetId), $ = b((c) => c.selectedFrameId), R = b((c) => c.dashboard), x = b((c) => c.filterValues), O = b(
    (c) => c.inlineFilterValuesMap
  ), S = se((t == null ? void 0 : t.id) || "", {
    enabled: !!(t != null && t.id) && !!(e != null && e.accessToken)
  }), G = A(
    async (c) => {
      try {
        o(c), N(), L();
        const { data: u, fromCache: v } = await Q(
          a.apiServiceUrl,
          (e == null ? void 0 : e.accessToken) || "",
          c.id,
          s
        );
        if (!me(u, {
          setFrame: l,
          setCard: n,
          setIsDevMode: i,
          initializeModeDrafts: f,
          setActiveTabCardId: h,
          updateDataSource: F,
          setQueryResultColumns: C,
          setSelectedConnectionId: y,
          setSelectedDatabaseName: I,
          setSelectedSchemaName: m,
          setSelectedTableName: p,
          setSelectedDatamodelId: g,
          setFilterValues: P,
          setInlineFilterValuesMap: j,
          setApplyFilters: D,
          setIsDashboardEditing: U,
          setIsVisualEditing: T,
          dashboard: R,
          selectedSheetId: E,
          selectedFrameId: $,
          filterValues: x,
          inlineFilterValuesMap: O
        }))
          throw new Error("Failed to setup editor with visual data");
        return { success: !0, fromCache: v };
      } catch (u) {
        return console.error("Error editing visual:", u), { success: !1, error: "Failed to load visual for editing" };
      }
    },
    [
      e == null ? void 0 : e.accessToken,
      a.apiServiceUrl,
      s,
      o,
      l,
      n,
      U,
      T,
      i,
      f,
      h,
      F,
      C,
      y,
      I,
      m,
      p,
      g,
      P,
      j,
      D,
      L,
      N,
      R,
      E,
      $,
      x,
      O
    ]
  ), J = A(
    async (c) => {
      var v;
      const u = (d) => (V.error(d), { success: !1, error: d });
      try {
        if (o(c), !E)
          return u("No sheet selected. Please select a sheet first.");
        const { data: d, fromCache: K } = await Q(
          a.apiServiceUrl,
          (e == null ? void 0 : e.accessToken) || "",
          c.id,
          s
        ), _ = (d == null ? void 0 : d.frameObject) ?? ((v = d == null ? void 0 : d.visual) == null ? void 0 : v.frameObject);
        if (!_)
          return u("Visual has no frame data");
        const w = q(_);
        if (!(w != null && w.cards) || w.cards.length === 0)
          return u("Visual frame is malformed");
        const B = {
          ...ae(w),
          visualId: c.id
          // Link this frame to the library visual
        };
        return await r(
          E,
          B,
          "end"
        ), U(!0), k(B.id), W(!1), { success: !0, fromCache: K };
      } catch (d) {
        return console.error("Error adding visual:", d), u(
          d instanceof Error ? d.message : "Failed to add visual to dashboard"
        );
      }
    },
    [
      e == null ? void 0 : e.accessToken,
      a.apiServiceUrl,
      s,
      o,
      E,
      U,
      k,
      W,
      r
    ]
  );
  return {
    visual: S.data,
    isLoading: S.isLoading,
    isError: S.isError,
    error: S.error,
    handleEditLibraryVisual: G,
    handleAddLibraryVisual: J,
    getUpdatedFrame: pe().getUpdatedFrame,
    refetch: S.refetch
  };
}
export {
  fe as f,
  we as r,
  be as u
};
