/* global React */
(function(){
const { useState, useEffect, useRef } = React;
const RichText = window.RichText;

/* =============================================================
   PostView.jsx — single submission detail
   Full-screen on mobile, centered card on desktop.
   Media → header → caption → tags → reactions/rate → comments.
   ============================================================= */

const fmtFa = (n) => String(n).replace(/\d/g, d => "۰۱۲۳۴۵۶۷۸۹"[d]);
const fmtCount = (n) => {
  if (n < 1000) return fmtFa(n);
  if (n < 1000000) return fmtFa((n/1000).toFixed(1).replace(/\.0$/, "")) + " هزار";
  return fmtFa((n/1000000).toFixed(1).replace(/\.0$/, "")) + " م";
};

const SAMPLE_POST = {
  id: "sub_01HXZ7",
  kind: "video",
  author: { name: "نگار رستمی", handle: "negar.r", city: "رشت", winsBadge: "برندهٔ مرداد" },
  duration: "۲:۱۴",
  views: 12430,
  likes: 2380,
  saves: 412,
  rating: 4.7,
  ratings_count: 318,
  posted_at: "۲ ساعت پیش",
  caption: "این اولین چالشمه که برای کشوردوست می‌فرستم. توی محله گیلان ما هنوز رقص محلی زنده است — آدم‌ها بعد از خریدِ صبح، توی کوچهٔ سنگ‌فرش بدون هیچ بهانه‌ای می‌رقصن. خواستم این لحظهٔ معمولی رو ثبت کنم.",
  tags: ["رقص محلی", "گیلان", "چالش هفته", "روایت شهر"],
  challenge: { id: "win_today", title: "یه عکس از پنجره‌ت" },
};

const SAMPLE_COMMENTS = [
  { id: 1, author: "علی رحمانی",  text: "این انرژی رو از کجا میاری؟ یه نفس گرفتم با دیدنش.", time: "۴۸ د", likes: 24, mine: false, pinned: true },
  { id: 2, author: "مهسا کریمی",  text: "موزیکش خیلی نشست — اسم آهنگو بذار لطفاً.", time: "۳۲ د", likes: 11, mine: false, replyTo: null },
  { id: 3, author: "نگار رستمی",  text: "@مهسا کریمی موزیک محلی‌ست، اسمش «گیله‌مرد»ـه ❤", time: "۲۹ د", likes: 8, mine: false, replyTo: 2 },
  { id: 4, author: "زهرا مرادی",  text: "ایده برای چالش بعدی: «صبحانه شهرت». هرکس صبحانهٔ معمولی محله‌ش رو نشون بده.", time: "۱۸ د", likes: 42, mine: false },
];

/* Menu for each comment — actions depend on:
   - mine        → edit / delete
   - isPostAuthor → pin / hide
   - always      → report */
function CommentMenu({ comment, isPostAuthor, onClose, onEdit, onDelete, onPin, onHide, onReport }) {
  const ref = useRef(null);
  useEffect(() => {    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [onClose]);
  const mine = !!comment.mine;
  return (
    <div className="kd-comment__menu" ref={ref}>
      {mine && (
        <React.Fragment>
          <button onClick={onEdit}><Icon name="text" size={12} stroke={2} /> ویرایش</button>
          <button className="kd-explore-menu__report" onClick={onDelete}><Icon name="close" size={12} stroke={2.2} /> حذف</button>
        </React.Fragment>
      )}
      {!mine && isPostAuthor && (
        <React.Fragment>
          <button onClick={onPin}>
            <Icon name="bookmark" size={12} stroke={2} /> {comment.pinned ? "برداشتن سنجاق" : "سنجاق کن"}
          </button>
          <button onClick={onHide}><Icon name="filter" size={12} stroke={2} /> پنهان کن</button>
          <div className="kd-explore-menu__sep" />
        </React.Fragment>
      )}
      {!mine && (
        <button className="kd-explore-menu__report" onClick={onReport}><Icon name="flame" size={12} stroke={2} /> گزارش بده</button>
      )}
    </div>
  );
}

window.PostView = function PostView({ post = SAMPLE_POST, onBack, onAuthor, onOpenComments }) {
  const [liked, setLiked] = useState(false);
  const [saved, setSaved] = useState(false);
  const [myRate, setMyRate] = useState(0);
  const [rateHover, setRateHover] = useState(0);
  const [comments, setComments] = useState(SAMPLE_COMMENTS);
  const [newComment, setNewComment] = useState("");
  const [playing, setPlaying] = useState(false);
  const [shareOpen, setShareOpen] = useState(false);
  const [frameOpen, setFrameOpen] = useState(false);
  const [menuOpenId, setMenuOpenId] = useState(null);
  const [headMenu, setHeadMenu] = useState(false);
  const headMenuRef = useRef(null);
  useEffect(() => {
    if (!headMenu) return;
    const onDoc = (e) => { if (headMenuRef.current && !headMenuRef.current.contains(e.target)) setHeadMenu(false); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [headMenu]);
  const [editingId, setEditingId] = useState(null);
  const [editText, setEditText] = useState("");
  const composerRef = useRef(null);

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

  // ----- mention typeahead (P2-04) -----
  const MENTIONABLE = [
    { 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: "roozbeh.b", ring: "#ff8a3d" },
    { name: "مهسا کریمی", handle: "mahsa_k", ring: "#ff4ea8" },
  ];
  const [mentionOpen, setMentionOpen] = useState(false);
  const [mentionQuery, setMentionQuery] = useState("");
  const [mentionIndex, setMentionIndex] = useState(0);

  const mentionMatches = mentionOpen
    ? MENTIONABLE.filter(u =>
        u.handle.toLowerCase().includes(mentionQuery.toLowerCase()) ||
        u.name.includes(mentionQuery)
      ).slice(0, 5)
    : [];

  // detect "@token" at the caret
  const onComposerChange = (val, el) => {
    setNewComment(val);
    const caret = el ? el.selectionStart : val.length;
    const upto = val.slice(0, caret);
    const m = upto.match(/(?:^|\s)@([\u0600-\u06FF\w._]*)$/);
    if (m) {
      setMentionOpen(true);
      setMentionQuery(m[1] || "");
      setMentionIndex(0);
    } else {
      setMentionOpen(false);
    }
  };
  const pickMention = (u) => {
    // replace the trailing @token with @handle + space
    setNewComment(prev => prev.replace(/@([\u0600-\u06FF\w._]*)$/, `@${u.handle} `));
    setMentionOpen(false);
    setMentionQuery("");
  };
  const onComposerKey = (e) => {
    if (mentionOpen && mentionMatches.length > 0) {
      if (e.key === "ArrowDown") { e.preventDefault(); setMentionIndex(i => (i + 1) % mentionMatches.length); return; }
      if (e.key === "ArrowUp")   { e.preventDefault(); setMentionIndex(i => (i - 1 + mentionMatches.length) % mentionMatches.length); return; }
      if (e.key === "Enter" || e.key === "Tab") { e.preventDefault(); pickMention(mentionMatches[mentionIndex]); return; }
      if (e.key === "Escape") { setMentionOpen(false); return; }
    }
    if (e.key === "Enter") submitComment();
  };

  // Treat current user as the post author for demo — so they see
  // moderation actions (pin/hide) on others' comments.
  const isPostAuthor = true;

  const submitRate = (n) => {
    if (window.kdRequireAuth) window.kdRequireAuth("rate", () => setMyRate(n));
    else setMyRate(n);
  };
  const submitComment = () => {
    if (!newComment.trim()) return;
    const post = () => {
      setComments(c => [...c, {
        id: Date.now(), author: "من", text: newComment.trim(),
        time: "همین حالا", likes: 0, mine: true,
      }]);
      setNewComment("");
    };
    if (window.kdRequireAuth) window.kdRequireAuth("comment", post);
    else post();
  };
  const toggleLike = () => {
    if (window.kdRequireAuth) window.kdRequireAuth("follow", () => setLiked(l => !l));
    else setLiked(l => !l);
  };
  const toggleSave = () => {
    if (window.kdRequireAuth) window.kdRequireAuth("save", () => setSaved(s => !s));
    else setSaved(s => !s);
  };

  return (
    <div className="kd-post-page">
      {/* ---- Sticky compact header ---- */}
      <header className="kd-post-head">
        <button className="kd-post-head__back" onClick={onBack} aria-label="برگشت">
          <Icon name="back" size={20} stroke={2.2} />
        </button>
        <div className="kd-post-head__center">
          <strong>اثر</strong>
          <span>{fmtCount(post.views)} بازدید</span>
        </div>
        <div className="kd-post-head__morewrap" ref={headMenuRef}>
          <button className="kd-post-head__more" aria-label="گزینه‌ها" onClick={() => setHeadMenu(o => !o)}>
            <Icon name="more" size={20} stroke={2} />
          </button>
          {headMenu && (
            <div className="kd-post-head__menu">
              <button onClick={() => { setHeadMenu(false); setShareOpen(true); }}>
                <Icon name="share" size={14} stroke={2} /> هم‌رسانی
              </button>
              <button onClick={() => { setHeadMenu(false); toggleSave(); }}>
                <Icon name="bookmark" size={14} stroke={2} /> {saved ? "حذف از ذخیره‌ها" : "ذخیره"}
              </button>
              <button onClick={() => { setHeadMenu(false); window.dispatchEvent(new CustomEvent("kd-promote-open", { detail: { post } })); }}>
                <Icon name="trending" size={14} stroke={2} /> تبلیغ این پست
              </button>
              <div className="kd-explore-menu__sep" />
              <button onClick={() => { setHeadMenu(false); window.dispatchEvent(new CustomEvent("kd-auth-prompt", { detail: { action: "save" } })); }}>
                <Icon name="bell" size={14} stroke={2} /> خاموش‌کردن اعلان این پست
              </button>
              <button className="kd-explore-menu__report" onClick={() => { setHeadMenu(false); window.dispatchEvent(new CustomEvent("kd-report-open", { detail: { source: "post", target: { id: post.id, name: post.author?.name } } })); }}>
                <Icon name="flame" size={14} stroke={2} /> گزارش این پست
              </button>
            </div>
          )}
        </div>
      </header>

      {/* ---- Media ---- */}
      <div className={`kd-post-media kd-post-media--${post.kind}`}>
        <div className="kd-post-media__bg" />
        {post.kind !== "audio" && (
          <img className="kd-post-media__img" src={(window.kdImgFor ? window.kdImgFor(post.id || post.caption || "post", 960, 720) : "")} alt={post.caption || ""} loading="lazy" />
        )}
        <button className={`kd-post-media__play ${playing ? "is-playing" : ""}`} onClick={() => setPlaying(p => !p)} aria-label={playing ? "توقف" : "پخش"}>
          {playing
            ? <span style={{ display: "inline-flex", gap: 4 }}><i style={{ width: 5, height: 22, background: "currentColor", borderRadius: 2 }} /><i style={{ width: 5, height: 22, background: "currentColor", borderRadius: 2 }} /></span>
            : <Icon name="video" size={26} stroke={2.4} />}
        </button>
        <div className="kd-post-media__chip"><Icon name={post.kind} size={12} stroke={2.2} /> {post.kind === "video" ? "ویدیو" : post.kind}</div>
        <div className="kd-post-media__dur">{post.duration}</div>
      </div>

      <div className="kd-post-body">
        {/* ---- Author row ---- */}
        <div className="kd-post-author">
          <button className="kd-post-author__avatarbtn" onClick={() => onAuthor?.(post.author)} aria-label={`پروفایل ${post.author.name}`}>
            <Avatar name={post.author.name} size={44} ring="#ff4ea8" />
          </button>
          <button className="kd-post-author__id" onClick={() => onAuthor?.(post.author)}>
            <strong>{post.author.name}</strong>
            <span>@{post.author.handle} · {post.author.city} · {post.posted_at}</span>
          </button>
          <button className="kd-post-author__follow">دنبال کن</button>
        </div>

        {post.author.winsBadge && (
          <div className="kd-post-badge">
            <Icon name="trophy" size={14} stroke={2.2} /> {post.author.winsBadge}
          </div>
        )}

        {/* ---- Caption ---- */}
        <p className="kd-post-caption"><RichText text={post.caption} /></p>

        {/* ---- Tags ---- */}
        <div className="kd-post-tags">
          {post.tags.map(t => (
            <button key={t} className="kd-post-tag"
              onClick={() => window.dispatchEvent(new CustomEvent("kd-open-tag", { detail: { tag: t.replace(/ /g, "_") } }))}>
              #{t}
            </button>
          ))}
        </div>

        {/* ---- Challenge link ---- */}
        {post.challenge && (
          <div className="kd-post-challenge">
            <span className="kd-post-challenge__lab"><Icon name="target" size={14} stroke={2.2} /> پاسخ به چالش</span>
            <strong>{post.challenge.title}</strong>
            <button className="kd-post-challenge__cta">ببین <Icon name="chevron" size={14} stroke={2.4} /></button>
          </div>
        )}

        {/* ---- Reactions strip ---- */}
        <div className="kd-post-react">
          <button className={`kd-post-react__btn ${liked ? "is-on kd-post-react__btn--like" : ""}`} onClick={toggleLike}>
            <Icon name="heart" size={20} stroke={liked ? 0 : 2.2} style={{ fill: liked ? "#ff4ea8" : "none" }} />
            <span>{fmtCount(post.likes + (liked ? 1 : 0))}</span>
          </button>
          <button className="kd-post-react__btn" onClick={onOpenComments}>
            <Icon name="comment" size={20} stroke={2.2} />
            <span>{fmtFa(comments.length)}</span>
          </button>
          <button className={`kd-post-react__btn ${saved ? "is-on kd-post-react__btn--save" : ""}`} onClick={toggleSave}>
            <Icon name="bookmark" size={20} stroke={saved ? 0 : 2.2} style={{ fill: saved ? "#ff8a3d" : "none" }} />
            <span>{fmtCount(post.saves + (saved ? 1 : 0))}</span>
          </button>
          <button className="kd-post-react__btn" onClick={() => setShareOpen(true)}>
            <Icon name="share" size={20} stroke={2.2} />
            <span>هم‌رسانی</span>
          </button>
        </div>

        {/* ---- 5-star rating ---- */}
        <div className="kd-post-rate">
          <div className="kd-post-rate__head">
            <span className="kd-post-rate__lab">امتیاز بده</span>
            <span className="kd-post-rate__avg">
              <Icon name="star" size={14} stroke={0} style={{ fill: "#f5d589" }} />
              <strong>{post.rating}</strong>
              <span>از {fmtFa(post.ratings_count)} رای</span>
            </span>
          </div>
          <div className="kd-post-rate__row" onMouseLeave={() => setRateHover(0)}>
            {[1,2,3,4,5].map(n => (
              <button key={n}
                className={`kd-post-rate__star ${(rateHover || myRate) >= n ? "is-lit" : ""}`}
                onMouseEnter={() => setRateHover(n)}
                onClick={() => submitRate(n)}
                aria-label={`${n} ستاره`}>
                <Icon name="star" size={32} stroke={(rateHover || myRate) >= n ? 0 : 1.6} style={{ fill: (rateHover || myRate) >= n ? "currentColor" : "none" }} />
              </button>
            ))}
          </div>
          {myRate > 0 && (
            <p className="kd-post-rate__thx">
              {myRate === 5 ? "🎉 پنج! کیف کردیم با امتیازت." : "ثبت شد — ممنون."}
            </p>
          )}
        </div>

        {/* ---- Comments ---- */}
        <section className="kd-post-comments">
          <div className="kd-post-comments__h-row">
            <h3 className="kd-post-comments__h">گفت‌وگو ({fmtFa(comments.length)})</h3>
            <button className="kd-post-comments__all" onClick={onOpenComments}>مشاهده همه <Icon name="chevron" size={13} stroke={2.4} style={{ verticalAlign: "-2px", transform: "scaleX(-1)", display: "inline" }} /></button>
          </div>
          <ul className="kd-post-comments__list">
            {[...comments].sort((a,b) => (b.pinned?1:0) - (a.pinned?1:0)).map(c => (
              <li key={c.id} className={`kd-comment ${c.replyTo ? "kd-comment--reply" : ""} ${c.pinned ? "is-pinned" : ""} ${c.hidden ? "is-hidden" : ""}`}>
                <Avatar name={c.author} size={32} />
                <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 && (
                      <CommentMenu
                        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 : (x.pinned && c.pinned ? 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><Icon name="heart" size={13} stroke={2} /> {c.likes > 0 ? fmtFa(c.likes) : "لایک"}</button>
                    <button onClick={() => replyTo(c)}>پاسخ</button>
                  </div>
                </div>
              </li>
            ))}
          </ul>
        </section>
      </div>

      {/* ---- Composer (sticky) ---- */}
      <div className="kd-post-composer">
        <Avatar name="من" size={32} />
        <div className="kd-post-composer__field">
          {mentionOpen && mentionMatches.length > 0 && (
            <div className="kd-mention">
              <div className="kd-mention__head">منشن کن</div>
              {mentionMatches.map((u, i) => (
                <button
                  key={u.handle}
                  className={`kd-mention__item ${i === mentionIndex ? "is-active" : ""}`}
                  onMouseEnter={() => setMentionIndex(i)}
                  onClick={() => pickMention(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={newComment}
            onChange={e => onComposerChange(e.target.value, e.target)}
            onKeyDown={onComposerKey}
          />
        </div>
        <button className="kd-post-composer__send" onClick={submitComment} disabled={!newComment.trim()} aria-label="ارسال">
          <Icon name="send" size={18} stroke={2.2} style={{ transform: "scaleX(-1)" }} />
        </button>
      </div>

      {/* ---- Share sheet ---- */}
      {shareOpen && (
        <div className="kd-share" onClick={() => setShareOpen(false)}>
          <div className="kd-share__sheet" onClick={e => e.stopPropagation()}>
            <div className="kd-share__handle" />
            <h3 className="kd-share__h">هم‌رسانی</h3>
            <div className="kd-share__grid">
              <button className="kd-share__opt"><span style={{ background: "linear-gradient(135deg,#229ED9,#0088cc)" }}><Icon name="send" size={20} stroke={0} style={{ fill: "#fff" }} /></span>تلگرام</button>
              <button className="kd-share__opt"><span style={{ background: "linear-gradient(135deg,#833AB4,#FD1D1D,#FCB045)" }}><Icon name="image" size={20} stroke={2.2} style={{ color: "#fff" }} /></span>استوری اینستا</button>
              <button className="kd-share__opt"><span style={{ background: "linear-gradient(135deg,#25D366,#128C7E)" }}><Icon name="comment" size={20} stroke={2.2} style={{ color: "#fff" }} /></span>واتساپ</button>
              <button className="kd-share__opt"><span style={{ background: "rgba(255,255,255,.08)" }}><Icon name="bookmark" size={20} stroke={2.2} style={{ color: "#fff" }} /></span>کپی لینک</button>
            </div>
            <div className="kd-share__frame" onClick={() => { setShareOpen(false); setFrameOpen(true); }} role="button" tabIndex={0}>
              <span className="kd-share__frame-tag"><Icon name="image" size={12} stroke={2.2} /> قاب کشوردوست</span>
              <p>یه قاب گرافیکی با لوگوی جشنواره دور اثر می‌ذاره و آماده می‌فرسته به استوری.</p>
              <span className="kd-share__frame-open">باز کن <Icon name="back" size={12} stroke={2.4} /></span>
            </div>
            <button
              className="kd-share__promote"
              onClick={() => { setShareOpen(false); window.dispatchEvent(new CustomEvent("kd-promote-open", { detail: { post } })); }}>
              <span className="kd-share__promote-icon"><Icon name="trending" size={16} stroke={2.2} /></span>
              <span className="kd-share__promote-text">
                <strong>این پست رو تبلیغ کن</strong>
                <span>به کاربرای هم‌سلیقه نشونش بده — از ۵۰ هزار تومن</span>
              </span>
              <Icon name="back" size={14} stroke={2.4} />
            </button>
          </div>
        </div>
      )}

      {/* ---- Branded share frame ---- */}
      <ShareFrame open={frameOpen} onClose={() => setFrameOpen(false)} post={post} />
    </div>
  );
};
window.CommentMenu = CommentMenu;
})();
