/* global React */
(function(){

/* =============================================================
   States.jsx — Empty / Loading-Skeleton / Error templates
   --------------------------------------------------------------
   Reusable components used across the product. The voice is
   casual «تو» — warm, never blamey. Each empty state ships
   with a CTA.

   Exports (global):
     EmptyState · ErrorState · RateLimit · OfflineState
     Skeleton (variant="card|row|feed|profile|post|search")
   ============================================================= */

window.EmptyState = function EmptyState({ icon = "search", title, sub, cta, tone = "cyan" }) {
  const tones = {
    cyan:   { bg: "rgba(75,227,255,0.08)",  ring: "rgba(75,227,255,0.18)",  c: "#7ff0d2" },
    rose:   { bg: "rgba(255,78,168,0.08)",  ring: "rgba(255,78,168,0.18)",  c: "#ffb1d4" },
    gold:   { bg: "rgba(245,213,137,0.08)", ring: "rgba(245,213,137,0.18)", c: "#f5d589" },
    violet: { bg: "rgba(154,108,255,0.08)", ring: "rgba(154,108,255,0.18)", c: "#bda0ff" },
    mint:   { bg: "rgba(68,227,184,0.08)",  ring: "rgba(68,227,184,0.18)",  c: "#7ff0d2" },
  };
  const t = tones[tone] || tones.cyan;
  return (
    <div className="kd-state kd-state--empty">
      <div className="kd-state__icon" style={{ background: t.bg, border: `1px solid ${t.ring}`, color: t.c }}>
        <Icon name={icon} size={32} stroke={1.6} />
      </div>
      <h3 className="kd-state__title">{title}</h3>
      {sub && <p className="kd-state__sub">{sub}</p>}
      {cta && (
        <button className="kd-btn kd-btn--primary kd-btn--md kd-state__cta" onClick={cta.onClick}>
          {cta.label}
        </button>
      )}
    </div>
  );
};

window.ErrorState = function ErrorState({ code = "۴۰۴", title, sub, cta, tone = "rose" }) {
  return (
    <div className="kd-state kd-state--error">
      <div className="kd-state__code">{code}</div>
      <h3 className="kd-state__title">{title}</h3>
      {sub && <p className="kd-state__sub">{sub}</p>}
      <div className="kd-state__ctas">
        {cta && (
          <button className="kd-btn kd-btn--primary kd-btn--md" onClick={cta.onClick}>
            {cta.label}
          </button>
        )}
        <button className="kd-btn kd-btn--secondary kd-btn--md" onClick={() => location.reload()}>
          دوباره امتحان کن
        </button>
      </div>
    </div>
  );
};

window.RateLimit = function RateLimit({ secondsLeft = 18 }) {
  return (
    <div className="kd-state kd-state--rate">
      <div className="kd-state__icon" style={{ background: "rgba(245,213,137,0.10)", border: "1px solid rgba(245,213,137,0.32)", color: "#f5d589" }}>
        <Icon name="flame" size={28} stroke={1.7} />
      </div>
      <h3 className="kd-state__title">آروم‌تر، یه نفس بکش</h3>
      <p className="kd-state__sub">
        کمی سریع پیش رفتی. تا {String(secondsLeft).replace(/\d/g, d => "۰۱۲۳۴۵۶۷۸۹"[d])} ثانیه دیگه دوباره بزن.
      </p>
    </div>
  );
};

window.OfflineState = function OfflineState({ onRetry }) {
  return (
    <div className="kd-state kd-state--offline">
      <div className="kd-state__icon" style={{ background: "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.12)", color: "rgba(255,255,255,0.7)" }}>
        <Icon name="bell" size={28} stroke={1.7} />
      </div>
      <h3 className="kd-state__title">به نظر نمیاد اینترنت داری</h3>
      <p className="kd-state__sub">وقتی برگشت، خودکار درست می‌شه. تا اون موقع، می‌تونی پست‌های ذخیره‌شده‌ت رو ببینی.</p>
      <button className="kd-btn kd-btn--primary kd-btn--md" onClick={onRetry || (() => location.reload())}>
        بررسی دوباره
      </button>
    </div>
  );
};

/* ============================================================
   Skeleton — animated loading placeholders
   ============================================================ */
window.Skeleton = function Skeleton({ variant = "card", count = 1 }) {
  const items = Array.from({ length: count });

  if (variant === "feed" || variant === "masonry") {
    // masonry with varied heights
    const heights = [160, 240, 200, 280, 180, 220, 260, 200];
    return (
      <div className="kd-masonry kd-skel-feed">
        {items.flatMap((_, j) => heights.map((h, i) => (
          <SkelCard key={`${j}-${i}`} height={h} delay={i * 50} />
        )))}
      </div>
    );
  }

  if (variant === "post") {
    return (
      <div className="kd-skel-post">
        <div className="kd-skel kd-skel--rect" style={{ height: 320, borderRadius: 18 }} />
        <div className="kd-skel-post__author">
          <div className="kd-skel kd-skel--circle" style={{ width: 44, height: 44 }} />
          <div className="kd-skel-post__author-lines">
            <div className="kd-skel" style={{ width: "40%", height: 14 }} />
            <div className="kd-skel" style={{ width: "60%", height: 11 }} />
          </div>
        </div>
        <div className="kd-skel" style={{ width: "85%", height: 14, marginBottom: 8 }} />
        <div className="kd-skel" style={{ width: "70%", height: 14, marginBottom: 8 }} />
        <div className="kd-skel" style={{ width: "55%", height: 14 }} />
      </div>
    );
  }

  if (variant === "profile") {
    return (
      <div className="kd-skel-profile">
        <div className="kd-skel kd-skel--circle" style={{ width: 92, height: 92, margin: "0 auto 14px" }} />
        <div className="kd-skel" style={{ width: 180, height: 22, margin: "0 auto 8px" }} />
        <div className="kd-skel" style={{ width: 140, height: 14, margin: "0 auto 24px" }} />
        <div className="kd-skel-profile__stats">
          {[1,2,3,4].map(i => (
            <div key={i} className="kd-skel-profile__stat">
              <div className="kd-skel" style={{ width: 36, height: 18, margin: "0 auto 4px" }} />
              <div className="kd-skel" style={{ width: 60, height: 10 }} />
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (variant === "search" || variant === "list") {
    return (
      <div className="kd-skel-list">
        {Array.from({ length: 6 }).map((_, i) => (
          <div key={i} className="kd-skel-row" style={{ animationDelay: i * 50 + "ms" }}>
            <div className="kd-skel kd-skel--circle" style={{ width: 40, height: 40 }} />
            <div style={{ flex: 1 }}>
              <div className="kd-skel" style={{ width: "45%", height: 13, marginBottom: 6 }} />
              <div className="kd-skel" style={{ width: "70%", height: 11 }} />
            </div>
          </div>
        ))}
      </div>
    );
  }

  // default 'card'
  return (
    <div className="kd-skel-card">
      <div className="kd-skel kd-skel--rect" style={{ height: 160, borderRadius: 12, marginBottom: 12 }} />
      <div className="kd-skel" style={{ width: "70%", height: 14, marginBottom: 8 }} />
      <div className="kd-skel" style={{ width: "50%", height: 12 }} />
    </div>
  );
};

function SkelCard({ height = 180, delay = 0 }) {
  return (
    <div className="kd-skel-card" style={{ animationDelay: delay + "ms" }}>
      <div className="kd-skel kd-skel--rect" style={{ height, borderRadius: 12 }} />
      <div className="kd-skel" style={{ width: "65%", height: 13, marginTop: 10 }} />
      <div className="kd-skel kd-skel-foot">
        <div className="kd-skel kd-skel--circle" style={{ width: 22, height: 22 }} />
        <div className="kd-skel" style={{ width: "30%", height: 10 }} />
      </div>
    </div>
  );
}

/* ============================================================
   States Gallery — design review surface
   ============================================================ */
window.StatesGallery = function StatesGallery({ onBack, onBanned }) {
  return (
    <div className="kd-states-gallery">
      <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">گالری حالت‌ها</h1>
        <span style={{ width: 36 }} />
      </header>

      <p className="kd-states-gallery__intro">
        نمونه‌ی همه‌ی حالت‌های خالی، خطا، و loading skeletonها. این صفحه برای طراحی‌ست — تو محصول از این کامپوننت‌ها هرجا که لازم باشه استفاده می‌کنیم.
      </p>

      {onBanned && (
        <div className="kd-states-gallery__fulltakes">
          <button className="kd-states-fulltake" onClick={() => onBanned("suspended")}>
            <span className="kd-states-fulltake__icon" style={{ ['--c']: '#f5d589' }}><Icon name="bell" size={18} stroke={2} /></span>
            <span><strong>حساب معلق</strong><em>تعلیق موقت + شمارش معکوس</em></span>
            <Icon name="back" size={14} stroke={2.4} />
          </button>
          <button className="kd-states-fulltake" onClick={() => onBanned("banned")}>
            <span className="kd-states-fulltake__icon" style={{ ['--c']: '#ff5774' }}><Icon name="close" size={18} stroke={2.2} /></span>
            <span><strong>حساب مسدود</strong><em>مسدودیت دائم + اعتراض</em></span>
            <Icon name="back" size={14} stroke={2.4} />
          </button>
        </div>
      )}

      {/* ===== EMPTY STATES ===== */}
      <h2 className="kd-states-gallery__h">حالت‌های خالی</h2>
      <div className="kd-states-gallery__grid">
        <Demo title="فید خالی">
          <EmptyState
            icon="search" tone="cyan"
            title="هنوز چیزی برات پیدا نکردیم"
            sub="کمی فعالیت کن تا بفهمیم چی دوست داری."
            cta={{ label: "برو سراغ کاوش", onClick: () => {} }}
          />
        </Demo>
        <Demo title="فالووینگ خالی">
          <EmptyState
            icon="profile" tone="violet"
            title="کسی رو دنبال نمی‌کنی"
            sub="یه چند نفر خوب رو پیدا کن — کمک‌مون می‌کنه فید بهتر بشه."
            cta={{ label: "پیشنهادهای ما", onClick: () => {} }}
          />
        </Demo>
        <Demo title="ذخیره‌شده‌ها خالی">
          <EmptyState
            icon="bookmark" tone="gold"
            title="هنوز چیزی ذخیره نکردی"
            sub="هرجا پستی دیدی دوست داشتی، روی نشانک بزن. اینجا برات نگه می‌داریم."
          />
        </Demo>
        <Demo title="اعلان‌ها خالی">
          <EmptyState
            icon="bell" tone="mint"
            title="هیچ اعلانی نیست"
            sub="وقتی کسی روی پست‌هات ستاره داد یا کامنت گذاشت، اینجا خبرت می‌کنیم."
          />
        </Demo>
        <Demo title="جستجو بی‌نتیجه">
          <EmptyState
            icon="search" tone="rose"
            title="چیزی پیدا نکردیم"
            sub="شاید با یه کلمه‌ی دیگه امتحان کنی؟"
          />
        </Demo>
      </div>

      {/* ===== ERROR STATES ===== */}
      <h2 className="kd-states-gallery__h">حالت‌های خطا</h2>
      <div className="kd-states-gallery__grid">
        <Demo title="۴۰۴ پست">
          <ErrorState
            code="۴۰۴"
            title="این پست پیدا نشد"
            sub="شاید پاک شده یا کاربر خصوصیش کرده."
            cta={{ label: "برو خونه", onClick: () => {} }}
          />
        </Demo>
        <Demo title="۴۰۴ کاربر">
          <ErrorState
            code="۴۰۴"
            title="این کاربر دیگه نیست"
            sub="حساب پاک شده یا اسمش رو عوض کرده."
            cta={{ label: "جستجوی کاربر", onClick: () => {} }}
          />
        </Demo>
        <Demo title="۵۰۰ سرور">
          <ErrorState
            code="۵۰۰"
            title="یه چیزی این طرف خراب شد"
            sub="تقصیر تو نیست. ما داریم درستش می‌کنیم — یه دقیقه دیگه امتحان کن."
          />
        </Demo>
        <Demo title="آفلاین">
          <OfflineState onRetry={() => {}} />
        </Demo>
        <Demo title="Rate limit">
          <RateLimit secondsLeft={18} />
        </Demo>
      </div>

      {/* ===== SKELETONS ===== */}
      <h2 className="kd-states-gallery__h">Skeletonها</h2>
      <div className="kd-states-gallery__skel">
        <Demo title="Masonry feed">
          <Skeleton variant="feed" />
        </Demo>
        <Demo title="Post">
          <Skeleton variant="post" />
        </Demo>
        <Demo title="Profile">
          <Skeleton variant="profile" />
        </Demo>
        <Demo title="List / search results">
          <Skeleton variant="list" />
        </Demo>
      </div>
    </div>
  );
};

function Demo({ title, children }) {
  return (
    <div className="kd-states-demo">
      <div className="kd-states-demo__lbl">{title}</div>
      <div className="kd-states-demo__body">{children}</div>
    </div>
  );
}
})();
