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

/* =============================================================
   Explore.jsx — personalized masonry feed
   --------------------------------------------------------------
   Like Feed, but every card carries a CoaffinityAttributionChip
   explaining *why* it was surfaced ("هم‌ولایتی"، "ادامه‌ی موضوع X"،
   "هم‌سلیقه‌ها هم پسندیدن"…), and a 3-dot menu with
   "این رو دیگه نشون نده" + reason sub-options.
   ============================================================= */

const fmtFa = (n) => String(n).replace(/\d/g, d => "۰۱۲۳۴۵۶۷۸۹"[d]);

// reasons drive both the attribution chip + the filter pill row
const REASONS = [
  { id: "for_you",   label: "برای تو",          icon: "star",     color: "#ff4ea8" },
  { id: "hometown",  label: "هم‌ولایتی",         icon: "target",   color: "#4be3ff" },
  { id: "topic",     label: "ادامه‌ی موضوع",     icon: "trending", color: "#9a6cff" },
  { id: "similar",   label: "هم‌سلیقه‌ها",       icon: "heart",    color: "#f5d589" },
  { id: "following", label: "از فالووینگ‌ها",   icon: "profile",  color: "#44e3b8" },
];

// attribution sub-copy per item
const ATTRIB = {
  for_you:   "براساس فعالیتت این رو لایک می‌کنی",
  hometown:  "گیلانی‌ها این رو زیاد نگاه کردن",
  topic:     "چون دنبال موضوع «شعر معاصر» بودی",
  similar:   "کسایی شبیه تو ۵ ستاره دادن",
  following: "از «راضیه ت.» — تو دنبالش می‌کنی",
};

const SAMPLE = [
  { kind: "video", reason: "hometown",  title: "صبحانه بندری",           author: "فاطمه دلیری", rating: 5, count: 3120, duration: "۱:۰۴", aspect: 1.2 },
  { kind: "text",  reason: "topic",     body:  "وقتی حرف می‌زنی، شهر گوش می‌ده.", author: "علی رحمانی",  rating: 4, count: 540, gradient: "gold" },
  { kind: "image", reason: "similar",   title: "هوش مصنوعی، خیال شیراز", author: "رضا فلاحی",   rating: 4, count: 980,  color: "#9a6cff", aspect: 0.85 },
  { kind: "audio", reason: "following", title: "پادکست: قصه‌های جاده چالوس", author: "سعید نوری", rating: 4, count: 412, duration: "۸:۱۲" },
  { kind: "image", reason: "for_you",   title: "نقاشی دیجیتال از یزد",    author: "آرمان احمدی", rating: 4, count: 720,  color: "#4be3ff", aspect: 1.3 },
  { kind: "video", reason: "topic",     title: "چالش رقص محلی گیلان",     author: "نگار رستمی",  rating: 5, count: 2300, duration: "۲:۱۴", aspect: 0.75 },
  { kind: "text",  reason: "similar",   body:  "از ترافیک شهر خسته‌ام، اما نه از مردمش.", author: "زهرا مرادی", rating: 5, count: 1240, gradient: "rose" },
  { kind: "image", reason: "hometown",  title: "پنجره خانه مادربزرگ",     author: "مهسا کریمی",   rating: 5, count: 1820, color: "#ff4ea8", aspect: 1 },
  { kind: "audio", reason: "for_you",   title: "صدامو می‌شنوی؟ — انتقادمو", author: "محمد رضایی", rating: 5, count: 622, duration: "۳:۴۸" },
  { kind: "text",  reason: "following", body:  "یه روز که آفتاب پشت البرز قایم شد، فهمیدم.", author: "سارا حسینی", rating: 4, count: 410, gradient: "violet" },
];

/* small attribution chip — 3-dot sits on the visual RIGHT (inline-start),
   to the right of the label text, never near the card's content-type chip
   (which lives at the opposite top corner). */
function CoaffinityChip({ reason, onMore, menuOpen, menuChildren }) {
  const r = REASONS.find(x => x.id === reason);
  if (!r) return null;
  return (
    <span className="kd-explore-chip" style={{ ['--accent']: r.color }} title={ATTRIB[reason] || ''}>
      <button
        className="kd-explore-chip__more"
        onClick={(e) => { e.stopPropagation(); onMore?.(); }}
        aria-label="گزینه‌ها">
        <Icon name="more" size={12} stroke={2} />
      </button>
      <Icon name={r.icon} size={11} stroke={2} />
      <span>{r.label}</span>
      {menuOpen && menuChildren}
    </span>
  );
}

/* hide content menu — popover on the 3-dot tap */
function HideContentMenu({ open, onClose, onHide, onHideAuthor, onHideTopic, post }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="kd-explore-menu" ref={ref}>
      <button onClick={onHide}><Icon name="close" size={14} stroke={2.2} /> این رو دیگه نشون نده</button>
      <button onClick={onHideAuthor}><Icon name="profile" size={14} stroke={2} /> از «{post.author}» چیزی نشون نده</button>
      <button onClick={onHideTopic}><Icon name="filter" size={14} stroke={2} /> از این موضوع کمتر نشون بده</button>
      <div className="kd-explore-menu__sep" />
      <button className="kd-explore-menu__report"><Icon name="bell" size={14} stroke={2} /> گزارش بده</button>
    </div>
  );
}

