"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Label } from "@open-mercato/ui/primitives/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { raiseCrudError } from "@open-mercato/ui/backend/utils/serverErrors";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { resolvePartitionEnvKey } from "@open-mercato/core/modules/attachments/lib/partitionEnv";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("attachments").child({ component: "partitions" });
const DEFAULT_FORM = {
  code: "",
  title: "",
  description: "",
  isPublic: false,
  requiresOcr: true,
  ocrModel: "",
  storageDriver: "local",
  s3CredentialsSource: "integration",
  s3CredentialsEnvPrefix: "",
  s3Bucket: "",
  s3Region: "",
  s3Endpoint: "",
  s3ForcePathStyle: false
};
const ALL_STORAGE_DRIVER_OPTIONS = [
  { value: "local", label: "Local filesystem" },
  { value: "s3", label: "Amazon S3 / S3-compatible", requiresModule: "s3" }
];
const OCR_MODEL_DEFAULT_VALUE = "__default__";
const OCR_MODEL_OPTIONS = [
  { value: OCR_MODEL_DEFAULT_VALUE, label: "Default (from environment)" },
  { value: "gpt-4o", label: "GPT-4o (Recommended)" },
  { value: "gpt-4o-mini", label: "GPT-4o Mini (Faster, Lower Cost)" }
];
function AttachmentPartitionSettings({ s3Enabled }) {
  const storageDriverOptions = ALL_STORAGE_DRIVER_OPTIONS.filter(
    (opt) => !opt.requiresModule || opt.requiresModule === "s3" && s3Enabled
  );
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [search, setSearch] = React.useState("");
  const [dialog, setDialog] = React.useState(null);
  const [form, setForm] = React.useState(DEFAULT_FORM);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const s3Unavailable = !s3Enabled;
  const s3SelectedWhileUnavailable = s3Unavailable && form.storageDriver === "s3";
  const loadErrorMessage = t("attachments.partitions.errors.load", "Failed to load partitions.");
  const loadItems = React.useCallback(async () => {
    setLoading(true);
    try {
      const payload = await readApiResultOrThrow(
        "/api/attachments/partitions",
        void 0,
        { errorMessage: loadErrorMessage }
      );
      const normalized = Array.isArray(payload.items) ? payload.items : [];
      const withDefaults = normalized.map((entry) => ({
        ...entry,
        requiresOcr: typeof entry.requiresOcr === "boolean" ? entry.requiresOcr : true
      }));
      setItems(withDefaults);
    } catch (err) {
      logger.error("Partition list failed", { err });
      flash(loadErrorMessage, "error");
    } finally {
      setLoading(false);
    }
  }, [loadErrorMessage]);
  React.useEffect(() => {
    loadItems().catch(() => {
    });
  }, [loadItems]);
  const filteredItems = React.useMemo(() => {
    if (!search.trim()) return items;
    const term = search.trim().toLowerCase();
    return items.filter(
      (entry) => entry.code.toLowerCase().includes(term) || entry.title.toLowerCase().includes(term) || (entry.description ?? "").toLowerCase().includes(term)
    );
  }, [items, search]);
  const openDialog = React.useCallback((state) => {
    if (state.mode === "edit") {
      const cfg = state.entry.configJson ?? {};
      const credsPrefix = typeof cfg.credentialsEnvPrefix === "string" ? cfg.credentialsEnvPrefix : "";
      setForm({
        code: state.entry.code,
        title: state.entry.title,
        description: state.entry.description ?? "",
        isPublic: state.entry.isPublic,
        requiresOcr: state.entry.requiresOcr,
        ocrModel: state.entry.ocrModel ?? "",
        storageDriver: state.entry.storageDriver ?? "local",
        s3CredentialsSource: credsPrefix ? "env" : "integration",
        s3CredentialsEnvPrefix: credsPrefix,
        s3Bucket: typeof cfg.bucket === "string" ? cfg.bucket : "",
        s3Region: typeof cfg.region === "string" ? cfg.region : "",
        s3Endpoint: typeof cfg.endpoint === "string" ? cfg.endpoint : "",
        s3ForcePathStyle: cfg.forcePathStyle === true
      });
    } else {
      setForm(DEFAULT_FORM);
    }
    setError(null);
    setDialog(state);
  }, []);
  const closeDialog = React.useCallback(() => {
    setDialog(null);
    setError(null);
    setSubmitting(false);
    setForm(DEFAULT_FORM);
  }, []);
  const handleSubmit = React.useCallback(async () => {
    if (!dialog) return;
    const trimmedCode = form.code.trim();
    const trimmedTitle = form.title.trim();
    if (!trimmedCode || !trimmedTitle) {
      setError(t("attachments.partitions.errors.required", "Code and title are required."));
      return;
    }
    if (form.storageDriver === "s3" && form.s3CredentialsSource === "env") {
      if (!form.s3CredentialsEnvPrefix.trim()) {
        setError(
          t(
            "attachments.partitions.errors.s3EnvPrefixRequired",
            "Credentials env prefix is required when using a separate credentials source."
          )
        );
        return;
      }
      if (!form.s3Bucket.trim()) {
        setError(
          t(
            "attachments.partitions.errors.s3BucketRequired",
            "Bucket is required when using a separate credentials source."
          )
        );
        return;
      }
    }
    setSubmitting(true);
    setError(null);
    try {
      const s3ConfigJson = form.storageDriver === "s3" ? {
        bucket: form.s3Bucket.trim() || void 0,
        region: form.s3Region.trim() || void 0,
        endpoint: form.s3Endpoint.trim() || void 0,
        forcePathStyle: form.s3ForcePathStyle || void 0,
        ...form.s3CredentialsSource === "env" ? { credentialsEnvPrefix: form.s3CredentialsEnvPrefix.trim() || void 0 } : {}
      } : null;
      const payload = {
        code: trimmedCode,
        title: trimmedTitle,
        description: form.description.trim() || void 0,
        isPublic: form.isPublic,
        requiresOcr: form.requiresOcr,
        ocrModel: form.ocrModel.trim() || null,
        storageDriver: form.storageDriver,
        configJson: s3ConfigJson
      };
      const method = dialog.mode === "create" ? "POST" : "PUT";
      const body = dialog.mode === "edit" ? JSON.stringify({ id: dialog.entry.id, ...payload }) : JSON.stringify(payload);
      const lockHeader = dialog.mode === "edit" ? buildOptimisticLockHeader(dialog.entry.updatedAt) : {};
      const call = await withScopedApiRequestHeaders(
        lockHeader,
        () => apiCall("/api/attachments/partitions", {
          method,
          headers: { "content-type": "application/json" },
          body
        })
      );
      if (!call.ok) {
        await raiseCrudError(
          call.response,
          t("attachments.partitions.errors.save", "Failed to save partition.")
        );
      }
      flash(
        dialog.mode === "create" ? t("attachments.partitions.messages.created", "Partition created.") : t("attachments.partitions.messages.updated", "Partition updated."),
        "success"
      );
      closeDialog();
      await loadItems();
    } catch (err) {
      logger.error("Partition save failed", { err });
      if (surfaceRecordConflict(err, t)) return;
      const message = err instanceof Error ? err.message : t("attachments.partitions.errors.save", "Failed to save partition.");
      setError(message);
    } finally {
      setSubmitting(false);
    }
  }, [dialog, form, t, closeDialog, loadItems]);
  const handleDelete = React.useCallback(
    async (entry) => {
      const confirmMessage = t("attachments.partitions.confirm.delete", 'Delete partition "{{code}}"?').replace(
        "{{code}}",
        entry.code
      );
      const confirmed = await confirm({
        title: confirmMessage,
        variant: "destructive"
      });
      if (!confirmed) return;
      try {
        const call = await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(entry.updatedAt),
          () => apiCall(`/api/attachments/partitions?id=${encodeURIComponent(entry.id)}`, {
            method: "DELETE"
          })
        );
        if (!call.ok) {
          await raiseCrudError(
            call.response,
            t("attachments.partitions.errors.delete", "Failed to delete partition.")
          );
        }
        flash(t("attachments.partitions.messages.deleted", "Partition removed."), "success");
        await loadItems();
      } catch (err) {
        logger.error("Partition delete failed", { err });
        if (surfaceRecordConflict(err, t)) return;
        flash(t("attachments.partitions.errors.delete", "Failed to delete partition."), "error");
      }
    },
    [confirm, loadItems, t]
  );
  const columns = React.useMemo(
    () => [
      {
        header: t("attachments.partitions.table.code", "Code"),
        accessorKey: "code",
        cell: ({ row }) => /* @__PURE__ */ jsx("code", { className: "font-mono text-xs", children: row.original.code })
      },
      {
        header: t("attachments.partitions.table.title", "Title"),
        accessorKey: "title",
        cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
          /* @__PURE__ */ jsx("span", { className: "font-medium", children: row.original.title }),
          row.original.description ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground line-clamp-2", children: row.original.description }) : null
        ] })
      },
      {
        header: t("attachments.partitions.table.visibility", "Visibility"),
        accessorKey: "isPublic",
        cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm", children: row.original.isPublic ? t("attachments.partitions.table.public", "Public") : t("attachments.partitions.table.private", "Private") })
      },
      {
        header: t("attachments.partitions.table.ocr", "OCR"),
        accessorKey: "requiresOcr",
        cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm", children: row.original.requiresOcr ? t("common.enabled", "Enabled") : t("common.disabled", "Disabled") })
      },
      {
        header: t("attachments.partitions.table.storageDriver", "Storage"),
        accessorKey: "storageDriver",
        cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm capitalize", children: row.original.storageDriver === "s3" ? "S3" : row.original.storageDriver ?? "local" })
      },
      {
        header: t("attachments.partitions.table.envKey", "Env variable"),
        accessorKey: "envKey",
        cell: ({ row }) => /* @__PURE__ */ jsx("code", { className: "text-xs", children: row.original.envKey })
      }
    ],
    [t]
  );
  const tableLabels = React.useMemo(
    () => ({
      search: t("attachments.partitions.table.search", "Search partitions\u2026"),
      empty: t("attachments.partitions.table.empty", "No partitions configured.")
    }),
    [t]
  );
  const formKeyHandler = React.useCallback(
    (event) => {
      if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
        event.preventDefault();
        void handleSubmit();
      }
    },
    [handleSubmit]
  );
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6 rounded-lg border bg-card p-6", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 md:flex-row md:items-center md:justify-between", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("attachments.partitions.title", "Attachment partitions") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("attachments.partitions.description", "Define storage partitions and visibility for uploads.") })
      ] }),
      /* @__PURE__ */ jsx(Button, { size: "sm", onClick: () => openDialog({ mode: "create" }), children: t("attachments.partitions.actions.add", "Add partition") })
    ] }),
    /* @__PURE__ */ jsx(
      DataTable,
      {
        columns,
        data: filteredItems,
        searchValue: search,
        onSearchChange: (value) => setSearch(value),
        searchPlaceholder: tableLabels.search,
        emptyState: /* @__PURE__ */ jsx("p", { className: "py-8 text-center text-sm text-muted-foreground", children: tableLabels.empty }),
        isLoading: loading,
        refreshButton: {
          label: t("attachments.partitions.actions.refresh", "Refresh"),
          onRefresh: () => {
            void loadItems();
          },
          isRefreshing: loading
        },
        rowActions: (entry) => /* @__PURE__ */ jsx(
          RowActions,
          {
            items: [
              {
                id: "edit",
                label: t("attachments.partitions.actions.edit", "Edit"),
                onSelect: () => openDialog({ mode: "edit", entry })
              },
              {
                id: "delete",
                label: t("attachments.partitions.actions.delete", "Delete"),
                destructive: true,
                onSelect: () => {
                  void handleDelete(entry);
                }
              }
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(Dialog, { open: dialog !== null, onOpenChange: (open) => {
      if (!open) closeDialog();
    }, children: /* @__PURE__ */ jsxs(DialogContent, { children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: dialog?.mode === "edit" ? t("attachments.partitions.dialog.editTitle", "Edit partition") : t("attachments.partitions.dialog.createTitle", "Create partition") }),
        /* @__PURE__ */ jsx(DialogDescription, { children: dialog?.mode === "edit" ? t("attachments.partitions.dialog.editDescription", "Update partition metadata and visibility.") : t("attachments.partitions.dialog.createDescription", "Define a storage partition for attachments.") })
      ] }),
      /* @__PURE__ */ jsxs(
        "form",
        {
          className: "space-y-4",
          onKeyDown: formKeyHandler,
          onSubmit: (event) => {
            event.preventDefault();
            void handleSubmit();
          },
          children: [
            /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: "partition-code", children: t("attachments.partitions.form.codeLabel", "Code") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: "partition-code",
                  value: form.code,
                  onChange: (event) => setForm((prev) => ({ ...prev, code: event.target.value })),
                  placeholder: t("attachments.partitions.form.codePlaceholder", "e.g. marketingAssets"),
                  disabled: dialog?.mode === "edit",
                  className: "font-mono uppercase"
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: "partition-title", children: t("attachments.partitions.form.titleLabel", "Title") }),
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: "partition-title",
                  value: form.title,
                  onChange: (event) => setForm((prev) => ({ ...prev, title: event.target.value })),
                  placeholder: t("attachments.partitions.form.titlePlaceholder", "e.g. Marketing assets")
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: "partition-description", children: t("attachments.partitions.form.descriptionLabel", "Description") }),
              /* @__PURE__ */ jsx(
                "textarea",
                {
                  id: "partition-description",
                  className: "min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm",
                  value: form.description,
                  onChange: (event) => setForm((prev) => ({ ...prev, description: event.target.value })),
                  placeholder: t("attachments.partitions.form.descriptionPlaceholder", "Explain how this partition is used.")
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm font-medium", children: [
              /* @__PURE__ */ jsx(
                "input",
                {
                  type: "checkbox",
                  className: "h-4 w-4 rounded border",
                  checked: form.isPublic,
                  onChange: (event) => setForm((prev) => ({ ...prev, isPublic: event.target.checked }))
                }
              ),
              t("attachments.partitions.form.publicLabel", "Publicly accessible")
            ] }),
            /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm font-medium", children: [
              /* @__PURE__ */ jsx(
                "input",
                {
                  type: "checkbox",
                  className: "h-4 w-4 rounded border",
                  checked: form.requiresOcr,
                  onChange: (event) => setForm((prev) => ({ ...prev, requiresOcr: event.target.checked }))
                }
              ),
              t("attachments.partitions.form.ocrLabel", "Require OCR/text extraction")
            ] }),
            form.requiresOcr && /* @__PURE__ */ jsxs("div", { className: "space-y-2 pl-6", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: "partition-ocr-model", children: t("attachments.partitions.form.ocrModelLabel", "OCR Model") }),
              /* @__PURE__ */ jsxs(
                Select,
                {
                  value: form.ocrModel ? form.ocrModel : OCR_MODEL_DEFAULT_VALUE,
                  onValueChange: (value) => setForm((prev) => ({
                    ...prev,
                    ocrModel: value === OCR_MODEL_DEFAULT_VALUE ? "" : value
                  })),
                  children: [
                    /* @__PURE__ */ jsx(SelectTrigger, { id: "partition-ocr-model", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                    /* @__PURE__ */ jsx(SelectContent, { children: OCR_MODEL_OPTIONS.map((option) => /* @__PURE__ */ jsx(SelectItem, { value: option.value, children: t(
                      `attachments.partitions.form.ocrModelOptions.${option.value === OCR_MODEL_DEFAULT_VALUE ? "default" : option.value}`,
                      option.label
                    ) }, option.value)) })
                  ]
                }
              ),
              /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                "attachments.partitions.form.ocrModelHelp",
                "Choose the LLM model for OCR processing. Falls back to OCR_MODEL environment variable or gpt-4o."
              ) })
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
              /* @__PURE__ */ jsx(Label, { htmlFor: "partition-storage-driver", children: t("attachments.partitions.form.storageDriverLabel", "Storage Driver") }),
              /* @__PURE__ */ jsx(
                "select",
                {
                  id: "partition-storage-driver",
                  className: "w-full rounded-md border border-input bg-background px-3 py-2 text-sm",
                  value: form.storageDriver,
                  onChange: (event) => setForm((prev) => ({ ...prev, storageDriver: event.target.value })),
                  children: storageDriverOptions.map((option) => /* @__PURE__ */ jsx(
                    "option",
                    {
                      value: option.value,
                      disabled: option.value === "s3" && s3Unavailable,
                      children: option.label
                    },
                    option.value
                  ))
                }
              ),
              s3Unavailable ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                "attachments.partitions.form.storageDriverS3DisabledHelp",
                "S3 is disabled. Set OM_ENABLE_STORAGE_S3=true and restart to enable S3 partitions."
              ) }) : null
            ] }),
            form.storageDriver === "s3" && /* @__PURE__ */ jsxs("div", { className: "space-y-3 rounded-md border bg-muted/30 p-3", children: [
              /* @__PURE__ */ jsx("p", { className: "text-xs font-medium text-muted-foreground", children: t("attachments.partitions.form.s3ConfigTitle", "S3 Configuration") }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsx(Label, { htmlFor: "partition-s3-creds-source", children: t("attachments.partitions.form.s3CredsSourceLabel", "Credentials source") }),
                /* @__PURE__ */ jsxs(
                  "select",
                  {
                    id: "partition-s3-creds-source",
                    className: "w-full rounded-md border border-input bg-background px-3 py-2 text-sm",
                    value: form.s3CredentialsSource,
                    onChange: (event) => setForm((prev) => ({
                      ...prev,
                      s3CredentialsSource: event.target.value,
                      ...event.target.value === "integration" ? { s3CredentialsEnvPrefix: "" } : {}
                    })),
                    children: [
                      /* @__PURE__ */ jsx("option", { value: "integration", children: t(
                        "attachments.partitions.form.s3CredsSourceIntegration",
                        "Use Integration Marketplace credentials"
                      ) }),
                      /* @__PURE__ */ jsx("option", { value: "env", children: t(
                        "attachments.partitions.form.s3CredsSourceEnv",
                        "Use separate env-based credentials"
                      ) })
                    ]
                  }
                ),
                /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: form.s3CredentialsSource === "integration" ? t(
                  "attachments.partitions.form.s3CredsSourceIntegrationHelp",
                  "This partition reuses the credentials, bucket, region and endpoint configured in the S3 integration. Override individual fields below only when needed."
                ) : t(
                  "attachments.partitions.form.s3CredsSourceEnvHelp",
                  "This partition uses its own credentials read from environment variables. The integration credentials are ignored. Bucket and credentials prefix are required."
                ) })
              ] }),
              form.s3CredentialsSource === "env" && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsx(Label, { htmlFor: "partition-s3-creds-prefix", children: t("attachments.partitions.form.s3CredsPrefixLabel", "Credentials Env Prefix") }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    id: "partition-s3-creds-prefix",
                    value: form.s3CredentialsEnvPrefix,
                    onChange: (event) => setForm((prev) => ({ ...prev, s3CredentialsEnvPrefix: event.target.value })),
                    placeholder: "OM_INTEGRATION_STORAGE_S3",
                    className: "font-mono"
                  }
                ),
                /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
                  "attachments.partitions.form.s3CredsPrefixHelp",
                  "Reads {PREFIX}_ACCESS_KEY_ID and {PREFIX}_SECRET_ACCESS_KEY from environment variables."
                ) })
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsx(Label, { htmlFor: "partition-s3-bucket", children: form.s3CredentialsSource === "integration" ? t("attachments.partitions.form.s3BucketOverrideLabel", "Bucket override (optional)") : t("attachments.partitions.form.s3BucketLabel", "Bucket") }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    id: "partition-s3-bucket",
                    value: form.s3Bucket,
                    onChange: (event) => setForm((prev) => ({ ...prev, s3Bucket: event.target.value })),
                    placeholder: form.s3CredentialsSource === "integration" ? t(
                      "attachments.partitions.form.s3BucketOverridePlaceholder",
                      "Leave empty to use integration bucket"
                    ) : "my-company-attachments"
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsx(Label, { htmlFor: "partition-s3-region", children: form.s3CredentialsSource === "integration" ? t("attachments.partitions.form.s3RegionOverrideLabel", "Region override (optional)") : t("attachments.partitions.form.s3RegionLabel", "Region") }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    id: "partition-s3-region",
                    value: form.s3Region,
                    onChange: (event) => setForm((prev) => ({ ...prev, s3Region: event.target.value })),
                    placeholder: form.s3CredentialsSource === "integration" ? t(
                      "attachments.partitions.form.s3RegionOverridePlaceholder",
                      "Leave empty to use integration region"
                    ) : "us-east-1"
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
                /* @__PURE__ */ jsx(Label, { htmlFor: "partition-s3-endpoint", children: form.s3CredentialsSource === "integration" ? t("attachments.partitions.form.s3EndpointOverrideLabel", "Custom endpoint override (optional)") : t("attachments.partitions.form.s3EndpointLabel", "Custom Endpoint") }),
                /* @__PURE__ */ jsx(
                  Input,
                  {
                    id: "partition-s3-endpoint",
                    value: form.s3Endpoint,
                    onChange: (event) => setForm((prev) => ({ ...prev, s3Endpoint: event.target.value })),
                    placeholder: form.s3CredentialsSource === "integration" ? t(
                      "attachments.partitions.form.s3EndpointOverridePlaceholder",
                      "Leave empty to use integration endpoint"
                    ) : "https://fra1.digitaloceanspaces.com"
                  }
                ),
                /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("attachments.partitions.form.s3EndpointHelp", "Leave empty for AWS S3. Required for MinIO, DigitalOcean Spaces, etc.") })
              ] }),
              /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm font-medium", children: [
                /* @__PURE__ */ jsx(
                  "input",
                  {
                    type: "checkbox",
                    className: "h-4 w-4 rounded border",
                    checked: form.s3ForcePathStyle,
                    onChange: (event) => setForm((prev) => ({ ...prev, s3ForcePathStyle: event.target.checked }))
                  }
                ),
                t("attachments.partitions.form.s3ForcePathStyleLabel", "Force Path Style (required for MinIO)")
              ] })
            ] }),
            dialog ? /* @__PURE__ */ jsxs("div", { className: "rounded-md border bg-muted/50 px-3 py-2 text-xs text-muted-foreground", children: [
              /* @__PURE__ */ jsx("div", { children: t("attachments.partitions.form.envKeyHelp", "Set this env var to override storage path:") }),
              /* @__PURE__ */ jsx("code", { children: dialog.mode === "edit" ? dialog.entry.envKey : form.code.trim() ? resolvePartitionEnvKey(form.code.trim()) : "ATTACHMENTS_PARTITION_CODE_ROOT" })
            ] }) : null,
            s3SelectedWhileUnavailable ? /* @__PURE__ */ jsx("p", { className: "text-sm text-status-error-text", children: t(
              "attachments.partitions.errors.s3Disabled",
              "This partition uses S3, but S3 is disabled. Set OM_ENABLE_STORAGE_S3=true and restart the app."
            ) }) : null,
            error ? /* @__PURE__ */ jsx("p", { className: "text-sm text-status-error-text", children: error }) : null
          ]
        }
      ),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: closeDialog, children: t("attachments.partitions.actions.cancel", "Cancel") }),
        /* @__PURE__ */ jsx(Button, { onClick: () => void handleSubmit(), disabled: submitting || s3SelectedWhileUnavailable, children: dialog?.mode === "edit" ? t("attachments.partitions.actions.save", "Save changes") : t("attachments.partitions.actions.create", "Create partition") })
      ] })
    ] }) }),
    ConfirmDialogElement
  ] });
}
export {
  AttachmentPartitionSettings
};
//# sourceMappingURL=AttachmentPartitionSettings.js.map
