/* global React */
(function(){
const { useState, useRef } = React;

/* =============================================================
   CommentsPage.jsx — dedicated full-screen comment thread
   --------------------------------------------------------------
   Linked from PostView (comment button / "همه") and from
   comment-type notifications. Shows the post context up top,
   sort tabs (برترین / جدیدترین), the full thread with the same
   moderation menu (window.CommentMenu), and a sticky composer
   with @ mention + # hashtag typeahead.
   ============================================================= */

const fmtFa = (n) => String(n).replace(/\d/g, d => "۰۱۲۳۴۵۶۷۸۹"[d]);
const fmtCount = (n) => n >= 1000 ? fmtFa((n/1000).toFixed(1)) + "هزار" : fmtFa(n);

const POST_CTX = {
  author: "نگار رستمی",
  handle: "negar.rashti",
  ring: "#f5d589",
  kind: "video",
  color: "#ff4ea8",
  caption: "رقص محلی گیلان روی پشت‌بوم خونه‌ی مادربزرگ — اولین باری که جلوی دوربین رقصیدم.",
};

const SEED = [
  { id: "c1", author: "علی رحمانی",  handle: "ali.r",   time: "۲ ساعت پیش", text: "این انرژی رو از کجا میاری؟ معرکه بود 👏 با #جشنواره_تهران حتماً دیده می‌شه.", likes: 34, pinned: true },
  { id: "c2", author: "زهرا مرادی",  handle: "z.moradi", time: "۳ ساعت پیش", text: "گیلان رو خیلی خوب نشون دادی. @negar.rashti ادامه بده!", likes: 12 },
  { id: "c3", author: "سعید نوری",   handle: "saeid.podcast", time: "۴ ساعت پیش", text: "موسیقیش رو از کجا آوردی؟ دنبال همین حال‌وهوا بودم.", likes: 8 },
  { id: "c4", author: "مهسا کریمی",  handle: "mahsa_k", time: "۵ ساعت پیش", text: "قشنگ‌ترین چیزی که امروز دیدم.", likes: 21 },
  { id: "c5", author: "روزبه بهزاد", handle: "roozbeh.b", time: "دیروز", text: "نور غروب رو عالی گرفتی. کاش پشت‌صحنه‌شم می‌ذاشتی.", likes: 5 },
  { id: "c6", author: "فاطمه دلیری", handle: "f.daliri", time: "دیروز", text: "به دوستام نشون دادم، همه ذوق کردن. منتظر کار بعدیتیم 🌿", likes: 17 },
];

const USER_POOL = [
  { name: "علی رحمانی", handle: "ali.r", ring: "#ff4ea8", followsYou: true },
  { name: "نگار رستمی", handle: "negar.rashti", ring: "#f5d589", verified: true },
  { name: "زهرا مرادی", handle: "z.moradi", ring: "#4be3ff", followsYou: true },
  { name: "سعید نوری", handle: "saeid.podcast", ring: "#9a6cff" },
  { name: "فاطمه دلیری", handle: "f.daliri", ring: "#44e3b8", followsYou: true },
  { name: "مهسا کریمی", handle: "mahsa_k", ring: "#ff4ea8" },
];
const TAG_POOL = [
  { tag: "جشنواره_تهران", count: 12400 }, { tag: "رقص_محلی", count: 6200 },
  { tag: "گیلان", count: 3400 }, { tag: "قاب_کشور", count: 5300 },
  { tag: "موسیقی_محلی", count: 760 }, { tag: "غروب", count: 2100 },
];

// render caption/comment text with #tag and @handle highlighted (shared global)
const RichText = window.RichText;

window.CommentsPage = function CommentsPage({ onBack, onAuthor, onOpenPost }) {
  const [sort, setSort] = useState("top");        // top | new
  const [comments, setComments] = useState(SEED);
  const [menuOpenId, setMenuOpenId] = useState(null);
  const [editingId, setEditingId] = useState(null);
  const [editText, setEditText] = useState("");
  const [draft, setDraft] = useState("");
  const [likedIds, setLikedIds] = useState({});
  const composerRef = useRef(null);

  // reply → prefill composer with @handle and focus
  const replyTo = (c) => {
    const handle = c.handle || (c.author ? c.author.replace(/\s+/g, "_") : "");
    setDraft("@" + handle + " ");
    setTimeout(() => {
      const el = composerRef.current;
      if (el) { el.focus(); const v = el.value; el.setSelectionRange(v.length, v.length); }
    }, 30);
  };

  // token typeahead
  const [tokOpen, setTokOpen] = useState(false);
  const [tokType, setTokType] = useState("@");
  const [tokQuery, setTokQuery] = useState("");
  const [tokIndex, setTokIndex] = useState(0);
  const isPostAuthor = true; // viewing your own post's comments

  const tokMatches = !tokOpen ? [] : (
    tokType === "#"
      ? TAG_POOL.filter(t => t.tag.includes(tokQuery)).slice(0, 5)
      : USER_POOL.filter(u => u.handle.toLowerCase().includes(tokQuery.toLowerCase()) || u.name.includes(tokQuery)).slice(0, 5)
  );

  const onDraftChange = (val, el) => {
    setDraft(val);
    const caret = el ? el.selectionStart : val.length;
    const m = val.slice(0, caret).match(/(?:^|\s)([@#])([\u0600-\u06FF\w._]*)$/);
    if (m) { setTokOpen(true); setTokType(m[1]); setTokQuery(m[2] || ""); setTokIndex(0); }
    else setTokOpen(false);
  };
  const pickToken = (item) => {
    const ins = tokType === "#" ? `#${item.tag} ` : `@${item.handle} `;
    setDraft(prev => prev.replace(/([@#])([\u0600-\u06FF\w._]*)$/, ins));
    setTokOpen(false); setTokQuery("");
  };
  const onDraftKey = (e) => {
    if (tokOpen && tokMatches.length > 0) {
      if (e.key === "ArrowDown") { e.preventDefault(); setTokIndex(i => (i + 1) % tokMatches.length); return; }
      if (e.key === "ArrowUp")   { e.preventDefault(); setTokIndex(i => (i - 1 + tokMatches.length) % tokMatches.length); return; }
      if (e.key === "Enter" || e.key === "Tab") { e.preventDefault(); pickToken(tokMatches[tokIndex]); return; }
      if (e.key === "Escape") { setTokOpen(false); return; }
    }
    if (e.key === "Enter") submit();
  };

  const submit = () => {
    const t = draft.trim();
    if (!t) return;
    setComments(cs => [{ id: "n" + Date.now(), author: "من", handle: "me", time: "همین حالا", text: t, likes: 0 }, ...cs]);
    setDraft(""); setTokOpen(false);
  };

  const sorted = [...comments].sort((a, b) => {
    if (a.pinned && !b.pinned) return -1;
    if (b.pinned && !a.pinned) return 1;
    return sort === "top" ? b.likes - a.likes : 0;
  });

  const Menu = window.CommentMenu;

  return (
    <div className="kd-comments-page">
      {/* header */}
      <header className="kd-comments-page__top">
        <button className="kd-comments-page__back" onClick={onBack} aria-label="برگرد">
          <Icon name="back" size={18} stroke={2.4} />
        </button>
        <h1>گفت‌وگو <span>({fmtFa(comments.length)})</span></h1>
        <span style={{ width: 36 }} />
      </header>

      {/* post context */}
      <button className="kd-comments-ctx" onClick={onOpenPost}>
        <span className="kd-comments-ctx__thumb" style={{ ['--c']: POST_CTX.color }}>
          <Icon name={POST_CTX.kind} size={20} stroke={1.7} />
        </span>
        <span className="kd-comments-ctx__body">
          <span className="kd-comments-ctx__author">
            <Avatar name={POST_CTX.author} size={20} ring={POST_CTX.ring} />
            <strong>{POST_CTX.author}</strong>
          </span>
          <span className="kd-comments-ctx__cap"><RichText text={POST_CTX.caption} /></span>
        </span>
        <Icon name="back" size={14} stroke={2.4} />
      </button>

      {/* sort */}
      <div className="kd-comments-sort">
        <button className={sort === "top" ? "is-on" : ""} onClick={() => setSort("top")}>برترین</button>
        <button className={sort === "new" ? "is-on" : ""} onClick={() => setSort("new")}>جدیدترین</button>
      </div>

      {/* list */}
      <ul className="kd-comments-page__list">
        {sorted.map(c => (
          <li key={c.id} className={`kd-comment ${c.pinned ? "is-pinned" : ""} ${c.hidden ? "is-hidden" : ""}`}>
            <button className="kd-comment__avatar-btn" onClick={() => onAuthor?.(c)}>
              <Avatar name={c.author} size={36} />
            </button>
            <div className="kd-comment__body">
              {c.pinned && (
                <span className="kd-comment__pinned">
                  <Icon name="bookmark" size={11} stroke={2} /> سنجاق‌شده توسط نویسنده
                </span>
              )}
              <div className="kd-comment__head">
                <strong>{c.author}</strong>
                <span>{c.time}{c.edited ? " · ویرایش شده" : ""}</span>
                <span style={{ flex: 1 }} />
                <button className="kd-comment__more"
                  onClick={(e) => { e.stopPropagation(); setMenuOpenId(menuOpenId === c.id ? null : c.id); }}
                  aria-label="گزینه‌ها">
                  <Icon name="more" size={14} stroke={2} />
                </button>
                {menuOpenId === c.id && Menu && (
                  <Menu
                    comment={c}
                    isPostAuthor={isPostAuthor}
                    onClose={() => setMenuOpenId(null)}
                    onEdit={() => { setEditingId(c.id); setEditText(c.text); setMenuOpenId(null); }}
                    onDelete={() => { setComments(cs => cs.filter(x => x.id !== c.id)); setMenuOpenId(null); }}
                    onPin={() => { setComments(cs => cs.map(x => ({ ...x, pinned: x.id === c.id ? !x.pinned : false }))); setMenuOpenId(null); }}
                    onHide={() => { setComments(cs => cs.map(x => x.id === c.id ? { ...x, hidden: true } : x)); setMenuOpenId(null); }}
                    onReport={() => { setMenuOpenId(null); window.dispatchEvent(new CustomEvent("kd-report-open", { detail: { source: "comment", target: { id: c.id, name: c.author } } })); }}
                  />
                )}
              </div>
              {c.hidden ? (
                <p className="kd-comment__text" style={{ color: "rgba(255,255,255,.4)", fontStyle: "italic" }}>این کامنت پنهان شده.</p>
              ) : editingId === c.id ? (
                <div className="kd-comment__editor">
                  <textarea value={editText} onChange={e => setEditText(e.target.value)} autoFocus />
                  <div className="kd-comment__editor-actions">
                    <button className="kd-comment__editor-cancel" onClick={() => setEditingId(null)}>منصرف شدم</button>
                    <button className="kd-btn kd-btn--primary kd-btn--sm" onClick={() => {
                      setComments(cs => cs.map(x => x.id === c.id ? { ...x, text: editText.trim(), edited: true } : x));
                      setEditingId(null);
                    }}>ذخیره</button>
                  </div>
                </div>
              ) : (
                <p className="kd-comment__text"><RichText text={c.text} /></p>
              )}
              <div className="kd-comment__actions">
                <button className={likedIds[c.id] ? "is-liked" : ""} onClick={() => setLikedIds(l => ({ ...l, [c.id]: !l[c.id] }))}>
                  <Icon name="heart" size={13} stroke={likedIds[c.id] ? 0 : 2} style={{ fill: likedIds[c.id] ? "#ff4ea8" : "none" }} />
                  {(c.likes + (likedIds[c.id] ? 1 : 0)) > 0 ? fmtFa(c.likes + (likedIds[c.id] ? 1 : 0)) : "لایک"}
                </button>
                <button onClick={() => replyTo(c)}>پاسخ</button>
              </div>
            </div>
          </li>
        ))}
      </ul>

      {/* composer */}
      <div className="kd-post-composer kd-comments-page__composer">
        <Avatar name="من" size={32} />
        <div className="kd-post-composer__field">
          {tokOpen && tokMatches.length > 0 && (
            <div className="kd-mention">
              <div className="kd-mention__head">{tokType === "#" ? "هشتگ" : "منشن کن"}</div>
              {tokType === "#"
                ? tokMatches.map((t, i) => (
                    <button key={t.tag} className={`kd-mention__item ${i === tokIndex ? "is-active" : ""}`}
                      onMouseDown={e => e.preventDefault()} onMouseEnter={() => setTokIndex(i)} onClick={() => pickToken(t)}>
                      <span className="kd-tokenbox__hash">#</span>
                      <span className="kd-mention__text"><strong>{t.tag}</strong><span>{fmtCount(t.count)} پست</span></span>
                    </button>
                  ))
                : tokMatches.map((u, i) => (
                    <button key={u.handle} className={`kd-mention__item ${i === tokIndex ? "is-active" : ""}`}
                      onMouseDown={e => e.preventDefault()} onMouseEnter={() => setTokIndex(i)} onClick={() => pickToken(u)}>
                      <Avatar name={u.name} size={30} ring={u.ring} />
                      <span className="kd-mention__text"><strong>{u.name}</strong><span>@{u.handle}{u.followsYou ? " · دنبالت می‌کنه" : ""}</span></span>
                      {u.verified && <span className="kd-userlist__verified"><Icon name="check" size={8} stroke={3} /></span>}
                    </button>
                  ))}
            </div>
          )}
          <input
            className="kd-post-composer__input"
            ref={composerRef}
            placeholder="یه چیزی بگو… (# هشتگ، @ منشن)"
            value={draft}
            onChange={e => onDraftChange(e.target.value, e.target)}
            onKeyDown={onDraftKey}
            onBlur={() => setTimeout(() => setTokOpen(false), 150)}
          />
        </div>
        <button className="kd-post-composer__send" onClick={submit} disabled={!draft.trim()} aria-label="ارسال">
          <Icon name="send" size={18} stroke={2.2} style={{ transform: "scaleX(-1)" }} />
        </button>
      </div>
    </div>
  );
};
})();