window.Explore = function Explore({ onOpenPost, onOpenUser }) {
  const [filter, setFilter] = useState("all");
  const [hidden, setHidden] = useState(new Set()); // hidden item indices
  const [hiddenAuthors, setHiddenAuthors] = useState(new Set());
  const [hiddenReasons, setHiddenReasons] = useState(new Set());
  const [menuOpenIdx, setMenuOpenIdx] = useState(null);
  const [undo, setUndo] = useState(null); // { idx, label } | null

  const visible = useMemo(() => {
    return SAMPLE.map((p, idx) => ({ ...p, idx }))
      .filter(p => !hidden.has(p.idx))
      .filter(p => !hiddenAuthors.has(p.author))
      .filter(p => !hiddenReasons.has(p.reason))
      .filter(p => filter === "all" || p.reason === filter);
  }, [filter, hidden, hiddenAuthors, hiddenReasons]);

  const hideItem = (idx, label) => {
    setHidden(s => new Set([...s, idx]));
    setUndo({ idx, label });
    setMenuOpenIdx(null);
    setTimeout(() => setUndo(u => (u && u.idx === idx) ? null : u), 5000);
  };
  const hideAuthor = (author, idx) => {
    setHiddenAuthors(s => new Set([...s, author]));
    setUndo({ author, label: `دیگه از «${author}» چیزی نشون نمی‌دیم` });
    setMenuOpenIdx(null);
    setTimeout(() => setUndo(u => (u && u.author === author) ? null : u), 5000);
  };
  const hideReason = (reason, idx) => {
    const r = REASONS.find(x => x.id === reason);
    setHiddenReasons(s => new Set([...s, reason]));
    setUndo({ reason, label: `از «${r?.label || reason}» کمتر نشون می‌دیم` });
    setMenuOpenIdx(null);
    setTimeout(() => setUndo(u => (u && u.reason === reason) ? null : u), 5000);
  };
  const undoLast = () => {
    if (!undo) return;
    if (undo.idx !== undefined) setHidden(s => { const n = new Set(s); n.delete(undo.idx); return n; });
    if (undo.author) setHiddenAuthors(s => { const n = new Set(s); n.delete(undo.author); return n; });
    if (undo.reason) setHiddenReasons(s => { const n = new Set(s); n.delete(undo.reason); return n; });
    setUndo(null);
  };

  return (
    <div className="kd-feed-page kd-explore-page">
      <header className="kd-feed-page__head">
        <h1 className="kd-feed-page__title">برات گشتیم</h1>
        <p className="kd-feed-page__sub">اینا رو فکر کردیم خوشت میاد. هر کدوم رو نمی‌خوای، بهمون بگو.</p>
      </header>

      <div className="kd-feed-page__filters" role="tablist">
        <Pill active={filter === "all"} onClick={() => setFilter("all")}>همه</Pill>
        {REASONS.map(r => (
          <Pill key={r.id} active={filter === r.id} dot={r.color} onClick={() => setFilter(r.id)}>
            {r.label}
          </Pill>
        ))}
      </div>

      {filter === "all" && window.PeopleYouMayKnow && (
        <PeopleYouMayKnow onOpenUser={onOpenUser} />
      )}

      {visible.length === 0 ? (
        <div className="kd-explore-empty">
          <div className="kd-explore-empty__icon"><Icon name="search" size={36} stroke={1.6} /></div>
          <h3>هنوز چیزی برات پیدا نکردیم</h3>
          <p>کمی فعالیت کن — لایک، امتیاز، فالو — تا بفهمیم چی دوست داری.</p>
          {(hidden.size > 0 || hiddenAuthors.size > 0 || hiddenReasons.size > 0) && (
            <button className="kd-explore-empty__cta" onClick={() => {
              setHidden(new Set()); setHiddenAuthors(new Set()); setHiddenReasons(new Set());
            }}>پنهان‌شده‌ها رو برگردون</button>
          )}
        </div>
      ) : (
        <div className="kd-masonry">
          {visible.map((p) => {
            const cardProps = { ...p, dark: true, onClick: () => onOpenPost?.(p) };
            let card = null;
            if (p.kind === "video") card = <VideoCard {...cardProps} />;
            if (p.kind === "image") card = <ImageCard {...cardProps} />;
            if (p.kind === "audio") card = <AudioCard {...cardProps} />;
            if (p.kind === "text")  card = <TextCard  {...cardProps} />;
            return (
              <div key={p.idx} className="kd-explore-card">
                {card}
                <div className="kd-explore-card__overlay">
                  <CoaffinityChip
                    reason={p.reason}
                    onMore={() => setMenuOpenIdx(menuOpenIdx === p.idx ? null : p.idx)}
                    menuOpen={menuOpenIdx === p.idx}
                    menuChildren={
                      <HideContentMenu
                        open={true}
                        onClose={() => setMenuOpenIdx(null)}
                        onHide={() => hideItem(p.idx, p.title || p.body || "این")}
                        onHideAuthor={() => hideAuthor(p.author, p.idx)}
                        onHideTopic={() => hideReason(p.reason, p.idx)}
                        post={p}
                      />
                    }
                  />
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Undo snack — appears for 5s after a hide action */}
      {undo && (
        <div className="kd-explore-undo" role="status">
          <Icon name="check" size={14} stroke={2.4} />
          <span>{undo.label}</span>
          <button onClick={undoLast}>بازگردانی</button>
        </div>
      )}
    </div>
  );
};
})();
