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

/* =============================================================
   UserLists.jsx — followers / following / liked / saved
   --------------------------------------------------------------
   Four list surfaces, all reachable by tapping a stat on Profile.
   Followers + Following render as scrollable user rows with
   search + follow-state per row. Liked + Saved render as a
   masonry of the saved/liked posts.
   ============================================================= */

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

const FOLLOWERS = [
  { id: "u_1", name: "علی رحمانی",   handle: "ali.r",        city: "تهران",     bio: "نقد ادبی · جمعه‌ها قهوه می‌خورم", follows_me: true, i_follow: true,  ring: "#ff4ea8" },
  { id: "u_2", name: "سعید نوری",     handle: "saeid.podcast",city: "مشهد",       bio: "پادکست‌ساز · «جاده چالوس»",        follows_me: true, i_follow: false, ring: "#9a6cff" },
  { id: "u_3", name: "زهرا مرادی",    handle: "z.moradi",     city: "تبریز",       bio: "عکاس کوچه‌ها",                      follows_me: true, i_follow: true,  ring: "#4be3ff" },
  { id: "u_4", name: "نگار رستمی",    handle: "negar.rashti", city: "رشت",         bio: "ولاگر · رقص محلی گیلان",              follows_me: true, i_follow: false, ring: "#f5d589" },
  { id: "u_5", name: "آرمان احمدی",    handle: "armana_art",   city: "یزد",         bio: "نقاش دیجیتال · AI و من",              follows_me: true, i_follow: false, ring: "#ff8a3d" },
  { id: "u_6", name: "فاطمه دلیری",    handle: "f.daliri",     city: "بندرعباس",     bio: "آشپزی بندری · ۳ کتاب",                follows_me: true, i_follow: true,  ring: "#44e3b8" },
  { id: "u_7", name: "محمد رضایی",    handle: "m.rezaei",     city: "اصفهان",       bio: "موسیقی فولک · نوازنده‌ی تار",        follows_me: true, i_follow: false, ring: "#9a6cff" },
  { id: "u_8", name: "روزبه بهزاد",   handle: "roozbeh.b",    city: "همدان",        bio: "ولاگ سفر · ۲۰ هزار کیلومتر",         follows_me: true, i_follow: true,  ring: "#ff4ea8" },
];

const FOLLOWING = [
  { id: "u_8", name: "روزبه بهزاد",   handle: "roozbeh.b",    city: "همدان",   bio: "ولاگ سفر · ۲۰ هزار کیلومتر", follows_me: true,  i_follow: true, ring: "#ff4ea8" },
  { id: "u_3", name: "زهرا مرادی",    handle: "z.moradi",     city: "تبریز",    bio: "عکاس کوچه‌ها",                follows_me: true,  i_follow: true, ring: "#4be3ff" },
  { id: "u_1", name: "علی رحمانی",   handle: "ali.r",        city: "تهران",   bio: "نقد ادبی",                     follows_me: true,  i_follow: true, ring: "#ff4ea8" },
  { id: "u_6", name: "فاطمه دلیری",    handle: "f.daliri",     city: "بندرعباس", bio: "آشپزی بندری · ۳ کتاب",         follows_me: true,  i_follow: true, ring: "#44e3b8" },
  { id: "u_9", name: "رادیو مرز",     handle: "radiomarz",    city: "تهران",   bio: "پادکست رسمی · کانال بَله",     follows_me: false, i_follow: true, ring: "#f5d589", verified: true },
  { id: "u_10",name: "خبرگزاری ایسنا", handle: "isna_news",    city: "تهران",   bio: "اخبار رسمی",                   follows_me: false, i_follow: true, ring: "#4be3ff", verified: true },
];

const LIKED = [
  { kind: "image", title: "پنجره خانه مادربزرگ",         author: "مهسا کریمی",     rating: 5, count: 1820, color: "#ff4ea8", aspect: 1 },
  { kind: "video", title: "صبحانه بندری",                author: "فاطمه دلیری",    rating: 5, count: 3120, duration: "۱:۰۴", aspect: 1.2 },
  { kind: "text",  body: "وقتی حرف می‌زنی، شهر گوش می‌ده.", author: "علی رحمانی",   rating: 4, count: 540, gradient: "gold" },
  { kind: "audio", title: "صدای بوی بازار کرمانشاه",      author: "روزبه بهزاد",   rating: 4, count: 540, duration: "۴:۲۲" },
  { kind: "image", title: "نقاشی دیجیتال از یزد",        author: "آرمان احمدی",   rating: 4, count: 720,  color: "#4be3ff", aspect: 1.3 },
];

const SAVED = [
  { kind: "video", title: "چالش رقص محلی گیلان",     author: "نگار رستمی", rating: 5, count: 2300, duration: "۲:۱۴", aspect: 0.75 },
  { kind: "audio", title: "پادکست: قصه‌های جاده چالوس", author: "سعید نوری", rating: 4, count: 412, duration: "۸:۱۲" },
  { kind: "text",  body: "از ترافیک شهر خسته‌ام، اما نه از مردمش.", author: "زهرا مرادی", rating: 5, count: 1240, gradient: "rose" },
];

