"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { apiCall, readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
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 { Switch } from "@open-mercato/ui/primitives/switch";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@open-mercato/ui/primitives/card";
const emptySettings = {
  panelPath: "/backend/notifications",
  strategies: {
    database: { enabled: true },
    email: { enabled: true },
    custom: {}
  }
};
const SETTINGS_CONTEXT_ID = "notifications-settings";
function NotificationSettingsPageClient() {
  const t = useT();
  const [settings, setSettings] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState(null);
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: SETTINGS_CONTEXT_ID,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const fetchSettings = React.useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const body = await readApiResultOrThrow(
        "/api/notifications/settings",
        void 0,
        { errorMessage: t("notifications.settings.loadError", "Failed to load notification settings"), allowNullResult: true }
      );
      if (body?.settings) {
        setSettings(body.settings);
      } else {
        setSettings(emptySettings);
      }
    } catch (err) {
      const message = err instanceof Error ? err.message : t("notifications.settings.loadError", "Failed to load notification settings");
      setError(message);
      flash(message, "error");
    } finally {
      setLoading(false);
    }
  }, [t]);
  React.useEffect(() => {
    fetchSettings();
  }, [fetchSettings]);
  const updateSettings = (patch) => {
    setSettings((prev) => prev ? { ...prev, ...patch } : prev);
  };
  const updateStrategy = (strategy, patch) => {
    setSettings((prev) => {
      if (!prev) return prev;
      return {
        ...prev,
        strategies: {
          ...prev.strategies,
          [strategy]: {
            ...prev.strategies[strategy],
            ...patch
          }
        }
      };
    });
  };
  const handleSave = async () => {
    if (!settings) return;
    setSaving(true);
    try {
      const response = await runMutation({
        operation: () => apiCall("/api/notifications/settings", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(settings)
        }),
        context: { formId: SETTINGS_CONTEXT_ID, resourceKind: "notifications.settings", retryLastMutation },
        mutationPayload: { settings }
      });
      if (!response.ok) {
        const message = response.result?.error || t("notifications.settings.saveError", "Failed to save notification settings");
        throw new Error(message);
      }
      if (response.result?.settings) {
        setSettings(response.result.settings);
      }
      flash(t("notifications.settings.saveSuccess", "Notification settings saved"), "success");
    } catch (err) {
      const message = err instanceof Error ? err.message : t("notifications.settings.saveError", "Failed to save notification settings");
      flash(message, "error");
    } finally {
      setSaving(false);
    }
  };
  if (loading || !settings) {
    return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
      /* @__PURE__ */ jsx(Spinner, { size: "sm" }),
      t("notifications.settings.loading", "Loading notification settings...")
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-6", children: [
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-semibold", children: t("notifications.settings.pageTitle", "Notification Delivery") }),
      /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm", children: t("notifications.settings.pageDescription", "Configure delivery strategies for in-app notifications.") })
    ] }),
    /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsxs(CardHeader, { children: [
        /* @__PURE__ */ jsx(CardTitle, { children: t("notifications.settings.core.title", "Core delivery") }),
        /* @__PURE__ */ jsx(CardDescription, { children: t("notifications.settings.core.description", "Control the default notification center and panel link used by external channels.") })
      ] }),
      /* @__PURE__ */ jsxs(CardContent, { className: "grid gap-4 md:grid-cols-2", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "notifications-app-url", children: t("notifications.settings.core.appUrl", "Application URL") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "notifications-app-url",
              value: settings.appUrl ?? "",
              placeholder: "https://app.open-mercato.com",
              onChange: (event) => updateSettings({ appUrl: event.target.value || void 0 })
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("notifications.settings.core.appUrlHint", "Used to build absolute links in email notifications.") })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "notifications-panel-path", children: t("notifications.settings.core.panelPath", "Notification panel path") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "notifications-panel-path",
              value: settings.panelPath,
              onChange: (event) => updateSettings({ panelPath: event.target.value })
            }
          ),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("notifications.settings.core.panelPathHint", "Relative path for the read-only notification panel.") })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between rounded-lg border p-3", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: t("notifications.settings.core.databaseLabel", "In-app notifications") }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("notifications.settings.core.databaseHint", "Store notifications in the database for the panel and bell.") })
          ] }),
          /* @__PURE__ */ jsx(
            Switch,
            {
              checked: settings.strategies.database.enabled,
              disabled: true,
              onCheckedChange: (checked) => updateStrategy("database", { enabled: checked })
            }
          )
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxs(Card, { children: [
      /* @__PURE__ */ jsxs(CardHeader, { children: [
        /* @__PURE__ */ jsx(CardTitle, { children: t("notifications.settings.email.title", "Email strategy") }),
        /* @__PURE__ */ jsx(CardDescription, { children: t("notifications.settings.email.description", "Send notification copies via Resend using React templates.") })
      ] }),
      /* @__PURE__ */ jsxs(CardContent, { className: "grid gap-4 md:grid-cols-2", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between rounded-lg border p-3 md:col-span-2", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: t("notifications.settings.email.enabledLabel", "Enable email delivery") }),
            /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("notifications.settings.email.enabledHint", "Email actions are read-only and link back to the notification center.") })
          ] }),
          /* @__PURE__ */ jsx(
            Switch,
            {
              checked: settings.strategies.email.enabled,
              onCheckedChange: (checked) => updateStrategy("email", { enabled: checked })
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "notifications-email-from", children: t("notifications.settings.email.from", "From address") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "notifications-email-from",
              value: settings.strategies.email.from ?? "",
              placeholder: "notifications@open-mercato.com",
              onChange: (event) => updateStrategy("email", { from: event.target.value || void 0 })
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "notifications-email-reply", children: t("notifications.settings.email.replyTo", "Reply-to") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "notifications-email-reply",
              value: settings.strategies.email.replyTo ?? "",
              placeholder: "support@open-mercato.com",
              onChange: (event) => updateStrategy("email", { replyTo: event.target.value || void 0 })
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2 md:col-span-2", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "notifications-email-subject-prefix", children: t("notifications.settings.email.subjectPrefix", "Subject prefix") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "notifications-email-subject-prefix",
              value: settings.strategies.email.subjectPrefix ?? "",
              placeholder: "[Open Mercato]",
              onChange: (event) => updateStrategy("email", { subjectPrefix: event.target.value || void 0 })
            }
          )
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
      /* @__PURE__ */ jsx(Button, { type: "button", onClick: handleSave, disabled: saving, children: saving ? t("notifications.settings.saving", "Saving...") : t("notifications.settings.save", "Save settings") }),
      error && /* @__PURE__ */ jsx("span", { className: "text-sm text-destructive", children: error })
    ] })
  ] });
}
var NotificationSettingsPageClient_default = NotificationSettingsPageClient;
export {
  NotificationSettingsPageClient,
  NotificationSettingsPageClient_default as default
};
//# sourceMappingURL=NotificationSettingsPageClient.js.map
