import { n as noop, a as safe_not_equal, b as subscribe, r as run_all, i as is_function, c as create_ssr_component, g as getContext, d as add_attribute, e as escape, s as setContext, v as validate_component } from "../../chunks/index-0e008fb3.js";
import omit from "lodash/omit.js";
import c from "@getanthill/datastore/dist/sdk/Datastore.js";
import { p as page } from "../../chunks/stores-9eb273d1.js";
var app = "";
const subscriber_queue = [];
function readable(value, start) {
  return {
    subscribe: writable(value, start).subscribe
  };
}
function writable(value, start = noop) {
  let stop;
  const subscribers = /* @__PURE__ */ new Set();
  function set(new_value) {
    if (safe_not_equal(value, new_value)) {
      value = new_value;
      if (stop) {
        const run_queue = !subscriber_queue.length;
        for (const subscriber of subscribers) {
          subscriber[1]();
          subscriber_queue.push(subscriber, value);
        }
        if (run_queue) {
          for (let i = 0; i < subscriber_queue.length; i += 2) {
            subscriber_queue[i][0](subscriber_queue[i + 1]);
          }
          subscriber_queue.length = 0;
        }
      }
    }
  }
  function update(fn) {
    set(fn(value));
  }
  function subscribe2(run, invalidate = noop) {
    const subscriber = [run, invalidate];
    subscribers.add(subscriber);
    if (subscribers.size === 1) {
      stop = start(set) || noop;
    }
    run(value);
    return () => {
      subscribers.delete(subscriber);
      if (subscribers.size === 0) {
        stop();
        stop = null;
      }
    };
  }
  return { set, update, subscribe: subscribe2 };
}
function derived(stores2, fn, initial_value) {
  const single = !Array.isArray(stores2);
  const stores_array = single ? [stores2] : stores2;
  const auto = fn.length < 2;
  return readable(initial_value, (set) => {
    let inited = false;
    const values = [];
    let pending = 0;
    let cleanup = noop;
    const sync = () => {
      if (pending) {
        return;
      }
      cleanup();
      const result = fn(single ? values[0] : values, set);
      if (auto) {
        set(result);
      } else {
        cleanup = is_function(result) ? result : noop;
      }
    };
    const unsubscribers = stores_array.map((store, i) => subscribe(store, (value) => {
      values[i] = value;
      pending &= ~(1 << i);
      if (inited) {
        sync();
      }
    }, () => {
      pending |= 1 << i;
    }));
    inited = true;
    sync();
    return function stop() {
      run_all(unsubscribers);
      cleanup();
    };
  });
}
const Datastore = c.default ? c.default : c;
const DATASTORE_CONFIGS_PATH = "configs";
let storedConfigs = '[{ "base_url": "http://localhost:3001", "access_token": "token" }]';
const configs = writable(JSON.parse(storedConfigs));
const DATASTORE_ACTIVE_CONFIG_INDEX_PATH = "active_config_index";
let storedActiveConfigIndex = 0;
const activeConfigIndex = writable(storedActiveConfigIndex);
const activeConfig = derived([configs, activeConfigIndex], ([$configs, $activeConfigIndex]) => {
  console.log("[store] Update activeConfig");
  return $configs[$activeConfigIndex];
});
const activeClient = derived([activeConfig], ([$activeConfig]) => {
  console.log("[store] Update activeClient");
  if (!$activeConfig) {
    return;
  }
  const client = new Datastore({
    baseUrl: $activeConfig.base_url,
    token: $activeConfig.access_token
  });
  return client;
});
const models = derived([activeClient], async ([$activeClient], set) => {
  console.log("[store] Update models");
  set({});
  if (!$activeClient) {
    return;
  }
  try {
    const { data } = await $activeClient.getModels();
    set(data);
  } catch (err) {
    console.error(err.message);
  }
});
const filterModels = writable("");
const EDITOR_VALUE_PATH = "editor_value";
let storedEditorValue = "";
const editorValue = writable(storedEditorValue);
const stores = {
  models,
  configs,
  activeConfigIndex,
  activeConfig,
  activeClient,
  filterModels,
  editorValue
};
if (typeof window !== "undefined") {
  storedConfigs = JSON.parse(localStorage.getItem(DATASTORE_CONFIGS_PATH) || storedConfigs);
  configs.set(storedConfigs);
  configs.subscribe((value) => {
    localStorage.setItem(DATASTORE_CONFIGS_PATH, JSON.stringify(value));
  });
  storedActiveConfigIndex = parseInt(`${localStorage.getItem(DATASTORE_ACTIVE_CONFIG_INDEX_PATH) || "0"}`, 10);
  activeConfigIndex.set(storedActiveConfigIndex);
  activeConfigIndex.subscribe((value) => {
    localStorage.setItem(DATASTORE_ACTIVE_CONFIG_INDEX_PATH, `${value}`);
  });
  storedEditorValue = localStorage.getItem(EDITOR_VALUE_PATH) || "";
  editorValue.set(storedEditorValue);
  editorValue.subscribe((value) => {
    localStorage.setItem(EDITOR_VALUE_PATH, `${value}`);
  });
}
const services = {
  stores,
  stringify: (value) => JSON.stringify(value, null, 2),
  parse: (str) => JSON.parse(str),
  sanitize: (obj) => omit(obj, "created_at", "updated_at", "version", "_id")
};
const Header = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let path;
  let configName;
  let model;
  let $models, $$unsubscribe_models;
  let $activeConfig, $$unsubscribe_activeConfig;
  let $page, $$unsubscribe_page;
  $$unsubscribe_page = subscribe(page, (value) => $page = value);
  const activeConfig2 = getContext("stores").activeConfig;
  $$unsubscribe_activeConfig = subscribe(activeConfig2, (value) => $activeConfig = value);
  const models2 = getContext("stores").models;
  $$unsubscribe_models = subscribe(models2, (value) => $models = value);
  function getModelPath(configName2, model2) {
    return `/datastore/${model2}`.toLowerCase();
  }
  path = $page.url.pathname;
  configName = $activeConfig.name || "datastore";
  model = Object.keys($models || {})[0];
  $$unsubscribe_models();
  $$unsubscribe_activeConfig();
  $$unsubscribe_page();
  return `<nav style="${"background-color: #171812;"}"><div class="${"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"}"><div class="${"flex items-center justify-between h-16"}"><div class="${"flex items-center"}"><div class="${"flex-shrink-0"}"><code class="${"text-gray-500"}">Datastore</code></div>
				<div class="${"hidden sm:block sm:ml-6"}"><div class="${"flex space-x-4"}"><a href="${"/config"}" class="${[
    "text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium",
    (path === "/config" ? "bg-gray-900" : "") + " " + (path === "/config" ? "text-white" : "")
  ].join(" ").trim()}"${add_attribute("aria-current", path === "/config" ? "page" : "", 0)}>Config</a>

						<a href="${"/aggregation"}" class="${[
    "text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium",
    (path === "/aggregation" ? "bg-gray-900" : "") + " " + (path === "/aggregation" ? "text-white" : "")
  ].join(" ").trim()}"${add_attribute("aria-current", path === "/aggregation" ? "page" : "", 0)}>Aggregation</a>

						${!!model ? `<a${add_attribute("href", getModelPath(configName, ""), 0)} class="${[
    "border-blue-300 text-blue-500 hover:text-white px-3 py-2 rounded-md text-sm font-medium flex",
    (path === getModelPath(configName, "") ? "bg-gray-900" : "") + " " + (path === getModelPath(configName, "") ? "text-white" : "")
  ].join(" ").trim()}"${add_attribute("aria-current", path === getModelPath(configName, "") ? "page" : "", 0)}>${escape($activeConfig.name || "Models")}

								\xA0

								<svg xmlns="${"http://www.w3.org/2000/svg"}" class="${"h-4 w-4"}" fill="${"none"}" viewBox="${"0 0 24 24"}" stroke="${"currentColor"}"><path stroke-linecap="${"round"}" stroke-linejoin="${"round"}" stroke-width="${"2"}" d="${"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"}"></path></svg></a>` : `<a${add_attribute("href", `/config`, 0)} class="${[
    "border-red-300 text-red-500 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium flex",
    (path === `/config` ? "bg-gray-900" : "") + " " + (path === `/config` ? "text-white" : "")
  ].join(" ").trim()}"${add_attribute("aria-current", path === `/config` ? "page" : "", 0)}>NOT CONNECTED \xA0

								<svg xmlns="${"http://www.w3.org/2000/svg"}" class="${"h-4 w-4"}" fill="${"none"}" viewBox="${"0 0 24 24"}" stroke="${"currentColor"}"><path stroke-linecap="${"round"}" stroke-linejoin="${"round"}" stroke-width="${"2"}" d="${"M13 10V3L4 14h7v7l9-11h-7z"}"></path></svg></a>`}

						<a href="${"/config"}" class="${[
    "text-gray-300 hover:text-white px-3 py-2 rounded-md text-sm font-medium",
    (path === "/config" ? "bg-gray-900" : "") + " " + (path === "/config" ? "text-white" : "")
  ].join(" ").trim()}"${add_attribute("aria-current", path === "/config" ? "page" : "", 0)}><code class="${"text-gray-500"}">${escape($activeConfig.base_url)}</code></a></div></div></div>

			<div class="${"-mr-2 flex sm:hidden"}">
				<button type="${"button"}" class="${"inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-white hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white"}" aria-controls="${"mobile-menu"}" aria-expanded="${"false"}"><span class="${"sr-only"}">Open main menu</span>
					
					<svg class="${"block h-6 w-6"}" xmlns="${"http://www.w3.org/2000/svg"}" fill="${"none"}" viewBox="${"0 0 24 24"}" stroke="${"currentColor"}" aria-hidden="${"true"}"><path stroke-linecap="${"round"}" stroke-linejoin="${"round"}" stroke-width="${"2"}" d="${"M4 6h16M4 12h16M4 18h16"}"></path></svg>
					
					<svg class="${"hidden h-6 w-6"}" xmlns="${"http://www.w3.org/2000/svg"}" fill="${"none"}" viewBox="${"0 0 24 24"}" stroke="${"currentColor"}" aria-hidden="${"true"}"><path stroke-linecap="${"round"}" stroke-linejoin="${"round"}" stroke-width="${"2"}" d="${"M6 18L18 6M6 6l12 12"}"></path></svg></button></div></div></div></nav>`;
});
const Footer = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  return `<footer class="${"w-full mt-auto bg-gray-700"}">...
</footer>`;
});
const _layout = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  setContext("services", services);
  setContext("datastore", services.datastore);
  setContext("stores", services.stores);
  return `${validate_component(Header, "Header").$$render($$result, {}, {}, {})}

<div class="${"w-full flex flex-col sm:flex-row flex-grow overflow-hidden"}"><main class="${"bg-gray-100 w-full h-screen flex-grow overflow-auto"}">${slots.default ? slots.default({}) : ``}</main></div>

${validate_component(Footer, "Footer").$$render($$result, {}, {}, {})}`;
});
export { _layout as default };
