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

/* =============================================================
   FollowHub.jsx — personal stream sources
   Two tabs:
     • کاربران — follow people on Koshvardoust
     • کانال‌ها — connect external social channels (Bale, Eitaa,
       Virasti, Wisgoon, Rubika, Twitter, Instagram, Telegram, FB)
   Each external channel passes through server review before
   appearing in the user's personal stream.
   ============================================================= */

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$/, "")) + " م";
};

/* ---- External networks. Pure-CSS glyphs (a small mark + brand color)
   keep this kit free of third-party logo files; replace with real SVGs
   once you have signed brand assets. ---- */
const NETWORKS = [
  { id: "bale",      label: "بَله",       glyph: "B",  color: "#2C7DFA", placeholder: "@username یا لینک کانال bale.ai/joinchat/..." },
  { id: "eitaa",     label: "ایتا",       glyph: "E",  color: "#FFA300", placeholder: "@username یا eitaa.com/joinchat/..." },
  { id: "virasti",   label: "ویراستی",    glyph: "و",  color: "#7A4DFF", placeholder: "@username یا لینک ویراستی" },
  { id: "wisgoon",   label: "ویسگون",     glyph: "س",  color: "#F1535E", placeholder: "@username ویسگون" },
  { id: "rubika",    label: "روبیکا",     glyph: "R",  color: "#FF1E56", placeholder: "@username یا rubika.ir/joing/..." },
  { id: "twitter",   label: "توییتر / X", glyph: "𝕏", color: "#101418", placeholder: "@username" },
  { id: "instagram", label: "اینستاگرام", glyph: "◯", color: "#E1306C", placeholder: "@username" },
  { id: "telegram",  label: "تلگرام",     glyph: "✈", color: "#229ED9", placeholder: "@channel یا t.me/..." },
  { id: "facebook",  label: "فیسبوک",     glyph: "f",  color: "#1877F2", placeholder: "نام صفحه یا facebook.com/..." },
];

const PEOPLE = [
  { id: 1, name: "نگار رستمی",  handle: "negar.r",   city: "رشت",   bio: "روایت‌گر شهرهای شمال.",           followers: 12480, mutual: 4, badge: "برندهٔ مرداد" },
  { id: 2, name: "آرمان احمدی", handle: "armana",    city: "تبریز", bio: "تصویرسازی دیجیتال و خوش‌نویسی.",  followers: 9320,  mutual: 2 },
  { id: 3, name: "مهسا کریمی",  handle: "mahsa.k",   city: "اصفهان", bio: "داستانک می‌نویسم.",              followers: 7140,  mutual: 8, badge: "تالار افتخار" },
  { id: 4, name: "سعید نوری",   handle: "saeed.n",   city: "شیراز",  bio: "پادکست «قصه‌های جاده».",          followers: 5220,  mutual: 1 },
  { id: 5, name: "زهرا مرادی",  handle: "zahra.m",   city: "تهران",  bio: "نقد شهری، با عشق.",               followers: 18230, mutual: 6 },
  { id: 6, name: "فاطمه دلیری", handle: "fatima.d",  city: "بندرعباس", bio: "غذای محلی و آشپزی بومی.",      followers: 4180,  mutual: 0 },
];

const SUBSCRIBED = [
  { id: "s1", network: "telegram",  handle: "@radiomarz",        title: "رادیو مرز",         posts_week: 24, status: "approved", added: "۲ هفته پیش" },
  { id: "s2", network: "twitter",   handle: "@persianpoetry",    title: "شعر فارسی",         posts_week: 86, status: "approved", added: "۱ ماه پیش" },
  { id: "s3", network: "instagram", handle: "@tehrandayreal",    title: "تهران امروز",       posts_week: 12, status: "pending",  added: "۲ روز پیش" },
  { id: "s4", network: "bale",      handle: "@khabar_eqtesadi",  title: "اقتصاد روز",        posts_week: 38, status: "approved", added: "۳ هفته پیش" },
  { id: "s5", network: "rubika",    handle: "@cinemaSafarbash",  title: "سفر با سینما",      posts_week: 6,  status: "rejected", added: "دیروز", reason: "کانال خصوصی است؛ به آن دسترسی نداریم." },
];

