import { N as w, u as C, a as G, k as I, h as j, j as d, M as E, n as F, s as R, l as P, m as M } from "./index-c65ca4a4.mjs";
import { F as q } from "./Form-f4ced0f0.mjs";
import { U as T } from "./URLTextField-a472a6c7.mjs";
import { R as O } from "./RecommendationReasonForm-b6fdb352.mjs";
import "./TextArea-65b41e1e.mjs";
const $ = ({ recommendation: l, animate: c }) => {
  const o = C(), { updateRoute: a } = G(), { mutateAsync: e } = I(), { formState: u, updateForm: t, handleSave: y, saveState: m, errors: h } = j({
    initialState: {
      ...l
    },
    onSave: async () => {
      await e(u), o.remove(), a("recommendations");
    },
    onValidate: () => {
      const f = {};
      return u.title || (f.title = "Title is required"), f;
    }
  });
  let g = "Add";
  m === "saving" ? g = "Adding..." : m === "saved" && (g = "Added");
  let v = {
    label: "Back",
    icon: "arrow-left",
    size: "sm",
    onClick: () => {
      m !== "saving" && (o.remove(), w.show(K, {
        animate: !1,
        recommendation: {
          ...u
        }
      }));
    }
  };
  return /* @__PURE__ */ d.jsx(
    E,
    {
      afterClose: () => {
        a("recommendations");
      },
      animate: c ?? !0,
      backDropClick: !1,
      cancelLabel: "Cancel",
      dirty: !0,
      leftButtonProps: v,
      okColor: "black",
      okLabel: g,
      size: "sm",
      testId: "add-recommendation-modal",
      title: "Add recommendation",
      onCancel: () => {
        m !== "saving" && (o.remove(), a("recommendations"));
      },
      onOk: async () => {
        m !== "saving" && (F.remove(), await y({ force: !0 }) || R({
          type: "pageError",
          message: "One or more fields have errors, please doublecheck you filled all mandatory fields"
        }));
      },
      children: /* @__PURE__ */ d.jsx(O, { errors: h, formState: u, updateForm: t })
    }
  );
}, B = w.create($), N = (l, c, o = {}) => {
  const a = new URL(`${l}${c}`, window.location.origin);
  return a.search = new URLSearchParams(o).toString(), a.toString();
}, z = () => {
  const l = P(), c = "/members/api/site";
  return {
    async query(o) {
      o = o.replace(/\/$/, "");
      const a = N(o, c);
      try {
        const e = await l(a, {
          method: "GET",
          credentials: "omit"
          // Allow CORS wildcard
        });
        if (typeof e != "object" || !e.site || typeof e.site != "object" || typeof e.site.title != "string" || typeof e.site.allow_self_signup != "boolean" || typeof e.site.url != "string" || e.site.description !== null && typeof e.site.description != "string" || e.site.logo !== null && typeof e.site.logo != "string" || e.site.icon !== null && typeof e.site.icon != "string" || e.site.cover_image !== null && typeof e.site.cover_image != "string")
          return console.warn("Received invalid response from external Ghost site API", e), null;
        try {
          return {
            site: {
              title: e.site.title,
              description: e.site.description,
              logo: e.site.logo ? new URL(e.site.logo) : null,
              icon: e.site.icon ? new URL(e.site.icon) : null,
              cover_image: e.site.cover_image ? new URL(e.site.cover_image) : null,
              allow_self_signup: e.site.allow_self_signup,
              url: new URL(e.site.url)
            }
          };
        } catch (u) {
          return console.warn("Received invalid response from external Ghost site API", e, u), null;
        }
      } catch (e) {
        return console.error(e), null;
      }
    }
  };
}, D = () => {
  const l = P(), c = "/oembed/";
  return {
    async query(o) {
      const a = M(c, o);
      try {
        return await l(a, {
          method: "GET"
        });
      } catch (e) {
        return console.error(e), null;
      }
    }
  };
}, V = ({ recommendation: l, animate: c }) => {
  const o = C(), { updateRoute: a } = G(), { query: e } = D(), { query: u } = z(), { formState: t, updateForm: y, handleSave: m, errors: h, validate: g, saveState: v, clearError: f } = j({
    initialState: l ?? {
      title: "",
      url: "",
      reason: "",
      excerpt: null,
      featured_image: null,
      favicon: null,
      one_click_subscribe: !1
    },
    onSave: async () => {
      var _, k, S, A, b, U, L;
      let n = null;
      try {
        n = new URL(t.url);
      } catch {
      }
      let i = n && n.protocol === "https:" ? await u("https://" + n.host) : null, p = t.title;
      p || (n ? p = n.hostname.replace("www.", "") : p = t.url);
      const s = {
        ...t,
        title: p
      };
      if (i)
        s.title = i.site.title || p, s.excerpt = i.site.description ?? t.excerpt ?? null, s.featured_image = ((_ = i.site.cover_image) == null ? void 0 : _.toString()) ?? t.featured_image ?? null, s.favicon = ((k = i.site.icon) == null ? void 0 : k.toString()) ?? ((S = i.site.logo) == null ? void 0 : S.toString()) ?? t.favicon ?? null, s.one_click_subscribe = i.site.allow_self_signup, s.url = i.site.url.toString();
      else {
        const r = await e({
          url: t.url,
          type: "mention"
        });
        s.title = ((A = r == null ? void 0 : r.metadata) == null ? void 0 : A.title) ?? p, s.excerpt = ((b = r == null ? void 0 : r.metadata) == null ? void 0 : b.description) ?? t.excerpt ?? null, s.featured_image = ((U = r == null ? void 0 : r.metadata) == null ? void 0 : U.thumbnail) ?? t.featured_image ?? null, s.favicon = ((L = r == null ? void 0 : r.metadata) == null ? void 0 : L.icon) ?? t.favicon ?? null, s.one_click_subscribe = !1;
      }
      o.remove(), w.show(B, {
        animate: !1,
        recommendation: s
      });
    },
    onValidate: () => {
      const n = {};
      try {
        new URL(t.url).hostname.includes(".") || (n.url = "Please enter a valid URL");
      } catch {
        n.url = "Please enter a valid URL";
      }
      return n;
    }
  });
  let x = "Next";
  return v === "saving" && (x = "Checking..."), /* @__PURE__ */ d.jsx(
    E,
    {
      afterClose: () => {
        a("recommendations");
      },
      animate: c ?? !0,
      backDropClick: !1,
      okColor: "black",
      okLabel: x,
      size: "sm",
      testId: "add-recommendation-modal",
      title: "Add recommendation",
      onOk: async () => {
        if (v !== "saving") {
          F.remove();
          try {
            await m({ force: !0 }) || R({
              type: "pageError",
              message: "One or more fields have errors, please doublecheck you filled all mandatory fields"
            });
          } catch {
            R({
              type: "pageError",
              message: "Something went wrong while checking this URL, please try again"
            });
          }
        }
      },
      children: /* @__PURE__ */ d.jsx(
        q,
        {
          marginBottom: !1,
          marginTop: !0,
          children: /* @__PURE__ */ d.jsx(
            T,
            {
              autoFocus: !0,
              error: !!h.url,
              hint: h.url || /* @__PURE__ */ d.jsxs(d.Fragment, { children: [
                "Need inspiration? ",
                /* @__PURE__ */ d.jsx("a", { className: "text-green", href: "https://www.ghost.org/explore", rel: "noopener noreferrer", target: "_blank", children: "Explore thousands of sites" }),
                " to recommend"
              ] }),
              placeholder: "https://www.example.com",
              title: "URL",
              value: t.url,
              onBlur: g,
              onChange: (n) => y((i) => ({
                ...i,
                url: n
              })),
              onKeyDown: () => f == null ? void 0 : f("url")
            }
          )
        }
      )
    }
  );
}, K = w.create(V);
export {
  K as default
};
//# sourceMappingURL=AddRecommendationModal-485731c2.mjs.map
