"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const context = require('@btst/stack/context');
const button = require('../../../../../../../ui/src/components/button.cjs');
const input = require('../../../../../../../ui/src/components/input.cjs');
const select = require('../../../../../../../ui/src/components/select.cjs');
const popover = require('../../../../../../../ui/src/components/popover.cjs');
const label = require('../../../../../../../ui/src/components/label.cjs');
const LucideIcons = require('lucide-react');
const sonner = require('sonner');
const index$1 = require('../../../../../../../ui/src/components/ui-builder/index.cjs');
const layerStore = require('../../../../../../../ui/src/lib/ui-builder/store/layer-store.cjs');
const context$1 = require('@btst/stack/plugins/ai-chat/client/context');
const uiBuilderHooks = require('../../hooks/ui-builder-hooks.cjs');
const index = require('../../localization/index.cjs');
const registry = require('../../registry.cjs');

function buildRegistryDescription(registry) {
  const lines = [];
  for (const [name, entry] of Object.entries(registry)) {
    let propsLine = "";
    try {
      const shape = entry.schema?.shape;
      if (shape) {
        const fields = Object.keys(shape).join(", ");
        propsLine = ` \u2014 props: ${fields}`;
      }
    } catch {
    }
    lines.push(`- ${name}${propsLine}`);
  }
  return lines.join("\n");
}
function buildPageDescription(id, slug, layers, registry) {
  const header = id ? `UI Builder \u2014 editing page (slug: "${slug}")` : "UI Builder \u2014 creating new page";
  const layersJson = JSON.stringify(layers, null, 2);
  const registryDesc = buildRegistryDescription(registry);
  const layerFormat = `Each layer: { id: string, type: string, name: string, props: Record<string,any>, children?: ComponentLayer[] | string }`;
  const full = [
    header,
    "",
    `## Current Layers (${layers.length})`,
    layersJson,
    "",
    `## Available Component Types`,
    registryDesc,
    "",
    `## ComponentLayer format`,
    layerFormat
  ].join("\n");
  if (full.length <= 16e3) return full;
  const overhead = [
    header,
    "",
    `## Current Layers (${layers.length})`,
    "",
    "",
    `## Available Component Types`,
    registryDesc,
    "",
    `## ComponentLayer format`,
    layerFormat
  ].join("\n").length + 30;
  const budget = Math.max(0, 16e3 - overhead);
  const truncatedLayers = layersJson.length > budget ? layersJson.slice(0, budget) + "\n...(truncated)" : layersJson;
  return [
    header,
    "",
    `## Current Layers (${layers.length})`,
    truncatedLayers,
    "",
    `## Available Component Types`,
    registryDesc,
    "",
    `## ComponentLayer format`,
    layerFormat
  ].join("\n");
}
function slugify(str) {
  return str.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
}
function PageBuilderPage({ id }) {
  if (id) {
    return /* @__PURE__ */ jsxRuntime.jsx(EditPageBuilderPage, { id });
  }
  return /* @__PURE__ */ jsxRuntime.jsx(CreatePageBuilderPage, {});
}
function EditPageBuilderPage({ id }) {
  const { page: existingPage } = uiBuilderHooks.useSuspenseUIBuilderPage(id);
  return /* @__PURE__ */ jsxRuntime.jsx(PageBuilderPageContent, { id, existingPage });
}
function CreatePageBuilderPage() {
  return /* @__PURE__ */ jsxRuntime.jsx(PageBuilderPageContent, {});
}
function parseLayers(layersJson) {
  if (!layersJson) return [];
  try {
    return JSON.parse(layersJson);
  } catch {
    return [];
  }
}
function parseVariables(variablesJson) {
  if (!variablesJson) return [];
  try {
    return JSON.parse(variablesJson);
  } catch {
    return [];
  }
}
function PageBuilderPageContent({
  id,
  existingPage
}) {
  const {
    navigate,
    Link,
    componentRegistry: customRegistry,
    functionRegistry
  } = context.usePluginOverrides("ui-builder");
  const basePath = context.useBasePath();
  const createMutation = uiBuilderHooks.useCreateUIBuilderPage();
  const updateMutation = uiBuilderHooks.useUpdateUIBuilderPage();
  const loc = index.uiBuilderLocalization;
  const LinkComponent = Link || "a";
  const componentRegistry = customRegistry || registry.defaultComponentRegistry;
  const existingLayers = parseLayers(existingPage?.parsedData?.layers);
  const existingVariables = parseVariables(existingPage?.parsedData?.variables);
  const [slug, setSlug] = React.useState(existingPage?.slug || "");
  const [status, setStatus] = React.useState(
    existingPage?.parsedData?.status || "draft"
  );
  const [layers, setLayers] = React.useState(existingLayers);
  const [variables, setVariables] = React.useState(existingVariables);
  const [autoSlug, setAutoSlug] = React.useState(!id);
  context$1.useRegisterPageAIContext({
    routeName: id ? "ui-builder-edit-page" : "ui-builder-new-page",
    pageDescription: buildPageDescription(id, slug, layers, componentRegistry),
    suggestions: [
      "Add a hero section",
      "Add a 3-column feature grid",
      "Make the layout full-width",
      "Add a card with a title, description, and button",
      "Replace the layout with a centered single-column design"
    ],
    clientTools: {
      updatePageLayers: async ({ layers: newLayers }) => {
        const store = layerStore.useLayerStore.getState();
        store.initialize(
          newLayers,
          store.selectedPageId || newLayers[0]?.id,
          void 0,
          store.variables
        );
        return {
          success: true,
          message: `Applied ${newLayers.length} layer(s) to the page`
        };
      }
    }
  });
  const handleLayersChange = React.useCallback(
    (newLayers) => {
      setLayers(newLayers);
      if (autoSlug && newLayers.length > 0 && newLayers[0]?.name) {
        setSlug(slugify(newLayers[0].name));
      }
    },
    [autoSlug]
  );
  const handleVariablesChange = React.useCallback((newVariables) => {
    setVariables(newVariables);
  }, []);
  const handleSave = async () => {
    if (!slug.trim()) {
      sonner.toast.error(loc.pageBuilder.validation.slugRequired);
      return;
    }
    if (!/^[a-z0-9-]+$/.test(slug)) {
      sonner.toast.error(loc.pageBuilder.validation.slugFormat);
      return;
    }
    if (layers.length === 0) {
      sonner.toast.error(loc.pageBuilder.validation.layersRequired);
      return;
    }
    try {
      if (id) {
        await updateMutation.mutateAsync({
          id,
          data: {
            layers,
            variables,
            status
          }
        });
        sonner.toast.success(loc.pageBuilder.saved);
      } else {
        const newPage = await createMutation.mutateAsync({
          slug,
          layers,
          variables,
          status
        });
        sonner.toast.success(loc.pageBuilder.saved);
        navigate?.(`${basePath}/ui-builder/${newPage.id}/edit`);
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : "Unknown error";
      if (message.includes("slug already exists")) {
        sonner.toast.error("A page with this slug already exists");
      } else {
        sonner.toast.error(loc.pageBuilder.saveError);
      }
    }
  };
  const isSaving = createMutation.isPending || updateMutation.isPending;
  const pageSettingsFields = (isMobile) => /* @__PURE__ */ jsxRuntime.jsxs(
    "div",
    {
      className: isMobile ? "flex flex-col gap-4" : "flex items-center gap-4",
      children: [
        /* @__PURE__ */ jsxRuntime.jsxs("div", { className: isMobile ? "flex flex-col gap-2" : "", children: [
          isMobile && /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "page-slug", className: "text-sm font-medium", children: loc.pageBuilder.slugLabel }),
          /* @__PURE__ */ jsxRuntime.jsx(
            input.Input,
            {
              id: "page-slug",
              value: slug,
              onChange: (e) => {
                setSlug(e.target.value);
                setAutoSlug(false);
              },
              placeholder: loc.pageBuilder.slugPlaceholder,
              className: isMobile ? "h-9 font-mono text-sm" : "h-8 w-48 font-mono text-sm",
              disabled: !!id
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntime.jsxs("div", { className: isMobile ? "flex flex-col gap-2" : "", children: [
          isMobile && /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "page-status", className: "text-sm font-medium", children: loc.pageBuilder.statusLabel }),
          /* @__PURE__ */ jsxRuntime.jsxs(
            select.Select,
            {
              value: status,
              onValueChange: (v) => setStatus(v),
              children: [
                /* @__PURE__ */ jsxRuntime.jsx(select.SelectTrigger, { className: isMobile ? "h-9 w-full" : "h-8 w-28", children: /* @__PURE__ */ jsxRuntime.jsx(select.SelectValue, {}) }),
                /* @__PURE__ */ jsxRuntime.jsxs(select.SelectContent, { children: [
                  /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "draft", children: loc.pageBuilder.statusOptions.draft }),
                  /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "published", children: loc.pageBuilder.statusOptions.published }),
                  /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "archived", children: loc.pageBuilder.statusOptions.archived })
                ] })
              ]
            }
          )
        ] })
      ]
    }
  );
  const navLeftChildren = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 md:gap-4", children: [
    /* @__PURE__ */ jsxRuntime.jsx(button.Button, { variant: "ghost", size: "icon", asChild: true, className: "shrink-0", children: /* @__PURE__ */ jsxRuntime.jsx(LinkComponent, { href: `${basePath}/ui-builder`, children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.ArrowLeft, { className: "h-4 w-4" }) }) }),
    /* @__PURE__ */ jsxRuntime.jsx("div", { className: "md:hidden", children: /* @__PURE__ */ jsxRuntime.jsxs(popover.Popover, { children: [
      /* @__PURE__ */ jsxRuntime.jsx(popover.PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs(button.Button, { variant: "outline", size: "sm", className: "gap-2", children: [
        /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Settings2, { className: "h-4 w-4" }),
        /* @__PURE__ */ jsxRuntime.jsx("span", { className: "max-w-20 truncate font-mono text-xs", children: slug || loc.pageBuilder.slugPlaceholder })
      ] }) }),
      /* @__PURE__ */ jsxRuntime.jsx(popover.PopoverContent, { className: "z-[9999] w-72", align: "start", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid gap-4", children: [
        /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxRuntime.jsx("h4", { className: "font-medium leading-none", children: "Page Settings" }),
          /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Configure page slug and status" })
        ] }),
        pageSettingsFields(true)
      ] }) })
    ] }) }),
    /* @__PURE__ */ jsxRuntime.jsx("div", { className: "hidden md:flex md:items-center md:gap-4", children: pageSettingsFields(false) })
  ] });
  const navRightChildren = /* @__PURE__ */ jsxRuntime.jsxs(
    button.Button,
    {
      onClick: handleSave,
      disabled: isSaving,
      size: "icon",
      className: "md:w-auto md:px-4",
      children: [
        /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Save, { className: "h-4 w-4 md:mr-2" }),
        /* @__PURE__ */ jsxRuntime.jsx("span", { className: "hidden md:inline", children: isSaving ? loc.pageBuilder.saving : id ? loc.pageBuilder.save : loc.pageBuilder.save })
      ]
    }
  );
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-full flex-col", "data-testid": "page-builder-page", children: /* @__PURE__ */ jsxRuntime.jsx(
    index$1.default,
    {
      initialLayers: existingLayers.length > 0 ? existingLayers : void 0,
      onChange: handleLayersChange,
      initialVariables: existingVariables.length > 0 ? existingVariables : void 0,
      onVariablesChange: handleVariablesChange,
      componentRegistry,
      functionRegistry,
      persistLayerStore: false,
      allowVariableEditing: true,
      allowPagesCreation: false,
      allowPagesDeletion: false,
      showExport: false,
      navLeftChildren,
      navRightChildren
    }
  ) });
}

exports.PageBuilderPage = PageBuilderPage;