window.FollowHub = function FollowHub({ onBack }) {
  const [tab, setTab] = useState("channels"); // people | channels
  const [pickedNet, setPickedNet] = useState(null);
  const [handle, setHandle] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [subs, setSubs] = useState(SUBSCRIBED);
  const [follow, setFollow] = useState({}); // {personId: bool}

  const resetWizard = () => { setPickedNet(null); setHandle(""); setSubmitting(false); };

  const submit = () => {
    if (!pickedNet || !handle.trim()) return;
    setSubmitting(true);
    setTimeout(() => {
      const id = "s" + Date.now();
      setSubs(s => [{
        id, network: pickedNet.id,
        handle: handle.trim().startsWith("@") || handle.includes("/") ? handle.trim() : "@" + handle.trim(),
        title: handle.trim().replace(/^@/, "").replace(/.*\//, ""),
        posts_week: 0, status: "pending", added: "همین حالا",
      }, ...s]);
      resetWizard();
    }, 1100);
  };

  const removeSub = (id) => setSubs(s => s.filter(x => x.id !== id));
  const toggleFollow = (id) => setFollow(f => ({ ...f, [id]: !f[id] }));

  return (
    <div className="kd-fh-page">
      {/* ---- Header ---- */}
      <header className="kd-fh-head">
        <button className="kd-fh-back" onClick={onBack} aria-label="برگشت">
          <Icon name="back" size={20} stroke={2.2} />
        </button>
        <div className="kd-fh-head__id">
          <h1 className="kd-fh-head__title">استریم تو</h1>
          <p className="kd-fh-head__sub">هرکس و هر کانالی رو دنبال کن. ما برات یه فید شخصی می‌سازیم.</p>
        </div>
      </header>

      {/* ---- Tabs ---- */}
      <div className="kd-fh-tabs">
        <button className={`kd-fh-tab ${tab === "channels" ? "is-on" : ""}`} onClick={() => setTab("channels")}>
          <Icon name="share" size={16} stroke={2} />
          <span>کانال‌های شبکه‌های دیگه</span>
          <em>{fmtFa(subs.length)}</em>
        </button>
        <button className={`kd-fh-tab ${tab === "people" ? "is-on" : ""}`} onClick={() => setTab("people")}>
          <Icon name="profile" size={16} stroke={2} />
          <span>کاربران کشوردوست</span>
          <em>{fmtFa(Object.values(follow).filter(Boolean).length)}</em>
        </button>
      </div>

      {/* ====================================================== */}
      {/* ===== TAB: CHANNELS ================================== */}
      {/* ====================================================== */}
      {tab === "channels" && (
        <React.Fragment>
          {/* Wizard — pick a network, enter handle/link */}
          <section className="kd-fh-wizard">
            <header className="kd-fh-wizard__head">
              <h3>یه کانال جدید اضافه کن</h3>
              <span className="kd-fh-wizard__step">{pickedNet ? "مرحلهٔ ۲ از ۲" : "مرحلهٔ ۱ از ۲"}</span>
            </header>

            {!pickedNet && (
              <React.Fragment>
                <p className="kd-fh-wizard__sub">از کدوم شبکه می‌خوای کانال دنبال کنی؟</p>
                <div className="kd-fh-netgrid">
                  {NETWORKS.map(n => (
                    <button key={n.id} className="kd-fh-net" style={{ ['--net-color']: n.color }} onClick={() => setPickedNet(n)}>
                      <span className="kd-fh-net__glyph" style={{ background: n.color }}>{n.glyph}</span>
                      <span className="kd-fh-net__label">{n.label}</span>
                    </button>
                  ))}
                </div>
              </React.Fragment>
            )}

            {pickedNet && (
              <React.Fragment>
                <div className="kd-fh-wizard__chosen">
                  <span className="kd-fh-net__glyph" style={{ background: pickedNet.color, width: 36, height: 36, fontSize: 18 }}>{pickedNet.glyph}</span>
                  <div>
                    <strong>{pickedNet.label}</strong>
                    <span>یوزرنیم یا لینک کانال رو بزن.</span>
                  </div>
                  <button className="kd-fh-wizard__change" onClick={resetWizard}>تغییر</button>
                </div>
                <input
                  className="kd-fh-wizard__input"
                  placeholder={pickedNet.placeholder}
                  value={handle}
                  onChange={e => setHandle(e.target.value)}
                  autoFocus
                  dir="ltr"
                />
                <p className="kd-fh-wizard__note">
                  <Icon name="microscope" size={13} stroke={2.2} />
                  سرور کانال رو بررسی می‌کنه. اگه عمومی و فعال باشه، تو فید شخصیت اضافه می‌شه.
                </p>
                <div className="kd-fh-wizard__actions">
                  <button className="kd-btn kd-btn--ghost" onClick={resetWizard}>انصراف</button>
                  <button className="kd-btn kd-btn--primary" disabled={!handle.trim() || submitting} onClick={submit}>
                    {submitting ? "در حال ارسال…" : "ارسال برای بررسی"}
                  </button>
                </div>
              </React.Fragment>
            )}
          </section>

          {/* Subscribed list */}
          <section className="kd-fh-subs">
            <header className="kd-fh-section">
              <h3>کانال‌هایی که اضافه کردی</h3>
              <span>{fmtFa(subs.length)} کانال</span>
            </header>

            {subs.length === 0 && (
              <div className="kd-fh-empty">
                <Icon name="share" size={36} stroke={1.6} />
                <p>هنوز کانالی اضافه نکردی.</p>
              </div>
            )}

            <ul className="kd-fh-sublist">
              {subs.map(s => {
                const net = NETWORKS.find(n => n.id === s.network);
                return (
                  <li key={s.id} className={`kd-fh-sub kd-fh-sub--${s.status}`}>
                    <span className="kd-fh-net__glyph" style={{ background: net?.color || "#444", width: 40, height: 40, fontSize: 18, flexShrink: 0 }}>{net?.glyph}</span>
                    <div className="kd-fh-sub__id">
                      <strong>{s.title}</strong>
                      <span className="kd-fh-sub__handle" dir="ltr">{s.handle}</span>
                      <span className="kd-fh-sub__net">{net?.label} · {s.added}</span>
                    </div>
                    <div className="kd-fh-sub__stat">
                      {s.status === "approved" && (
                        <React.Fragment>
                          <strong>{fmtFa(s.posts_week)}</strong>
                          <span>پست این هفته</span>
                        </React.Fragment>
                      )}
                      {s.status === "pending" && (
                        <span className="kd-fh-sub__badge kd-fh-sub__badge--pending">
                          <span className="kd-fh-sub__pulse" /> در حال بررسی
                        </span>
                      )}
                      {s.status === "rejected" && (
                        <span className="kd-fh-sub__badge kd-fh-sub__badge--rejected" title={s.reason}>
                          <Icon name="close" size={11} stroke={2.4} /> رد شد
                        </span>
                      )}
                    </div>
                    <button className="kd-fh-sub__remove" onClick={() => removeSub(s.id)} aria-label="حذف">
                      <Icon name="close" size={16} stroke={2.2} />
                    </button>
                    {s.status === "rejected" && s.reason && (
                      <p className="kd-fh-sub__reason"><Icon name="microscope" size={12} stroke={2.2} /> {s.reason}</p>
                    )}
                  </li>
                );
              })}
            </ul>
          </section>
        </React.Fragment>
      )}

      {/* ====================================================== */}
      {/* ===== TAB: PEOPLE ==================================== */}
      {/* ====================================================== */}
      {tab === "people" && (
        <section className="kd-fh-people">
          <div className="kd-fh-search">
            <Icon name="search" size={18} stroke={2.2} />
            <input placeholder="بین کاربران بگرد…" />
          </div>

          <header className="kd-fh-section">
            <h3>پیشنهاد بر اساس علاقه‌مندی‌هات</h3>
            <span>{fmtFa(PEOPLE.length)} نفر</span>
          </header>

          <ul className="kd-fh-peoplelist">
            {PEOPLE.map(p => {
              const followed = !!follow[p.id];
              return (
                <li key={p.id} className="kd-fh-person">
                  <Avatar name={p.name} size={48} ring={p.badge ? "#f5d589" : undefined} />
                  <div className="kd-fh-person__id">
                    <strong>{p.name}</strong>
                    <span className="kd-fh-person__handle">@{p.handle} · {p.city}</span>
                    <p className="kd-fh-person__bio">{p.bio}</p>
                    <div className="kd-fh-person__meta">
                      <span>{fmtCount(p.followers)} دنبال‌کننده</span>
                      {p.mutual > 0 && <span>· {fmtFa(p.mutual)} مشترک با تو</span>}
                      {p.badge && <span className="kd-fh-person__badge"><Icon name="trophy" size={11} stroke={2.2} /> {p.badge}</span>}
                    </div>
                  </div>
                  <button
                    className={`kd-fh-person__follow ${followed ? "is-on" : ""}`}
                    onClick={() => toggleFollow(p.id)}>
                    {followed ? (<React.Fragment><Icon name="check" size={14} stroke={2.4} /> دنبال می‌کنی</React.Fragment>) : "دنبال کن"}
                  </button>
                </li>
              );
            })}
          </ul>
        </section>
      )}
    </div>
  );
};
})();
