// article-interactions.jsx — оценка, комментарии, ознакомление

const formatWhen = (iso) => {
  if (!iso) return '—';
  const d = new Date(iso);
  return d.toLocaleString('ru', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
};

const CommentItem = ({
  fb,
  replies,
  uid,
  canModerate,
  busy,
  replyTo,
  setReplyTo,
  replyText,
  setReplyText,
  onSubmitReply,
  onDelete,
}) => {
  const author = window.findPerson(fb.personId);
  const canDelete = fb.personId === uid || canModerate;
  const isReplying = replyTo === fb.id;

  return (
    <div className={`article-ix-item${fb.parentId ? ' article-ix-item--reply' : ''}`}>
      <div className="article-ix-item-head">
        <span className="article-ix-author">{author?.name || 'Сотрудник'}</span>
        <span className="article-ix-date">{formatWhen(fb.createdAt)}</span>
      </div>
      <p className="article-ix-body">{fb.body}</p>
      <div className="article-ix-item-actions">
        <button
          type="button"
          className="article-ix-link-btn"
          disabled={busy}
          onClick={() => setReplyTo(isReplying ? null : fb.id)}
        >
          {isReplying ? 'Отмена' : 'Ответить'}
        </button>
        {canDelete && (
          <button
            type="button"
            className="article-ix-link-btn article-ix-link-btn--danger"
            disabled={busy}
            onClick={() => onDelete(fb)}
          >
            Удалить
          </button>
        )}
      </div>
      {isReplying && (
        <form className="article-ix-reply-form" onSubmit={(e) => onSubmitReply(e, fb.id)}>
          <textarea
            className="article-ix-textarea"
            placeholder="Ваш ответ…"
            value={replyText}
            onChange={(e) => setReplyText(e.target.value)}
            rows={2}
            autoFocus
          />
          <button type="submit" className="btn btn-primary btn-sm" disabled={busy || !replyText.trim()}>
            Отправить
          </button>
        </form>
      )}
      {replies.length > 0 && (
        <div className="article-ix-replies">
          {replies.map((r) => (
            <CommentItem
              key={r.id}
              fb={r}
              replies={[]}
              uid={uid}
              canModerate={canModerate}
              busy={busy}
              replyTo={replyTo}
              setReplyTo={setReplyTo}
              replyText={replyText}
              setReplyText={setReplyText}
              onSubmitReply={onSubmitReply}
              onDelete={onDelete}
            />
          ))}
        </div>
      )}
    </div>
  );
};

const ArticleInteractions = ({ article, linkedTest, onTakeTest, onOpenArticle }) => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [comment, setComment] = React.useState('');
  const [replyTo, setReplyTo] = React.useState(null);
  const [replyText, setReplyText] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  const uid = window.KB.getCurrentUserId();
  const canModerate = article.authorId === uid
    || (article.responsibles || []).includes(uid);

  const tagNav = React.useMemo(
    () => window.getArticleTagNeighbors(article.id),
    [article.id, article.tags],
  );

  const reload = React.useCallback(async (silent = false) => {
    if (!silent) setLoading(true);
    try {
      const ix = await window.KB.getArticleInteractions(article.id);
      setData(ix);
      if (ix.usefulStats) window.KB.setVoteStats(article.id, ix.usefulStats);
    } catch (err) {
      await window.UI.alert({ title: 'Ошибка', message: err.message });
    } finally {
      if (!silent) setLoading(false);
    }
  }, [article.id]);

  React.useEffect(() => { reload(); }, [reload]);

  const handleVote = async (value) => {
    const scrollEl = document.querySelector('.main-area');
    const scrollTop = scrollEl?.scrollTop ?? 0;
    setBusy(true);
    try {
      if (data?.vote?.value === value) {
        await window.KB.removeUsefulVote(article.id);
      } else {
        await window.KB.voteUseful(article.id, value, null);
      }
      await reload(true);
      requestAnimationFrame(() => {
        if (scrollEl) scrollEl.scrollTop = scrollTop;
      });
    } catch (err) {
      await window.UI.alert({ title: 'Ошибка', message: err.message });
    } finally {
      setBusy(false);
      document.activeElement?.blur?.();
    }
  };

  const handleAck = async () => {
    const hasTest = Boolean(linkedTest?.status === 'published' && onTakeTest);
    if (hasTest) {
      const go = await window.UI.choice({
        title: 'Переход к тесту',
        message: `Вы ознакомились со статьёй. Сейчас вы перейдёте к тесту для проверки знаний. После подтверждения запустится таймер${linkedTest.duration ? ` на ${linkedTest.duration} мин` : ''}.`,
        yesLabel: 'Продолжить',
        noLabel: 'Назад',
        icon: 'quiz',
      });
      if (!go) return;
    }
    setBusy(true);
    try {
      await window.KB.acknowledgeArticle(article.id);
      await reload();
      if (hasTest) onTakeTest(linkedTest);
    } catch (err) {
      await window.UI.alert({ title: 'Ошибка', message: err.message });
    } finally {
      setBusy(false);
    }
  };

  const handleComment = async (e) => {
    e.preventDefault();
    if (!comment.trim()) return;
    setBusy(true);
    try {
      await window.KB.postFeedback(article.id, comment.trim());
      setComment('');
      await reload();
    } catch (err) {
      await window.UI.alert({ title: 'Ошибка', message: err.message });
    } finally {
      setBusy(false);
    }
  };

  const handleReply = async (e, parentId) => {
    e.preventDefault();
    if (!replyText.trim()) return;
    setBusy(true);
    try {
      await window.KB.postFeedback(article.id, replyText.trim(), { parentId });
      setReplyText('');
      setReplyTo(null);
      await reload();
    } catch (err) {
      await window.UI.alert({ title: 'Ошибка', message: err.message });
    } finally {
      setBusy(false);
    }
  };

  const handleDelete = async (fb) => {
    if (!await window.UI.confirm({
      title: 'Удалить комментарий?',
      message: 'Комментарий и ответы на него будут удалены.',
      confirmLabel: 'Удалить',
      cancelLabel: 'Отмена',
      danger: true,
    })) return;
    setBusy(true);
    try {
      await window.KB.deleteFeedback(fb.id);
      await reload();
    } catch (err) {
      await window.UI.alert({ title: 'Ошибка', message: err.message });
    } finally {
      setBusy(false);
    }
  };

  if (loading && !data) {
    return <div className="article-ix-loading">Загрузка…</div>;
  }

  const comments = (data?.feedback || []).filter((f) => f.type === 'comment');
  const repliesByParent = {};
  comments.filter((c) => c.parentId).forEach((c) => {
    if (!repliesByParent[c.parentId]) repliesByParent[c.parentId] = [];
    repliesByParent[c.parentId].push(c);
  });
  const rootComments = comments.filter((c) => !c.parentId);
  const { prev, next } = tagNav;

  return (
    <section className="article-ix">
      {article.isMandatory && (
        <div className={`article-ix-mandatory-bar${data?.acknowledged ? ' is-done' : ''}`}>
          <div className="article-ix-mandatory-bar-text">
            <Icon name="check" size={16} />
            <span>
              Обязательно к прочтению
              {linkedTest && !data?.acknowledged && (
                <span className="article-ix-mandatory-test-hint"> · далее тест</span>
              )}
            </span>
          </div>
          {data?.acknowledged ? (
            <span className="article-ix-ack-done">Ознакомлены {formatWhen(data.acknowledgedAt)}</span>
          ) : (
            <button type="button" className="btn btn-primary btn-sm" disabled={busy} onClick={handleAck}>
              Я ознакомлен(а)
            </button>
          )}
        </div>
      )}

      <div className="article-feedback">
        <p className="article-feedback-question">Была ли эта статья полезной?</p>
        <div className="article-feedback-actions">
          <button
            type="button"
            className={`article-feedback-btn${data?.vote?.value === 1 ? ' is-active is-yes' : ''}`}
            disabled={busy}
            onClick={() => handleVote(1)}
          >
            <Icon name="thumbsUp" size={16} />
            Да
          </button>
          <button
            type="button"
            className={`article-feedback-btn${data?.vote?.value === -1 ? ' is-active is-no' : ''}`}
            disabled={busy}
            onClick={() => handleVote(-1)}
          >
            <Icon name="thumbsDown" size={16} />
            Нет
          </button>
        </div>
      </div>

      {(prev || next) && (
        <div className="article-nav">
          {prev ? (
            <button
              type="button"
              className="article-nav-item article-nav-item--prev"
              onClick={() => onOpenArticle?.(prev)}
            >
              <Icon name="chevronRight" size={18} className="article-nav-chevron article-nav-chevron--left" />
              <span className="article-nav-content">
                <span className="article-nav-label">Предыдущая статья</span>
                <span className="article-nav-title">{prev.title}</span>
              </span>
            </button>
          ) : (
            <div className="article-nav-item article-nav-item--empty" aria-hidden="true" />
          )}
          {next ? (
            <button
              type="button"
              className="article-nav-item article-nav-item--next"
              onClick={() => onOpenArticle?.(next)}
            >
              <span className="article-nav-content">
                <span className="article-nav-label">Следующая статья</span>
                <span className="article-nav-title">{next.title}</span>
              </span>
              <Icon name="chevronRight" size={18} className="article-nav-chevron" />
            </button>
          ) : (
            <div className="article-nav-item article-nav-item--empty" aria-hidden="true" />
          )}
        </div>
      )}

      <div className="article-comments">
        <h3 className="article-comments-title">
          Комментарии{comments.length > 0 ? ` (${comments.length})` : ''}
        </h3>
        <form className="article-ix-comment-form" onSubmit={handleComment}>
          <textarea
            className="article-ix-textarea"
            placeholder="Написать комментарий…"
            value={comment}
            onChange={(e) => setComment(e.target.value)}
            rows={3}
          />
          <button type="submit" className="btn btn-primary btn-sm" disabled={busy || !comment.trim()}>
            Отправить
          </button>
        </form>
        {rootComments.length > 0 && (
          <div className="article-ix-thread">
            {rootComments.map((fb) => (
              <CommentItem
                key={fb.id}
                fb={fb}
                replies={repliesByParent[fb.id] || []}
                uid={uid}
                canModerate={canModerate}
                busy={busy}
                replyTo={replyTo}
                setReplyTo={setReplyTo}
                replyText={replyText}
                setReplyText={setReplyText}
                onSubmitReply={handleReply}
                onDelete={handleDelete}
              />
            ))}
          </div>
        )}
      </div>
    </section>
  );
};

window.ArticleInteractions = ArticleInteractions;
