"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import React__default, { useState, useMemo, useEffect, useCallback } from 'react';
import LayersPanel from './internal/layers-panel.mjs';
import EditorPanel from './internal/editor-panel.mjs';
import PropsPanel from './internal/props-panel.mjs';
import { NavBar } from './internal/components/nav.mjs';
import { ThemeProvider as J } from '../../../../../node_modules/.pnpm/next-themes@0.4.6_react-dom@19.2.0_react@19.2.0__react@19.2.0/node_modules/next-themes/dist/index.mjs';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '../tabs.mjs';
import { ResizablePanelGroup, ResizableHandle, ResizablePanel } from '../resizable.mjs';
import { Button } from '../button.mjs';
import { useLayerStore } from '../../lib/ui-builder/store/layer-store.mjs';
import { useStore } from '../../hooks/use-store.mjs';
import { useEditorStore } from '../../lib/ui-builder/store/editor-store.mjs';
import { TailwindThemePanel } from './internal/tailwind-theme-panel.mjs';
import { ConfigPanel } from './internal/config-panel.mjs';
import { VariablesPanel } from './internal/variables-panel.mjs';
import { TooltipProvider } from '../tooltip.mjs';

const UIBuilder = ({
  initialLayers,
  onChange,
  initialVariables,
  onVariablesChange,
  componentRegistry,
  panelConfig: userPanelConfig,
  persistLayerStore = true,
  allowVariableEditing = true,
  allowPagesCreation = true,
  allowPagesDeletion = true,
  navLeftChildren,
  navRightChildren,
  showExport = true,
  blocks
}) => {
  const layerStore = useStore(useLayerStore, (state) => state);
  const editorStore = useStore(useEditorStore, (state) => state);
  const [editorStoreInitialized, setEditorStoreInitialized] = useState(false);
  const [layerStoreInitialized, setLayerStoreInitialized] = useState(false);
  const memoizedDefaultTabsContent = useMemo(() => defaultConfigTabsContent(), []);
  const currentPanelConfig = useMemo(() => {
    const effectiveTabsContent = userPanelConfig?.pageConfigPanelTabsContent || memoizedDefaultTabsContent;
    const defaultPanels = getDefaultPanelConfigValues(effectiveTabsContent, navLeftChildren, navRightChildren, showExport);
    return {
      navBar: userPanelConfig?.navBar ?? defaultPanels.navBar,
      pageConfigPanel: userPanelConfig?.pageConfigPanel ?? defaultPanels.pageConfigPanel,
      editorPanel: userPanelConfig?.editorPanel ?? defaultPanels.editorPanel,
      propsPanel: userPanelConfig?.propsPanel ?? defaultPanels.propsPanel
    };
  }, [userPanelConfig, memoizedDefaultTabsContent, navLeftChildren, navRightChildren, showExport]);
  useEffect(() => {
    if (editorStore && componentRegistry && !editorStoreInitialized) {
      editorStore.initialize(componentRegistry, persistLayerStore, allowPagesCreation, allowPagesDeletion, allowVariableEditing, blocks);
      setEditorStoreInitialized(true);
    }
  }, [
    editorStore,
    componentRegistry,
    editorStoreInitialized,
    persistLayerStore,
    allowPagesCreation,
    allowPagesDeletion,
    allowVariableEditing,
    blocks
  ]);
  useEffect(() => {
    if (layerStore && editorStore) {
      if (initialLayers && !layerStoreInitialized) {
        layerStore.initialize(initialLayers, void 0, void 0, initialVariables);
        setLayerStoreInitialized(true);
        const { clear } = useLayerStore.temporal.getState();
        clear();
      } else {
        setLayerStoreInitialized(true);
      }
    }
  }, [
    layerStore,
    editorStore,
    componentRegistry,
    initialLayers,
    initialVariables,
    layerStoreInitialized
  ]);
  useEffect(() => {
    if (onChange && layerStore?.pages && layerStoreInitialized) {
      onChange(layerStore.pages);
    }
  }, [layerStore?.pages, onChange, layerStoreInitialized]);
  useEffect(() => {
    if (onVariablesChange && layerStore?.variables && layerStoreInitialized) {
      onVariablesChange(layerStore.variables);
    }
  }, [layerStore?.variables, onVariablesChange, layerStoreInitialized]);
  const isLoading = !layerStoreInitialized || !editorStoreInitialized;
  const layout = isLoading ? /* @__PURE__ */ jsx(LoadingSkeleton, {}) : /* @__PURE__ */ jsx(MainLayout, { panelConfig: currentPanelConfig });
  return /* @__PURE__ */ jsx(
    J,
    {
      "data-testid": "theme-provider",
      attribute: "class",
      defaultTheme: "system",
      enableSystem: true,
      disableTransitionOnChange: true,
      children: /* @__PURE__ */ jsx(TooltipProvider, { children: layout })
    }
  );
};
function MainLayout({ panelConfig }) {
  const showLeftPanel = useEditorStore((state) => state.showLeftPanel);
  const showRightPanel = useEditorStore((state) => state.showRightPanel);
  const mainPanels = useMemo(() => {
    const panels = [];
    if (showLeftPanel) {
      panels.push({
        title: "Page Config",
        content: panelConfig.pageConfigPanel,
        defaultSize: showRightPanel ? 25 : 33
      });
    }
    panels.push({
      title: "UI Editor",
      content: panelConfig.editorPanel,
      defaultSize: showLeftPanel && showRightPanel ? 50 : showLeftPanel || showRightPanel ? 67 : 100
    });
    if (showRightPanel) {
      panels.push({
        title: "Props",
        content: panelConfig.propsPanel,
        defaultSize: showLeftPanel ? 25 : 33
      });
    }
    return panels;
  }, [panelConfig, showLeftPanel, showRightPanel]);
  const [selectedPanel, setSelectedPanel] = useState(() => {
    const editorPanel = mainPanels.find((panel) => panel.title === "UI Editor");
    return editorPanel || mainPanels[0];
  });
  useEffect(() => {
    const editorPanel = mainPanels.find((panel) => panel.title === "UI Editor");
    const currentPanel = mainPanels.find((panel) => panel.title === selectedPanel?.title);
    if (!currentPanel) {
      setSelectedPanel(editorPanel || mainPanels[0]);
    }
  }, [mainPanels, selectedPanel?.title]);
  const handlePanelClickById = useCallback((e) => {
    const panelIndex = parseInt(e.currentTarget.dataset.panelIndex || "0");
    setSelectedPanel(mainPanels[panelIndex]);
  }, [mainPanels]);
  return /* @__PURE__ */ jsxs(
    "div",
    {
      "data-testid": "component-editor",
      className: "flex flex-col w-full flex-grow h-dvh",
      children: [
        panelConfig.navBar,
        /* @__PURE__ */ jsx("div", { className: "hidden md:flex flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(
          ResizablePanelGroup,
          {
            direction: "horizontal",
            className: "flex overflow-hidden flex-1",
            children: mainPanels.map((panel, index) => /* @__PURE__ */ jsxs(React__default.Fragment, { children: [
              index > 0 && /* @__PURE__ */ jsx(ResizableHandle, { withHandle: true }),
              /* @__PURE__ */ jsx(
                ResizablePanel,
                {
                  defaultSize: panel.defaultSize,
                  minSize: 15,
                  className: "min-h-full flex-1",
                  children: panel.content
                }
              )
            ] }, panel.title))
          }
        ) }),
        /* @__PURE__ */ jsxs("div", { className: "flex size-full flex-col md:hidden overflow-hidden ", children: [
          selectedPanel?.content,
          /* @__PURE__ */ jsx("div", { className: "absolute bottom-4 left-4 right-4 z-50", children: /* @__PURE__ */ jsx("div", { className: "flex justify-center rounded-full bg-primary p-2 shadow-lg", children: mainPanels.map((panel, index) => /* @__PURE__ */ jsx(
            Button,
            {
              variant: selectedPanel?.title !== panel.title ? "default" : "secondary",
              size: "sm",
              className: "flex-1",
              "data-panel-index": index,
              onClick: handlePanelClickById,
              children: panel.title
            },
            panel.title
          )) }) })
        ] })
      ]
    }
  );
}
function PageConfigPanel({
  className,
  tabsContent
}) {
  const { layers, appearance, data } = tabsContent;
  const tabCount = 1 + (appearance ? 1 : 0) + (data ? 1 : 0);
  return /* @__PURE__ */ jsxs(
    Tabs,
    {
      "data-testid": "page-config-panel",
      defaultValue: "layers",
      className,
      children: [
        /* @__PURE__ */ jsxs(TabsList, { className: `grid grid-cols-${tabCount} mx-4`, children: [
          /* @__PURE__ */ jsx(TabsTrigger, { value: "layers", children: layers.title }),
          appearance && /* @__PURE__ */ jsx(TabsTrigger, { value: "appearance", children: appearance.title }),
          data && /* @__PURE__ */ jsx(TabsTrigger, { value: "variables", children: data.title })
        ] }),
        /* @__PURE__ */ jsx(TabsContent, { value: "layers", children: layers.content }),
        appearance && /* @__PURE__ */ jsx(TabsContent, { value: "appearance", children: appearance.content }),
        data && /* @__PURE__ */ jsx(TabsContent, { value: "variables", children: data.content })
      ]
    }
  );
}
function defaultConfigTabsContent() {
  return {
    layers: { title: "Layers", content: /* @__PURE__ */ jsx(LayersPanel, {}) },
    appearance: {
      title: "Appearance",
      content: /* @__PURE__ */ jsxs("div", { className: "py-2 px-4 gap-2 flex flex-col overflow-y-auto overflow-x-auto", children: [
        /* @__PURE__ */ jsx(ConfigPanel, {}),
        /* @__PURE__ */ jsx(TailwindThemePanel, {})
      ] })
    },
    data: { title: "Data", content: /* @__PURE__ */ jsx(VariablesPanel, {}) }
  };
}
function LoadingSkeleton() {
  return /* @__PURE__ */ jsxs(
    "div",
    {
      "data-testid": "loading-skeleton",
      className: "flex flex-col flex-1 gap-1 bg-secondary/90",
      children: [
        /* @__PURE__ */ jsx("div", { className: "w-full h-16 animate-pulse bg-background rounded-md" }),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-1 gap-1", children: [
          /* @__PURE__ */ jsx("div", { className: "w-1/4 animate-pulse bg-background rounded-md" }),
          /* @__PURE__ */ jsx("div", { className: "w-1/2 animate-pulse bg-muted-background/90 rounded-md" }),
          /* @__PURE__ */ jsx("div", { className: "w-1/4 animate-pulse bg-background rounded-md" })
        ] })
      ]
    }
  );
}
const getDefaultPanelConfigValues = (tabsContent, navLeftChildren, navRightChildren, showExport) => {
  return {
    navBar: /* @__PURE__ */ jsx(NavBar, { leftChildren: navLeftChildren, rightChildren: navRightChildren, showExport }),
    pageConfigPanel: /* @__PURE__ */ jsx(PageConfigPanel, { className: "pt-4 pb-20 md:pb-4 overflow-y-auto relative size-full", tabsContent }),
    editorPanel: /* @__PURE__ */ jsx(
      EditorPanel,
      {
        className: "pb-20 md:pb-0 overflow-y-auto"
      }
    ),
    propsPanel: /* @__PURE__ */ jsx(PropsPanel, { className: "px-4 pt-4 pb-20 md:pb-4 overflow-y-auto relative size-full" })
  };
};

export { LoadingSkeleton, PageConfigPanel, UIBuilder as default, defaultConfigTabsContent, getDefaultPanelConfigValues };
