'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const config = require('./config.cjs');
const classnameGroupControl = require('./classname-group-control.cjs');
const utils = require('../../../../../lib/utils.cjs');
const helpers = require('./helpers.cjs');

function ClassNameItemControl({ value, onChange }) {
  const parsed = React.useMemo(() => {
    if (value) {
      const tokens = value.trim().split(/\s+/);
      const parsedState = Object.entries(config.CONFIG).reduce(
        (acc, [key, config]) => {
          const parsed2 = tokens.filter((token) => helpers.isTailwindClass(config.possibleTypes.filter((type) => type !== null), token));
          if (parsed2.length > 0) {
            acc[key] = config.multiple ? parsed2 : parsed2[0];
          }
          return acc;
        },
        Object.fromEntries(Object.keys(config.CONFIG).map((k) => [k, null]))
      );
      const initialSelected = {};
      config.LAYOUT_GROUPS.forEach((group) => {
        let found = false;
        group.keys.forEach((key) => {
          if (parsedState[key]) {
            if (!found) {
              found = true;
              initialSelected[group.label] = key;
            } else {
              parsedState[key] = null;
            }
          }
        });
        if (!found && group.keys[0]) {
          initialSelected[group.label] = group.keys[0];
        }
      });
      const handledTokens = new Set(
        Object.values(parsedState).flatMap(
          (v) => Array.isArray(v) ? v : v ? [v] : []
        )
      );
      const unhandledTokens = tokens.filter(
        (token) => !handledTokens.has(token)
      );
      return {
        parsedState,
        unhandledTokens,
        initialSelected
      };
    } else {
      const initialSelected = {};
      config.LAYOUT_GROUPS.forEach((group) => {
        if (group.keys[0]) {
          initialSelected[group.label] = group.keys[0];
        }
      });
      return {
        parsedState: {},
        unhandledTokens: [],
        initialSelected
      };
    }
  }, [value]);
  const [state, setState] = React.useState(parsed.parsedState);
  const [unhandled, setUnhandled] = React.useState(parsed.unhandledTokens);
  const [selectedKeys, setSelectedKeys] = React.useState(parsed.initialSelected);
  React.useEffect(() => {
    const stateChanged = JSON.stringify(state) !== JSON.stringify(parsed.parsedState);
    const unhandledChanged = JSON.stringify(unhandled) !== JSON.stringify(parsed.unhandledTokens);
    const selectedChanged = JSON.stringify(selectedKeys) !== JSON.stringify(parsed.initialSelected);
    if (stateChanged) setState(parsed.parsedState);
    if (unhandledChanged) setUnhandled(parsed.unhandledTokens);
    if (selectedChanged) setSelectedKeys(parsed.initialSelected);
  }, [parsed]);
  const buildClassString = (customState = state, customUnhandled = unhandled) => {
    const classes = [];
    for (const key in customState) {
      const value2 = customState[key];
      if (value2) {
        if (Array.isArray(value2)) {
          classes.push(...value2);
        } else {
          classes.push(value2);
        }
      }
    }
    return [...classes, ...customUnhandled].join(" ").trim();
  };
  const handleStateChange = React.useCallback((key, value2) => {
    setState((prev) => {
      const newState = { ...prev, [key]: value2 };
      const group = config.LAYOUT_GROUPS.find((g) => g.keys.includes(key));
      if (group) {
        setSelectedKeys((prevSel) => ({
          ...prevSel,
          [group.label]: key
        }));
        group.keys.forEach((k) => {
          if (k !== key) newState[k] = null;
        });
        if (typeof group.clearState === "function") {
          const classesToClear = group.clearState(key, newState);
          setUnhandled(
            (prevUnhandled) => prevUnhandled.filter((token) => !classesToClear.includes(token))
          );
        }
      }
      const layoutOrderItemsInvisible = config.LAYOUT_ORDER.filter(
        (item) => item.isVisible && !item.isVisible(newState)
      );
      layoutOrderItemsInvisible.forEach((item) => {
        if (item.type === "item") {
          newState[item.key] = null;
        } else if (item.type === "group") {
          const group2 = config.LAYOUT_GROUPS.find((g) => g.label === item.label);
          if (group2) {
            group2.keys.forEach((key2) => {
              newState[key2] = null;
            });
          }
        }
      });
      return newState;
    });
  }, []);
  const createChangeHandler = React.useCallback(
    (key) => (value2) => handleStateChange(key, value2),
    [handleStateChange]
  );
  const handleGroupKeySelect = (groupLabel, key) => {
    setSelectedKeys((prev) => ({
      ...prev,
      [groupLabel]: key
    }));
    const group = config.LAYOUT_GROUPS.find((g) => g.label === groupLabel);
    if (group) {
      let classesToClear = [];
      setState((prevState) => {
        const newState = { ...prevState };
        if (typeof group.clearState === "function") {
          classesToClear = group.clearState(key, newState);
        }
        for (const k of group.keys) {
          if (k !== key) {
            const config$1 = config.CONFIG[k];
            if (!config$1) continue;
            if (config$1.multiple && Array.isArray(newState[k])) {
              newState[k] = newState[k].filter(
                (v) => !classesToClear.includes(v)
              );
              if (Array.isArray(newState[k]) && newState[k]?.length === 0)
                newState[k] = null;
            } else if (classesToClear.includes(newState[k])) {
              newState[k] = null;
            }
          }
        }
        setUnhandled(
          (prevUnhandled) => prevUnhandled.filter((token) => !classesToClear.includes(token))
        );
        if (!newState[key]) newState[key] = null;
        return newState;
      });
    }
  };
  React.useEffect(() => {
    const classString = buildClassString(state, unhandled);
    if (onChange) onChange(classString);
  }, [state, unhandled]);
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full", "data-testid": "classname-item-control", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-wrap gap-y-1 px-4 pt-2 pb-4", children: config.LAYOUT_ORDER.map((entry) => {
    if (entry.type === "group") {
      const group = config.LAYOUT_GROUPS.find((g) => g.label === entry.label);
      if (!group) return null;
      const keys = group.keys.map(String);
      const selectedKey = selectedKeys[group.label] || keys[0];
      if (entry.isVisible && !entry.isVisible(state)) return null;
      if (!selectedKey) return null;
      const groupConfig = config.CONFIG[selectedKey];
      if (!groupConfig) return null;
      return /* @__PURE__ */ jsxRuntime.jsx("div", { className: utils.cn("w-full", entry.className), "data-testid": `group-${group.label.toLowerCase().replace(/\s+/g, "-")}`, children: /* @__PURE__ */ jsxRuntime.jsx(
        classnameGroupControl.ClassNameGroupControl,
        {
          groupConfig,
          group,
          state,
          handleStateChange,
          handleGroupKeySelect,
          selectedKey
        }
      ) }, group.label);
    } else if (entry.type === "item") {
      if (entry.isVisible && !entry.isVisible(state)) return null;
      const configKey = entry.key;
      const ungroupedConfig = config.CONFIG[configKey];
      if (!ungroupedConfig) return null;
      return /* @__PURE__ */ jsxRuntime.jsx("div", { className: utils.cn("w-full", entry.className), "data-testid": `item-${configKey}`, children: /* @__PURE__ */ jsxRuntime.jsx(
        ungroupedConfig.component,
        {
          ...ungroupedConfig,
          ..."multiple" in ungroupedConfig ? { multiple: ungroupedConfig.multiple } : {},
          value: state[configKey],
          onChange: createChangeHandler(configKey)
        }
      ) }, configKey);
    }
    return null;
  }) }) });
}

exports.ClassNameItemControl = ClassNameItemControl;
