(function () {
  "use strict";

  var registerBlockType = wp.blocks.registerBlockType;
  var useBlockProps = wp.blockEditor.useBlockProps;
  var InspectorControls = wp.blockEditor.InspectorControls;
  var PanelBody = wp.components.PanelBody;
  var SelectControl = wp.components.SelectControl;
  var Spinner = wp.components.Spinner;
  var useState = wp.element.useState;
  var useEffect = wp.element.useEffect;
  var useRef = wp.element.useRef;
  var Fragment = wp.element.Fragment;
  var createElement = wp.element.createElement;
  var __ = wp.i18n.__;

  function irepProjectEdit(props) {
    var attributes = props.attributes;
    var setAttributes = props.setAttributes;

    var blockProps = useBlockProps({
      style: {
        background: "#f0f4f8",
        border: "1px solid #c5d0de",
        borderRadius: "4px",
        padding: "20px",
        fontFamily: "sans-serif",
      },
    });

    var _state = useState({ projects: [], loading: true, error: "" });
    var state = _state[0];
    var setState = _state[1];
    var aliveRef = useRef(true);

    useEffect(function () {
      aliveRef.current = true;
      return function () {
        aliveRef.current = false;
      };
    }, []);

    useEffect(function () {
      if (
        typeof irepBlockData === "undefined" ||
        !irepBlockData.ajax_url ||
        !irepBlockData.nonce
      ) {
        setState({
          projects: [],
          loading: false,
          error: "irepBlockData not found.",
        });
        return;
      }

      var formData = new FormData();
      formData.append("action", "irep_get_projects");
      formData.append("nonce", irepBlockData.nonce);

      fetch(irepBlockData.ajax_url, {
        method: "POST",
        credentials: "same-origin",
        body: formData,
      })
        .then(function (res) {
          return res.json();
        })
        .then(function (json) {
          if (!aliveRef.current) {
            return;
          }
          if (!json.success || !Array.isArray(json.data)) {
            setState({
              projects: [],
              loading: false,
              error: "Failed to load projects.",
            });
            return;
          }

          var options = [
            {
              label: __("— Select a project —", "interactive-real-estate"),
              value: "0",
            },
          ];

          json.data.forEach(function (project) {
            options.push({
              label: project.title || "#" + project.id,
              value: String(project.id),
            });
          });

          setState({ projects: options, loading: false, error: "" });
        })
        .catch(function (err) {
          if (!aliveRef.current) {
            return;
          }
          setState({ projects: [], loading: false, error: String(err) });
        });
    }, []);

    var shortcodePreview =
      "[irep_project" + ' id="' + (attributes.projectId || "") + '"' + "]";

    return createElement(
      Fragment,
      null,
      createElement(
        InspectorControls,
        null,
        createElement(
          PanelBody,
          {
            title: __("Project Settings", "interactive-real-estate"),
            initialOpen: true,
          },
          state.loading &&
            createElement(
              "div",
              {
                style: {
                  display: "flex",
                  alignItems: "center",
                  gap: "8px",
                  marginBottom: "12px",
                },
              },
              createElement(Spinner),
              createElement(
                "span",
                null,
                __("Loading projects…", "interactive-real-estate"),
              ),
            ),
          state.error &&
            createElement(
              "p",
              { style: { color: "#cc1818", fontSize: "12px" } },
              state.error,
            ),
          !state.loading &&
            !state.error &&
            createElement(SelectControl, {
              label: __("Project", "interactive-real-estate"),
              value: String(
                attributes.projectId != null ? attributes.projectId : 0,
              ),
              options: state.projects,
              onChange: function (val) {
                var n = parseInt(val, 10);
                setAttributes({ projectId: isNaN(n) ? 0 : n });
              },
            }),
        ),
      ),
      createElement(
        "div",
        blockProps,
        createElement(
          "p",
          {
            style: {
              fontWeight: "500",
              fontSize: "14px",
              marginBottom: "8px",
              color: "#1e1e1e",
            },
          },
          __("Shortcode Preview", "interactive-real-estate"),
        ),
        createElement(
          "code",
          {
            style: {
              display: "block",
              marginTop: "0",
              padding: "8px",
              background: "#fff",
              border: "1px solid #c5d0de",
              borderRadius: "3px",
              fontSize: "12px",
              wordBreak: "break-all",
            },
          },
          shortcodePreview,
        ),
      ),
    );
  }

  registerBlockType("interactive-real-estate/project", {
    apiVersion: 2,
    title: __("IRE Project", "interactive-real-estate"),
    description: __(
      "Display a project from Interactive Real Estate.",
      "interactive-real-estate",
    ),
    category: "widgets",
    icon: "building",
    supports: {
      html: false,
    },
    attributes: {
      projectId: { type: "number", default: 0 },
    },
    edit: irepProjectEdit,
    save: function () {
      return null;
    },
  });
})();
