// sections.jsx — дерево разделов: список с раскрытием

const SECTION_ICON_OPTIONS = [
  { id: 'folder', label: 'Общее' },
  { id: 'sparks', label: 'Старт' },
  { id: 'chart', label: 'Продажи' },
  { id: 'megaphone', label: 'Маркетинг' },
  { id: 'box', label: 'Продукт' },
  { id: 'user', label: 'Команда' },
  { id: 'code', label: 'Техника' },
  { id: 'file', label: 'Документ' },
  { id: 'grid', label: 'Каталог' },
];

const IconPicker = ({ value, onChange }) => (
  <div className="sections-icon-strip">
    {SECTION_ICON_OPTIONS.map((opt) => (
      <button
        type="button"
        key={opt.id}
        className={`sections-icon-strip-btn${value === opt.id ? ' selected' : ''}`}
        onClick={() => onChange(opt.id)}
        title={opt.label}
      >
        <Icon name={opt.id} size={15} />
      </button>
    ))}
  </div>
);

const SectionForm = ({ form, setForm, onSubmit, onCancel, submitLabel, busy }) => (
  <div className="sections-inline-form">
    <input
      className="sections-form-input"
      placeholder="Название"
      value={form.name}
      onChange={(e) => setForm({ ...form, name: e.target.value })}
      autoFocus
    />
    <IconPicker value={form.icon} onChange={(icon) => setForm({ ...form, icon })} />
    <button type="button" className="btn btn-primary btn-sm" disabled={busy || !form.name.trim()} onClick={onSubmit}>
      {submitLabel}
    </button>
    <button type="button" className="btn btn-ghost btn-sm" onClick={onCancel} disabled={busy}>
      Отмена
    </button>
  </div>
);

const TreeActions = ({ onEdit, onDelete, onAddSub, busyId, id, showAddSub }) => (
  <div className="sections-tree-actions" onClick={(e) => e.stopPropagation()}>
    {showAddSub && (
      <button type="button" className="sections-tree-action" onClick={onAddSub} title="Добавить подраздел">
        <Icon name="plus" size={13} />
      </button>
    )}
    <button type="button" className="sections-tree-action" onClick={onEdit} disabled={busyId === id} title="Изменить">
      <Icon name="edit" size={13} />
    </button>
    <button type="button" className="sections-tree-action" onClick={onDelete} disabled={busyId === id} title="Удалить">
      <Icon name="trash" size={13} />
    </button>
  </div>
);

