// tags-modal.jsx — управление тегами

const TAG_COLORS = [
  { id: 'tag-blue', label: 'Синий' },
  { id: 'tag-amber', label: 'Янтарный' },
  { id: 'tag-violet', label: 'Фиолетовый' },
  { id: 'tag-rose', label: 'Розовый' },
  { id: 'tag-green', label: 'Зелёный' },
  { id: 'tag-accent', label: 'Акцент' },
];

const TagsModal = ({ open, onClose, onChange }) => {
  const [, tick] = React.useReducer((n) => n + 1, 0);
  const [name, setName] = React.useState('');
  const [color, setColor] = React.useState('tag-blue');
  const [busy, setBusy] = React.useState(false);

  React.useEffect(() => {
    if (!open) return undefined;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);

  if (!open) return null;

  const handleAdd = async (e) => {
    e.preventDefault();
    const trimmed = name.trim();
    if (!trimmed) return;
    if (window.TAGS.some((t) => t.name === trimmed.toLowerCase())) {
      await window.UI.alert({ title: 'Тег уже существует', message: 'Такой тег уже есть' });
      return;
    }
    setBusy(true);
    try {
      await window.KB.saveTag({ name: trimmed, color });
      setName('');
      tick();
      onChange?.();
    } catch (err) {
      await window.UI.alert({ title: 'Ошибка', message: err.message });
    } finally {
      setBusy(false);
    }
  };

  const handleDelete = async (tag) => {
    const count = window.KB.getTagUsageCount(tag.id);
    const msg = count
      ? `Тег будет убран из ${count} ${window.pluralRu(count, 'статьи', 'статей', 'статей')}.`
      : 'Тег будет удалён без возможности восстановления.';
    if (!await window.UI.confirm({
      title: `Удалить «${tag.name}»?`,
      message: msg,
      confirmLabel: 'Удалить',
      cancelLabel: 'Отмена',
      danger: true,
    })) return;
    setBusy(true);
    try {
      await window.KB.deleteTag(tag.id);
      tick();
      onChange?.();
    } catch (err) {
      await window.UI.alert({ title: 'Ошибка', message: err.message });
    } finally {
      setBusy(false);
    }
  };

  const tags = [...window.TAGS].sort((a, b) => a.name.localeCompare(b.name));

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal tags-modal" onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-labelledby="tags-modal-title">
        <div className="modal-header">
          <div>
            <h2 id="tags-modal-title" className="modal-title">Теги</h2>
            <p className="modal-sub">Добавляйте и удаляйте теги для статей</p>
          </div>
          <button type="button" className="topbar-icon-btn" onClick={onClose} aria-label="Закрыть">
            <Icon name="x" size={16} />
          </button>
        </div>

        <form className="tags-modal-add" onSubmit={handleAdd}>
          <input
            className="tags-modal-input"
            placeholder="Название нового тега"
            value={name}
            onChange={(e) => setName(e.target.value)}
            disabled={busy}
            autoFocus
          />
          <div className="tags-modal-colors">
            {TAG_COLORS.map((c) => (
              <button
                type="button"
                key={c.id}
                className={`tags-modal-color${color === c.id ? ' selected' : ''}`}
                onClick={() => setColor(c.id)}
                title={c.label}
              >
                <span className={`tag ${c.id}`}>{c.label}</span>
              </button>
            ))}
          </div>
          <button type="submit" className="btn btn-primary btn-sm" disabled={busy || !name.trim()}>
            <Icon name="plus" size={13} /> Добавить
          </button>
        </form>

        <div className="tags-modal-list">
          {tags.length === 0 ? (
            <p className="tags-modal-empty">Тегов пока нет — создайте первый выше</p>
          ) : (
            tags.map((tag) => {
              const count = window.KB.getTagUsageCount(tag.id);
              return (
                <div key={tag.id} className="tags-modal-row">
                  <TagChip tag={tag} />
                  <span className="tags-modal-count">
                    {count} {window.pluralRu(count, 'статья', 'статьи', 'статей')}
                  </span>
                  <button
                    type="button"
                    className="tags-modal-delete"
                    onClick={() => handleDelete(tag)}
                    disabled={busy}
                    title="Удалить тег"
                  >
                    <Icon name="trash" size={14} />
                  </button>
                </div>
              );
            })
          )}
        </div>
      </div>
    </div>
  );
};

window.TagsModal = TagsModal;
