/* ctor-hierarchy-view.jsx — панель раскрытия и фильтров прозрачности */
const { useEffect: hvUseEffect } = React;
const HV = () => window.HierarchyView;

function HViewSeg({ value, onChange, options }) {
  return (
    <div className="hview-seg" role="group">
      {options.map((o) => (
        <button key={o.v} type="button" className={value === o.v ? 'on' : ''} onClick={() => onChange(o.v)}>{o.l}</button>
      ))}
    </div>
  );
}

function HViewFilterTag({ label, on, onChange }) {
  return (
    <button type="button" className={'hview-filter-tag' + (on ? ' on' : '')} aria-pressed={!!on} onClick={onChange}>{label}</button>
  );
}

function HierarchyViewBar({ view, onChange, catalog, onApplyExpand, showExpand = true }) {
  const api = HV();
  if (!api) return null;

  const setView = (next) => {
    onChange(next);
    api.saveView(next);
  };

  const setDepth = (depth) => {
    const next = { ...view, expandDepth: depth };
    setView(next);
    if (onApplyExpand && catalog && catalog.length) {
      onApplyExpand(api.expandToDepth(catalog, depth));
    }
  };

  const toggleField = (fieldId) => {
    const cur = view.fields[fieldId] ?? 2;
    const next = cur === 0 ? 2 : 0;
    setView({ ...view, fields: { ...view.fields, [fieldId]: next } });
  };

  const resetView = () => {
    const next = api.defaultView();
    setView(next);
    if (onApplyExpand && catalog && catalog.length) {
      onApplyExpand(api.expandToDepth(catalog, next.expandDepth));
    }
  };

  return (
    <div className="hview-bar">
      {showExpand && (
        <div className="hview-bar-top">
          <span className="hview-bar-label">Раскрытие</span>
          <HViewSeg value={view.expandDepth} onChange={setDepth} options={api.EXPAND_OPTIONS} />
        </div>
      )}
      <div className="hview-filters" aria-label="Видимость полей">
        {api.FIELD_DEFS.map((f) => {
          const lvl = view.fields[f.id] ?? 2;
          const on = lvl > 0;
          return (
            <HViewFilterTag
              key={f.id}
              label={f.label}
              on={on}
              onChange={() => toggleField(f.id)}
            />
          );
        })}
        <button type="button" className="hview-reset" onClick={resetView}>Сбросить</button>
      </div>
    </div>
  );
}

function HierarchyVis({ view, field, children, inline, style }) {
  const api = HV();
  if (!api || !api.visibleFor(view, field)) return null;
  const op = api.opacityFor(view, field);
  return (
    <span className="hview-vis" style={{ display: inline ? 'inline-flex' : 'contents', opacity: op, ...(style || {}) }}>
      {children}
    </span>
  );
}

function useHierarchyView(onExternalChange) {
  const [view, setView] = React.useState(() => (HV() || { loadView: () => ({ expandDepth: 'task', fields: {} }) }).loadView());

  hvUseEffect(() => {
    const api = HV();
    if (!api) return undefined;
    const onStorage = (e) => {
      if (e.key === api.STORAGE_KEY) setView(api.loadView());
    };
    window.addEventListener('storage', onStorage);
    return () => window.removeEventListener('storage', onStorage);
  }, []);

  const update = (next) => {
    setView(next);
    if (HV()) HV().saveView(next);
    if (onExternalChange) onExternalChange(next);
  };

  return [view, update];
}

/** Переключатель «Этапы / Задачи / Подзадачи» для stat-strip (тот же setDepth, что в HierarchyViewBar) */
function HierarchyExpandSeg({ catalog, view, onChange, onApplyExpand }) {
  const api = HV();
  if (!api) return null;

  const setDepth = (depth) => {
    const next = { ...view, expandDepth: depth };
    onChange(next);
    api.saveView(next);
    if (onApplyExpand && catalog && catalog.length) {
      onApplyExpand(api.expandToDepth(catalog, depth));
    }
  };

  return (
    <div className="ctor-view-expand" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span className="hview-bar-label" style={{ whiteSpace: 'nowrap' }}>Раскрытие</span>
      <HViewSeg value={view.expandDepth} onChange={setDepth} options={api.EXPAND_OPTIONS} />
    </div>
  );
}

Object.assign(window, { HierarchyViewBar, HierarchyVis, useHierarchyView, HierarchyExpandSeg });
