// section-picker.jsx — выбор папки с деревом

const SECTION_PICKER_TONES = ['folder-blue', 'folder-amber', 'folder-violet', 'folder-green'];

const SectionPickerItem = ({ section, depth, value, onSelect, excludeIds }) => {
  if (excludeIds?.has(section.id)) return null;
  if (!window.KB.canAccessSection(section.id)) return null;
  const tone = SECTION_PICKER_TONES[depth % SECTION_PICKER_TONES.length];
  const isSelected = value === section.id;
  const children = window.getChildSections(section.id);

  return (
    <>
      <button
        type="button"
        className={`section-picker-item${isSelected ? ' is-selected' : ''}`}
        style={{ '--sp-depth': depth }}
        onClick={() => onSelect(section.id)}
      >
        <span className="section-picker-item-indent" aria-hidden="true">
          {depth > 0 && <span className="section-picker-item-branch" />}
        </span>
        <span className={`section-picker-item-icon ${tone}`}>
          <Icon name={section.icon || 'folder'} size={14} />
        </span>
        <span className="section-picker-item-name">{section.name}</span>
        {isSelected && <Icon name="check" size={14} className="section-picker-item-check" />}
      </button>
      {children.map((child) => (
        <SectionPickerItem
          key={child.id}
          section={child}
          depth={depth + 1}
          value={value}
          onSelect={onSelect}
          excludeIds={excludeIds}
        />
      ))}
    </>
  );
};

const SectionPicker = ({
  value,
  onChange,
  placeholder = '— Выберите папку —',
  allowEmpty = true,
  excludeIds = null,
}) => {
  const [open, setOpen] = React.useState(false);
  const wrapRef = React.useRef(null);
  const roots = window.getRootSections();

  React.useEffect(() => {
    if (!open) return undefined;
    const close = (e) => {
      if (!wrapRef.current?.contains(e.target)) setOpen(false);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [open]);

  const selectedSection = value ? window.findSection(value) : null;
  const selectedPath = value ? window.getSectionPath(value) : [];

  const handleSelect = (id) => {
    onChange(id);
    setOpen(false);
  };

  return (
    <div className={`section-picker${open ? ' is-open' : ''}`} ref={wrapRef}>
      <button
        type="button"
        className={`section-picker-trigger${!selectedSection ? ' is-empty' : ''}`}
        onClick={() => setOpen((v) => !v)}
        aria-expanded={open}
      >
        <span className={`section-picker-trigger-icon ${selectedSection ? SECTION_PICKER_TONES[(selectedPath.length - 1) % SECTION_PICKER_TONES.length] : ''}`}>
          <Icon name={selectedSection?.icon || 'folder'} size={15} />
        </span>
        <span className="section-picker-trigger-text">
          {selectedPath.length > 0 ? (
            selectedPath.map((s, i) => (
              <React.Fragment key={s.id}>
                {i > 0 && <span className="section-picker-trigger-sep">/</span>}
                <span>{s.name}</span>
              </React.Fragment>
            ))
          ) : placeholder}
        </span>
        <Icon name="chevronDown" size={14} className="section-picker-trigger-chevron" />
      </button>

      {open && (
        <div className="section-picker-menu" role="listbox">
          {allowEmpty && (
            <button
              type="button"
              className={`section-picker-item section-picker-item--empty${!value ? ' is-selected' : ''}`}
              style={{ '--sp-depth': 0 }}
              onClick={() => handleSelect(null)}
            >
              <span className="section-picker-item-indent" />
              <span className="section-picker-item-icon section-picker-item-icon--muted">
                <Icon name="folder" size={14} />
              </span>
              <span className="section-picker-item-name">{placeholder}</span>
              {!value && <Icon name="check" size={14} className="section-picker-item-check" />}
            </button>
          )}
          {roots.map((section) => (
            <SectionPickerItem
              key={section.id}
              section={section}
              depth={0}
              value={value}
              onSelect={handleSelect}
              excludeIds={excludeIds}
            />
          ))}
        </div>
      )}
    </div>
  );
};

window.SectionPicker = SectionPicker;