const SectionsView = ({ onOpenArticle, onCreate, onRefresh }) => {
  const [, tick] = React.useReducer((n) => n + 1, 0);
  const [openRoots, setOpenRoots] = React.useState({});
  const [openSubs, setOpenSubs] = React.useState({});
  const [addingRoot, setAddingRoot] = React.useState(false);
  const [addingSubFor, setAddingSubFor] = React.useState(null);
  const [editingId, setEditingId] = React.useState(null);
  const [form, setForm] = React.useState({ name: '', icon: 'folder' });
  const [busyId, setBusyId] = React.useState(null);

  const roots = window.getRootSections();

  const resetForm = () => {
    setForm({ name: '', icon: 'folder' });
    setAddingRoot(false);
    setAddingSubFor(null);
    setEditingId(null);
  };

  const handleSave = async (parentId = null) => {
    if (!form.name.trim()) return;
    setBusyId(editingId || 'new');
    try {
      await window.KB.saveSection({
        id: editingId || undefined,
        name: form.name.trim(),
        icon: form.icon,
        ...(!editingId ? { parentId } : {}),
      });
      if (parentId) {
        setOpenRoots((p) => ({ ...p, [parentId]: true }));
      }
      resetForm();
      tick();
      onRefresh?.();
    } catch (err) {
      await window.UI.alert({ title: 'Ошибка', message: err.message });
    } finally {
      setBusyId(null);
    }
  };

  const handleDelete = async (section) => {
    const count = window.getSectionArticleCount(section.id);
    const children = window.getSubsections(section.id);
    if (children.length) {
      await window.UI.alert({ title: 'Нельзя удалить', message: 'Сначала удалите подразделы' });
      return;
    }
    if (count > 0) {
      await window.UI.alert({ title: 'Нельзя удалить', message: 'В разделе есть статьи — перенесите их в другой раздел' });
      return;
    }
    if (!await window.UI.confirm({
      title: `Удалить «${section.name}»?`,
      message: 'Раздел будет удалён без возможности восстановления.',
      confirmLabel: 'Удалить',
      cancelLabel: 'Отмена',
      danger: true,
    })) return;
    setBusyId(section.id);
    try {
      await window.KB.deleteSection(section.id);
      tick();
      onRefresh?.();
    } catch (err) {
      await window.UI.alert({ title: 'Ошибка', message: err.message });
    } finally {
      setBusyId(null);
    }
  };

  const startEdit = (section, e) => {
    e?.stopPropagation?.();
    setEditingId(section.id);
    setAddingRoot(false);
    setAddingSubFor(null);
    setForm({ name: section.name, icon: section.icon || 'folder' });
    if (section.parentId) {
      setOpenRoots((p) => ({ ...p, [section.parentId]: true }));
    }
  };

  const toggleRoot = (id) => {
    setOpenRoots((prev) => ({ ...prev, [id]: !prev[id] }));
  };

  const toggleSub = (id) => {
    setOpenSubs((prev) => ({ ...prev, [id]: !prev[id] }));
  };

  const openArticle = (article, e) => {
    e?.stopPropagation?.();
    onOpenArticle(article);
  };

  return (
    <div className="page sections-page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Разделы</h1>
          <p className="page-sub">Нажмите на раздел — откроются подразделы и статьи</p>
        </div>
        <button
          type="button"
          className="btn btn-primary"
          onClick={() => { resetForm(); setAddingRoot(true); }}
          disabled={addingRoot || addingSubFor || editingId}
        >
          <Icon name="plus" size={14} /> Раздел
        </button>
      </div>

      <div className="sections-tree-panel">
        {addingRoot && (
          <div className="sections-tree-form-row">
            <span className="sections-tree-form-label">Новый раздел</span>
            <SectionForm
              form={form}
              setForm={setForm}
              onSubmit={() => handleSave(null)}
              onCancel={resetForm}
              submitLabel="Создать"
              busy={busyId === 'new'}
            />
          </div>
        )}

        {roots.length === 0 && !addingRoot && (
          <div className="sections-tree-empty">
            <p>Разделов пока нет</p>
            <button type="button" className="btn btn-primary btn-sm" onClick={() => { resetForm(); setAddingRoot(true); }}>
              Создать первый раздел
            </button>
          </div>
        )}

        {roots.map((root) => {
          const subs = window.getSubsections(root.id);
          const isRootOpen = !!openRoots[root.id];
          const totalCount = window.getSectionArticleCount(root.id);
          const rootArticles = window.getSectionArticles(root.id);
          const isEditingRoot = editingId === root.id;

          return (
            <div key={root.id} className="sections-tree-group">
              {isEditingRoot ? (
                <div className="sections-tree-form-row sections-tree-form-row--nested">
                  <SectionForm
                    form={form}
                    setForm={setForm}
                    onSubmit={() => handleSave()}
                    onCancel={resetForm}
                    submitLabel="Сохранить"
                    busy={busyId === root.id}
                  />
                </div>
              ) : (
                <button
                  type="button"
                  className={`sections-tree-row sections-tree-row--root${isRootOpen ? ' is-open' : ''}`}
                  onClick={() => toggleRoot(root.id)}
                >
                  <span className="sections-tree-chevron">
                    <Icon
                      name="chevronRight"
                      size={14}
                      style={{ transform: isRootOpen ? 'rotate(90deg)' : 'none', transition: 'transform 0.15s' }}
                    />
                  </span>
                  <span className="sections-tree-icon">
                    <Icon name={root.icon || 'folder'} size={16} />
                  </span>
                  <span className="sections-tree-label">{root.name}</span>
                  <span className="sections-tree-count">{totalCount}</span>
                  <TreeActions
                    id={root.id}
                    busyId={busyId}
                    showAddSub
                    onAddSub={() => {
                      resetForm();
                      setAddingSubFor(root.id);
                      setOpenRoots((p) => ({ ...p, [root.id]: true }));
                    }}
                    onEdit={(e) => startEdit(root, e)}
                    onDelete={() => handleDelete(root)}
                  />
                </button>
              )}

              {isRootOpen && (
                <div className="sections-tree-children">
                  {subs.map((sub) => {
                    const articles = window.getSectionArticles(sub.id);
                    const isSubOpen = !!openSubs[sub.id];
                    const isEditingSub = editingId === sub.id;

                    if (isEditingSub) {
                      return (
                        <div key={sub.id} className="sections-tree-form-row sections-tree-form-row--sub">
                          <SectionForm
                            form={form}
                            setForm={setForm}
                            onSubmit={() => handleSave()}
                            onCancel={resetForm}
                            submitLabel="Сохранить"
                            busy={busyId === sub.id}
                          />
                        </div>
                      );
                    }

                    return (
                      <div key={sub.id} className="sections-tree-subgroup">
                        <button
                          type="button"
                          className={`sections-tree-row sections-tree-row--sub${isSubOpen ? ' is-open' : ''}`}
                          onClick={() => toggleSub(sub.id)}
                        >
                          <span className="sections-tree-chevron">
                            <Icon
                              name="chevronRight"
                              size={13}
                              style={{ transform: isSubOpen ? 'rotate(90deg)' : 'none', transition: 'transform 0.15s' }}
                            />
                          </span>
                          <span className="sections-tree-icon sections-tree-icon--sub">
                            <Icon name={sub.icon || 'file'} size={14} />
                          </span>
                          <span className="sections-tree-label">{sub.name}</span>
                          <span className="sections-tree-count">{articles.length}</span>
                          <TreeActions
                            id={sub.id}
                            busyId={busyId}
                            onEdit={(e) => startEdit(sub, e)}
                            onDelete={() => handleDelete(sub)}
                          />
                        </button>

                        {isSubOpen && (
                          <div className="sections-tree-articles">
                            {articles.length === 0 ? (
                              <div className="sections-tree-empty-sub">Нет статей</div>
                            ) : (
                              articles.map((article) => (
                                <button
                                  type="button"
                                  key={article.id}
                                  className="sections-tree-row sections-tree-row--article"
                                  onClick={(e) => openArticle(article, e)}
                                >
                                  <span className="sections-tree-chevron sections-tree-chevron--empty" />
                                  <span className="sections-tree-icon sections-tree-icon--article">
                                    <Icon name="file" size={13} />
                                  </span>
                                  <span className="sections-tree-label">{article.title}</span>
                                  <span className={`sections-tree-status status-${article.status}`}>
                                    {article.status === 'published' ? 'Опубл.' : article.status === 'review' ? 'Ревью' : 'Черновик'}
                                  </span>
                                </button>
                              ))
                            )}
                          </div>
                        )}
                      </div>
                    );
                  })}

                  {rootArticles.length > 0 && (
                    <div className="sections-tree-articles sections-tree-articles--root">
                      {subs.length > 0 && (
                        <div className="sections-tree-articles-heading">Статьи раздела</div>
                      )}
                      {rootArticles.map((article) => (
                        <button
                          type="button"
                          key={article.id}
                          className="sections-tree-row sections-tree-row--article"
                          onClick={(e) => openArticle(article, e)}
                        >
                          <span className="sections-tree-chevron sections-tree-chevron--empty" />
                          <span className="sections-tree-icon sections-tree-icon--article">
                            <Icon name="file" size={13} />
                          </span>
                          <span className="sections-tree-label">{article.title}</span>
                          <span className={`sections-tree-status status-${article.status}`}>
                            {article.status === 'published' ? 'Опубл.' : article.status === 'review' ? 'Ревью' : 'Черновик'}
                          </span>
                        </button>
                      ))}
                    </div>
                  )}

                  {addingSubFor === root.id && (
                    <div className="sections-tree-form-row sections-tree-form-row--sub">
                      <span className="sections-tree-form-label">Подраздел</span>
                      <SectionForm
                        form={form}
                        setForm={setForm}
                        onSubmit={() => handleSave(root.id)}
                        onCancel={resetForm}
                        submitLabel="Создать"
                        busy={busyId === 'new'}
                      />
                    </div>
                  )}

                  {subs.length === 0 && rootArticles.length === 0 && addingSubFor !== root.id && (
                    <div className="sections-tree-empty-sub">
                      Пусто ·{' '}
                      <button
                        type="button"
                        className="sections-tree-link"
                        onClick={() => { resetForm(); setAddingSubFor(root.id); }}
                      >
                        добавить подраздел
                      </button>
                      {' '}или{' '}
                      <button type="button" className="sections-tree-link" onClick={onCreate}>
                        создать статью
                      </button>
                    </div>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

window.SectionsView = SectionsView;
