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

/* =============================================================
   Notifications.jsx — full-screen activity center
   Grouped sections + filter tabs + unread badge logic.
   ============================================================= */

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 TABS = [
  { id: "all",     label: "همه",       count: 21 },
  { id: "requests",label: "درخواست‌ها",count: 3 },
  { id: "social",  label: "تعامل",     count: 12 },
  { id: "rate",    label: "امتیاز",    count: 4 },
  { id: "prize",   label: "پاداش",     count: 2 },
];

const FOLLOW_REQUESTS = [
  { id: "fr_1", user: { name: "علیرضا کمالی",  handle: "alireza.k", city: "تهران",   bio: "نقد ادبی و فیلم" }, time: "همین حالا", mutual: 4 },
  { id: "fr_2", user: { name: "نرگس فولاد",   handle: "nargess",    city: "اصفهان",   bio: "عکاس مستند" },     time: "۲ ساعت",     mutual: 1 },
  { id: "fr_3", user: { name: "حسام تابش",     handle: "hesam.t",    city: "شیراز",     bio: "ولاگر سفر" },        time: "دیروز",      mutual: 0 },
];

const NOTES = [
  // ---- TODAY
  { group: "امروز", type: "prize", id: 1, unread: true, icon: "trophy", tone: "gold", title: "تبریک! انتخاب شدی برای اکران شهری.", body: "تصویر «پنجره خانهٔ مادربزرگ» تو، فردا از ۸ صبح روی ۱۰ بیلبورد اصفهان اکران می‌شه.", time: "همین حالا", cta: "ببین کجاست" },
  { group: "امروز", type: "rate",  id: 2, unread: true, icon: "star", tone: "magenta", title: "۵ ستارهٔ کامل گرفتی!", body: "نگار رستمی به ویدیوت «رقص محلی گیلان» امتیاز ۵ داد.", actor: { name: "نگار رستمی", ring: "#ff4ea8" }, time: "۱۲ دقیقه" },
  { group: "امروز", type: "social", id: 3, unread: true, icon: "comment", tone: "cyan", title: "علی رحمانی کامنت گذاشت.", body: "«این انرژی رو از کجا میاری؟ یه نفس گرفتم با دیدنش.»", actor: { name: "علی رحمانی", ring: "#9a6cff" }, time: "۲۸ دقیقه" },
  { group: "امروز", type: "social", id: 4, unread: true, icon: "heart", tone: "magenta", title: "۳ نفر اثرت رو لایک کردن.", body: "مهسا کریمی، آرمان احمدی و +۱ نفر دیگه.", actors: ["مهسا", "آرمان", "فاطمه"], time: "۱ ساعت" },
  { group: "امروز", type: "social", id: 5, unread: true, icon: "profile", tone: "violet", title: "سعید نوری دنبالت کرد.", body: "هم‌شهری از شیراز · ۳ مشترک با تو", actor: { name: "سعید نوری", ring: "#9a6cff" }, time: "۲ ساعت", cta: "دنبال کن" },
  { group: "امروز", type: "system", id: 6, unread: false, icon: "microscope", tone: "cyan", title: "کانال «رادیو مرز» تأیید شد.", body: "حالا پست‌های جدیدش تو فید شخصی توئه.", time: "۳ ساعت" },

  // ---- YESTERDAY
  { group: "دیروز", type: "rate", id: 7, unread: false, icon: "trending", tone: "orange", title: "اثرت ترند شد!", body: "«رقص محلی گیلان» به فهرست ۲۴ ویدیوی برتر ماه اضافه شد.", time: "دیروز · ۲۲:۴۰" },
  { group: "دیروز", type: "social", id: 8, unread: false, icon: "comment", tone: "cyan", title: "زهرا مرادی کامنت گذاشت.", body: "«ایده برای چالش بعدی: صبحانهٔ شهرت. هرکس صبحانهٔ محله‌ش رو نشون بده.»", actor: { name: "زهرا مرادی", ring: "#44e3b8" }, time: "دیروز · ۱۸:۱۲" },
  { group: "دیروز", type: "social", id: 9, unread: false, icon: "heart", tone: "magenta", title: "۱۲ نفر اثرت رو ذخیره کردن.", body: "بیشترین ذخیره‌سازی روزانهٔ این هفته‌ت.", time: "دیروز · ۱۲:۰۰" },
  { group: "دیروز", type: "system", id: 10, unread: false, icon: "flame", tone: "orange", title: "شعلهٔ استریک ۷ روزه‌ت روشن شد!", body: "ادامه بده تا برای روز ۱۴، نشان «روشن نگه‌دار» بگیری.", time: "دیروز · ۰۹:۰۰" },

  // ---- THIS WEEK
  { group: "این هفته", type: "prize", id: 11, unread: false, icon: "tv", tone: "gold", title: "نامزد ستارهٔ رسانهٔ ملی شدی.", body: "از بین ۲۴ ویدیوی ترند ماه، اثر تو به نامزدی مهمان ویژهٔ برنامهٔ گفت‌وگو رسید.", time: "۲ روز پیش", cta: "جزئیات" },
  { group: "این هفته", type: "rate", id: 12, unread: false, icon: "star", tone: "magenta", title: "میانگین امتیازت به ۴٫۸ رسید.", body: "+۰٫۲ نسبت به هفتهٔ پیش.", time: "۳ روز پیش" },
];

