/**
 * LearnDash Start Course Button - Gutenberg Blocks
 *
 * Registers custom Gutenberg blocks for Start Course and Start Group buttons
 */

(function (wp) {
  "use strict";

  // Destructure required WordPress packages
  const { __ } = wp.i18n;
  const { createElement: el } = wp.element;
  const { registerBlockType } = wp.blocks;
  const {
    TextControl,
    ToggleControl,
    PanelBody,
    PanelRow,
    SelectControl,
    Notice,
  } = wp.components;
  const { InspectorControls, BlockControls, AlignmentToolbar, useBlockProps } =
    wp.blockEditor;
  const { Fragment } = wp.element;

  // SVG Arrow Icon
  const arrowIcon = el(
    "svg",
    {
      className: "ldsb-button-arrow",
      width: "24",
      height: "24",
      viewBox: "0 0 24 24",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg",
    },
    el("path", {
      d: "M5 12H19M19 12L12 5M19 12L12 19",
      stroke: "currentColor",
      strokeWidth: "2",
      strokeLinecap: "round",
      strokeLinejoin: "round",
    }),
  );

  // Course block icon
  const courseBlockIcon = el(
    "svg",
    {
      width: "24",
      height: "24",
      viewBox: "0 0 24 24",
      fill: "none",
    },
    el("path", {
      d: "M13 7L18 12M18 12L13 17M18 12H6",
      stroke: "currentColor",
      strokeWidth: "2",
      strokeLinecap: "round",
      strokeLinejoin: "round",
    }),
    el("rect", {
      x: "3",
      y: "3",
      width: "18",
      height: "18",
      rx: "2",
      stroke: "currentColor",
      strokeWidth: "2",
    }),
  );

  // Group block icon
  const groupBlockIcon = el(
    "svg",
    {
      width: "24",
      height: "24",
      viewBox: "0 0 24 24",
      fill: "none",
    },
    el("path", {
      d: "M17 21V19C17 17.9391 16.5786 16.9217 15.8284 16.1716C15.0783 15.4214 14.0609 15 13 15H5C3.93913 15 2.92172 15.4214 2.17157 16.1716C1.42143 16.9217 1 17.9391 1 19V21",
      stroke: "currentColor",
      strokeWidth: "2",
      strokeLinecap: "round",
      strokeLinejoin: "round",
    }),
    el("circle", {
      cx: "9",
      cy: "7",
      r: "4",
      stroke: "currentColor",
      strokeWidth: "2",
    }),
    el("path", {
      d: "M23 21V19C22.9993 18.1137 22.7044 17.2528 22.1614 16.5523C21.6184 15.8519 20.8581 15.3516 20 15.13",
      stroke: "currentColor",
      strokeWidth: "2",
      strokeLinecap: "round",
      strokeLinejoin: "round",
    }),
    el("path", {
      d: "M16 3.13C16.8604 3.35031 17.623 3.85071 18.1676 4.55232C18.7122 5.25392 19.0078 6.11683 19.0078 7.005C19.0078 7.89318 18.7122 8.75608 18.1676 9.45769C17.623 10.1593 16.8604 10.6597 16 10.88",
      stroke: "currentColor",
      strokeWidth: "2",
      strokeLinecap: "round",
      strokeLinejoin: "round",
    }),
  );

  // Register the Course Start button block
  registerBlockType("ldsb/start-button", {
    title: __("LearnDash Start Course Button", "learndash-start-button"),
    description: __(
      "A prominent button to start LearnDash courses",
      "learndash-start-button",
    ),
    icon: courseBlockIcon,
    category: "common",
    keywords: [
      __("learndash", "learndash-start-button"),
      __("start", "learndash-start-button"),
      __("course", "learndash-start-button"),
      __("button", "learndash-start-button"),
    ],
    attributes: {
      courseId: {
        type: "number",
        default: 0,
      },
      buttonText: {
        type: "string",
        default: "Start Course",
      },
      newTab: {
        type: "boolean",
        default: false,
      },
      alignment: {
        type: "string",
        default: "left",
        enum: ["left", "center", "right"],
      },
    },
    supports: {
      align: false, // We handle alignment internally
      className: true,
      html: false,
    },

    // Edit function - what you see in the editor
    edit: function (props) {
      const {
        attributes: { courseId, buttonText, newTab, alignment },
        setAttributes,
        className,
      } = props;

      const blockProps = useBlockProps({
        className: `align-${alignment} ${courseId === 0 ? "no-course" : ""}`,
      });

      // Update alignment
      function onChangeAlignment(newAlignment) {
        setAttributes({ alignment: newAlignment || "left" });
      }

      return el(
        Fragment,
        {},
        // Block Controls (toolbar)
        el(
          BlockControls,
          {},
          el(AlignmentToolbar, {
            value: alignment,
            onChange: onChangeAlignment,
            alignmentControls: [
              {
                icon: "editor-alignleft",
                title: __("Align left", "learndash-start-button"),
                align: "left",
              },
              {
                icon: "editor-aligncenter",
                title: __("Align center", "learndash-start-button"),
                align: "center",
              },
              {
                icon: "editor-alignright",
                title: __("Align right", "learndash-start-button"),
                align: "right",
              },
            ],
          }),
        ),

        // Inspector Controls (sidebar)
        el(
          InspectorControls,
          {},
          el(
            PanelBody,
            {
              title: __("Button Settings", "learndash-start-button"),
              initialOpen: true,
            },
            el(
              PanelRow,
              {},
              el(TextControl, {
                label: __("Course ID", "learndash-start-button"),
                help: __(
                  "Enter the LearnDash course ID. Leave empty to use current course.",
                  "learndash-start-button",
                ),
                value: courseId || "",
                onChange: function (value) {
                  var parsed = parseInt(value, 10);
                  setAttributes({ courseId: isNaN(parsed) || parsed < 0 ? 0 : parsed });
                },
                type: "number",
                min: 0,
              }),
            ),
            el(
              PanelRow,
              {},
              el(TextControl, {
                label: __("Button Text", "learndash-start-button"),
                help: __(
                  "The text to display on the button",
                  "learndash-start-button",
                ),
                value: buttonText,
                onChange: function (value) {
                  setAttributes({ buttonText: value || "Start Course" });
                },
              }),
            ),
            el(
              PanelRow,
              {},
              el(ToggleControl, {
                label: __("Open in New Tab", "learndash-start-button"),
                help: __(
                  "Open the course in a new browser tab",
                  "learndash-start-button",
                ),
                checked: newTab,
                onChange: function (value) {
                  setAttributes({ newTab: value });
                },
              }),
            ),
          ),

          // Usage instructions panel
          el(
            PanelBody,
            {
              title: __("Usage Instructions", "learndash-start-button"),
              initialOpen: false,
            },
            el(
              "div",
              { className: "ldsb-help-text" },
              el(
                "p",
                {},
                __("This button will automatically:", "learndash-start-button"),
              ),
              el(
                "ul",
                {},
                el(
                  "li",
                  {},
                  __(
                    "• Link to the first lesson if available",
                    "learndash-start-button",
                  ),
                ),
                el(
                  "li",
                  {},
                  __(
                    '• Show "Login to Start" for logged-out users',
                    "learndash-start-button",
                  ),
                ),
                el(
                  "li",
                  {},
                  __(
                    '• Show "Enroll to Start" for non-enrolled users',
                    "learndash-start-button",
                  ),
                ),
              ),
            ),
          ),
        ),

        // Block Preview
        el(
          "div",
          blockProps,
          el(
            "div",
            {
              className: `ldsb-button-wrapper align-${alignment}`,
              style: { textAlign: alignment },
            },
            el(
              "a",
              {
                className: "ldsb-start-button",
                href: "#",
                onClick: function (e) {
                  e.preventDefault();
                },
              },
              el("span", { className: "ldsb-button-text" }, buttonText),
              arrowIcon,
            ),
          ),
        ),
      );
    },

    // Save function - null because this is a dynamic block
    save: function () {
      return null; // Dynamic block rendered by PHP
    },
  });

  // Register the Group Start button block
  registerBlockType("ldsb/start-group", {
    title: __("LearnDash Start Group Work", "learndash-start-button"),
    description: __(
      "A button to start the first course in a LearnDash group",
      "learndash-start-button",
    ),
    icon: groupBlockIcon,
    category: "common",
    keywords: [
      __("learndash", "learndash-start-button"),
      __("group", "learndash-start-button"),
      __("start", "learndash-start-button"),
      __("button", "learndash-start-button"),
    ],
    attributes: {
      groupId: {
        type: "number",
        default: 0,
      },
      buttonText: {
        type: "string",
        default: "Start First Course",
      },
      newTab: {
        type: "boolean",
        default: false,
      },
      alignment: {
        type: "string",
        default: "left",
        enum: ["left", "center", "right"],
      },
    },
    supports: {
      align: false,
      className: true,
      html: false,
    },

    // Edit function
    edit: function (props) {
      const {
        attributes: { groupId, buttonText, newTab, alignment },
        setAttributes,
        className,
      } = props;

      const blockProps = useBlockProps({
        className: `align-${alignment} ${groupId === 0 ? "no-group" : ""}`,
      });

      function onChangeAlignment(newAlignment) {
        setAttributes({ alignment: newAlignment || "left" });
      }

      return el(
        Fragment,
        {},
        // Block Controls
        el(
          BlockControls,
          {},
          el(AlignmentToolbar, {
            value: alignment,
            onChange: onChangeAlignment,
            alignmentControls: [
              {
                icon: "editor-alignleft",
                title: __("Align left", "learndash-start-button"),
                align: "left",
              },
              {
                icon: "editor-aligncenter",
                title: __("Align center", "learndash-start-button"),
                align: "center",
              },
              {
                icon: "editor-alignright",
                title: __("Align right", "learndash-start-button"),
                align: "right",
              },
            ],
          }),
        ),

        // Inspector Controls
        el(
          InspectorControls,
          {},
          el(
            PanelBody,
            {
              title: __("Group Button Settings", "learndash-start-button"),
              initialOpen: true,
            },
            el(
              PanelRow,
              {},
              el(TextControl, {
                label: __("Group ID", "learndash-start-button"),
                help: __(
                  "Enter the LearnDash group ID. Leave empty to use current group.",
                  "learndash-start-button",
                ),
                value: groupId || "",
                onChange: function (value) {
                  var parsed = parseInt(value, 10);
                  setAttributes({ groupId: isNaN(parsed) || parsed < 0 ? 0 : parsed });
                },
                type: "number",
                min: 0,
              }),
            ),
            el(
              PanelRow,
              {},
              el(TextControl, {
                label: __("Button Text", "learndash-start-button"),
                help: __(
                  "The text to display on the button",
                  "learndash-start-button",
                ),
                value: buttonText,
                onChange: function (value) {
                  setAttributes({ buttonText: value || "Start First Course" });
                },
              }),
            ),
            el(
              PanelRow,
              {},
              el(ToggleControl, {
                label: __("Open in New Tab", "learndash-start-button"),
                help: __(
                  "Open the course in a new browser tab",
                  "learndash-start-button",
                ),
                checked: newTab,
                onChange: function (value) {
                  setAttributes({ newTab: value });
                },
              }),
            ),
          ),

          el(
            PanelBody,
            {
              title: __("How It Works", "learndash-start-button"),
              initialOpen: false,
            },
            el(
              "div",
              { className: "ldsb-help-text" },
              el("p", {}, __("This button will:", "learndash-start-button")),
              el(
                "ul",
                {},
                el(
                  "li",
                  {},
                  __(
                    "• Link to the first course in the group",
                    "learndash-start-button",
                  ),
                ),
                el(
                  "li",
                  {},
                  __(
                    "• Go to the first lesson if available",
                    "learndash-start-button",
                  ),
                ),
                el(
                  "li",
                  {},
                  __(
                    '• Show "Login to Start" for logged-out users',
                    "learndash-start-button",
                  ),
                ),
                el(
                  "li",
                  {},
                  __(
                    '• Show "Join Group to Start" for non-members',
                    "learndash-start-button",
                  ),
                ),
              ),
            ),
          ),
        ),

        // Block Preview
        el(
          "div",
          blockProps,
          el(
            "div",
            {
              className: `ldsb-button-wrapper align-${alignment}`,
              style: { textAlign: alignment },
            },
            el(
              "a",
              {
                className: "ldsb-start-button ldsb-group-button",
                href: "#",
                onClick: function (e) {
                  e.preventDefault();
                },
              },
              el("span", { className: "ldsb-button-text" }, buttonText),
              arrowIcon,
            ),
          ),
        ),
      );
    },

    save: function () {
      return null; // Dynamic block
    },
  });
})(window.wp);
