import { __ } from "@wordpress/i18n";
import { CheckboxControl } from "@wordpress/components";

import { NextToggleControl } from "./NextControls";

const normalizeSelectedPostTypes = (selectedPostTypes) => {
  if (!Array.isArray(selectedPostTypes)) {
    return [];
  }

  return Array.from(
    new Set(
      selectedPostTypes
        .map((postType) => `${postType || ""}`.trim())
        .filter((postType) => postType !== ""),
    ),
  );
};

const normalizePostTypeCatalog = (postTypeCatalog) => {
  if (!postTypeCatalog || typeof postTypeCatalog !== "object") {
    return {};
  }

  const out = {};

  Object.entries(postTypeCatalog).forEach(([slug, postType]) => {
    const normalizedSlug = `${slug || ""}`.trim();
    if (normalizedSlug === "") {
      return;
    }

    if (typeof postType === "string") {
      out[normalizedSlug] = {
        label: `${postType || ""}`.trim() || normalizedSlug,
        public: true,
      };
      return;
    }

    const raw = postType && typeof postType === "object" ? postType : {};
    out[normalizedSlug] = {
      label: `${raw.label || ""}`.trim() || normalizedSlug,
      public: raw.public === true,
    };
  });

  return out;
};

/**
 * Shared post type checklist with non-public visibility toggle.
 */
export default function PostTypeVisibilityChecklist({
  postTypeCatalog,
  selectedPostTypes,
  onTogglePostType = () => {},
  includeNonPublicPostTypes = false,
  onIncludeNonPublicPostTypesChange,
  helperText = "",
  emptyMessage,
  disabled = false,
  classNamePrefix = "eci-post-type-visibility-panel",
}) {
  const selectedLookup = new Set(normalizeSelectedPostTypes(selectedPostTypes));
  const normalizedCatalog = normalizePostTypeCatalog(postTypeCatalog);
  const showNonPublicToggle =
    typeof onIncludeNonPublicPostTypesChange === "function";

  const entries = Object.entries(normalizedCatalog)
    .filter(([slug, postType]) => {
      const isSelected = selectedLookup.has(slug);
      return (
        postType.public === true ||
        isSelected ||
        includeNonPublicPostTypes === true
      );
    })
    .sort(([leftSlug, leftPostType], [rightSlug, rightPostType]) => {
      const labelCompare = `${leftPostType?.label || ""}`.localeCompare(
        `${rightPostType?.label || ""}`,
        undefined,
        { sensitivity: "base" },
      );

      return labelCompare !== 0
        ? labelCompare
        : `${leftSlug || ""}`.localeCompare(`${rightSlug || ""}`);
    });

  return (
      <div className={classNamePrefix}>

          {showNonPublicToggle && (
            <div className='settings-inner-container mb-xl'>
                  <div className='settings-inner-container__item'>
                      <NextToggleControl
                          label={__("Show non-public post types", "cache-autopilot")}
                          help={__(
                            "Include post types that do not have their own public URLs (e.g. embedded or admin-only content).",
                            "cache-autopilot",
                          )}
                          checked={!!includeNonPublicPostTypes}
                          onChange={(value) =>
                            onIncludeNonPublicPostTypesChange(!!value)
                          }
                          />
                  </div>
              </div>
          )}

          {helperText && (
              <p className={"ekesto-section-description mb-lg"}>{helperText}</p>
          )}

          {entries.length === 0 ? (
              <p className={`${classNamePrefix}__empty`}>
                  {emptyMessage || __("No post types available.", "cache-autopilot")}
              </p>
          ) : (
              <div className={`${classNamePrefix}__list`}>
                  {entries.map(([slug, postType]) => (
                      <CheckboxControl
                          key={slug}
                          label={postType.label}
                          checked={selectedLookup.has(slug)}
                          onChange={(checked) =>
                              onTogglePostType(slug, checked)
                          }
                          disabled={disabled}
                          className={`${classNamePrefix}__checkbox`}
                      />
                  ))}
              </div>
          )}
      </div>
  );
}