window.Notifications = function Notifications({ onBack, onRoute }) {
  const [tab, setTab] = useState("all");
  const [items, setItems] = useState(NOTES);
  const [requests, setRequests] = useState(FOLLOW_REQUESTS);

  const filtered = tab === "all" ? items
    : tab === "requests" ? []
    : items.filter(n => n.type === tab);
  const grouped = filtered.reduce((acc, n) => {
    (acc[n.group] = acc[n.group] || []).push(n);
    return acc;
  }, {});

  const markAll = () => setItems(items.map(i => ({ ...i, unread: false })));
  const open = (n) => {
    setItems(items.map(i => i.id === n.id ? { ...i, unread: false } : i));
    if (n.icon === "comment") onRoute?.("comments");
    else if (n.type === "rate" || n.type === "prize") onRoute?.("post");
  };
  const acceptReq = (id) => setRequests(r => r.filter(x => x.id !== id));
  const rejectReq = (id) => setRequests(r => r.filter(x => x.id !== id));

  const unreadTotal = items.filter(i => i.unread).length;
  const showRequests = (tab === "all" || tab === "requests") && requests.length > 0;

  return (
    <div className="kd-notif-page">
      {/* Header */}
      <header className="kd-notif-head">
        <button className="kd-fh-back" onClick={onBack} aria-label="برگشت">
          <Icon name="back" size={20} stroke={2.2} />
        </button>
        <div className="kd-notif-head__id">
          <h1>اعلان‌ها</h1>
          <p>{unreadTotal > 0 ? `${fmtFa(unreadTotal)} نخوانده` : "همه چی رو دیدی."}</p>
        </div>
        {unreadTotal > 0 && (
          <button className="kd-notif-head__mark" onClick={markAll}>
            <Icon name="check" size={14} stroke={2.4} /> همه را خوانده‌شده کن
          </button>
        )}
      </header>

      {/* Tabs */}
      <div className="kd-notif-tabs" role="tablist">
        {TABS.map(t => (
          <button key={t.id} className={`kd-notif-tab ${tab === t.id ? "is-on" : ""}`} onClick={() => setTab(t.id)}>
            <span>{t.label}</span>
            <em>{fmtFa(t.count)}</em>
          </button>
        ))}
      </div>

      {/* List */}
      <div className="kd-notif-list">
        {showRequests && (
          <section>
            <h2 className="kd-notif-group">درخواست‌های دنبال‌کردن <span style={{ color: "#f5d589" }}>({fmtFa(requests.length)})</span></h2>
            <ul className="kd-followreq__list">
              {requests.map(r => (
                <li key={r.id} className="kd-followreq__item">
                  <Avatar name={r.user.name} size={44} ring="#f5d589" />
                  <div className="kd-followreq__text">
                    <strong>{r.user.name}</strong>
                    <span className="kd-followreq__handle">@{r.user.handle} · {r.user.city}{r.mutual > 0 ? ` · ${fmtFa(r.mutual)} مشترک` : ""}</span>
                    {r.user.bio && <p className="kd-followreq__bio">{r.user.bio}</p>}
                  </div>
                  <div className="kd-followreq__actions">
                    <button className="kd-btn kd-btn--primary kd-btn--sm" onClick={() => acceptReq(r.id)}>
                      <Icon name="check" size={12} stroke={2.6} /> قبول
                    </button>
                    <button className="kd-btn kd-btn--secondary kd-btn--sm" onClick={() => rejectReq(r.id)}>رد</button>
                  </div>
                </li>
              ))}
            </ul>
          </section>
        )}

        {Object.entries(grouped).map(([group, list]) => (
          <section key={group}>
            <h2 className="kd-notif-group">{group}</h2>
            <ul>
              {list.map(n => (
                <li key={n.id} className={`kd-notif-item kd-notif-item--${n.tone} ${n.unread ? "is-unread" : ""}`} onClick={() => open(n)}>
                  <span className={`kd-notif-icon kd-notif-icon--${n.tone}`}>
                    <Icon name={n.icon} size={18} stroke={2} />
                  </span>
                  <div className="kd-notif-mid">
                    <div className="kd-notif-row">
                      {n.actor && <Avatar name={n.actor.name} size={22} ring={n.actor.ring} />}
                      {n.actors && (
                        <span className="kd-notif-actors">
                          {n.actors.map((a, i) => <Avatar key={i} name={a} size={22} />)}
                        </span>
                      )}
                      <strong className="kd-notif-title">{n.title}</strong>
                    </div>
                    <p className="kd-notif-body">{n.body}</p>
                    <div className="kd-notif-foot">
                      <span className="kd-notif-time">{n.time}</span>
                      {n.cta && (
                        <button className="kd-notif-cta">
                          {n.cta} <Icon name="back" size={12} stroke={2.4} />
                        </button>
                      )}
                    </div>
                  </div>
                  {n.unread && <span className="kd-notif-dot" />}
                </li>
              ))}
            </ul>
          </section>
        ))}

        {filtered.length === 0 && !showRequests && (
          <div className="kd-notif-empty">
            <Icon name="bell" size={36} stroke={1.6} />
            <p>این‌جا چیزی نیست.</p>
            <span>وقتی اتفاقی بیفته، اول از همه به تو می‌گیم.</span>
          </div>
        )}

        <div className="kd-notif-footer">
          <Icon name="check" size={18} stroke={2.2} />
          <span>تا اینجا رو دیدی. برای بقیه، فردا سر بزن.</span>
        </div>
      </div>
    </div>
  );
};
})();