const TITLES = {
  followers: "دنبال‌کننده‌ها",
  following: "دنبال می‌کنم",
  liked:     "پسندیده‌ها",
  saved:     "ذخیره‌شده‌ها",
};

/* Reusable row — also exposed for FollowHub if needed */
window.UserListItem = function UserListItem({ user, onOpen, onToggleFollow }) {
  const [following, setFollowing] = useState(user.i_follow);
  const toggle = () => {
    const next = !following;
    setFollowing(next);
    onToggleFollow?.(user.id, next);
  };
  return (
    <button className="kd-userlist__row" onClick={onOpen}>
      <Avatar name={user.name} size={44} ring={user.ring} />
      <div className="kd-userlist__row-text">
        <div className="kd-userlist__row-name">
          <strong>{user.name}</strong>
          {user.verified && (
            <span className="kd-userlist__verified" title="تایید شده">
              <Icon name="check" size={9} stroke={3} />
            </span>
          )}
          {user.follows_me && !user.verified && <span className="kd-userlist__followsyou">دنبالت می‌کنه</span>}
        </div>
        <div className="kd-userlist__row-handle">@{user.handle} · {user.city}</div>
        {user.bio && <div className="kd-userlist__row-bio">{user.bio}</div>}
      </div>
      <button
        className={`kd-btn kd-btn--sm ${following ? "kd-user-follow--on" : "kd-btn--primary"}`}
        onClick={(e) => { e.stopPropagation(); toggle(); }}>
        {following ? <React.Fragment><Icon name="check" size={12} stroke={2.6} /> دنبال می‌کنی</React.Fragment> : "دنبال کن"}
      </button>
    </button>
  );
};

window.UserLists = function UserLists({ kind = "followers", onBack, onOpenUser, onOpenPost }) {
  const [q, setQ] = useState("");

  const isUserList = kind === "followers" || kind === "following";
  const isPostList = kind === "liked" || kind === "saved";

  const userSource = kind === "followers" ? FOLLOWERS : FOLLOWING;
  const postSource = kind === "liked" ? LIKED : SAVED;

  const filteredUsers = useMemo(() => {
    if (!q.trim()) return userSource;
    const s = q.trim().toLowerCase();
    return userSource.filter(u =>
      u.name.includes(q) || u.handle.toLowerCase().includes(s) || (u.city && u.city.includes(q))
    );
  }, [q, userSource]);

  return (
    <div className="kd-userlists">
      <header className="kd-settings__head">
        <button className="kd-settings__back" onClick={onBack} aria-label="برگشت">
          <Icon name="back" size={20} stroke={2.2} />
        </button>
        <h1 className="kd-settings__title">
          {TITLES[kind]}
          <span className="kd-userlists__count">{fmtFa(isUserList ? userSource.length : postSource.length)}</span>
        </h1>
        <span style={{ width: 36 }} />
      </header>

      {isUserList && (
        <React.Fragment>
          <div className="kd-userlists__search">
            <Icon name="search" size={16} stroke={2} />
            <input
              type="search"
              placeholder={kind === "followers" ? "بین دنبال‌کننده‌ها بگرد…" : "بین کسایی که دنبال می‌کنی بگرد…"}
              value={q}
              onChange={e => setQ(e.target.value)}
            />
            {q && <button className="kd-userlists__clear" onClick={() => setQ("")} aria-label="پاک کن"><Icon name="close" size={14} stroke={2.2} /></button>}
          </div>

          {filteredUsers.length === 0 ? (
            <EmptyState
              icon="search" tone="rose"
              title="کسی با این نام پیدا نشد"
              sub={`بین ${fmtFa(userSource.length)} نفر گشتیم — هیچی نبود.`}
            />
          ) : (
            <div className="kd-userlist">
              {filteredUsers.map(u => (
                <UserListItem key={u.id} user={u} onOpen={() => onOpenUser?.(u)} />
              ))}
            </div>
          )}
        </React.Fragment>
      )}

      {isPostList && (
        <React.Fragment>
          {postSource.length === 0 ? (
            <EmptyState
              icon={kind === "liked" ? "heart" : "bookmark"}
              tone={kind === "liked" ? "rose" : "gold"}
              title={kind === "liked" ? "هنوز هیچ پستی رو نپسندیدی" : "هنوز هیچی ذخیره نکردی"}
              sub={kind === "liked"
                ? "هرجا پستی دیدی دوست داشتی، روی قلب بزن."
                : "هرجا پستی دیدی دوست داشتی، روی نشانک بزن. اینجا برات نگه می‌داریم."}
            />
          ) : (
            <div className="kd-masonry">
              {postSource.map((p, i) => {
                const props = { ...p, dark: true, onClick: () => onOpenPost?.(p) };
                if (p.kind === "video") return <VideoCard key={i} {...props} />;
                if (p.kind === "image") return <ImageCard key={i} {...props} />;
                if (p.kind === "audio") return <AudioCard key={i} {...props} />;
                if (p.kind === "text")  return <TextCard  key={i} {...props} />;
                return null;
              })}
            </div>
          )}
        </React.Fragment>
      )}
    </div>
  );
};
})();
